text:
// This file was generated by Mendix Business Modeler.
//
// WARNING: Code you write here will be lost the next time you deploy the project.

package administration.proxies;

import com.mendix.core.Core;
import com.mendix.core.CoreException;
import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.systemwideinterfaces.core.IMendixIdentifier;
import com.mendix.systemwideinterfaces.core.IMendixObject;

/**
 *
 */
public class AccountPasswordData
{
	private final IMendixObject accountPasswordDataMendixObject;

	private final IContext context;

	/**
	 * Internal name of this entity
	 */
	public static final String entityName = "Administration.AccountPasswordData";

	/**
	 * Enum describing members of this entity
	 */
	public enum MemberNames
	{
		OldPassword("OldPassword"),
		NewPassword("NewPassword"),
		ConfirmPassword("ConfirmPassword"),
		AccountPasswordData_Account("Administration.AccountPasswordData_Account");

		private String metaName;

		MemberNames(String s)
		{
			metaName = s;
		}

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

	public AccountPasswordData(IContext context)
	{
		this(context, Core.instantiate(context, "Administration.AccountPasswordData"));
	}

	protected AccountPasswordData(IContext context, IMendixObject accountPasswordDataMendixObject)
	{
		if (accountPasswordDataMendixObject == null)
			throw new IllegalArgumentException("The given object cannot be null.");
		if (!Core.isSubClassOf("Administration.AccountPasswordData", accountPasswordDataMendixObject.getType()))
			throw new IllegalArgumentException("The given object is not a Administration.AccountPasswordData");

		this.accountPasswordDataMendixObject = accountPasswordDataMendixObject;
		this.context = context;
	}

	/**
	 * @deprecated Use 'AccountPasswordData.load(IContext, IMendixIdentifier)' instead.
	 */
	@Deprecated
	public static administration.proxies.AccountPasswordData initialize(IContext context, IMendixIdentifier mendixIdentifier) throws CoreException
	{
		return administration.proxies.AccountPasswordData.load(context, mendixIdentifier);
	}

	/**
	 * Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called.
	 * The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.getSudoContext() can be used to obtain sudo access).
	 */
	public static administration.proxies.AccountPasswordData initialize(IContext context, IMendixObject mendixObject)
	{
		return new administration.proxies.AccountPasswordData(context, mendixObject);
	}

	public static administration.proxies.AccountPasswordData load(IContext context, IMendixIdentifier mendixIdentifier) throws CoreException
	{
		IMendixObject mendixObject = Core.retrieveId(context, mendixIdentifier);
		return administration.proxies.AccountPasswordData.initialize(context, mendixObject);
	}

	/**
	 * Commit the changes made on this proxy object.
	 */
	public final void commit() throws CoreException
	{
		Core.commit(context, getMendixObject());
	}

	/**
	 * Commit the changes made on this proxy object using the specified context.
	 */
	public final void commit(IContext context) throws CoreException
	{
		Core.commit(context, getMendixObject());
	}

	/**
	 * Delete the object.
	 */
	public final void delete()
	{
		Core.delete(context, getMendixObject());
	}

	/**
	 * Delete the object using the specified context.
	 */
	public final void delete(IContext context)
	{
		Core.delete(context, getMendixObject());
	}
	/**
	 * @return value of OldPassword
	 */
	public final String getOldPassword()
	{
		return getOldPassword(getContext());
	}

	/**
	 * @param context
	 * @return value of OldPassword
	 */
	public final String getOldPassword(IContext context)
	{
		return (String) getMendixObject().getValue(context, MemberNames.OldPassword.toString());
	}

	/**
	 * Set value of OldPassword
	 * @param oldpassword
	 */
	public final void setOldPassword(String oldpassword)
	{
		setOldPassword(getContext(), oldpassword);
	}

	/**
	 * Set value of OldPassword
	 * @param context
	 * @param oldpassword
	 */
	public final void setOldPassword(IContext context, String oldpassword)
	{
		getMendixObject().setValue(context, MemberNames.OldPassword.toString(), oldpassword);
	}

	/**
	 * @return value of NewPassword
	 */
	public final String getNewPassword()
	{
		return getNewPassword(getContext());
	}

	/**
	 * @param context
	 * @return value of NewPassword
	 */
	public final String getNewPassword(IContext context)
	{
		return (String) getMendixObject().getValue(context, MemberNames.NewPassword.toString());
	}

	/**
	 * Set value of NewPassword
	 * @param newpassword
	 */
	public final void setNewPassword(String newpassword)
	{
		setNewPassword(getContext(), newpassword);
	}

	/**
	 * Set value of NewPassword
	 * @param context
	 * @param newpassword
	 */
	public final void setNewPassword(IContext context, String newpassword)
	{
		getMendixObject().setValue(context, MemberNames.NewPassword.toString(), newpassword);
	}

	/**
	 * @return value of ConfirmPassword
	 */
	public final String getConfirmPassword()
	{
		return getConfirmPassword(getContext());
	}

	/**
	 * @param context
	 * @return value of ConfirmPassword
	 */
	public final String getConfirmPassword(IContext context)
	{
		return (String) getMendixObject().getValue(context, MemberNames.ConfirmPassword.toString());
	}

	/**
	 * Set value of ConfirmPassword
	 * @param confirmpassword
	 */
	public final void setConfirmPassword(String confirmpassword)
	{
		setConfirmPassword(getContext(), confirmpassword);
	}

	/**
	 * Set value of ConfirmPassword
	 * @param context
	 * @param confirmpassword
	 */
	public final void setConfirmPassword(IContext context, String confirmpassword)
	{
		getMendixObject().setValue(context, MemberNames.ConfirmPassword.toString(), confirmpassword);
	}

	/**
	 * @return value of AccountPasswordData_Account
	 */
	public final administration.proxies.Account getAccountPasswordData_Account() throws CoreException
	{
		return getAccountPasswordData_Account(getContext());
	}

	/**
	 * @param context
	 * @return value of AccountPasswordData_Account
	 */
	public final administration.proxies.Account getAccountPasswordData_Account(IContext context) throws CoreException
	{
		administration.proxies.Account result = null;
		IMendixIdentifier identifier = getMendixObject().getValue(context, MemberNames.AccountPasswordData_Account.toString());
		if (identifier != null)
			result = administration.proxies.Account.load(context, identifier);
		return result;
	}

	/**
	 * Set value of AccountPasswordData_Account
	 * @param accountpassworddata_account
	 */
	public final void setAccountPasswordData_Account(administration.proxies.Account accountpassworddata_account)
	{
		setAccountPasswordData_Account(getContext(), accountpassworddata_account);
	}

	/**
	 * Set value of AccountPasswordData_Account
	 * @param context
	 * @param accountpassworddata_account
	 */
	public final void setAccountPasswordData_Account(IContext context, administration.proxies.Account accountpassworddata_account)
	{
		if (accountpassworddata_account == null)
			getMendixObject().setValue(context, MemberNames.AccountPasswordData_Account.toString(), null);
		else
			getMendixObject().setValue(context, MemberNames.AccountPasswordData_Account.toString(), accountpassworddata_account.getMendixObject().getId());
	}

	/**
	 * @return the IMendixObject instance of this proxy for use in the Core interface.
	 */
	public final IMendixObject getMendixObject()
	{
		return accountPasswordDataMendixObject;
	}

	/**
	 * @return the IContext instance of this proxy, or null if no IContext instance was specified at initialization.
	 */
	public final IContext getContext()
	{
		return context;
	}

	@Override
	public boolean equals(Object obj)
	{
		if (obj == this)
			return true;

		if (obj != null && getClass().equals(obj.getClass()))
		{
			final administration.proxies.AccountPasswordData that = (administration.proxies.AccountPasswordData) obj;
			return getMendixObject().equals(that.getMendixObject());
		}
		return false;
	}

	@Override
	public int hashCode()
	{
		return getMendixObject().hashCode();
	}

	/**
	 * @return String name of this class
	 */
	public static String getType()
	{
		return "Administration.AccountPasswordData";
	}

