text:
<?xml version="1.0" encoding="utf-8"?>
<com.example.aluno.olay.slidinguppanel.SlidingUpPanelLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:sothree="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.aluno.olay.MainActivity"
    android:id="@+id/sliding_layout"
    android:gravity="bottom"
    sothree:umanoPanelHeight="68dp"
    sothree:umanoShadowHeight="4dp"
    sothree:umanoParallaxOffset="100dp"
    sothree:umanoDragView="@+id/dragView"
    sothree:umanoOverlay="true"
    sothree:umanoScrollableView="@+id/list">

    <!-- MAIN LAYOUT -->
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <fragment xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            xmlns:map="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/mapEvent"
            tools:context=".MapLocationActivity"
            android:name="com.google.android.gms.maps.SupportMapFragment">

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fabCreat"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom|center"
                android:layout_margin="@dimen/fab_margin"
                app:srcCompat="@drawable/ic_add_white_24dp"/>

        </fragment>
    </FrameLayout>

    <!-- SLIDING LAYOUT -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#EEEEEE"
        android:orientation="vertical"
        android:clickable="true"
        android:focusable="false"
        android:id="@+id/dragView">

        <ImageView
            android:id="@+id/imvFoto"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:scaleType="centerCrop"
            android:contentDescription="@string/foto"/>

        <!-- CARDS-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_margin="7dp">

            <!-- NOME-->
            <android.support.v7.widget.CardView
                xmlns:card_view="http://schemas.android.com/apk/res-auto"
                android:id="@+id/card_view"
                android:layout_gravity="center"
                android:layout_width="match_parent"
                android:layout_height="100dp"
                card_view:cardElevation="2dp"
                card_view:cardCornerRadius="4dp">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_margin="10dp">

                    <TextView
                        android:id="@+id/lblNomeEvento"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:maxLines="3"
                        android:textColor="#ff5722"
                        android:textStyle="bold"
                        android:textSize="28sp"/>

                    <TextView
                        android:id="@+id/lblamplia"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/lblNomeEvento"
                        android:text="@string/amplia"
                        android:padding="8dp"
                        android:textColor="#666"
                        android:textSize="14sp" />

                </RelativeLayout>

            </android.support.v7.widget.CardView>

            <!-- HORARIO -->
            <android.support.v7.widget.CardView
                xmlns:card_view="http://schemas.android.com/apk/res-auto"
                android:id="@+id/card_view2"
                android:layout_gravity="center"
                android:layout_width="match_parent"
                android:layout_height="100dp"
                card_view:cardElevation="2dp"
                card_view:cardCornerRadius="4dp">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_margin="10dp">

                    <TextView
                        android:id="@+id/lblTituloHorario"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:maxLines="3"
                        android:padding="8dp"
                        android:text="@string/datahora"
                        android:textColor="#222"
                        android:textStyle="bold"
                        android:textSize="20sp" />

                    <TextView
                        android:id="@+id/lblDataHora"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/lblTituloHorario"
                        android:maxLines="3"
                        android:textColor="#666"
                        android:textSize="14sp" />

                </RelativeLayout>

            </android.support.v7.widget.CardView>

            <!-- DESCRICAO -->
            <android.support.v7.widget.CardView
                xmlns:card_view="http://schemas.android.com/apk/res-auto"
                android:id="@+id/card_view3"
                android:layout_gravity="center"
                android:layout_width="match_parent"
                android:layout_height="140dp"
                card_view:cardElevation="2dp"
                card_view:cardCornerRadius="4dp">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_margin="10dp">

                    <TextView
                        android:id="@+id/lblTituloDescricao"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:maxLines="3"
                        android:padding="8dp"
                        android:text="@string/descricao"
                        android:textColor="#673ab7"
                        android:textStyle="bold"
                        android:textSize="20sp" />

                    <TextView
                        android:id="@+id/lblDescricao"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/lblTituloDescricao"
                        android:maxLines="3"
                        android:textColor="#666"
                        android:textSize="14sp" />

                </RelativeLayout>

            </android.support.v7.widget.CardView>

        </LinearLayout>

    </LinearLayout>

</com.example.aluno.olay.slidinguppanel.SlidingUpPanelLayout>


text:
import React from 'react';
import ReactDOM from 'react-dom';
import Toggle from '../index';
import {
  createTestContainer,
  getDOMNode,
  getStyle,
  toRGB,
  getDefaultPalette
} from '@test/testUtils';

import '../styles/index';

describe('Toggle styles', () => {
  it('Should render the correct styles', () => {
    const instanceRef = React.createRef();
    ReactDOM.render(<Toggle ref={instanceRef} />, createTestContainer());
    const dom = getDOMNode(instanceRef.current);
    assert.equal(getStyle(dom, 'backgroundColor'), toRGB('#d9d9d9'), 'Toggle background-color');
  });
});

redpajama_set_name: RedPajamaGithub


text:
PYTHON ?= python

export PYTHONPATH = $(shell echo "$$PYTHONPATH"):$(shell python -c 'import os; print ":".join(os.path.abspath(line.strip()) for line in file("PYTHONPATH"))' 2>/dev/null)

.PHONY: all check clean clean-pyc codetags docs mapfiles \
	pylint reindent test test-coverage

all: clean-pyc check test

check:
	@$(PYTHON) scripts/detect_missing_analyse_text.py || true
	@$(PYTHON) scripts/check_sources.py -i apidocs -i pygments/lexers/_mapping.py \
		   -i docs/build -i pygments/formatters/_mapping.py -i pygments/unistring.py \
		   -i pygments/lexers/_vimbuiltins.py

clean: clean-pyc
	rm -f codetags.html
	rm -rf apidocs

clean-pyc:
	find . -name '*.pyc' -exec rm -f {} +
	find . -name '*.pyo' -exec rm -f {} +
	find . -name '*~' -exec rm -f {} +

codetags:
	@$(PYTHON) scripts/find_codetags.py -i apidocs -i scripts/pylintrc \
		   -i scripts/find_codetags.py -o codetags.html .

docs: docs/build

docs/build: docs/src/*.txt
	$(PYTHON) docs/generate.py html docs/build $?
	touch docs/build

mapfiles:
	(cd pygments/lexers; $(PYTHON) _mapping.py)
	(cd pygments/formatters; $(PYTHON) _mapping.py)

pylint:
	@pylint --rcfile scripts/pylintrc pygments

reindent:
	@$(PYTHON) scripts/reindent.py -r -B .

test:
	@$(PYTHON) tests/run.py $(TESTS)

test-coverage:
	@$(PYTHON) tests/run.py -C $(TESTS)


text:
Recent Encounters
    See an Alien? Report it!

				{{ encounter.date }} - {{ encounter.atype }}

				{{ encounter.action }}

		<button routerLink="/report">Report Encounter</button>


text:
package cz.metacentrum.perun.core.blImpl;

import cz.metacentrum.perun.core.api.AuthzResolver;
import cz.metacentrum.perun.core.api.Facility;
import cz.metacentrum.perun.core.api.Group;
import cz.metacentrum.perun.core.api.Pair;
import cz.metacentrum.perun.core.api.PerunBean;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.Role;
import cz.metacentrum.perun.core.api.SecurityTeam;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.exceptions.AlreadyAdminException;
import cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException;
import cz.metacentrum.perun.core.api.exceptions.GroupNotAdminException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.RelationExistsException;
import cz.metacentrum.perun.core.api.exceptions.SecurityTeamExistsException;
import cz.metacentrum.perun.core.api.exceptions.SecurityTeamNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.UserAlreadyBlacklistedException;
import cz.metacentrum.perun.core.api.exceptions.UserAlreadyRemovedException;
import cz.metacentrum.perun.core.api.exceptions.UserNotAdminException;
import cz.metacentrum.perun.core.bl.PerunBl;
import cz.metacentrum.perun.core.bl.SecurityTeamsManagerBl;
import cz.metacentrum.perun.core.implApi.SecurityTeamsManagerImplApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Ondrej Velisek <ondrejvelisek@gmail.com>
 */
public class SecurityTeamsManagerBlImpl implements SecurityTeamsManagerBl {

	private final static Logger log = LoggerFactory.getLogger(SecurityTeamsManagerBlImpl.class);

	private final SecurityTeamsManagerImplApi securityTeamsManagerImpl;
	private PerunBl perunBl;

	public SecurityTeamsManagerBlImpl(SecurityTeamsManagerImplApi securityTeamsManagerImpl) {
		this.securityTeamsManagerImpl = securityTeamsManagerImpl;
	}

	@Override
	public List<SecurityTeam> getSecurityTeams(PerunSession sess) throws InternalErrorException {
		if (AuthzResolverBlImpl.hasRole(sess.getPerunPrincipal(), Role.PERUNADMIN)) {
			return getSecurityTeamsManagerImpl().getAllSecurityTeams(sess);
		} else if (AuthzResolverBlImpl.hasRole(sess.getPerunPrincipal(), Role.SECURITYADMIN)) {

			List<SecurityTeam> securityTeams = new ArrayList<>();

			// Get SecurityTeams where user is Admin
			for (PerunBean st: AuthzResolver.getComplementaryObjectsForRole(sess, Role.SECURITYADMIN, SecurityTeam.class)) {
				securityTeams.add((SecurityTeam) st);
			}

			return securityTeams;
		} else {
			throw new InternalErrorException("Wrong Entry. Should throw PrivilegeException");
		}
	}

	@Override
	public List<SecurityTeam> getAllSecurityTeams(PerunSession sess) throws InternalErrorException {
		return getSecurityTeamsManagerImpl().getAllSecurityTeams(sess);
	}

	@Override
	public SecurityTeam createSecurityTeam(PerunSession sess, SecurityTeam securityTeam) throws SecurityTeamExistsException, InternalErrorException {
		securityTeam = getSecurityTeamsManagerImpl().createSecurityTeam(sess, securityTeam);
		getPerunBl().getAuditer().log(sess, "{} was created.", securityTeam);

		// set creator as security team admin
		User user = sess.getPerunPrincipal().getUser();
		if(user != null) {   //user can be null in tests
			try {
				AuthzResolverBlImpl.setRole(sess, user, securityTeam, Role.SECURITYADMIN);
			} catch (AlreadyAdminException e) {
				throw new ConsistencyErrorException("Newly created securityTeam already have an admin.", e);
			}
		}

		return securityTeam;
	}

	@Override
	public SecurityTeam updateSecurityTeam(PerunSession sess, SecurityTeam securityTeam) throws InternalErrorException, SecurityTeamNotExistsException {
		securityTeam = getSecurityTeamsManagerImpl().updateSecurityTeam(sess, securityTeam);
		getPerunBl().getAuditer().log(sess, "{} was updated.", securityTeam);
		return securityTeam;
	}

	@Override
	public void deleteSecurityTeam(PerunSession sess, SecurityTeam securityTeam, boolean forceDelete) throws SecurityTeamNotExistsException, InternalErrorException, RelationExistsException {

		// remove all users from blacklist, which were blacklisted by this security team.
		List<User> blacklist = getSecurityTeamsManagerImpl().getBlacklist(sess, Arrays.asList(securityTeam));
		if (blacklist != null && !blacklist.isEmpty() && !forceDelete) {
			throw new RelationExistsException("SecurityTeam has blacklisted users.");
		}
		for (User blacklistedUser : blacklist) {
			// calling BL will make auditer message about user to appear.
			getPerunBl().getSecurityTeamsManagerBl().removeUserFromBlacklist(sess, securityTeam, blacklistedUser);
		}

		// remove security team from all facilities
		List<Facility> facilities = getPerunBl().getFacilitiesManagerBl().getAssignedFacilities(sess, securityTeam);
		if (facilities != null && !facilities.isEmpty() && !forceDelete) {
			throw new RelationExistsException("SecurityTeam is assigned to some facilities.");
		}
		for (Facility facility : facilities) {
			// calling BL will make auditer message about facility to appear.
			getPerunBl().getFacilitiesManagerBl().removeSecurityTeam(sess, facility, securityTeam);
		}

		getSecurityTeamsManagerImpl().deleteSecurityTeam(sess, securityTeam);
		getPerunBl().getAuditer().log(sess, "{} was deleted.", securityTeam);
	}

	@Override
	public SecurityTeam getSecurityTeamById(PerunSession sess, int id) throws SecurityTeamNotExistsException, InternalErrorException {
		return getSecurityTeamsManagerImpl().getSecurityTeamById(sess, id);
	}

	@Override
	public SecurityTeam getSecurityTeamByName(PerunSession sess, String name) throws SecurityTeamNotExistsException, InternalErrorException {
		return getSecurityTeamsManagerImpl().getSecurityTeamByName(sess, name);
	}

	@Override
	public List<User> getAdmins(PerunSession sess, SecurityTeam securityTeam) throws InternalErrorException {
		return getSecurityTeamsManagerImpl().getAdmins(sess, securityTeam);
	}

	@Override
	public void addAdmin(PerunSession sess, SecurityTeam securityTeam, User user) throws AlreadyAdminException, InternalErrorException {
		AuthzResolverBlImpl.addAdmin(sess, securityTeam, user);
		getPerunBl().getAuditer().log(sess, "{} was added as security admin of {}.", user, securityTeam);
	}

	@Override
	public void addAdmin(PerunSession sess, SecurityTeam securityTeam, Group group) throws InternalErrorException, AlreadyAdminException {
		AuthzResolverBlImpl.addAdmin(sess, securityTeam, group);
		getPerunBl().getAuditer().log(sess, "{} was added as security admins of {}.", group, securityTeam);
	}

	@Override
	public void removeAdmin(PerunSession sess, SecurityTeam securityTeam, User user) throws UserNotAdminException, InternalErrorException {
		AuthzResolverBlImpl.removeAdmin(sess, securityTeam, user);
		getPerunBl().getAuditer().log(sess, "{} was removed from security admins of {}.", user, securityTeam);
	}

	@Override
	public void removeAdmin(PerunSession sess, SecurityTeam securityTeam, Group group) throws InternalErrorException, GroupNotAdminException {
		AuthzResolverBlImpl.removeAdmin(sess, securityTeam, group);
		getPerunBl().getAuditer().log(sess, "{} was removed from security admins of {}.", group, securityTeam);
	}

	@Override
	public void addUserToBlacklist(PerunSession sess, SecurityTeam securityTeam, User user, String description) throws InternalErrorException {
		getSecurityTeamsManagerImpl().addUserToBlacklist(sess, securityTeam, user, description);
		getPerunBl().getAuditer().log(sess, "{} add to blacklist of {} with description '{}'.", user, securityTeam, description);
	}