	/**
	 * @return String GUID from this object, format: ID_0000000000
	 * @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object.
	 */
	@Deprecated
	public String getGUID()
	{
		return "ID_" + getMendixObject().getId().toLong();
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2014-2022 Aurélien Broszniowski
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<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/xsd/maven-4.0.0.xsd">
  <parent>
    <artifactId>rainfall</artifactId>
    <groupId>io.rainfall</groupId>
    <version>1.6.4-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <artifactId>Rainfall-tutorial</artifactId>

  <properties>
    <rainfall.core.version>1.6.4-SNAPSHOT</rainfall.core.version>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <project.build.outputEncoding>UTF-8</project.build.outputEncoding>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>io.rainfall</groupId>
      <artifactId>rainfall-core</artifactId>
      <version>${rainfall.core.version}</version>
    </dependency>

    <dependency>
      <groupId>io.rainfall</groupId>
      <artifactId>rainfall-store-client</artifactId>
      <version>${version}</version>
    </dependency>

    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>[1.2.0,)</version>
    </dependency>

    <dependency>
      <groupId>org.hdrhistogram</groupId>
      <artifactId>HdrHistogram</artifactId>
      <version>2.1.8</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.2</version>
        <configuration>
          <showDeprecation>true</showDeprecation>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>

    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.17</version>
          <configuration>
            <includes>
              <include>**/*.class</include>
            </includes>
            <excludedGroups>io.rainfall.utils.SystemTest</excludedGroups>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-failsafe-plugin</artifactId>
          <version>2.17</version>
          <configuration>
            <groups>io.rainfall.utils.SystemTest</groups>
          </configuration>
          <executions>
            <execution>
              <goals>
                <goal>integration-test</goal>
              </goals>
              <configuration>
                <includes>
                  <include>**/*.class</include>
                </includes>
              </configuration>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>


text:
package org.hl7.fhir.instance.formats;

import java.math.BigDecimal;
import java.net.URI;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.hl7.fhir.instance.model.AtomFeed;
import org.hl7.fhir.instance.model.Resource;
import org.hl7.fhir.utilities.Utilities;
import org.xmlpull.v1.XmlPullParser;

public abstract class ParserBase extends XmlBase {

  public class ResourceOrFeed {
    protected Resource resource;
    protected AtomFeed feed;
    public Resource getResource() {
      return resource;
    }
    public AtomFeed getFeed() {
      return feed;
    }
  }

  protected Map<String, Object> idMap = new HashMap<String, Object>();

//protected Element resolveElement(String id) {
//  return idMap.get(id);
//}

  protected int parseIntegerPrimitive(String value) {
    if (value.startsWith("+") && Utilities.IsInteger(value.substring(1)))
      value = value.substring(1);
	return java.lang.Integer.parseInt(value);
  }

  protected String parseDateTimePrimitive(String value) {
    return value;
  }

  protected String parseCodePrimitive(String value) {
    return value;
  }

  protected String parseDatePrimitive(String value) {
    return value;
  }

  protected BigDecimal parseDecimalPrimitive(String value) {
    return new BigDecimal(value);
  }

  protected String parseUriPrimitive(String value) throws Exception {
  	 return value;
  }

  protected byte[] parseBase64BinaryPrimitive(String value) {
    return Base64.decodeBase64(value.getBytes());
  }

  protected String parseOidPrimitive(String value) {
    return value;
  }

  protected boolean parseBooleanPrimitive(String value) {
    return java.lang.Boolean.valueOf(value);
  }

  protected Calendar parseInstantPrimitive(String value) throws Exception {
    return xmlToDate(value);
  }

  protected String parseIdPrimitive(String value) {
    return value;
  }

  protected String parseStringPrimitive(String value) {
    return value;
  }

  protected String parseUuidPrimitive(String value) {
    return value;
  }

}


text:
import abc
import collections
import copy
import json
import msgpack

from ..validators import ValidationError
from ..fields import ViewModelField, Field

__ALL__ = ['StrictDict']

class StrictDictMeta(abc.ABCMeta):
    # ABCMeta is metaclass of collections.MutableMapping
    def __new__(meta, name, bases, dict_):
        fields = dict_.setdefault('__fields__', {})
        ignored_fields = set(dict_.setdefault('__ignored_fields__', []))
        for base_class in bases:
            if hasattr(base_class, '__fields__'):
                fields.update(base_class.__fields__)
            if hasattr(base_class, '__ignored_fields__'):
                ignored_fields.update(base_class.__ignored_fields__)

        for attrname, attr in list(dict_.items()):
            if isinstance(attr, Field):
                if any(hasattr(base, attrname) for base in bases):
                    raise NameCollisionError(attrname)
                fields[attrname] = dict_.pop(attrname)

        for ifield in ignored_fields:
            fields.pop(ifield, None)
        dict_['__ignored_fields__'] = ignored_fields
        dict_['__fields__'] = fields
        return super(StrictDictMeta, meta).__new__(meta, name, bases, dict_)

class _StrictDictInterface(collections.MutableMapping):
    def __repr__(self):
        return self.to_string()

    def __getitem__(self, key):
        try:
            return self._get_item(key)
        except AttributeError:
            raise KeyError('key "%s" does not exist' % key)

    def __contains__(self, key):
        if key not in self.__fields__:
            return False
        return key in self._storage or key in self._simplified

    def __setitem__(self, key, value):
        raise AttributeError("Object is immutable")

    def __delitem__(self, key):
        raise AttributeError("Object is immutable")

    def __delattr__(self, key):
        raise AttributeError("Object is immutable")

    def __getattr__(self, key):
        return self._get_item(key)

    def __setattr__(self, key, value):
        raise AttributeError("Object is immutable")

    def __len__(self):
        return len(self._keys())

    def __iter__(self):
        for key in self._keys():
            if key in self:
                yield key

    def __hash__(self):
        return hash(self.to_string(msg_pack=True))

class StrictDict(_StrictDictInterface, metaclass=StrictDictMeta):
    """
    Provides dict interface with validation and serialization/deserialization
    """
    __fields__ = {}
    __ignored_fields__ = ()
    is_ignore_unknown_fields = False

    def __init__(self, **kwargs):
        if self.is_ignore_unknown_fields:
            # Silently swallow all extra keys
            kwargs = {k: v for k, v in kwargs.items() if k in self.__fields__.keys()}

        # Underlying python dict
        self._direct_set('_storage', dict())
        # Simplified storage ready to be serialized
        self._direct_set('_simplified', dict())
        full_kwargs = kwargs
        kwargs = kwargs.copy()
        _errors = []
        for key, field in self.__fields__.items():
            value = kwargs.pop(key, None)
            value_is_empty = field.is_empty(value)
            if value_is_empty and field.required:
                exc = ValidationError('Required field {} is empty or missing!'.format(key), path=[],
                                      class_=self.__class__, value=full_kwargs)
                _errors.append({key: exc.message})
            elif value_is_empty:
                validated = field.empty_value()
            else:
                try:
                    validated = field.validate(value, key)
                except ValidationError as exc:
                    exc.class_ = self.__class__
                    if exc.errors:
                        value = exc.errors
                    else:
                        value = exc.message
                    _errors.append({key: value})

            if not _errors:
                self._storage[key] = validated
                if not value_is_empty:
                    self._simplified[key] = field.serialize(validated)

        if _errors:
            msg = 'ValidationError in fields: {}'.format(', '.join(self._format_error(_errors)))
            exc = ValidationError(msg, class_=self.__class__, path=[], value=full_kwargs, errors=_errors)
            raise exc

        extra_keys = set(kwargs.keys()) - set(self.__ignored_fields__)
        if extra_keys:
            raise ValidationError('No such fields: {}'.format(', '.join(str(x) for x in extra_keys)),
                                  class_=self.__class__)

    def _direct_set(self, key, value):
        object.__setattr__(self, key, value)

    def _format_error(self, errors, prefix=''):
        fields = []
        for error in errors:
            for key, value in error.items():
                if isinstance(value, list):
                    fields.extend(self._format_error(errors=value, prefix=key))
                else:
                    if prefix:
                        key = '{0}.{1}'.format(prefix, key)
                    fields.append(key)
        return fields

    def _keys(self):
        return self._simplified.keys()

    def _get_item(self, key):
        key = str(key)
        try:
            field = self.__fields__[key]
        except KeyError:
            raise AttributeError('No such field: "%s"' % key)

        if key in self._storage:
            # Value is ready
            return self._storage[key]
        if key in self._simplified:
            # Value is in simplified form
            val_simpl = self._simplified[key]
            value = field.deserialize(val_simpl)
            self._storage[key] = value
            return value
        self._storage[key] = value = field.empty_value()
        return value

    def simplify(self):
        return self._simplified

    def to_dict(self):
        """
        For backwards compatibility
        """
        plain_dict = dict()
        for k, v in self.items():
            if self.__fields__[k].is_list:
                if isinstance(self.__fields__[k], ViewModelField):
                    plain_dict[k] = tuple(vt.to_dict() for vt in v)
                    continue

                plain_dict[k] = tuple(copy.deepcopy(vt) for vt in v)
                continue

            if isinstance(self.__fields__[k], ViewModelField):
                plain_dict[k] = v.to_dict()
                continue

            plain_dict[k] = copy.deepcopy(v)

        return plain_dict

    @classmethod
    def restore(cls, data_dict):
        """
        Restore from previously simplified data. Data is supposed to be valid,
        no checks are performed!
        """
        obj = cls.__new__(cls)  # Avoid calling constructor
        object.__setattr__(obj, '_simplified', data_dict)
        object.__setattr__(obj, '_storage', dict())
        return obj

    def to_string(self, msg_pack=False):
        return self.dumps(self, msg_pack=msg_pack)

    @classmethod
    def dumps(cls, data, msg_pack=False):
        if isinstance(data, (list, tuple,)):
            data = [d.simplify() for d in data]
        else:
            data = data.simplify()

        if msg_pack:
            return msgpack.dumps(data)
        kw = {}
        return json.dumps(data, **kw)

    @classmethod
    def loads(cls, data_str, msg_pack=False):
        if msg_pack:
            if isinstance(data_str, bytes):
                data = msgpack.loads(data_str, encoding='utf-8')
            else:
                data = msgpack.loads(data_str)
        else:
            data = json.loads(data_str)

        if isinstance(data, (list, tuple,)):
            return [cls.restore(d) for d in data]
        return cls.restore(data)

    def clone(self):
        """
        Return a deep copy of self
        """
        return self.restore(self.simplify())

class NameCollisionError(Exception):
    pass


text:
/* eslint-disable no-undef */
import {countBy} from 'lodash';
import achievements from './achievements';

describe('achievements', () => {
	it('all ids are unique', () => {
		const ids = new Set(Array.from(achievements.values()).map(({id}) => id));
		expect(Array.from(achievements)).toHaveLength(ids.size);
	});

	it('all titles are unique', () => {
		const titles = new Set(Array.from(achievements.values()).map(({title}) => title));
		expect(Array.from(achievements)).toHaveLength(titles.size);
	});

	it('no isolated category exists', () => {
		const categories = countBy(Array.from(achievements.values()).map(({category}) => category));
		for (const count of Object.values(categories)) {
			expect(count).toBeGreaterThan(1);
		}
	});

	it('value is defined if counter is defined', () => {
		for (const achievement of achievements.values()) {
			if (achievement.counter !== undefined) {
				expect(achievement.value).toBeTruthy();
			}
		}
	});
});


text:
<partInstance>
<version>2.2</version>
<targetInstances>
<targetPart>
	<id>ORGATE</id>
	<type>chip-ORGATE</type>
	<is_root>true</is_root>
	<instance_name>ORGATE</instance_name>
	<position>-1</position>
	<parent>mrw-chip</parent>
	<parent_type>card-motherboard</parent_type>
	<parent_type>card-daughtercard</parent_type>
	<child_id>ORGATE.gpio-master-0</child_id>
	<child_id>ORGATE.gpio-slave-1</child_id>
	<child_id>ORGATE.gpio-slave-2</child_id>
	<attribute>
		<id>CHIP_ID</id>
		<default></default>
	</attribute>
	<attribute>
		<id>CLASS</id>
		<default>CHIP</default>
	</attribute>
	<attribute>
		<id>MODEL</id>
		<default></default>
	</attribute>
	<attribute>
		<id>MRU_ID</id>
		<default>0</default>
	</attribute>
	<attribute>
		<id>MRW_TYPE</id>
		<default>NA</default>
	</attribute>
	<attribute>
		<id>POSITION</id>
		<default></default>
	</attribute>
	<attribute>
		<id>RESOURCE_IS_CRITICAL</id>
		<default>0</default>
	</attribute>
	<attribute>
		<id>RU_TYPE</id>
		<default></default>
	</attribute>
	<attribute>
		<id>TYPE</id>
		<default></default>
	</attribute>
</targetPart>
<targetPart>
	<id>ORGATE.gpio-master-0</id>
	<type>unit-gpio-generic</type>
	<is_root>false</is_root>
	<instance_name>ORGATE.gpio-master-0</instance_name>
	<position>-1</position>
	<parent>mrw-unit</parent>
	<attribute>
		<id>BUS_TYPE</id>
		<default>GPIO</default>
	</attribute>
	<attribute>
		<id>CHIP_UNIT</id>
		<default>0</default>
	</attribute>
	<attribute>
		<id>CLASS</id>
		<default>UNIT</default>
	</attribute>
	<attribute>
		<id>DIRECTION</id>
		<default>OUT</default>
	</attribute>
	<attribute>
		<id>DRIVER_TYPE</id>
		<default>NA</default>
	</attribute>
	<attribute>
		<id>GPIO_TYPE</id>
		<default>GENERIC_OUTPUT</default>
	</attribute>
	<attribute>
		<id>MODEL</id>
		<default></default>
	</attribute>
	<attribute>
		<id>MRW_TYPE</id>
		<default>NA</default>
	</attribute>
	<attribute>
		<id>PIN_NAME</id>
		<default>
				<field><id>Value</id><value></value></field>
		</default>
	</attribute>
	<attribute>
		<id>PIN_NUM</id>
		<default></default>
	</attribute>
	<attribute>
		<id>POR_VALUE</id>
		<default>0</default>
	</attribute>
	<attribute>
		<id>RESOURCE_IS_CRITICAL</id>
		<default>0</default>
	</attribute>
	<attribute>
		<id>SCHEMATIC_INTERFACE</id>
		<default></default>
	</attribute>
	<attribute>
		<id>TYPE</id>
		<default>NA</default>
	</attribute>
</targetPart>
<targetPart>
	<id>ORGATE.gpio-slave-1</id>
	<type>unit-gpio-generic</type>
	<is_root>false</is_root>
	<instance_name>ORGATE.gpio-slave-1</instance_name>
	<position>-1</position>
	<parent>mrw-unit</parent>
	<attribute>
		<id>BUS_TYPE</id>
		<default>GPIO</default>
	</attribute>
	<attribute>
		<id>CHIP_UNIT</id>
		<default>0</default>
	</attribute>
	<attribute>
		<id>CLASS</id>
		<default>UNIT</default>
	</attribute>
	<attribute>
		<id>DIRECTION</id>
		<default>IN</default>
	</attribute>
	<attribute>
		<id>DRIVER_TYPE</id>
		<default>NA</default>
	</attribute>
	<attribute>
		<id>GPIO_TYPE</id>
		<default>GENERIC_INPUT</default>
	</attribute>
	<attribute>
		<id>MODEL</id>
		<default></default>
	</attribute>
	<attribute>
		<id>MRW_TYPE</id>
		<default>NA</default>
	</attribute>
	<attribute>
		<id>PIN_NAME</id>
		<default>
				<field><id>Value</id><value></value></field>
		</default>
	</attribute>
	<attribute>
		<id>PIN_NUM</id>
		<default></default>
	</attribute>
	<attribute>
		<id>POR_VALUE</id>
		<default>0</default>
	</attribute>
	<attribute>
		<id>RESOURCE_IS_CRITICAL</id>
		<default>0</default>
	</attribute>
	<attribute>
		<id>SCHEMATIC_INTERFACE</id>
		<default></default>
	</attribute>
	<attribute>
		<id>TYPE</id>
		<default>NA</default>
	</attribute>
</targetPart>
<targetPart>
	<id>ORGATE.gpio-slave-2</id>
	<type>unit-gpio-generic</type>
	<is_root>false</is_root>
	<instance_name>ORGATE.gpio-slave-2</instance_name>
	<position>-1</position>
	<parent>mrw-unit</parent>
	<attribute>
		<id>BUS_TYPE</id>
		<default>GPIO</default>
	</attribute>
	<attribute>
		<id>CHIP_UNIT</id>
		<default>0</default>
	</attribute>
	<attribute>
		<id>CLASS</id>
		<default>UNIT</default>
	</attribute>
	<attribute>
		<id>DIRECTION</id>
		<default>IN</default>
	</attribute>
	<attribute>
		<id>DRIVER_TYPE</id>
		<default>NA</default>
	</attribute>
	<attribute>
		<id>GPIO_TYPE</id>
		<default>GENERIC_INPUT</default>
	</attribute>
	<attribute>
		<id>MODEL</id>
		<default></default>
	</attribute>
	<attribute>
		<id>MRW_TYPE</id>
		<default>NA</default>
	</attribute>
	<attribute>
		<id>PIN_NAME</id>
		<default>
				<field><id>Value</id><value></value></field>
		</default>
	</attribute>
	<attribute>
		<id>PIN_NUM</id>
		<default></default>
	</attribute>
	<attribute>
		<id>POR_VALUE</id>
		<default>0</default>
	</attribute>
	<attribute>
		<id>RESOURCE_IS_CRITICAL</id>
		<default>0</default>
	</attribute>
	<attribute>
		<id>SCHEMATIC_INTERFACE</id>
		<default></default>
	</attribute>
	<attribute>
		<id>TYPE</id>
		<default>NA</default>
	</attribute>
</targetPart>
</targetInstances>
</partInstance>


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Spark.CSharp.Core;

namespace Microsoft.Spark.CSharp.Sql
{
    /// <summary>
    /// The entry point to programming Spark with the Dataset and DataFrame API.
    /// </summary>
    public class Builder
    {
        internal Dictionary<string, string> options = new Dictionary<string, string>();

        internal Builder() { }

        /// <summary>
        /// Sets the Spark master URL to connect to, such as "local" to run locally, "local[4]" to
        /// run locally with 4 cores, or "spark://master:7077" to run on a Spark standalone cluster.
        /// </summary>
        /// <param name="master">Master URL</param>
        public Builder Master(string master)
        {
            Config("spark.master", master);
            return this;
        }

        /// <summary>
        /// Sets a name for the application, which will be shown in the Spark web UI.
        /// If no application name is set, a randomly generated name will be used.
        /// </summary>
        /// <param name="appName">Name of the app</param>
        public Builder AppName(string appName)
        {
            Config("spark.app.name", appName);
            return this;
        }

        /// <summary>
        /// Sets a config option. Options set using this method are automatically propagated to
        /// both SparkConf and SparkSession's own configuration.
        /// </summary>
        /// <param name="key">Key for the configuration</param>
        /// <param name="value">value of the configuration</param>
        public Builder Config(string key, string value)
        {
            options[key] = value;
            return this;
        }

        /// <summary>
        /// Sets a config option. Options set using this method are automatically propagated to
        /// both SparkConf and SparkSession's own configuration.
        /// </summary>
        /// <param name="key">Key for the configuration</param>
        /// <param name="value">value of the configuration</param>
        public Builder Config(string key, bool value)
        {
            options[key] = value.ToString();
            return this;
        }

        /// <summary>
        /// Sets a config option. Options set using this method are automatically propagated to
        /// both SparkConf and SparkSession's own configuration.
        /// </summary>
        /// <param name="key">Key for the configuration</param>
        /// <param name="value">value of the configuration</param>
        public Builder Config(string key, double value)
        {
            options[key] = value.ToString();
            return this;
        }

        /// <summary>
        /// Sets a config option. Options set using this method are automatically propagated to
        /// both SparkConf and SparkSession's own configuration.
        /// </summary>
        /// <param name="key">Key for the configuration</param>
        /// <param name="value">value of the configuration</param>
        public Builder Config(string key, long value)
        {
            options[key] = value.ToString();
            return this;
        }

        /// <summary>
        /// Sets a list of config options based on the given SparkConf
        /// </summary>
        public Builder Config(SparkConf conf)
        {
            foreach (var keyValuePair in conf.GetAll())
            {
                options[keyValuePair.Key] = keyValuePair.Value;
            }

            return this;
        }

        /// <summary>
        /// Enables Hive support, including connectivity to a persistent Hive metastore, support for
        /// Hive serdes, and Hive user-defined functions.
        /// </summary>
        public Builder EnableHiveSupport()
        {
            return Config("spark.sql.catalogImplementation", "hive");
        }

        /// <summary>
        /// Gets an existing [[SparkSession]] or, if there is no existing one, creates a new
        /// one based on the options set in this builder.
        /// </summary>
        /// <returns></returns>
        public SparkSession GetOrCreate()
        {
            var sparkConf = new SparkConf();
            foreach (var option in options)
            {
                sparkConf.Set(option.Key, option.Value);
            }
            var sparkContext = SparkContext.GetOrCreate(sparkConf);
            return SqlContext.GetOrCreate(sparkContext).SparkSession;
        }
    }
}


text:
package hotpepper4s

/**
 * @author ponkotuy
 */
trait CodeName {
  import CodeName._
  def code: String
  def name: String
  def toCodeName: CodeNameImpl = CodeNameImpl(code, name)
  def toTuple: (String, String) = code -> name
}

object CodeName {
  def apply(code: String, name :String): CodeName = CodeNameImpl(code, name)
  case class CodeNameImpl(code: String, name: String) extends CodeName
}


text:
var transitionTest = (function() {

    // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
    var querystring = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i)
        {
            var p=a[i].split('=', 2);
            if (p.length == 1)
                b[p[0]] = "";
            else
                b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'));

    var inter, duration = +querystring.duration, pause = +querystring.pause;
    if(isNaN(duration)) duration = 3000;
    if(isNaN(pause)) pause = 500;
    function stop() {
        window.clearInterval(inter);
        inter = null;
    }
    function oscillate(f1, f2) {
        return function() {
            stop();
            var which = false;
            f1();
            dc.redrawAll();
            inter = window.setInterval(function() {
                if((which = !which))
                    f2();
                else
                    f1();
                dc.redrawAll();
            }, duration+pause);
        };
    }
    // generate continuous data
    function progression(N, initial) {
        var _steps = 5, // number of data points to add each tick
            _interval = 1, // distance in x between points
            _magnitude = 1, // maximum change in y per observation
            _reverse = false; // whether to regress instead of progress
        var _data = [];
        var rand = d3.random.normal();
        function startval() { // .fill() (when can we drop ie?)
            var a = new Array(N);
            for(var i = 0; i<N; ++i) {
                a[i] = _magnitude*2;
            }
            return a;
        }
        function drop() {
            _data.splice(_reverse ? _data.length-1 : 0, 1);
        }
        function generate() {
            var basis = _data.length ?
                    _data[_reverse ? 0 : _data.length-1] :
                {key: 0, value: startval()};
            var obs = [], key = basis.key + (_reverse ? -1 : 1) * _interval;
            for(var i = 0; i<N; ++i) {
                obs[i] = Math.max(basis.value[i] + rand() * _magnitude, 0);
            }
            var datum = {key: key, value: obs};
            if(_reverse)
                _data.unshift(datum);
            else
                _data.push(datum);
        }
        while(initial--) generate();
        return {
            steps: function(steps) {
                if(!arguments.length)
                    return _steps;
                _steps = steps;
                return this;
            },
            interval: function(interval) {
                if(!arguments.length)
                    return _interval;
                _interval = interval;
                return this;
            },
            magnitude: function(magnitude) {
                if(!arguments.length)
                    return _magnitude;
                _magnitude = magnitude;
                return this;
            },
            reverse: function(reverse) {
                if(!arguments.length)
                    return _reverse;
                _reverse = reverse;
                return this;
            },
            start: function() {
                stop();
                dc.redrawAll();
                inter = window.setInterval(function() {
                    for(var i = 0; i < _steps; ++i) {
                        generate();
                        drop();
                    }
                    dc.redrawAll();
                }, duration+pause);
            },
            data: function() {
                return _data;
            }
        };
    }
    return {
        querystring : querystring,
        duration: duration,
        pause: pause,
        stop: stop,
        oscillate: oscillate,
        progression: progression
    };
})();


text: payload.update({'updates': pkg_output})


text:
<!DOCTYPE html>

  <title>Lesson 10</title>
  <meta charset="utf-8">
  <meta name="description" content="Lesson 10">
  <meta name="author" content="Andrew Do">
  <meta name="generator" content="slidify" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta http-equiv="X-UA-Compatible" content="chrome=1">
  <link rel="stylesheet" href="libraries/frameworks/io2012/css/default.css" media="all" >
  <link rel="stylesheet" href="libraries/frameworks/io2012/css/phone.css"
    media="only screen and (max-device-width: 480px)" >
  <link rel="stylesheet" href="libraries/frameworks/io2012/css/slidify.css" >
  <link rel="stylesheet" href="libraries/highlighters/highlight.js/css/tomorrow.css" />
  <base target="_blank">   <link rel=stylesheet href="./assets/css/ribbons.css"></link>

  <slides class="layout-widescreen">

        <slide class="title-slide segue nobackground">
  <hgroup class="auto-fadein">

Lesson 10

Tidy Data

Andrew Do

  </hgroup>

</slide>

    <slide class="" id="slide-1" style="background:;">
  <hgroup>

Motivation

  </hgroup>

How many variables are represented in this table?  What are they?

</slide>

<slide class="" id="slide-2" style="background:;">
  <hgroup>

Motivation

  </hgroup>

In the language of data wrangling, we convert the table from wide format to long format.

</slide>

<slide class="" id="slide-3" style="background:;">
  <hgroup>

Tidy Data

  </hgroup>

A data set is said to be tidy if:

Observations or cases are in the rows

Variables are in the columns

Everything is contained in a single dataset

Messy data is any other arrangement of data.

Advantages of tidy data:

Standard structure allows for standard wrangling and analysis tools

Ordering often makes sense

Easy to read off individual cases/variables used

</slide>

<slide class="" id="slide-4" style="background:;">
  <hgroup>

Common Problems of Messy Data Sets

  </hgroup>

Column headers contain values instead of variable names

Multiple variables are stored in one column

Variables stored in both rows and columns

Multiple types of observational units stored in the same table

Single observational unit stored in multiple tables

</slide>

<slide class="" id="slide-5" style="background:;">
  <hgroup>

Tidying Verbs

  </hgroup>

Just like with wrangling, we can formalize a good amount of the most common tidying actions in a few verbs:

Tidying verb
Description

gather
Take columns and collapse into key-value pairs

spread
Take key-value pair and lay it over multiple columns

separate
Turn a single character column into multiple columns

unite
Turn multiple character columns into one

</slide>

<slide class="" id="slide-6" style="background:;">
  <hgroup>

Gather

  </hgroup>

Gathering the keys A and B into a single column called Treatment and their values into a column Blood_Pressure:

##   names   A   B
## 1  John 121 166
## 2  Mary 110 145
## 3   Sue 130 141

gather(data = df, key = Treatment, value = Blood_Pressure, A, B)

##   names Treatment Blood_Pressure
## 1  John         A            121
## 2  Mary         A            110
## 3   Sue         A            130
## 4  John         B            166
## 5  Mary         B            145
## 6   Sue         B            141

</slide>

<slide class="" id="slide-7" style="background:;">
  <hgroup>

Spread

  </hgroup>

Gathering the key-value pair Treatment and Blood_Pressure across multiple columns:

##   names Treatment Blood_Pressure
## 1  John         A            121
## 2  Mary         A            110
## 3   Sue         A            130
## 4  John         B            166
## 5  Mary         B            145
## 6   Sue         B            141

spread(data = df, key = Treatment, value = Blood_Pressure)

##   names   A   B
## 1  John 121 166
## 2  Mary 110 145
## 3   Sue 130 141

</slide>

<slide class="" id="slide-8" style="background:;">
  <hgroup>

Separate

  </hgroup>

Separating x into first and second, which were separated by "."

##      x y
## 1 <NA> 1
## 2  a.b 2
## 3  a.d 3
## 4  b.c 4

separate(data = df, col = x, into = c("first", "second"), sep = "\\.")

##   first second y
## 1  <NA>   <NA> 1
## 2     a      b 2
## 3     a      d 3
## 4     b      c 4

</slide>

<slide class="" id="slide-9" style="background:;">
  <hgroup>

Column headers contain values and not variables

  </hgroup>

Income distribution within US religious groups

Survey that examines relationship between income and religious affiliation

Collected by the Pew Forum on Religious and Public Life LINK

Data is in the data folder for lesson 10

library(readr)
df <- read_tsv("../data/pew.txt")

Discuss:

What are the variables in this table?

Is this data tidy? If not, which verb would you use to fix it?

</slide>

<slide class="" id="slide-10" style="background:;">
  <hgroup>

Fixing the data

  </hgroup>

Using gather from tidyr, we can fix this data.  Notice that the - means "don't gather this column".

longdf <- gather(df, key = income, value = n, -religion)
head(longdf, 5)

## Source: local data frame [5 x 3]
##
##             religion income     n
##                <chr>  <chr> <int>
## 1           Agnostic  <$10k    27
## 2            Atheist  <$10k    12
## 3           Buddhist  <$10k    27
## 4           Catholic  <$10k   418
## 5 Don<U+0092>t know/refused  <$10k    15

</slide>

<slide class="" id="slide-11" style="background:;">
  <hgroup>

Multiple Variables in One Column

  </hgroup>

WHO Tuberculosis study

df <- read_csv("../data/tb.csv") %>%
  select(-new_sp)
names(df) <- str_replace(names(df), "new_sp_", "")

Discuss

What are the variables in this study? Hint: f=female and 1524=15-24.

</slide>

<slide class="" id="slide-12" style="background:;">
  <hgroup>

You try it

  </hgroup>

Tidy up the WHO data set

Some things you might want to think about:

Gather the appropriate columns (gather)

Separate gender and age into two columns

Maybe modify the string so you can use separate

Change m and f to male and female (mutate)

Make age more readable, e.g. "04" should be "0-4" (mutate)

</slide>

<slide class="" id="slide-13" style="background:;">
  <hgroup>

You try it

  </hgroup>

age_ranges <- c("04" = "0-4", "514" = "5-14", "014" = "0-14",
                "1524" = "15-24", "2534" = "25-34", "3544" = "35-44",
                "4554" = "45-54", "5564" = "55-64", "65" = "65+",
                "u" = "unknown")
gender_values <- c("m" = "male", "f" = "female")

tidydf <- gather(df, gender, n, -iso2, -year) %>%
  separate(gender, c("gender", "age"), 1) %>%
  mutate(age = str_replace_all(age, age_ranges),
         gender = str_replace_all(gender, gender_values)) %>%
  na.omit

</slide>

<slide class="" id="slide-14" style="background:;">
  <hgroup>

Variables in Row Names and Columns

  </hgroup>

Weather data in Cuernavaca, Mexico in 2010

df <- read_tsv("../data/weather.txt")

Inspect the data:

What are the variables in this data set?

tmin = minimum temperature

id = weather station identifier

Is the data tidy? If not, then what needs to be done?

</slide>

<slide class="" id="slide-15" style="background:;">
  <hgroup>

Your turn

  </hgroup>

Tidy up the data.  Discuss with those around you to figure out what needs to be done.

</slide>

<slide class="" id="slide-16" style="background:;">
  <hgroup>

Possible tidying procedure

  </hgroup>

tidydf <- df %>%
  gather(day, temperature, -id, -year, -month, -element) %>%
  mutate(day = str_replace(day, "d", ""),
         element = str_to_lower(element)) %>%
  select(id, year, month, day, element, temperature) %>%
  mutate(day = as.integer(day),
         temperature = as.numeric(str_replace_all(temperature, "(.*)(.)$", "\\1\\.\\2"))) %>%
  na.omit

</slide>

<slide class="" id="slide-17" style="background:;">
  <hgroup>

Multiple Data Types in One Table

  </hgroup>

df <- read_csv("../data/billboard.csv")

Try it yourself without guidance

</slide>

<slide class="" id="slide-18" style="background:;">
  <hgroup>

Multiple Data Types in One Table

  </hgroup>

tidydf <- df %>%
  gather(Week, Rank, -year, -artist.inverted, -track, -time, -genre,
         -date.entered, - date.peaked)

Do you notice anything undesirable about this "tidy" form?

</slide>

<slide class="" id="slide-19" style="background:;">
  <hgroup>

Multiple Data Types in One Table

  </hgroup>

Each fact about a song is repeated many many times. Sign that multiple types of
experimental unit stored in the same table. We can store our data more efficiently by separating it into different tables for each type of unit.

Need to separate out into song and rank tables.

</slide>

<slide class="" id="slide-20" style="background:;">
  <hgroup>

Multiple Data Types in One Table

  </hgroup>

Rankings <- tidydf %>%
  select(-Week, -Rank, -date.entered, -date.peaked) %>%
  unique %>%
  mutate(Song_ID = row_number())

</slide>

<slide class="" id="slide-21" style="background:;">
  <hgroup>

One Data Type in Multiple Tables

  </hgroup>

You'll see an example of this in the last problem of the homework.

Further reading

For a complete discussion on tidy data, please read the following paper:

Tidy Data by Hadley Wickham

</slide>

    <slide class="backdrop"></slide>
  </slides>

         1

         2

         3

         4

         5

         6

         7

         8

         9

         10

         11

         12

         13

         14

         15

         16

         17

         18

         19

         20

         21


text:
export const toggleCompleted = todo =>
  ({...todo, completed: !todo.completed})

export const create = (id, text) => ({
  id,
  text,
  completed: false
})

export default {toggleCompleted, create}


text:
// AUTO-GENERATED: do not modify this file directly.
// If you need to make changes, modify generate-fp.ts (if necessary), then open a terminal in types/lodash/scripts, and do:
// npm run fp

import _ = require("../index");

interface IndexOf {
    /**
     * Gets the index at which the first occurrence of `value` is found in `array`
     * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
     * for equality comparisons. If `fromIndex` is negative, it's used as the offset
     * from the end of `array`.
     *
     * @category Array
     * @param array The array to search.
     * @param value The value to search for.
     * @param [fromIndex=0] The index to search from.
     * @returns Returns the index of the matched value, else `-1`.
     * @example
     *
     * _.indexOf([1, 2, 1, 2], 2);
     * // => 1
     *
     * // using `fromIndex`
     * _.indexOf([1, 2, 1, 2], 2, 2);
     * // => 3
     */
    (): IndexOf;
    /**
     * Gets the index at which the first occurrence of `value` is found in `array`
     * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
     * for equality comparisons. If `fromIndex` is negative, it's used as the offset
     * from the end of `array`.
     *
     * @category Array
     * @param array The array to search.
     * @param value The value to search for.
     * @param [fromIndex=0] The index to search from.
     * @returns Returns the index of the matched value, else `-1`.
     * @example
     *
     * _.indexOf([1, 2, 1, 2], 2);
     * // => 1
     *
     * // using `fromIndex`
     * _.indexOf([1, 2, 1, 2], 2, 2);
     * // => 3
     */
    <T>(value: T): IndexOf1x1<T>;
    /**
     * Gets the index at which the first occurrence of `value` is found in `array`
     * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
     * for equality comparisons. If `fromIndex` is negative, it's used as the offset
     * from the end of `array`.
     *
     * @category Array
     * @param array The array to search.
     * @param value The value to search for.
     * @param [fromIndex=0] The index to search from.
     * @returns Returns the index of the matched value, else `-1`.
     * @example
     *
     * _.indexOf([1, 2, 1, 2], 2);
     * // => 1
     *
     * // using `fromIndex`
     * _.indexOf([1, 2, 1, 2], 2, 2);
     * // => 3
     */
    <T>(value: T, array: _.List<T> | null | undefined): number;
}
interface IndexOf1x1<T> {
    /**
     * Gets the index at which the first occurrence of `value` is found in `array`
     * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
     * for equality comparisons. If `fromIndex` is negative, it's used as the offset
     * from the end of `array`.
     *
     * @category Array
     * @param array The array to search.
     * @param value The value to search for.
     * @param [fromIndex=0] The index to search from.
     * @returns Returns the index of the matched value, else `-1`.
     * @example
     *
     * _.indexOf([1, 2, 1, 2], 2);
     * // => 1
     *
     * // using `fromIndex`
     * _.indexOf([1, 2, 1, 2], 2, 2);
     * // => 3
     */
    (): IndexOf1x1<T>;
    /**
     * Gets the index at which the first occurrence of `value` is found in `array`
     * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
     * for equality comparisons. If `fromIndex` is negative, it's used as the offset
     * from the end of `array`.
     *
     * @category Array
     * @param array The array to search.
     * @param value The value to search for.
     * @param [fromIndex=0] The index to search from.
     * @returns Returns the index of the matched value, else `-1`.
     * @example
     *
     * _.indexOf([1, 2, 1, 2], 2);
     * // => 1
     *
     * // using `fromIndex`
     * _.indexOf([1, 2, 1, 2], 2, 2);
     * // => 3
     */
    (array: _.List<T> | null | undefined): number;
}

declare const indexOf: IndexOf;
export = indexOf;


text:
FROM centos:centos6
RUN curl -sL https://rpm.nodesource.com/setup | bash -
RUN yum install -y nodejs  #
# Define working directory.
COPY ./ /src/
WORKDIR /src

RUN npm install
RUN npm run build

EXPOSE 3000 8020
# Define default command.
CMD ["node", "app.js"]


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

namespace KMCellCount
{
    class GlobalVar
    {
        private static string someString = "Hello, world!";
        public static string SomeString
        {
            get { return someString; }
            set { someString = value; }
        }
    }
}


text:
FROM birkhofflee/coffeeforever:node-0.10

MAINTAINER Birkhoff Lee <admin@birkhoff.me>

EXPOSE 1827

RUN /build.sh BirkhoffLee jumper
CMD [ "/run.sh" ]


text:
#include <linux/types.h>
#include <linux/termios.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/tty.h>
#include <linux/fcntl.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/bitops.h>
#include <linux/mutex.h>

#include <asm/io.h>
#include <asm/uaccess.h>
#include <asm/system.h>

#undef TTY_DEBUG_WAIT_UNTIL_SENT

#undef	DEBUG

/*
 * Internal flag options for termios setting behavior
 */
#define TERMIOS_FLUSH	1
#define TERMIOS_WAIT	2
#define TERMIOS_TERMIO	4
#define TERMIOS_OLD	8

/**
 *	tty_chars_in_buffer	-	characters pending
 *	@tty: terminal
 *
 *	Return the number of bytes of data in the device private
 *	output queue. If no private method is supplied there is assumed
 *	to be no queue on the device.
 */

int tty_chars_in_buffer(struct tty_struct *tty)
{
	if (tty->ops->chars_in_buffer)
		return tty->ops->chars_in_buffer(tty);
	else
		return 0;
}
EXPORT_SYMBOL(tty_chars_in_buffer);

/**
 *	tty_write_room		-	write queue space
 *	@tty: terminal
 *
 *	Return the number of bytes that can be queued to this device
 *	at the present time. The result should be treated as a guarantee
 *	and the driver cannot offer a value it later shrinks by more than
 *	the number of bytes written. If no method is provided 2K is always
 *	returned and data may be lost as there will be no flow control.
 */

int tty_write_room(struct tty_struct *tty)
{
	if (tty->ops->write_room)
		return tty->ops->write_room(tty);
	return 2048;
}
EXPORT_SYMBOL(tty_write_room);

/**
 *	tty_driver_flush_buffer	-	discard internal buffer
 *	@tty: terminal
 *
 *	Discard the internal output buffer for this device. If no method
 *	is provided then either the buffer cannot be hardware flushed or
 *	there is no buffer driver side.
 */
void tty_driver_flush_buffer(struct tty_struct *tty)
{
	if (tty->ops->flush_buffer)
		tty->ops->flush_buffer(tty);
}
EXPORT_SYMBOL(tty_driver_flush_buffer);

/**
 *	tty_throttle		-	flow control
 *	@tty: terminal
 *
 *	Indicate that a tty should stop transmitting data down the stack.
 *	Takes the termios mutex to protect against parallel throttle/unthrottle
 *	and also to ensure the driver can consistently reference its own
 *	termios data at this point when implementing software flow control.
 */

void tty_throttle(struct tty_struct *tty)
{
	mutex_lock(&tty->termios_mutex);
	/* check TTY_THROTTLED first so it indicates our state */
	if (!test_and_set_bit(TTY_THROTTLED, &tty->flags) &&
	    tty->ops->throttle)
		tty->ops->throttle(tty);
	mutex_unlock(&tty->termios_mutex);
}
EXPORT_SYMBOL(tty_throttle);

/**
 *	tty_unthrottle		-	flow control
 *	@tty: terminal
 *
 *	Indicate that a tty may continue transmitting data down the stack.
 *	Takes the termios mutex to protect against parallel throttle/unthrottle
 *	and also to ensure the driver can consistently reference its own
 *	termios data at this point when implementing software flow control.
 *
 *	Drivers should however remember that the stack can issue a throttle,
 *	then change flow control method, then unthrottle.
 */

void tty_unthrottle(struct tty_struct *tty)
{
	mutex_lock(&tty->termios_mutex);
	if (test_and_clear_bit(TTY_THROTTLED, &tty->flags) &&
	    tty->ops->unthrottle)
		tty->ops->unthrottle(tty);
	mutex_unlock(&tty->termios_mutex);
}
EXPORT_SYMBOL(tty_unthrottle);

/**
 *	tty_wait_until_sent	-	wait for I/O to finish
 *	@tty: tty we are waiting for
 *	@timeout: how long we will wait
 *
 *	Wait for characters pending in a tty driver to hit the wire, or
 *	for a timeout to occur (eg due to flow control)
 *
 *	Locking: none
 */

void tty_wait_until_sent(struct tty_struct *tty, long timeout)
{
#ifdef TTY_DEBUG_WAIT_UNTIL_SENT
	char buf[64];

	printk(KERN_DEBUG "%s wait until sent...\n", tty_name(tty, buf));
#endif
	if (!timeout)
		timeout = MAX_SCHEDULE_TIMEOUT;
	if (wait_event_interruptible_timeout(tty->write_wait,
			!tty_chars_in_buffer(tty), timeout) >= 0) {
		if (tty->ops->wait_until_sent)
			tty->ops->wait_until_sent(tty, timeout);
	}
}
EXPORT_SYMBOL(tty_wait_until_sent);

/*
 *		Termios Helper Methods
 */

static void unset_locked_termios(struct ktermios *termios,
				 struct ktermios *old,
				 struct ktermios *locked)
{
	int	i;

#define NOSET_MASK(x, y, z) (x = ((x) & ~(z)) | ((y) & (z)))

	if (!locked) {
		printk(KERN_WARNING "Warning?!? termios_locked is NULL.\n");
		return;
	}

	NOSET_MASK(termios->c_iflag, old->c_iflag, locked->c_iflag);
	NOSET_MASK(termios->c_oflag, old->c_oflag, locked->c_oflag);
	NOSET_MASK(termios->c_cflag, old->c_cflag, locked->c_cflag);
	NOSET_MASK(termios->c_lflag, old->c_lflag, locked->c_lflag);
	termios->c_line = locked->c_line ? old->c_line : termios->c_line;
	for (i = 0; i < NCCS; i++)
		termios->c_cc[i] = locked->c_cc[i] ?
			old->c_cc[i] : termios->c_cc[i];
	/* FIXME: What should we do for i/ospeed */
}

/*
 * Routine which returns the baud rate of the tty
 *
 * Note that the baud_table needs to be kept in sync with the
 * include/asm/termbits.h file.
 */
static const speed_t baud_table[] = {
	0, 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
	9600, 19200, 38400, 57600, 115200, 230400, 460800,
#ifdef __sparc__
	76800, 153600, 307200, 614400, 921600
#else
	500000, 576000, 921600, 1000000, 1152000, 1500000, 2000000,
	2500000, 3000000, 3500000, 4000000
#endif
};

#ifndef __sparc__
static const tcflag_t baud_bits[] = {
	B0, B50, B75, B110, B134, B150, B200, B300, B600,
	B1200, B1800, B2400, B4800, B9600, B19200, B38400,
	B57600, B115200, B230400, B460800, B500000, B576000,
	B921600, B1000000, B1152000, B1500000, B2000000, B2500000,
	B3000000, B3500000, B4000000
};
#else
static const tcflag_t baud_bits[] = {
	B0, B50, B75, B110, B134, B150, B200, B300, B600,
	B1200, B1800, B2400, B4800, B9600, B19200, B38400,
	B57600, B115200, B230400, B460800, B76800, B153600,
	B307200, B614400, B921600
};
#endif

static int n_baud_table = ARRAY_SIZE(baud_table);

/**
 *	tty_termios_baud_rate
 *	@termios: termios structure
 *
 *	Convert termios baud rate data into a speed. This should be called
 *	with the termios lock held if this termios is a terminal termios
 *	structure. May change the termios data. Device drivers can call this
 *	function but should use ->c_[io]speed directly as they are updated.
 *
 *	Locking: none
 */

speed_t tty_termios_baud_rate(struct ktermios *termios)
{
	unsigned int cbaud;

	cbaud = termios->c_cflag & CBAUD;

#ifdef BOTHER
	/* Magic token for arbitrary speed via c_ispeed/c_ospeed */
	if (cbaud == BOTHER)
		return termios->c_ospeed;
#endif
	if (cbaud & CBAUDEX) {
		cbaud &= ~CBAUDEX;

		if (cbaud < 1 || cbaud + 15 > n_baud_table)
			termios->c_cflag &= ~CBAUDEX;
		else
			cbaud += 15;
	}
	return baud_table[cbaud];
}
EXPORT_SYMBOL(tty_termios_baud_rate);

/**
 *	tty_termios_input_baud_rate
 *	@termios: termios structure
 *
 *	Convert termios baud rate data into a speed. This should be called
 *	with the termios lock held if this termios is a terminal termios
 *	structure. May change the termios data. Device drivers can call this
 *	function but should use ->c_[io]speed directly as they are updated.
 *
 *	Locking: none
 */

speed_t tty_termios_input_baud_rate(struct ktermios *termios)
{
#ifdef IBSHIFT
	unsigned int cbaud = (termios->c_cflag >> IBSHIFT) & CBAUD;

	if (cbaud == B0)
		return tty_termios_baud_rate(termios);

	/* Magic token for arbitrary speed via c_ispeed*/
	if (cbaud == BOTHER)
		return termios->c_ispeed;

	if (cbaud & CBAUDEX) {
		cbaud &= ~CBAUDEX;

		if (cbaud < 1 || cbaud + 15 > n_baud_table)
			termios->c_cflag &= ~(CBAUDEX << IBSHIFT);
		else
			cbaud += 15;
	}
	return baud_table[cbaud];
#else
	return tty_termios_baud_rate(termios);
#endif
}
EXPORT_SYMBOL(tty_termios_input_baud_rate);

/**
 *	tty_termios_encode_baud_rate
 *	@termios: ktermios structure holding user requested state
 *	@ispeed: input speed
 *	@ospeed: output speed
 *
 *	Encode the speeds set into the passed termios structure. This is
 *	used as a library helper for drivers so that they can report back
 *	the actual speed selected when it differs from the speed requested
 *
 *	For maximal back compatibility with legacy SYS5/POSIX *nix behaviour
 *	we need to carefully set the bits when the user does not get the
 *	desired speed. We allow small margins and preserve as much of possible
 *	of the input intent to keep compatibility.
 *
 *	Locking: Caller should hold termios lock. This is already held
 *	when calling this function from the driver termios handler.
 *
 *	The ifdefs deal with platforms whose owners have yet to update them
 *	and will all go away once this is done.
 */

void tty_termios_encode_baud_rate(struct ktermios *termios,
				  speed_t ibaud, speed_t obaud)
{
	int i = 0;
	int ifound = -1, ofound = -1;
	int iclose = ibaud/50, oclose = obaud/50;
	int ibinput = 0;

	if (obaud == 0)			/* CD dropped 		  */
		ibaud = 0;		/* Clear ibaud to be sure */

	termios->c_ispeed = ibaud;
	termios->c_ospeed = obaud;

#ifdef BOTHER
	/* If the user asked for a precise weird speed give a precise weird
	   answer. If they asked for a Bfoo speed they many have problems
	   digesting non-exact replies so fuzz a bit */

	if ((termios->c_cflag & CBAUD) == BOTHER)
		oclose = 0;
	if (((termios->c_cflag >> IBSHIFT) & CBAUD) == BOTHER)
		iclose = 0;
	if ((termios->c_cflag >> IBSHIFT) & CBAUD)
		ibinput = 1;	/* An input speed was specified */
#endif
	termios->c_cflag &= ~CBAUD;

	/*
	 *	Our goal is to find a close match to the standard baud rate
	 *	returned. Walk the baud rate table and if we get a very close
	 *	match then report back the speed as a POSIX Bxxxx value by
	 *	preference
	 */

	do {
		if (obaud - oclose <= baud_table[i] &&
		    obaud + oclose >= baud_table[i]) {
			termios->c_cflag |= baud_bits[i];
			ofound = i;
		}
		if (ibaud - iclose <= baud_table[i] &&
		    ibaud + iclose >= baud_table[i]) {
			/* For the case input == output don't set IBAUD bits
			   if the user didn't do so */
			if (ofound == i && !ibinput)
				ifound  = i;
#ifdef IBSHIFT
			else {
				ifound = i;
				termios->c_cflag |= (baud_bits[i] << IBSHIFT);
			}
#endif
		}
	} while (++i < n_baud_table);

	/*
	 *	If we found no match then use BOTHER if provided or warn
	 *	the user their platform maintainer needs to wake up if not.
	 */
#ifdef BOTHER
	if (ofound == -1)
		termios->c_cflag |= BOTHER;
	/* Set exact input bits only if the input and output differ or the
	   user already did */
	if (ifound == -1 && (ibaud != obaud || ibinput))
		termios->c_cflag |= (BOTHER << IBSHIFT);
#else
	if (ifound == -1 || ofound == -1) {
		printk_once(KERN_WARNING "tty: Unable to return correct "
			  "speed data as your architecture needs updating.\n");
	}
#endif
}
EXPORT_SYMBOL_GPL(tty_termios_encode_baud_rate);

/**
 *	tty_encode_baud_rate		-	set baud rate of the tty
 *	@ibaud: input baud rate
 *	@obad: output baud rate
 *
 *	Update the current termios data for the tty with the new speed
 *	settings. The caller must hold the termios_mutex for the tty in
 *	question.
 */

void tty_encode_baud_rate(struct tty_struct *tty, speed_t ibaud, speed_t obaud)
{
	tty_termios_encode_baud_rate(tty->termios, ibaud, obaud);
}
EXPORT_SYMBOL_GPL(tty_encode_baud_rate);

/**
 *	tty_get_baud_rate	-	get tty bit rates
 *	@tty: tty to query
 *
 *	Returns the baud rate as an integer for this terminal. The
 *	termios lock must be held by the caller and the terminal bit
 *	flags may be updated.
 *
 *	Locking: none
 */

speed_t tty_get_baud_rate(struct tty_struct *tty)
{
	speed_t baud = tty_termios_baud_rate(tty->termios);

	if (baud == 38400 && tty->alt_speed) {
		if (!tty->warned) {
			printk(KERN_WARNING "Use of setserial/setrocket to "
					    "set SPD_* flags is deprecated\n");
			tty->warned = 1;
		}
		baud = tty->alt_speed;
	}

	return baud;
}
EXPORT_SYMBOL(tty_get_baud_rate);

/**
 *	tty_termios_copy_hw	-	copy hardware settings
 *	@new: New termios
 *	@old: Old termios
 *
 *	Propagate the hardware specific terminal setting bits from
 *	the old termios structure to the new one. This is used in cases
 *	where the hardware does not support reconfiguration or as a helper
 *	in some cases where only minimal reconfiguration is supported
 */

void tty_termios_copy_hw(struct ktermios *new, struct ktermios *old)
{
	/* The bits a dumb device handles in software. Smart devices need
	   to always provide a set_termios method */
	new->c_cflag &= HUPCL | CREAD | CLOCAL;
	new->c_cflag |= old->c_cflag & ~(HUPCL | CREAD | CLOCAL);
	new->c_ispeed = old->c_ispeed;
	new->c_ospeed = old->c_ospeed;
}
EXPORT_SYMBOL(tty_termios_copy_hw);

/**
 *	tty_termios_hw_change	-	check for setting change
 *	@a: termios
 *	@b: termios to compare
 *
 *	Check if any of the bits that affect a dumb device have changed
 *	between the two termios structures, or a speed change is needed.
 */

int tty_termios_hw_change(struct ktermios *a, struct ktermios *b)
{
	if (a->c_ispeed != b->c_ispeed || a->c_ospeed != b->c_ospeed)
		return 1;
	if ((a->c_cflag ^ b->c_cflag) & ~(HUPCL | CREAD | CLOCAL))
		return 1;
	return 0;
}
EXPORT_SYMBOL(tty_termios_hw_change);

/**
 *	tty_set_termios		-	update termios values
 *	@tty: tty to update
 *	@new_termios: desired new value
 *
 *	Perform updates to the termios values set on this terminal. There
 *	is a bit of layering violation here with n_tty in terms of the
 *	internal knowledge of this function.
 *
 *	Locking: termios_mutex
 */

int tty_set_termios(struct tty_struct *tty, struct ktermios *new_termios)
{
	struct ktermios old_termios;
	struct tty_ldisc *ld;
	unsigned long flags;

	/*
	 *	Perform the actual termios internal changes under lock.
	 */

	/* FIXME: we need to decide on some locking/ordering semantics
	   for the set_termios notification eventually */
	mutex_lock(&tty->termios_mutex);
	old_termios = *tty->termios;
	*tty->termios = *new_termios;
	unset_locked_termios(tty->termios, &old_termios, tty->termios_locked);

	/* See if packet mode change of state. */
	if (tty->link && tty->link->packet) {
		int extproc = (old_termios.c_lflag & EXTPROC) |
				(tty->termios->c_lflag & EXTPROC);
		int old_flow = ((old_termios.c_iflag & IXON) &&
				(old_termios.c_cc[VSTOP] == '\023') &&
				(old_termios.c_cc[VSTART] == '\021'));
		int new_flow = (I_IXON(tty) &&
				STOP_CHAR(tty) == '\023' &&
				START_CHAR(tty) == '\021');
		if ((old_flow != new_flow) || extproc) {
			spin_lock_irqsave(&tty->ctrl_lock, flags);
			if (old_flow != new_flow) {
				tty->ctrl_status &= ~(TIOCPKT_DOSTOP | TIOCPKT_NOSTOP);
				if (new_flow)
					tty->ctrl_status |= TIOCPKT_DOSTOP;
				else
					tty->ctrl_status |= TIOCPKT_NOSTOP;
			}
			if (extproc)
				tty->ctrl_status |= TIOCPKT_IOCTL;
			spin_unlock_irqrestore(&tty->ctrl_lock, flags);
			wake_up_interruptible(&tty->link->read_wait);
		}
	}

	if (tty->ops->set_termios)
		(*tty->ops->set_termios)(tty, &old_termios);
	else
		tty_termios_copy_hw(tty->termios, &old_termios);

	ld = tty_ldisc_ref(tty);
	if (ld != NULL) {
		if (ld->ops->set_termios)
			(ld->ops->set_termios)(tty, &old_termios);
		tty_ldisc_deref(ld);
	}
	mutex_unlock(&tty->termios_mutex);
	return 0;
}
EXPORT_SYMBOL_GPL(tty_set_termios);

/**
 *	set_termios		-	set termios values for a tty
 *	@tty: terminal device
 *	@arg: user data
 *	@opt: option information
 *
 *	Helper function to prepare termios data and run necessary other
 *	functions before using tty_set_termios to do the actual changes.
 *
 *	Locking:
 *		Called functions take ldisc and termios_mutex locks
 */

static int set_termios(struct tty_struct *tty, void __user *arg, int opt)
{
	struct ktermios tmp_termios;
	struct tty_ldisc *ld;
	int retval = tty_check_change(tty);

	if (retval)
		return retval;

	mutex_lock(&tty->termios_mutex);
	memcpy(&tmp_termios, tty->termios, sizeof(struct ktermios));
	mutex_unlock(&tty->termios_mutex);

	if (opt & TERMIOS_TERMIO) {
		if (user_termio_to_kernel_termios(&tmp_termios,
						(struct termio __user *)arg))
			return -EFAULT;
#ifdef TCGETS2
	} else if (opt & TERMIOS_OLD) {
		if (user_termios_to_kernel_termios_1(&tmp_termios,
						(struct termios __user *)arg))
			return -EFAULT;
	} else {
		if (user_termios_to_kernel_termios(&tmp_termios,
						(struct termios2 __user *)arg))
			return -EFAULT;
	}
#else
	} else if (user_termios_to_kernel_termios(&tmp_termios,
					(struct termios __user *)arg))
		return -EFAULT;
#endif

	/* If old style Bfoo values are used then load c_ispeed/c_ospeed
	 * with the real speed so its unconditionally usable */
	tmp_termios.c_ispeed = tty_termios_input_baud_rate(&tmp_termios);
	tmp_termios.c_ospeed = tty_termios_baud_rate(&tmp_termios);

	ld = tty_ldisc_ref(tty);

	if (ld != NULL) {
		if ((opt & TERMIOS_FLUSH) && ld->ops->flush_buffer)
			ld->ops->flush_buffer(tty);
		tty_ldisc_deref(ld);
	}

	if (opt & TERMIOS_WAIT) {
		tty_wait_until_sent(tty, 0);
		if (signal_pending(current))
			return -EINTR;
	}

	tty_set_termios(tty, &tmp_termios);

	/* FIXME: Arguably if tmp_termios == tty->termios AND the
	   actual requested termios was not tmp_termios then we may
	   want to return an error as no user requested change has
	   succeeded */
	return 0;
}

static void copy_termios(struct tty_struct *tty, struct ktermios *kterm)
{
	mutex_lock(&tty->termios_mutex);
	memcpy(kterm, tty->termios, sizeof(struct ktermios));
	mutex_unlock(&tty->termios_mutex);
}

static void copy_termios_locked(struct tty_struct *tty, struct ktermios *kterm)
{
	mutex_lock(&tty->termios_mutex);
	memcpy(kterm, tty->termios_locked, sizeof(struct ktermios));
	mutex_unlock(&tty->termios_mutex);
}

static int get_termio(struct tty_struct *tty, struct termio __user *termio)
{
	struct ktermios kterm;
	copy_termios(tty, &kterm);
	if (kernel_termios_to_user_termio(termio, &kterm))
		return -EFAULT;
	return 0;
}

#ifdef TCGETX

/**
 *	set_termiox	-	set termiox fields if possible
 *	@tty: terminal
 *	@arg: termiox structure from user
 *	@opt: option flags for ioctl type
 *
 *	Implement the device calling points for the SYS5 termiox ioctl
 *	interface in Linux
 */

static int set_termiox(struct tty_struct *tty, void __user *arg, int opt)
{
	struct termiox tnew;
	struct tty_ldisc *ld;

	if (tty->termiox == NULL)
		return -EINVAL;
	if (copy_from_user(&tnew, arg, sizeof(struct termiox)))
		return -EFAULT;

	ld = tty_ldisc_ref(tty);
	if (ld != NULL) {
		if ((opt & TERMIOS_FLUSH) && ld->ops->flush_buffer)
			ld->ops->flush_buffer(tty);
		tty_ldisc_deref(ld);
	}
	if (opt & TERMIOS_WAIT) {
		tty_wait_until_sent(tty, 0);
		if (signal_pending(current))
			return -EINTR;
	}

	mutex_lock(&tty->termios_mutex);
	if (tty->ops->set_termiox)
		tty->ops->set_termiox(tty, &tnew);
	mutex_unlock(&tty->termios_mutex);
	return 0;
}

#endif

#ifdef TIOCGETP
/*
 * These are deprecated, but there is limited support..
 *
 * The "sg_flags" translation is a joke..
 */
static int get_sgflags(struct tty_struct *tty)
{
	int flags = 0;

	if (!(tty->termios->c_lflag & ICANON)) {
		if (tty->termios->c_lflag & ISIG)
			flags |= 0x02;		/* cbreak */
		else
			flags |= 0x20;		/* raw */
	}
	if (tty->termios->c_lflag & ECHO)
		flags |= 0x08;			/* echo */
	if (tty->termios->c_oflag & OPOST)
		if (tty->termios->c_oflag & ONLCR)
			flags |= 0x10;		/* crmod */
	return flags;
}

static int get_sgttyb(struct tty_struct *tty, struct sgttyb __user *sgttyb)
{
	struct sgttyb tmp;

	mutex_lock(&tty->termios_mutex);
	tmp.sg_ispeed = tty->termios->c_ispeed;
	tmp.sg_ospeed = tty->termios->c_ospeed;
	tmp.sg_erase = tty->termios->c_cc[VERASE];
	tmp.sg_kill = tty->termios->c_cc[VKILL];
	tmp.sg_flags = get_sgflags(tty);
	mutex_unlock(&tty->termios_mutex);

	return copy_to_user(sgttyb, &tmp, sizeof(tmp)) ? -EFAULT : 0;
}

static void set_sgflags(struct ktermios *termios, int flags)
{
	termios->c_iflag = ICRNL | IXON;
	termios->c_oflag = 0;
	termios->c_lflag = ISIG | ICANON;
	if (flags & 0x02) {	/* cbreak */
		termios->c_iflag = 0;
		termios->c_lflag &= ~ICANON;
	}
	if (flags & 0x08) {		/* echo */
		termios->c_lflag |= ECHO | ECHOE | ECHOK |
				    ECHOCTL | ECHOKE | IEXTEN;
	}
	if (flags & 0x10) {		/* crmod */
		termios->c_oflag |= OPOST | ONLCR;
	}
	if (flags & 0x20) {	/* raw */
		termios->c_iflag = 0;
		termios->c_lflag &= ~(ISIG | ICANON);
	}
	if (!(termios->c_lflag & ICANON)) {
		termios->c_cc[VMIN] = 1;
		termios->c_cc[VTIME] = 0;
	}
}

/**
 *	set_sgttyb		-	set legacy terminal values
 *	@tty: tty structure
 *	@sgttyb: pointer to old style terminal structure
 *
 *	Updates a terminal from the legacy BSD style terminal information
 *	structure.
 *
 *	Locking: termios_mutex
 */

static int set_sgttyb(struct tty_struct *tty, struct sgttyb __user *sgttyb)
{
	int retval;
	struct sgttyb tmp;
	struct ktermios termios;

	retval = tty_check_change(tty);
	if (retval)
		return retval;

	if (copy_from_user(&tmp, sgttyb, sizeof(tmp)))
		return -EFAULT;

	mutex_lock(&tty->termios_mutex);
	termios = *tty->termios;
	termios.c_cc[VERASE] = tmp.sg_erase;
	termios.c_cc[VKILL] = tmp.sg_kill;
	set_sgflags(&termios, tmp.sg_flags);
	/* Try and encode into Bfoo format */
#ifdef BOTHER
	tty_termios_encode_baud_rate(&termios, termios.c_ispeed,
						termios.c_ospeed);
#endif
	mutex_unlock(&tty->termios_mutex);
	tty_set_termios(tty, &termios);
	return 0;
}
#endif

#ifdef TIOCGETC
static int get_tchars(struct tty_struct *tty, struct tchars __user *tchars)
{
	struct tchars tmp;

	mutex_lock(&tty->termios_mutex);
	tmp.t_intrc = tty->termios->c_cc[VINTR];
	tmp.t_quitc = tty->termios->c_cc[VQUIT];
	tmp.t_startc = tty->termios->c_cc[VSTART];
	tmp.t_stopc = tty->termios->c_cc[VSTOP];
	tmp.t_eofc = tty->termios->c_cc[VEOF];
	tmp.t_brkc = tty->termios->c_cc[VEOL2];	/* what is brkc anyway? */
	mutex_unlock(&tty->termios_mutex);
	return copy_to_user(tchars, &tmp, sizeof(tmp)) ? -EFAULT : 0;
}

static int set_tchars(struct tty_struct *tty, struct tchars __user *tchars)
{
	struct tchars tmp;

	if (copy_from_user(&tmp, tchars, sizeof(tmp)))
		return -EFAULT;
	mutex_lock(&tty->termios_mutex);
	tty->termios->c_cc[VINTR] = tmp.t_intrc;
	tty->termios->c_cc[VQUIT] = tmp.t_quitc;
	tty->termios->c_cc[VSTART] = tmp.t_startc;
	tty->termios->c_cc[VSTOP] = tmp.t_stopc;
	tty->termios->c_cc[VEOF] = tmp.t_eofc;
	tty->termios->c_cc[VEOL2] = tmp.t_brkc;	/* what is brkc anyway? */
	mutex_unlock(&tty->termios_mutex);
	return 0;
}
#endif

#ifdef TIOCGLTC
static int get_ltchars(struct tty_struct *tty, struct ltchars __user *ltchars)
{
	struct ltchars tmp;

	mutex_lock(&tty->termios_mutex);
	tmp.t_suspc = tty->termios->c_cc[VSUSP];
	/* what is dsuspc anyway? */
	tmp.t_dsuspc = tty->termios->c_cc[VSUSP];
	tmp.t_rprntc = tty->termios->c_cc[VREPRINT];
	/* what is flushc anyway? */
	tmp.t_flushc = tty->termios->c_cc[VEOL2];
	tmp.t_werasc = tty->termios->c_cc[VWERASE];
	tmp.t_lnextc = tty->termios->c_cc[VLNEXT];
	mutex_unlock(&tty->termios_mutex);
	return copy_to_user(ltchars, &tmp, sizeof(tmp)) ? -EFAULT : 0;
}

static int set_ltchars(struct tty_struct *tty, struct ltchars __user *ltchars)
{
	struct ltchars tmp;

	if (copy_from_user(&tmp, ltchars, sizeof(tmp)))
		return -EFAULT;

	mutex_lock(&tty->termios_mutex);
	tty->termios->c_cc[VSUSP] = tmp.t_suspc;
	/* what is dsuspc anyway? */
	tty->termios->c_cc[VEOL2] = tmp.t_dsuspc;
	tty->termios->c_cc[VREPRINT] = tmp.t_rprntc;
	/* what is flushc anyway? */
	tty->termios->c_cc[VEOL2] = tmp.t_flushc;
	tty->termios->c_cc[VWERASE] = tmp.t_werasc;
	tty->termios->c_cc[VLNEXT] = tmp.t_lnextc;
	mutex_unlock(&tty->termios_mutex);
	return 0;
}
#endif

/**
 *	send_prio_char		-	send priority character
 *
 *	Send a high priority character to the tty even if stopped
 *
 *	Locking: none for xchar method, write ordering for write method.
 */

static int send_prio_char(struct tty_struct *tty, char ch)
{
	int	was_stopped = tty->stopped;

	if (tty->ops->send_xchar) {
		tty->ops->send_xchar(tty, ch);
		return 0;
	}

	if (tty_write_lock(tty, 0) < 0)
		return -ERESTARTSYS;

	if (was_stopped)
		start_tty(tty);
	tty->ops->write(tty, &ch, 1);
	if (was_stopped)
		stop_tty(tty);
	tty_write_unlock(tty);
	return 0;
}

/**
 *	tty_change_softcar	-	carrier change ioctl helper
 *	@tty: tty to update
 *	@arg: enable/disable CLOCAL
 *
 *	Perform a change to the CLOCAL state and call into the driver
 *	layer to make it visible. All done with the termios mutex
 */

static int tty_change_softcar(struct tty_struct *tty, int arg)
{
	int ret = 0;
	int bit = arg ? CLOCAL : 0;
	struct ktermios old;

	mutex_lock(&tty->termios_mutex);
	old = *tty->termios;
	tty->termios->c_cflag &= ~CLOCAL;
	tty->termios->c_cflag |= bit;
	if (tty->ops->set_termios)
		tty->ops->set_termios(tty, &old);
	if ((tty->termios->c_cflag & CLOCAL) != bit)
		ret = -EINVAL;
	mutex_unlock(&tty->termios_mutex);
	return ret;
}

/**
 *	tty_mode_ioctl		-	mode related ioctls
 *	@tty: tty for the ioctl
 *	@file: file pointer for the tty
 *	@cmd: command
 *	@arg: ioctl argument
 *
 *	Perform non line discipline specific mode control ioctls. This
 *	is designed to be called by line disciplines to ensure they provide
 *	consistent mode setting.
 */

int tty_mode_ioctl(struct tty_struct *tty, struct file *file,
			unsigned int cmd, unsigned long arg)
{
	struct tty_struct *real_tty;
	void __user *p = (void __user *)arg;
	int ret = 0;
	struct ktermios kterm;

	BUG_ON(file == NULL);

	if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
	    tty->driver->subtype == PTY_TYPE_MASTER)
		real_tty = tty->link;
	else
		real_tty = tty;

	switch (cmd) {
#ifdef TIOCGETP
	case TIOCGETP:
		return get_sgttyb(real_tty, (struct sgttyb __user *) arg);
	case TIOCSETP:
	case TIOCSETN:
		return set_sgttyb(real_tty, (struct sgttyb __user *) arg);
#endif
#ifdef TIOCGETC
	case TIOCGETC:
		return get_tchars(real_tty, p);
	case TIOCSETC:
		return set_tchars(real_tty, p);
#endif
#ifdef TIOCGLTC
	case TIOCGLTC:
		return get_ltchars(real_tty, p);
	case TIOCSLTC:
		return set_ltchars(real_tty, p);
#endif
	case TCSETSF:
		return set_termios(real_tty, p,  TERMIOS_FLUSH | TERMIOS_WAIT | TERMIOS_OLD);
	case TCSETSW:
		return set_termios(real_tty, p, TERMIOS_WAIT | TERMIOS_OLD);
	case TCSETS:
		return set_termios(real_tty, p, TERMIOS_OLD);
#ifndef TCGETS2
	case TCGETS:
		copy_termios(real_tty, &kterm);
		if (kernel_termios_to_user_termios((struct termios __user *)arg, &kterm))
			ret = -EFAULT;
		return ret;
#else
	case TCGETS:
		copy_termios(real_tty, &kterm);
		if (kernel_termios_to_user_termios_1((struct termios __user *)arg, &kterm))
			ret = -EFAULT;
		return ret;
	case TCGETS2:
		copy_termios(real_tty, &kterm);
		if (kernel_termios_to_user_termios((struct termios2 __user *)arg, &kterm))
			ret = -EFAULT;
		return ret;
	case TCSETSF2:
		return set_termios(real_tty, p,  TERMIOS_FLUSH | TERMIOS_WAIT);
	case TCSETSW2:
		return set_termios(real_tty, p, TERMIOS_WAIT);
	case TCSETS2:
		return set_termios(real_tty, p, 0);
#endif
	case TCGETA:
		return get_termio(real_tty, p);
	case TCSETAF:
		return set_termios(real_tty, p, TERMIOS_FLUSH | TERMIOS_WAIT | TERMIOS_TERMIO);
	case TCSETAW:
		return set_termios(real_tty, p, TERMIOS_WAIT | TERMIOS_TERMIO);
	case TCSETA:
		return set_termios(real_tty, p, TERMIOS_TERMIO);
#ifndef TCGETS2
	case TIOCGLCKTRMIOS:
		copy_termios_locked(real_tty, &kterm);
		if (kernel_termios_to_user_termios((struct termios __user *)arg, &kterm))
			ret = -EFAULT;
		return ret;
	case TIOCSLCKTRMIOS:
		if (!capable(CAP_SYS_ADMIN))
			return -EPERM;
		copy_termios_locked(real_tty, &kterm);
		if (user_termios_to_kernel_termios(&kterm,
					       (struct termios __user *) arg))
			return -EFAULT;
		mutex_lock(&real_tty->termios_mutex);
		memcpy(real_tty->termios_locked, &kterm, sizeof(struct ktermios));
		mutex_unlock(&real_tty->termios_mutex);
		return 0;
#else
	case TIOCGLCKTRMIOS:
		copy_termios_locked(real_tty, &kterm);
		if (kernel_termios_to_user_termios_1((struct termios __user *)arg, &kterm))
			ret = -EFAULT;
		return ret;
	case TIOCSLCKTRMIOS:
		if (!capable(CAP_SYS_ADMIN))
			return -EPERM;
		copy_termios_locked(real_tty, &kterm);
		if (user_termios_to_kernel_termios_1(&kterm,
					       (struct termios __user *) arg))
			return -EFAULT;
		mutex_lock(&real_tty->termios_mutex);
		memcpy(real_tty->termios_locked, &kterm, sizeof(struct ktermios));
		mutex_unlock(&real_tty->termios_mutex);
		return ret;
#endif
#ifdef TCGETX
	case TCGETX: {
		struct termiox ktermx;
		if (real_tty->termiox == NULL)
			return -EINVAL;
		mutex_lock(&real_tty->termios_mutex);
		memcpy(&ktermx, real_tty->termiox, sizeof(struct termiox));
		mutex_unlock(&real_tty->termios_mutex);
		if (copy_to_user(p, &ktermx, sizeof(struct termiox)))
			ret = -EFAULT;
		return ret;
	}
	case TCSETX:
		return set_termiox(real_tty, p, 0);
	case TCSETXW:
		return set_termiox(real_tty, p, TERMIOS_WAIT);
	case TCSETXF:
		return set_termiox(real_tty, p, TERMIOS_FLUSH);
#endif
	case TIOCGSOFTCAR:
		copy_termios(real_tty, &kterm);
		ret = put_user((kterm.c_cflag & CLOCAL) ? 1 : 0,
						(int __user *)arg);
		return ret;
	case TIOCSSOFTCAR:
		if (get_user(arg, (unsigned int __user *) arg))
			return -EFAULT;
		return tty_change_softcar(real_tty, arg);
	default:
		return -ENOIOCTLCMD;
	}
}
EXPORT_SYMBOL_GPL(tty_mode_ioctl);

int tty_perform_flush(struct tty_struct *tty, unsigned long arg)
{
	struct tty_ldisc *ld;
	int retval = tty_check_change(tty);
	if (retval)
		return retval;

	ld = tty_ldisc_ref_wait(tty);
	switch (arg) {
	case TCIFLUSH:
		if (ld && ld->ops->flush_buffer)
			ld->ops->flush_buffer(tty);
		break;
	case TCIOFLUSH:
		if (ld && ld->ops->flush_buffer)
			ld->ops->flush_buffer(tty);
		/* fall through */
	case TCOFLUSH:
		tty_driver_flush_buffer(tty);
		break;
	default:
		tty_ldisc_deref(ld);
		return -EINVAL;
	}
	tty_ldisc_deref(ld);
	return 0;
}
EXPORT_SYMBOL_GPL(tty_perform_flush);

int n_tty_ioctl_helper(struct tty_struct *tty, struct file *file,
		       unsigned int cmd, unsigned long arg)
{
	unsigned long flags;
	int retval;

	switch (cmd) {
	case TCXONC:
		retval = tty_check_change(tty);
		if (retval)
			return retval;
		switch (arg) {
		case TCOOFF:
			if (!tty->flow_stopped) {
				tty->flow_stopped = 1;
				stop_tty(tty);
			}
			break;
		case TCOON:
			if (tty->flow_stopped) {
				tty->flow_stopped = 0;
				start_tty(tty);
			}
			break;
		case TCIOFF:
			if (STOP_CHAR(tty) != __DISABLED_CHAR)
				return send_prio_char(tty, STOP_CHAR(tty));
			break;
		case TCION:
			if (START_CHAR(tty) != __DISABLED_CHAR)
				return send_prio_char(tty, START_CHAR(tty));
			break;
		default:
			return -EINVAL;
		}
		return 0;
	case TCFLSH:
		return tty_perform_flush(tty, arg);
	case TIOCPKT:
	{
		int pktmode;

		if (tty->driver->type != TTY_DRIVER_TYPE_PTY ||
		    tty->driver->subtype != PTY_TYPE_MASTER)
			return -ENOTTY;
		if (get_user(pktmode, (int __user *) arg))
			return -EFAULT;
		spin_lock_irqsave(&tty->ctrl_lock, flags);
		if (pktmode) {
			if (!tty->packet) {
				tty->packet = 1;
				tty->link->ctrl_status = 0;
			}
		} else
			tty->packet = 0;
		spin_unlock_irqrestore(&tty->ctrl_lock, flags);
		return 0;
	}
	default:
		/* Try the mode commands */
		return tty_mode_ioctl(tty, file, cmd, arg);
	}
}
EXPORT_SYMBOL(n_tty_ioctl_helper);


text:
/**
 * Rectangle tests
 **/
describe('Rectangle', function() {
    'use strict';
    var assert = chai.assert;

    describe('constructor', function() {
        it('should create itself with default values', function() {
            var rect = new Rectangle();
            assert.equal(rect.x, 0, 'x = 0');
            assert.equal(rect.y, 0, 'y = 0');
            assert.equal(rect.width, 0, 'width = 0');
            assert.equal(rect.height, 0, 'height = 0');
        });

        it('should create itself with initial values', function() {
            var rect = new Rectangle({
                x: 7,
                y: 11,
                width: 13,
                height: -2
            });
            assert.equal(rect.x, 7, 'x');
            assert.equal(rect.y, 11, 'y');
            assert.equal(rect.width, 13, 'width');
            assert.equal(rect.height, -2, 'height');
        });
    });

    describe('method contains', function() {
        var rectA;
        beforeEach(function() {
            rectA = new Rectangle({
                x: 20,
                y: 10,
                width: 100,
                height: 200
            });
        });
        it('should return `true` if rectangle contains given', function() {
            var rectB = new Rectangle({
                x: 30,
                y: 20,
                width: 10,
                height: 20
            });

            assert.strictEqual(rectA.contains(rectB), true, 'A contains B');

            rectB = new Rectangle({
                x: 30,
                y: 40
            });

            assert.strictEqual(rectA.contains(rectB), true,
                'A contains B, B is a point');

            rectB = new Rectangle({
                x: rectA.x,
                y: rectA.y,
                width: rectA.width,
                height: rectA.height
            });

            assert.strictEqual(rectA.contains(rectB), true, 'A and B are equal');
        });

        it('should return `false` if rectangle does not contain given', function() {
            var rectB = new Rectangle({
                x: 400,
                y: 50,
                width: 10,
                height: 40
            });

            assert.strictEqual(rectA.contains(rectB), false, 'A does not contain B');

            rectB = new Rectangle({
                x: rectA.x - 10,
                y: rectA.y,
                width: rectA.width,
                height: rectA.height
            });

            assert.strictEqual(rectA.contains(rectB), false,
                'A contain B. B is same size as A, but in different position');
        });
    });

    describe('method intersects', function() {
        var rectA, rectB;
        beforeEach(function() {
            rectA = new Rectangle({
                x: 200,
                y: 100,
                width: 600,
                height: 400
            });
            rectB = new Rectangle({
                x: 300,
                y: 200,
                width: 200,
                height: 100
            });
        });

        it('should return `true` if rectangle intersects with given', function() {
            assert.strictEqual(rectA.intersects(rectB), true, 'B ∈ A, A intersects B');
            assert.strictEqual(rectB.intersects(rectA), true, 'B ∈ A, B intersects A');

            rectB.x = 100;

            assert.strictEqual(rectA.intersects(rectB), true,
                'B intersects left edge of A, A intersects B');
            assert.strictEqual(rectB.intersects(rectA), true,
                'B intersects left edge of A, B intersects A');

            rectB.y = 50;

            assert.strictEqual(rectA.intersects(rectB), true,
                'B intersects left top corner of A, A intersects B');
            assert.strictEqual(rectB.intersects(rectA), true,
                'B intersects left top corner of A, B intersects A');

        });

        it('should return `false` if rectangle does not intersects with given', function() {
            rectB.x = 0;
            rectB.y = 0;

            assert.strictEqual(rectA.intersects(rectB), false,
                'B bottom right corner touches A top left corner, A DOES NOT intersect B');
            assert.strictEqual(rectB.intersects(rectA), false,
                'B bottom right corner touches A top left corner, B DOES NOT intersect A');

            rectB.x = rectA.x - rectB.width;
            rectB.y = rectA.y;
            rectB.height = rectA.height;

            assert.strictEqual(rectA.intersects(rectB), false,
                'B is completely adjacent to A, A DOES NOT intersect B');
            assert.strictEqual(rectB.intersects(rectA), false,
                'B is completely adjacent to A, B DOES NOT intersect A');
        });
    });

    describe('can check if other rectangle `.canFit` within', function() {
        var rect, rectSmall, rectEqual, rectBig;
        beforeEach(function() {
            rect = new Rectangle({
                width: 200,
                height: 100
            });
            rectSmall = new Rectangle({
                width: 180,
                height: 80
            });
            rectEqual = new Rectangle({
                width: 200,
                height: 100
            });
            rectBig = new Rectangle({
                width: 220,
                height: 100
            });
        });
        it("other rectangle can fit within", function() {
            assert.strictEqual(rect.canFit(rectSmall), true, "smaller fits");
            assert.strictEqual(rect.canFit(rectEqual), true, "equal fits");
            assert.strictEqual(rect.canFit(rectBig), false, "bigger don't");
        });
        it("smaller rectangle can fit within additional buffer space", function() {
            assert.strictEqual(rect.canFit(rectSmall, 10), true, "smaller fits with 10 buffer");
            assert.strictEqual(rect.canFit(rectEqual, 20), false, "smaller don't fit with 20 buffer");
            assert.strictEqual(rect.canFit(rectEqual, 10), false, "equal don't");
            assert.strictEqual(rect.canFit(rectBig, 10), false, "bigger don't");
        });

    });

    describe('can `getSlotsAround` given rectangle inside itself', function() {
        var rectA;
        beforeEach(function(){
            rectA = new Rectangle({
                height: 30,
                width: 40,
                x: 10,
                y: 20
            });
        });
        it("when it's complately inside", function() {
            // 1111
            //  BB
            //
            // -
            // 1
            // 1BB
            // 1
            // -
            //
            //  BB
            // 1111
            // -
            //    1
            //  BB1
            //    1
            var rectB = new Rectangle({
                x: 20,
                y: 30,
                width: 20,
                height: 10
            });
            var slots = rectA.getSlotsAround(rectB);
            assert.strictEqual(slots.length, 4, "4 slots around");
            var rectTop = new Rectangle({
                height: 10,
                width: 40,
                x: 10,
                y: 20
            });
            assert.include(slots, rectTop, "one on top");
            var rectLeft = new Rectangle({
                height: 30,
                width: 10,
                x: 10,
                y: 20
            });
            assert.include(slots, rectLeft, "one on left");
            var rectRight = new Rectangle({
                height: 30,
                width: 10,
                x: 40,
                y: 20
            });
            assert.include(slots, rectRight, "one on right");
            var rectBottom = new Rectangle({
                height: 10,
                width: 40,
                x: 10,
                y: 40
            });
            assert.include(slots, rectBottom, "one at the bottom");
        });

        it("when it's complately when its wider", function() {
            //  1111
            // BBBBBB
            //  2222
            var rectB = new Rectangle({
                x: 0,
                y: 30,
                width: 60,
                height: 10
            });
            var slots = rectA.getSlotsAround(rectB);
            assert.strictEqual(slots.length, 2, "2 slots around");
            var rect1 = new Rectangle({
                height: 10,
                width: 40,
                x: 10,
                y: 20
            });
            assert.include(slots, rect1, "one on top");
            var rect2 = new Rectangle({
                height: 10,
                width: 40,
                x: 10,
                y: 40
            });
            assert.include(slots, rect2, "second at the bottom");
        });
        it("when it's complately when its higher", function() {
            //  B
            // 1B22
            // 1B22
            // 1B22
            //  B
            var rectB = new Rectangle({
                x: 20,
                y: 10,
                width: 10,
                height: 50
            });
            var slots = rectA.getSlotsAround(rectB);
            assert.strictEqual(slots.length, 2, "2 slots around");
            var rect1 = new Rectangle({
                height: 30,
                width: 10,
                x: 10,
                y: 20
            });
            assert.include(slots, rect1, "one on left");
            var rect2 = new Rectangle({
                height: 30,
                width: 20,
                x: 30,
                y: 20
            });
            assert.include(slots, rect2, "second on right");
        });

    });

});