	@Override
	public void removeUserFromBlacklist(PerunSession sess, SecurityTeam securityTeam, User user) throws InternalErrorException {
		getSecurityTeamsManagerImpl().removeUserFromBlacklist(sess, securityTeam, user);
		getPerunBl().getAuditer().log(sess, "{} remove from blacklist of {}.", user, securityTeam);
	}

	@Override
	public void removeUserFromAllBlacklists(PerunSession sess, User user) throws InternalErrorException {
		getSecurityTeamsManagerImpl().removeUserFromAllBlacklists(sess, user);
		getPerunBl().getAuditer().log(sess, "{} remove from all blacklists.", user);
	}

	@Override
	public List<User> getBlacklist(PerunSession sess, SecurityTeam securityTeam) throws InternalErrorException {
		List<SecurityTeam> wrapper = new ArrayList<>();
		wrapper.add(securityTeam);
		return getSecurityTeamsManagerImpl().getBlacklist(sess, wrapper);
	}

	@Override
	public List<User> getBlacklist(PerunSession sess, Facility facility) throws InternalErrorException {
		List<SecurityTeam> securityTeams = perunBl.getFacilitiesManagerBl().getAssignedSecurityTeams(sess, facility);
		return getSecurityTeamsManagerImpl().getBlacklist(sess, securityTeams);
	}

	@Override
	public List<Pair<User, String>> getBlacklistWithDescription(PerunSession sess, SecurityTeam securityTeam) throws InternalErrorException {
		List<SecurityTeam> wrapper = new ArrayList<>();
		wrapper.add(securityTeam);
		return getSecurityTeamsManagerImpl().getBlacklistWithDescription(sess, wrapper);
	}

	@Override
	public List<Pair<User, String>> getBlacklistWithDescription(PerunSession sess, Facility facility) throws InternalErrorException {
		List<SecurityTeam> securityTeams = perunBl.getFacilitiesManagerBl().getAssignedSecurityTeams(sess, facility);
		return getSecurityTeamsManagerImpl().getBlacklistWithDescription(sess, securityTeams);
	}

	@Override
	public void checkSecurityTeamExists(PerunSession sess, SecurityTeam securityTeam) throws SecurityTeamNotExistsException, InternalErrorException {
		getSecurityTeamsManagerImpl().checkSecurityTeamExists(sess, securityTeam);
	}

	@Override
	public void checkSecurityTeamNotExists(PerunSession sess, SecurityTeam securityTeam) throws SecurityTeamExistsException, InternalErrorException {
		getSecurityTeamsManagerImpl().checkSecurityTeamNotExists(sess, securityTeam);
	}

	@Override
	public void checkSecurityTeamUniqueName(PerunSession sess, SecurityTeam securityTeam) throws InternalErrorException, SecurityTeamExistsException {
		getSecurityTeamsManagerImpl().checkSecurityTeamUniqueName(sess, securityTeam);
	}

	@Override
	public void checkUserIsNotSecurityAdmin(PerunSession sess, SecurityTeam securityTeam, User user) throws AlreadyAdminException, InternalErrorException {
		getSecurityTeamsManagerImpl().checkUserIsNotSecurityAdmin(sess, securityTeam, user);
	}

	@Override
	public void checkUserIsSecurityAdmin(PerunSession sess, SecurityTeam securityTeam, User user) throws UserNotAdminException, InternalErrorException {
		getSecurityTeamsManagerImpl().checkUserIsSecurityAdmin(sess, securityTeam, user);
	}

	@Override
	public void checkGroupIsNotSecurityAdmin(PerunSession sess, SecurityTeam securityTeam, Group group) throws AlreadyAdminException, InternalErrorException {
		getSecurityTeamsManagerImpl().checkGroupIsNotSecurityAdmin(sess, securityTeam, group);
	}

	@Override
	public void checkGroupIsSecurityAdmin(PerunSession sess, SecurityTeam securityTeam, Group group) throws GroupNotAdminException, InternalErrorException {
		getSecurityTeamsManagerImpl().checkGroupIsSecurityAdmin(sess, securityTeam, group);
	}

	@Override
	public void checkUserIsNotInBlacklist(PerunSession sess, SecurityTeam securityTeam, User user) throws UserAlreadyBlacklistedException, InternalErrorException {
		if (isUserBlacklisted(sess, securityTeam, user)) {
			throw new UserAlreadyBlacklistedException("User "+user+" is already in blacklist of security team "+securityTeam);
		}
	}

	@Override
	public void checkUserIsInBlacklist(PerunSession sess, SecurityTeam securityTeam, User user) throws UserAlreadyRemovedException, InternalErrorException {
		if (!isUserBlacklisted(sess, securityTeam, user)) {
			throw new UserAlreadyRemovedException("User "+user+" is not in blacklist of security team "+securityTeam);
		}
	}

	@Override
	public boolean isUserBlacklisted(PerunSession sess, SecurityTeam securityTeam, User user) throws InternalErrorException {
		return getSecurityTeamsManagerImpl().isUserBlacklisted(sess, securityTeam, user);
	}

	@Override
	public boolean isUserBlacklisted(PerunSession sess, User user) throws InternalErrorException {
		return getSecurityTeamsManagerImpl().isUserBlacklisted(sess, user);
	}

	/**
	 * Gets the securityTeamsManagerImpl.
	 *
	 * @return The securityTeamsManagerImpl.
	 */
	public SecurityTeamsManagerImplApi getSecurityTeamsManagerImpl() {
		return this.securityTeamsManagerImpl;
	}

	/**
	 * Sets the perunBl for this instance.
	 *
	 * @param perunBl The perunBl.
	 */
	public void setPerunBl(PerunBl perunBl) {
		this.perunBl = perunBl;
	}

	/**
	 * Gets the perunBl.
	 *
	 * @return The perunBl.
	 */
	public PerunBl getPerunBl() {
		return this.perunBl;
	}
}


text:
'use strict';
/*
 UMD Stuff
 @export Point
 */

/**
 * The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
 *
 * @class Point
 * @module StructureJS
 * @submodule geom
 * @constructor
 * @author Robert S. (www.codeBelt.com)
 */
class Point
{
    /**
     * The horizontal coordinate of the point.
     *
     * @property x
     * @type {number}
     * @public
     */
    public x:number = 0;

    /**
     * The vertical coordinate of the point.
     *
     * @property y
     * @type {number}
     * @public
     */
    public y:number = 0;

    constructor(x:number = 0, y:number = 0)
    {
        this.x = x;
        this.y = y;
    }

}

export = Point;


text:
<!DOCTYPE html>
<title>Image sampling techniques</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Image sampling techniques

      <input style="width:400px;" type="range" min="-10" max="10" value="0" step="0.01"
             class="slider" id="scale_slider" title="Scale">

          <canvas id="draw" width=2048 height=1600></canvas>

        Drop an Image onto the page (above)


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview
 * UI element for displaying paired Bluetooth devices.
 */

import '../../settings_shared_css.js';
import './os_paired_bluetooth_list_item.js';

import '//resources/polymer/v3_0/iron-list/iron-list.js';
import {CrScrollableBehavior, CrScrollableBehaviorInterface} from '//resources/cr_elements/cr_scrollable_behavior.m.js';
import {html, mixinBehaviors, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';

/**
 * @constructor
 * @extends {PolymerElement}
 * @implements {CrScrollableBehaviorInterface}
 */
const SettingsPairedBluetoothListElementBase =
    mixinBehaviors([CrScrollableBehavior], PolymerElement);

/** @polymer */
class SettingsPairedBluetoothListElement extends
    SettingsPairedBluetoothListElementBase {
  static get is() {
    return 'os-settings-paired-bluetooth-list';
  }

  static get template() {
    return html`{__html_template__}`;
  }

  static get properties() {
    return {
      /**
       * @private {!Array<!chromeos.bluetoothConfig.mojom.PairedBluetoothDeviceProperties>}
       */
      devices: {
        type: Array,
        observer: 'onDevicesChanged_',
        value: [],
      },

      /**
       * Used by FocusRowBehavior to track the last focused element on a row.
       * @private
       */
      lastFocused_: Object,
    };
  }

  constructor() {
    super();
    /**
     * The address of the device corresponding to the tooltip if it is currently
     * showing. If undefined, the tooltip is not showing.
     * @type {string|undefined}
     * @private
     */
    this.currentTooltipDeviceAddress_;
  }

  /** @private */
  onDevicesChanged_() {
    // CrScrollableBehaviorInterface method required for list items to be
    // properly rendered when devices updates.
    this.updateScrollableContents();
  }

  /**
   * Updates the visibility of the enterprise policy UI tooltip. This is
   * triggered by the managed-tooltip-state-change event. This event can be
   * fired in two cases:
   * 1) We want to show the tooltip for a given device's icon. Here, show will
   *    be true and the element will be defined.
   * 2) We want to make sure there is no tooltip showing for a given device's
   *    icon. Here, show will be false and the element undefined.
   * In both cases, address will be the item's device address.
   * We need to use a common tooltip since a tooltip within the item gets cut
   * off from the iron-list.
   * @param {!{detail: {address: string, show: boolean, element: ?HTMLElement}}}
   *     e
   * @private
   */
  onManagedTooltipStateChange_(e) {
    const target = e.detail.element;
    const hide = () => {
      /** @type {{hide: Function}} */ (this.$.tooltip).hide();
      this.$.tooltip.removeEventListener('mouseenter', hide);
      this.currentTooltipDeviceAddress_ = undefined;
      if (target) {
        target.removeEventListener('mouseleave', hide);
        target.removeEventListener('blur', hide);
        target.removeEventListener('tap', hide);
      }
    };

    if (!e.detail.show) {
      if (this.currentTooltipDeviceAddress_ &&
          e.detail.address === this.currentTooltipDeviceAddress_) {
        hide();
      }
      return;
    }

    // paper-tooltip normally determines the target from the |for| property,
    // which is a selector. Here paper-tooltip is being reused by multiple
    // potential targets. Since paper-tooltip does not expose a public property
    // or method to update the target, the private property |_target| is
    // updated directly.
    this.$.tooltip._target = target;
    /** @type {{updatePosition: Function}} */ (this.$.tooltip).updatePosition();
    target.addEventListener('mouseleave', hide);
    target.addEventListener('blur', hide);
    target.addEventListener('tap', hide);
    this.$.tooltip.addEventListener('mouseenter', hide);
    this.$.tooltip.show();
    this.currentTooltipDeviceAddress_ = e.detail.address;
  }
}

customElements.define(
    SettingsPairedBluetoothListElement.is, SettingsPairedBluetoothListElement);


text:
package water.rapids.ast.prims.reducers;

/**
 */
public class AstCumSum extends AstCumu {
  @Override
  public int nargs() { return 1 + 2; } // (cumsum x)

  @Override
  public String str() {
    return "cumsum";
  }

  @Override
  public double op(double l, double r) {
    return l + r;
  }

  @Override
  public double init() {
    return 0;
  }
}


text:
angular.module('nuttyapp')
    .factory('SlaveConnection', ['$rootScope', 'NuttySession', '$location',
        function($rootScope, NuttySession, $location) {
            var wsocketslave;
            var wrtcslave;
            var wrtcconn;
            var ondata;
            var retobj;

            Meteor._reload.onMigrate("onMigrate", function() {
                console.log(arguments);
                return [false];
            });
            retobj = {
                type: '',
                connect: function () {
                    function processinput(data) {
                        var msg = {};
                        console.log(data);
                        if (!data)
                            return;
                        if (data.data)
                            msg.data = data.data;
                        else if (data.settermshot)
                            msg.settermshot = data.settermshot;
                        else if (data.setcursorposition)
                            msg.setcursorposition = data.setcursorposition;
                        else
                            return;
                        if (ondata)
                            ondata(msg);
                    }
                    if (retobj.type === 'websocket') {
                        wsocketslave = new Meteor.PipeClientSlave(NuttySession.sessionid);
                        wsocketslave.on('data', processinput);
                        wsocketslave.on('ready', function() {
                            setTimeout ( function() {
                                wsocketslave.send({
                                    gettermshot: true
                                });
                            }, 1000);
                        });
                    } else if (retobj.type === 'webrtc') {
                        Meteor.call('getWebrtcConfig', $location.host(), function(err, webrtcconfig) {
                            if (err) {
                                console.log("Meteor.call(getWebrtcConfig) returned : " + (err.reason));
                                return;
                            }
                            if (!webrtcconfig.host)
                                webrtcconfig.host = $location.host();
                            if (!webrtcconfig.port)
                                webrtcconfig.port = 9000;
                            wrtcslave = new Peer(webrtcconfig);
                            wrtcslave.on('open', function(connid) {
                                console.log("Connected to PeerJS server");
                            });
                            wrtcslave.on('error', function(error) {
                                console.log("error from PeerJS server : " + error);
                            })
                            wrtcconn = wrtcslave.connect(NuttySession.sessionid);
                            wrtcconn.on('open', function() {
                                console.log('connected to master');
                                setTimeout ( function() {
                                    wrtcconn.send({
                                        gettermshot: true
                                    });
                                }, 1000);
                            });
                            wrtcconn.on('error', function(error) {
                                console.log('error on connection to master');
                            });
                            wrtcconn.on('close', function() {
                                console.log('master closed connection');
                            });
                            wrtcconn.on('data', processinput);
                        });
                    }
                },
                pipe: {
                    write: function(data) {
                        var msg = {};
                        if (data.data)
                            msg.data = data.data;
                        else if (data.newtmuxsession) {
                            msg.newtmuxsession = data.newtmuxsession;
                        } else if (data.gettermshot) {
                            msg.gettermshot = data.gettermshot;
                        } else {
                            return;
                        }
                        if (retobj.type === 'webrtc') {
                            if (wrtcconn)
                                wrtcconn.send(msg);
                        } else if (retobj.type === 'websocket'){
                            if (wsocketslave)
                                wsocketslave.send(msg);
                        } else {
                            console.log("SlaveConnection.type is neither websocket nor webrtc");
                        }
                    },
                    ondata: function(cbk) {
                        ondata = cbk;
                    }
                }
            }
            window.SlaveConnection = retobj;
            return retobj;
        }
    ]);


text:
rm bridge.js.zip;
zip bridge.js.zip bridge.js;
minjs bridge.js bridge.min.js;
rm bridge.min.zip;
zip bridge.min.zip  bridge.min.js;
cp bridge.js demo/bridge.js;
rm demo.zip;
zip -r demo.zip demo;
rm -rf tb;
mkdir tb;
cp bridge.js tb;
cp geo.js tb;
cd tb;
rm -rf ../../api;
yuidoc --themedir ../yui_theme -o ../../api .;
cd ..;
rm -rf tb;
cd ..;
git add --all;
git commit -m "modify js lib";
git push;


text:
using System.Collections.Generic;
using System.Linq;
using SilverlightMappingToolBasic.UI.SuperGraph.ViewModel;

namespace SilverlightMappingToolBasic.UI.SuperGraph.View.Selector
{
    public class SelectedNodesCollection
    {
        private List<Relationship> _relatedRelationships;
        private IEnumerable<Relationship> _relationships;
        private IEnumerable<Node> _nodes;

        public SelectedNodesCollection(IEnumerable<Node> selectedNodes, IEnumerable<Relationship> relationships)
        {
            Nodes = selectedNodes.ToList();
            Relationships = relationships.ToList();
            FindRelatedRelationships();
        }

        private IEnumerable<Relationship> Relationships
        {
            get
            {
                if (_relationships == null)
                    _relationships = new List<Relationship>();
                return _relationships;
            }
            set
            {
                _relationships = value;
            }
        }

        public List<Relationship> RelatedRelationships
        {
            get
            {
                if (_relatedRelationships == null)
                    _relatedRelationships = new List<Relationship>();
                return _relatedRelationships;
            }
            set
            {
                _relatedRelationships = value;
            }
        }

        public IEnumerable<Node> Nodes
        {
            get
            {
                if (_nodes == null)
                    _nodes = new List<Node>();
                return _nodes;
            }
            set
            {
                _nodes = value;
            }
        }

        private void FindRelatedRelationships()
        {
            //Copy relationships to a list for modification
            RelatedRelationships = Relationships.ToList();
            foreach (var relationship in Relationships)
            {
                //Check the nodes conntect by this relationship are all in selection or not
                //If any node is not exist in selection, then delete the relationship
                //This is aim to find out relationships between those nodes that have been selected
                var countRelationshipToNodes = Nodes.Count(q => q.Id == relationship.To);
                var countRelationshipFromNodes = Nodes.Count(q => q.Id == relationship.From);
                if (countRelationshipToNodes == 0 || countRelationshipFromNodes == 0)
                {
                    RelatedRelationships.Remove(relationship);
                }
            }
        }

    }
}


text:
import test from 'ava';
import TorrentLibrary from '../../index';
import { expectedJson, folders } from '../_constants';

/** @test {TorrentLibrary#toJSON} */
test('return a valid stringified JSON', async (t) => {
  const expectedJsonString = JSON.stringify(expectedJson);
  let libInstance = new TorrentLibrary();
  await t.notThrows(libInstance.addNewPath(...folders));
  await t.notThrows(libInstance.scan());
  const dataFromInstance = libInstance.toJSON();
  t.deepEqual(
    JSON.stringify(JSON.parse(dataFromInstance)),
    expectedJsonString,
    'Not the same JSON',
  );
});


text:
package at.ac.tuwien.utility

import java.io.{BufferedWriter, File, FileOutputStream, OutputStreamWriter}

import at.ac.tuwien.math.TreeTokenizer
import net.sourceforge.jeuclid.context.{LayoutContextImpl, Parameter}
import net.sourceforge.jeuclid.converter.Converter
import net.sourceforge.jeuclid.{MathMLParserSupport, MutableLayoutContext}

import scala.xml.transform.{RewriteRule, RuleTransformer}
import scala.xml.{Elem, Node}

/**
 * Created by aldo on 6/11/14.
 */
object Output {

  def readTemplate(file: File): String = scala.io.Source.fromFile(file).mkString

  def writeOutput(file: File, str: String) = {
    val p = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
    p.write(str)
    p.close()
  }

  def convertMathML2PNG(id: String, mathML: String) = {
    val file: File = new File("results/images", id + ".png")
    if (!file.exists()) {
      val doc = MathMLParserSupport.parseString(mathML)

      val params: MutableLayoutContext = new LayoutContextImpl(
        LayoutContextImpl.getDefaultLayoutContext)
      params.setParameter(Parameter.MATHSIZE, 25f)
      try {
        Converter.getInstance.convert(doc, file, "image/png", params)
      } catch {
        case e: Exception => e.printStackTrace()
      }
    }
  }

  def printMathTemplate4(out: File, title: String, query: (List[Node], String), tr1: String, r1: List[(String, scala.xml.Node)], tr2: String, r2: List[(String, scala.xml.Node)], tr3: String, r3: List[(String, scala.xml.Node)], tr4: String, r4: List[(String, List[(String, Float, String)])]) {
    val template = readTemplate(Resources.MATH_TEMPLATE)

    val esR1 = r1.filter(_ != null).map(e => {
      val pngName = (e._2 \ "@id").text
      convertMathML2PNG(pngName, e._2.toString)
      val img =
      MathTemplate.ITEM.replace(MathTemplate.VOID, e._1 + "
" + img.toString)
    }).mkString
    val liR1 = MathTemplate.LIST.replace(MathTemplate.VOID, esR1)
    val esR2 = r2.map(e => {
      val pngName = (e._2 \ "@id").text
      convertMathML2PNG(pngName, e._2.toString)
      val img =
      MathTemplate.ITEM.replace(MathTemplate.VOID, e._1 + "
" + img.toString)
    }).mkString
    val liR2 = MathTemplate.LIST.replace(MathTemplate.VOID, esR2)
    val esR3 = r3.map(e => {
      val pngName = (e._2 \ "@id").text
      convertMathML2PNG(pngName, e._2.toString)
      val img =
      MathTemplate.ITEM.replace(MathTemplate.VOID, e._1 + "
" + img.toString)
    }).mkString
    val liR3 = MathTemplate.LIST.replace(MathTemplate.VOID, esR3)
    val esR4 = r4.map(e => {
      val pngs = (for (p <- e._2) yield {
        val xml = scala.xml.XML.loadString(p._3)
        val pngName = (xml \ "@id").text
        convertMathML2PNG(pngName, p._3)
        p._1 + "
" + p._2 + "
" + ().toString
      }).mkString("
")
      MathTemplate.ITEM.replace(MathTemplate.VOID, e._1 + "
" + pngs)
    }).mkString
    val liR4 = MathTemplate.LIST.replace(MathTemplate.VOID, esR4)

    val res = template
      .replace(MathTemplate.TITLE, title)
      .replace(MathTemplate.QUERY, {
      //val pngName = out.getName
      //convertMathML2PNG(pngName, query._1.toString)
      //val img =
      val queryStr = query._1.map(_.toString()).mkString("-")
      MathTemplate.ITEM.replace(MathTemplate.VOID, queryStr + " keywords:" + query._2)
    })
      .replace(MathTemplate.TR1, tr1)
      .replace(MathTemplate.R1, liR1)
      .replace(MathTemplate.TR2, tr2)
      .replace(MathTemplate.R2, liR2)
      .replace(MathTemplate.TR3, tr3)
      .replace(MathTemplate.R3, liR3)
      .replace(MathTemplate.TR4, tr4)
      .replace(MathTemplate.R4, liR4)
    writeOutput(out, res)
  }

  def printXMLTextResult(out: File, label: String, query: (String, String, List[Node]), results: List[(String, Float, Node)]) = {
    val res =
      <result>
        <name>
          {label}
        </name>
        <query>
          <id>
            {query._1}
          </id>
          <content>
            {query._2}
          </content>
          <original>
            {for (i <- 0 until query._3.size) yield {
            <elem>
              {query._3(i)}
            </elem>
          }}
          </original>
        </query>
        <list>
          {for (result <- results) yield {
          <document>
            <id>
              {result._1}
            </id>
            <score>
              {result._2}
            </score>
            <original>
              {result._3}
            </original>
          </document>
        }}
        </list>
      </result>

    writeOutput(out, res.toString)
  }

  def printXMLFormulaResult(out: File, label: String, query: (String, String, List[Node]), results: List[(String, Float, Node)]) = {

    object MathmaticaRulesCSymbolTransform extends RewriteRule {
      override def transform(n: Node): Seq[Node] = n match {
        case <csymbol>
          {v}
          </csymbol> => {
          /*println(v.text);*/ <csymbol>
            {v.text.replaceAllLiterally("-", "\\[Dash]")}
          </csymbol>
        }
        case other => other
      }
    }

    object MathmaticaRulesCSymbol extends RuleTransformer(MathmaticaRulesCSymbolTransform)

    object MathmaticaRulesTransform extends RewriteRule {
      override def transform(n: Node): Seq[Node] = n match {
        case sn@Elem(_, _, _, _, _*) => MathmaticaRulesCSymbol(sn)
        case other => other
      }
    }

    object MathmaticaRules extends RuleTransformer(MathmaticaRulesTransform)

    def replacingValuesForMathematica(xml: Node): Node = {
      (MathmaticaRules transform xml).head
    }
    val res =
      <result>
        <name>
          {label}
        </name>
        <query>
          <id>
            {query._1}
          </id>
          <content>
            {query._2}
          </content>
          <original>
            {for (i <- 0 until query._3.size) yield {
            <elem>
              {query._3(i)}
            </elem>
          }}
          </original>
        </query>
        <list>
          {for (result <- results) yield {
          <document>
            <id>
              {result._1}
            </id>
            <score>
              {result._2}
            </score>
            <original>
              {result._3}
            </original>
            <subforumulas>
              {val annotationSeqXML = (result._3 \\ "annotation-xml")
            if (annotationSeqXML.nonEmpty) {
              val annotationXML = annotationSeqXML.head
              //println(annotationXML)
              val subformulas = TreeTokenizer.formulaTokenizerSubgroup(annotationXML).drop(1)
              //println(subformulas.size, subformulas)
              for (subformula <- subformulas) yield {
                <subformula>
                  <math id={(result._3 \ "@id").text} class="ltx_Math" xmlns="http://www.w3.org/1998/Math/MathML">
                    <semantics>
                      <annotation-xml>
                        {replacingValuesForMathematica(subformula)}
                      </annotation-xml>
                    </semantics>
                  </math>
                </subformula>
              }
            }}
            </subforumulas>
          </document>
        }}
        </list>
      </result>

    writeOutput(out, res.toString)
  }

  def printMath2NTCIR(groupID: String, runID: String, results: Map[String, List[(String, Float)]]) = {
    val formatter = new java.text.DecimalFormat("#.##########")
    val runTag = groupID + "_" + runID
    val out = new File("results/", runTag)
    //println(results.keys.toList)
    val sortedResults = results.keys.toList.sortBy(_.split("-")(2).toFloat)
    val res =
      (for (topic <- sortedResults) yield {
        val sortedList = results.get(topic).get.sortBy(-_._2)
        (for (i <- 0 until Math.min(sortedList.length, 1000)) yield {
          s"$topic 1 ${sortedList(i)._1} ${i + 1} ${formatter.format(sortedList(i)._2)} $runTag"
        }).mkString("\n")
      }).mkString("\n") + "\n"

    writeOutput(out, res)
  }

  def printMath2NTCIRWiki(groupID: String, runID: String, results: Map[String, List[(String, Float)]]) = {
    val formatter = new java.text.DecimalFormat("#.##########")
    val runTag = groupID + "_" + runID
    val out = new File("results/", runTag)
    val sortedResults = if (results.keys.head.contains("-"))
      results.keys.toList.sortBy(_.split("-")(2).toFloat)
    else
      results.keys.toList.sortBy(_.toFloat)

    val res =
      (for (topic <- sortedResults) yield {
        val sortedList = results.get(topic).get.sortBy(-_._2)
        (for (i <- 0 until Math.min(sortedList.length, 1000)) yield {
          s"$topic,${sortedList(i)._1}"
        }).mkString("\n")
      }).mkString("\n") + "\n"

    writeOutput(out, "queryId,formulaId\n" + res)
  }

  def printMathQRelsTemplate(out: File, title: String, r: List[(String, Int, List[(String, String)])]) {
    val template = readTemplate(Resources.MATH_QRELS_TEMPLATE)
    val esR = r.map(e => {
      val pngs = if (e._3 != null)
        (for (p <- e._3) yield {
          try {
            val xml = scala.xml.XML.loadString(p._2)
            val pngName = (xml \ "@id").text

            convertMathML2PNG(pngName, p._2)
            "
" + p._1 + "	" + ().toString + "
"
          } catch {
            case e: Exception => "
" + p._1 + "	" + e.getMessage + "
"
          }
        }).mkString
      else null

      val tablePngs =
        if (e._3 != null) {
          MathTemplate.TABLE.replace(MathTemplate.VOID, pngs.mkString)
        } else {
          "Document doesn't exist!"
        }
      MathTemplate.COL.replace(
        MathTemplate.VOID,
        MathTemplate.PANEL
          .replace(MathTemplate.TITLE, e._1)
          .replace(MathTemplate.CONTENT, tablePngs)
          .replace(MathTemplate.STYLE_HEADING, "background-color: " + (if (e._2 == 0) MathTemplate.RED_GRADING(0) else MathTemplate.GREEN_GRADING(e._2 - 1)) + "!important"))
    })

    val liR = esR.grouped(2).map(l => MathTemplate.ROW.replace(MathTemplate.VOID, l.mkString)).mkString

    val res = template
      .replace(MathTemplate.TITLE, title)
      .replace(MathTemplate.R, liR)
    writeOutput(out, res)
  }
}


text:
<?php

class Twig_Tests_Node_Expression_NullCoalesceTest extends Twig_Test_NodeTestCase
{
    public function getTests()
    {
        $left = new Twig_Node_Expression_Name('foo', 1);
        $right = new Twig_Node_Expression_Constant(2, 1);
        $node = new Twig_Node_Expression_NullCoalesce($left, $right, 1);

        return [[$node, "((// line 1\n\$context[\"foo\"]) ?? (2))"]];
    }
}


text:
import { queryDomainAddresses } from '@proton/shared/lib/api/domains';
import queryPages from '@proton/shared/lib/api/helpers/queryPages';

import { cachedPromise } from './helpers/cachedPromise';
import useApi from './useApi';
import useCache from './useCache';
import usePromiseResult from './usePromiseResult';

export const getAllDomainAddresses = (api, domainID) => {
    return queryPages((page, pageSize) => {
        return api(
            queryDomainAddresses(domainID, {
                Page: page,
                PageSize: pageSize,
            })
        );
    }).then((pages) => {
        return pages.flatMap(({ Addresses = [] }) => Addresses);
    });
};

const useDomainsAddresses = (domains) => {
    const cache = useCache();
    const api = useApi();

    return usePromiseResult(async () => {
        if (!Array.isArray(domains)) {
            return;
        }

        const domainAddresses = await Promise.all(
            domains.map((domain) => {
                return cachedPromise(
                    cache,
                    `${domain.ID}`,
                    () => {
                        return getAllDomainAddresses(api, domain.ID);
                    },
                    domain
                );
            })
        );

        return domains.reduce((acc, { ID }, i) => {
            return {
                ...acc,
                [ID]: domainAddresses[i],
            };
        }, {});
    }, [domains]);
};

export default useDomainsAddresses;


text:
#include "chilkatDefs.h"

#include "CkString.h"
#include "CkWideCharBase.h"

#if !defined(__sun__) && !defined(__sun)
#pragma pack (push, 8)
#endif

// CLASS: CkDtObjW
class CK_VISIBLE_PUBLIC CkDtObjW  : public CkWideCharBase
{
    private:

	// Don't allow assignment or copying these objects.
	CkDtObjW(const CkDtObjW &);
	CkDtObjW &operator=(const CkDtObjW &);

    public:
	CkDtObjW(void);
	virtual ~CkDtObjW(void);

	static CkDtObjW *createNew(void);

	void CK_VISIBLE_PRIVATE inject(void *impl);

	// May be called when finished with the object to free/dispose of any
	// internal resources held by the object.
	void dispose(void);

	// BEGIN PUBLIC INTERFACE

	// ----------------------
	// Properties
	// ----------------------
	// The day of the month. The valid values for this member are 1 through 31.
	int get_Day(void);
	// The day of the month. The valid values for this member are 1 through 31.
	void put_Day(int newVal);

	// The hour. The valid values for this member are 0 through 23.
	int get_Hour(void);
	// The hour. The valid values for this member are 0 through 23.
	void put_Hour(int newVal);

	// The minute. The valid values for this member are 0 through 59.
	int get_Minute(void);
	// The minute. The valid values for this member are 0 through 59.
	void put_Minute(int newVal);

	// The month. The valid values for this member are 1 through 12 where 1 = January
	// and 12 = December.
	int get_Month(void);
	// The month. The valid values for this member are 1 through 12 where 1 = January
	// and 12 = December.
	void put_Month(int newVal);

	// The second. The valid values for this member are 0 through 59.
	int get_Second(void);
	// The second. The valid values for this member are 0 through 59.
	void put_Second(int newVal);

	// The month. The valid values for this member are 0 through 11 where 0 = January
	// and 11 = December.
	int get_StructTmMonth(void);
	// The month. The valid values for this member are 0 through 11 where 0 = January
	// and 11 = December.
	void put_StructTmMonth(int newVal);

	// The year represented as the number of years since 1900.
	int get_StructTmYear(void);
	// The year represented as the number of years since 1900.
	void put_StructTmYear(int newVal);

	// true if this is a UTC time, otherwise false if this is a local time.
	bool get_Utc(void);
	// true if this is a UTC time, otherwise false if this is a local time.
	void put_Utc(bool newVal);

	// The year, such as 2012.
	int get_Year(void);
	// The year, such as 2012.
	void put_Year(int newVal);

	// ----------------------
	// Methods
	// ----------------------
	// Loads the date/time with a string having the format as produced by the Serialize
	// method, which is a string of SPACE separated integers containing (in this order)
	// year, month, day, hour, minutes, seconds, and a UTC flag having the value of
	// 1/0.
	void DeSerialize(const wchar_t *serializedDtObj);

	// Serializes the date/time to a us-ascii string that can be imported at a later
	// time via the DeSerialize method. The format of the string returned by this
	// method is not intended to match any published standard. It is formatted to a
	// string with SPACE separated integers containing (in this order) year, month,
	// day, hour, minutes, seconds, and a UTC flag having the value of 1/0.
	bool Serialize(CkString &outStr);
	// Serializes the date/time to a us-ascii string that can be imported at a later
	// time via the DeSerialize method. The format of the string returned by this
	// method is not intended to match any published standard. It is formatted to a
	// string with SPACE separated integers containing (in this order) year, month,
	// day, hour, minutes, seconds, and a UTC flag having the value of 1/0.
	const wchar_t *serialize(void);

	// END PUBLIC INTERFACE

};
#if !defined(__sun__) && !defined(__sun)
#pragma pack (pop)
#endif

#endif


text: module WearyExaminer.SensorServer.TimeSeries where


text:
import unittest
from doctest import DocTestSuite
from test import support
import weakref
import gc

# Modules under test
_thread = support.import_module('_thread')
threading = support.import_module('threading')
import _threading_local

class Weak(object):
    pass

def target(local, weaklist):
    weak = Weak()
    local.weak = weak
    weaklist.append(weakref.ref(weak))

class BaseLocalTest:

    def test_local_refs(self):
        self._local_refs(20)
        self._local_refs(50)
        self._local_refs(100)

    def _local_refs(self, n):
        local = self._local()
        weaklist = []
        for i in range(n):
            t = threading.Thread(target=target, args=(local, weaklist))
            t.start()
            t.join()
        del t

        gc.collect()
        self.assertEqual(len(weaklist), n)

        # XXX _threading_local keeps the local of the last stopped thread alive.
        deadlist = [weak for weak in weaklist if weak() is None]
        self.assertIn(len(deadlist), (n-1, n))

        # Assignment to the same thread local frees it sometimes (!)
        local.someothervar = None
        gc.collect()
        deadlist = [weak for weak in weaklist if weak() is None]
        self.assertIn(len(deadlist), (n-1, n), (n, len(deadlist)))

    def test_derived(self):
        # Issue 3088: if there is a threads switch inside the __init__
        # of a threading.local derived class, the per-thread dictionary
        # is created but not correctly set on the object.
        # The first member set may be bogus.
        import time
        class Local(self._local):
            def __init__(self):
                time.sleep(0.01)
        local = Local()

        def f(i):
            local.x = i
            # Simply check that the variable is correctly set
            self.assertEqual(local.x, i)

        threads= []
        for i in range(10):
            t = threading.Thread(target=f, args=(i,))
            t.start()
            threads.append(t)

        for t in threads:
            t.join()

    def test_derived_cycle_dealloc(self):
        # http://bugs.python.org/issue6990
        class Local(self._local):
            pass
        locals = None
        passed = False
        e1 = threading.Event()
        e2 = threading.Event()

        def f():
            nonlocal passed
            # 1) Involve Local in a cycle
            cycle = [Local()]
            cycle.append(cycle)
            cycle[0].foo = 'bar'

            # 2) GC the cycle (triggers threadmodule.c::local_clear
            # before local_dealloc)
            del cycle
            gc.collect()
            e1.set()
            e2.wait()

            # 4) New Locals should be empty
            passed = all(not hasattr(local, 'foo') for local in locals)

        t = threading.Thread(target=f)
        t.start()
        e1.wait()

        # 3) New Locals should recycle the original's address. Creating
        # them in the thread overwrites the thread state and avoids the
        # bug
        locals = [Local() for i in range(10)]
        e2.set()
        t.join()

        self.assertTrue(passed)

    def test_arguments(self):
        # Issue 1522237
        class MyLocal(self._local):
            def __init__(self, *args, **kwargs):
                pass

        MyLocal(a=1)
        MyLocal(1)
        self.assertRaises(TypeError, self._local, a=1)
        self.assertRaises(TypeError, self._local, 1)

    def _test_one_class(self, c):
        self._failed = "No error message set or cleared."
        obj = c()
        e1 = threading.Event()
        e2 = threading.Event()

        def f1():
            obj.x = 'foo'
            obj.y = 'bar'
            del obj.y
            e1.set()
            e2.wait()

        def f2():
            try:
                foo = obj.x
            except AttributeError:
                # This is expected -- we haven't set obj.x in this thread yet!
                self._failed = ""  # passed
            else:
                self._failed = ('Incorrectly got value %r from class %r\n' %
                                (foo, c))
                sys.stderr.write(self._failed)

        t1 = threading.Thread(target=f1)
        t1.start()
        e1.wait()
        t2 = threading.Thread(target=f2)
        t2.start()
        t2.join()
        # The test is done; just let t1 know it can exit, and wait for it.
        e2.set()
        t1.join()

        self.assertFalse(self._failed, self._failed)

    def test_threading_local(self):
        self._test_one_class(self._local)

    def test_threading_local_subclass(self):
        class LocalSubclass(self._local):
            """To test that subclasses behave properly."""
        self._test_one_class(LocalSubclass)

    def _test_dict_attribute(self, cls):
        obj = cls()
        obj.x = 5
        self.assertEqual(obj.__dict__, {'x': 5})
        with self.assertRaises(AttributeError):
            obj.__dict__ = {}
        with self.assertRaises(AttributeError):
            del obj.__dict__

    def test_dict_attribute(self):
        self._test_dict_attribute(self._local)

    def test_dict_attribute_subclass(self):
        class LocalSubclass(self._local):
            """To test that subclasses behave properly."""
        self._test_dict_attribute(LocalSubclass)

    def test_cycle_collection(self):
        class X:
            pass

        x = X()
        x.local = self._local()
        x.local.x = x
        wr = weakref.ref(x)
        del x
        gc.collect()
        self.assertIs(wr(), None)

class ThreadLocalTest(unittest.TestCase, BaseLocalTest):
    _local = _thread._local

class PyThreadingLocalTest(unittest.TestCase, BaseLocalTest):
    _local = _threading_local.local

def test_main():
    suite = unittest.TestSuite()
    suite.addTest(DocTestSuite('_threading_local'))
    suite.addTest(unittest.makeSuite(ThreadLocalTest))
    suite.addTest(unittest.makeSuite(PyThreadingLocalTest))

    local_orig = _threading_local.local
    def setUp(test):
        _threading_local.local = _thread._local
    def tearDown(test):
        _threading_local.local = local_orig
    suite.addTest(DocTestSuite('_threading_local',
                               setUp=setUp, tearDown=tearDown)
                  )

    support.run_unittest(suite)

if __name__ == '__main__':
    test_main()


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="author" content="Douglas Thompson" />
        <meta name="copyright" content="Douglas Thompson" />

<meta name="keywords" content="Algorithms, Mathematics, Optimization, Data Structures, Programming, " />
        <title>Combinations without Replacement - Brainscrape
</title>
        <link href="http://cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
        <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
        <link rel="stylesheet" type="text/css" href="./theme/css/style.css" media="screen">
        <link rel="stylesheet" type="text/css" href="./theme/css/solarizedlight.css" media="screen">
        <link rel="shortcut icon" href="./theme/images/favicon.ico" type="image/x-icon" />
        <link rel="apple-touch-icon" href="./theme/images/apple-touch-icon.png" />
        <link rel="apple-touch-icon" sizes="57x57" href="./theme/images/apple-touch-icon-57x57.png" />
        <link rel="apple-touch-icon" sizes="72x72" href="./theme/images/apple-touch-icon-72x72.png" />
        <link rel="apple-touch-icon" sizes="114x114" href="./theme/images/apple-touch-icon-114x114.png" />
        <link rel="apple-touch-icon" sizes="144x144" href="./theme/images/apple-touch-icon-144x144.png" />
        <link rel="icon" href="./theme/images/apple-touch-icon-144x144.png" />

                    Brainscrape

Home

About Me

Categories

Tags

Archives

<form class="navbar-search" action="./search.html" onsubmit="return validateForm(this.elements['q'].value);"> <input type="text" class="search-query" placeholder="Search" name="q" id="tipue_search_input"></form>

 Combinations without Replacement

Algorithm for Generating Combinations without Replacement

The algorithm this article is based around is nearly trivial, but it was something that tripped me up for a long time.  Thus, I feel compelled to write an article, but I also feel compelled to make it short (well, relatively speaking).

If you want a brief, but more technical overview, be sure to check out the associated YouTube video!  The simple algorithm and boring, abstract problem belie the much more widely applicable nature of the generalized problem.

The Problem

Sometimes you have a collection of things, and you want to select each of the things from the collection, one at a time, in some random order.  You don't want to take the same element twice, however.  How do you end up handling this in an effective way?

The Easy Soltion

One easy way to approach this problem is to simpy remove each element from the collection as you come across them, but which data structure would you use to do this?

You could use a resizable array, but each time you remove an element on average n/2 elements will need to be "shuffled down" in order to ensure the array is contiguous.  This can be an actual serious problem even on modern computers in many cases.

You could use a linked list, but then you'd have to transverse, on average, n/2 elements on average every iteration to find the item to remove.

A hash table might be suitable, but there's a good chance your data isn't in this format already, and you have to deal with the potentially substantial overheads associated with this.

The Good Solution

It turns out that there is a really simple solution to this problem which has nearly no drawbacks with respect to performance or memeory.  It works like this:

Manually maintain an index into the array

Randomly (or however) select an element

Swap this element with the last one in the array

Decrement the index

Return array[index]

Analysis

Should you use this algorithm?  I recently used it in a small program I wrote for finding scalping opportunities in the video game Eve Online.  But should I have?  This is a much harder question to answer.

This algorithm is dead simple

The thing that strikes me the most about this algorithm is that it is insanely simple.  Simply removing the selected element from the list is nearly as difficult!  In fact, there is a commonly used C++ idiom, "swap and pop", which leverages this exact same mechanic for nearly the same reason.

In today's world, this would usually be considered a vomit inducing micro-optimization

Most application programmers live in a world of immutable/persistent data structures and defensive copying.  The idea that an algorithm like this would ever see use in general is probably laughable to most programmers.  In particular, the program that I wrote would select an item at most once every 30 seconds.  Is this sort of optimization needed at all?  Obviously not.

Luckily, in my own side projects I get to do whatever I want!

Again, be sure to check out the associated YouTube video if you can stand it.  This algorithm address one solution to a larger class of problems which you probably encounter on a daily basis.

« Multiple Dispatch

Spitting Headaches and Binary Searches »

Published

            <time pubdate="pubdate" datetime="2015-09-20T00:00:00+02:00">Sep 20, 2015</time>

Category

            Programming

Tags

Algorithms
                    2

Data Structures
                    1

Mathematics
                    2

Optimization
                    2

Powered by Pelican. Theme: Elegant by Talha Mansoor