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

    <string name="app_name">Leaf Notification</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="action_more_settings">More Settings</string>
    <string name="title_activity_login">LoginActivity</string>
    <string name="title_activity_settings">Settings</string>
    <string name="action_signout">Sign out</string>
    <string name="updatenow">Update Now</string>
    <string name="str_disclaimer">A project by Jonathan Warner (@Jaxbot). Not affiliated with or supported by Nissan.</string>
    <string name="wear_warning">Wear Warning</string>
    <string name="undismissible">Undismissible notifications will not display on connected Wear devices due to current limitations.</string>
    <string name="okay">Okay</string>
    <string name="start_hvac">Start HVAC</string>
    <string name="stop_hvac">Stop HVAC</string>
    <string name="camp_mode">Camp Mode is an experimental feature that will keep your AC on as long as desired, instead of the usual 15 minute limit. This is an experimental feature and while it appears to work in testing, be warned that unexpected behavior may occur. By using this feature, you agree that the developer is not responsible for any damage done to your phone or car, or any other oddities. Do not trust this feature to protect someone who would otherwise be harmed in a hot car.</string>
    <string name="start_camp_mode">Start Camp Mode</string>
    <string name="stop_camp_mode">Stop Camp Mode</string>
    <string name="action_experiments">Experiments</string>
    <string name="battery_too_low">Battery too low</string>
    <string name="battery_too_low_desc">Refusing to start Camp Mode because the car is not charging and current battery bars are below 3. If the car has been plugged in recently, press Update Now on the main screen.</string>

    <string-array name="supported_countries">
        <item>United States</item>
        <item>Canada</item>
    </string-array>
    <string-array name="charge_levels">
        <item>Show Level 1 time when not charging</item>
        <item>Show Level 2 3.3kW time when not charging</item>
        <item>Show Level 2 6.6kW time when not charging</item>
    </string-array>

    <string name="title_activity_experiments">Experiments</string>

    <string name="charge_status_charging">Charging, %1$still full [%2$s]</string>
    <string name="charge_status_not_charging">%1$sto charge [%2$s]</string>
    <string name="charge_status_battery_bars">%1$d of 12</string>

</resources>


text:
package org.hbase.async;

import com.stumbleupon.async.Deferred;

/**
 * This exception notifies the application to throttle its use of HBase.
 *

 * Since all APIs of {@link HBaseClient} are asynchronous and non-blocking,
 * it's possible that the application would produce RPCs at a rate higher
 * than HBase is able to handle.  When this happens, {@link HBaseClient}
 * will typically do some buffering up to a certain point beyond which RPCs
 * will fail-fast with this exception, to prevent the application from
 * running itself out of memory.
 *

 * This exception is expected to be handled by having the application
 * throttle or pause itself for a short period of time before retrying the
 * RPC that failed with this exception as well as before sending other RPCs.
 * The reason this exception inherits from {@link NonRecoverableException}
 * instead of {@link RecoverableException} is that the usual course of action
 * when handling a {@link RecoverableException} is to retry right away, which
 * would defeat the whole purpose of this exception.  Here, we want the
 * application to retry after a reasonable delay as well as throttle
 * the pace of creation of new RPCs.  What constitutes a "reasonable
 * delay" depends on the nature of RPCs and rate at which they're produced.
 * For a write-heavy high-throughput application, this exception will
 * typically be used when HBase is in the process of splitting a region or
 * migrating a region to another server, in which case the application should
 * stop producing new writes for typically at least 1 second (or significantly
 * slow down its pace, to let {@link HBaseClient} buffer the writes).
 *

 * When {@link HBaseClient} buffers RPCs, it typically uses this exception
 * with a low watermark and a high watermark.  When the buffer hits the low
 * watermark, the next (unlucky) RPC that wants to be buffered will be failed
 * with a {@code PleaseThrottleException}, to send an "advisory warning" to
 * the application that it needs to throttle itself.  All subsequent RPCs
 * that need to be buffered will be buffered until the buffer hits the high
 * watermark.  Once the high watermark has been hit, all subsequent RPCs that
 * need to be buffered will fail-fast with a {@code PleaseThrottleException}.
 *

 * One effective strategy to handle this exception is to set a flag to true
 * when this exception is first emitted that causes the application to pause
 * or throttle its use of HBase.  Then you can retry the RPC that failed
 * (which is accessible through {@link #getFailedRpc}) and add a callback to
 * it in order to unset the flag once the RPC completes successfully.
 * Note that low-throughput applications will typically rarely (if ever)
 * hit the low watermark and should never hit the high watermark, so they
 * don't need complex throttling logic.
 */
public final class PleaseThrottleException extends NonRecoverableException
implements HasFailedRpcException {

  /** The RPC that was failed with this exception.  */
  private final HBaseRpc rpc;

  /** A deferred one can wait on before retrying the failed RPC.  */
  private final Deferred deferred;

  /**
   * Constructor.
   * @param msg A message explaining why the application has to throttle.
   * @param cause The exception that requires the application to throttle
   * itself (can be {@code null}).
   * @param rpc The RPC that was made to fail with this exception.
   * @param deferred A deferred one can wait on before retrying the failed RPC.
   */
  PleaseThrottleException(final String msg,
                          final HBaseException cause,
                          final HBaseRpc rpc,
                          final Deferred deferred) {
    super(msg, cause);
    this.rpc = rpc;
    this.deferred = deferred;
  }

  /**
   * The RPC that was made to fail with this exception.
   */
  public HBaseRpc getFailedRpc() {
    return rpc;
  }

  /**
   * Returns a deferred one can wait on before retrying the failed RPC.
   * @since 1.3
   */
  public Deferred getDeferred() {
    return deferred;
  }

  private static final long serialVersionUID = 1286782542;

}

redpajama_set_name: RedPajamaGithub


text:
package seedu.address.logic.commands;

import java.time.LocalDateTime;

import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.commons.util.StringUtil;
import seedu.address.model.Model;
import seedu.address.model.task.DeadlineTask;

/**
 * Adds an deadline task to the task book.
 */
public class AddDeadlineCommand implements AddTaskCommand {

    private static final String MESSAGE_SUCCESS = "Added new deadline task \"%s\", due on \"%s\".";

    private final DeadlineTask deadlineTask;

    public AddDeadlineCommand(DeadlineTask deadlineTask) {
        this.deadlineTask = deadlineTask;
    }

    public AddDeadlineCommand(String name, LocalDateTime due) throws IllegalValueException {
        this(new DeadlineTask(name, due));
    }

    @Override
    public DeadlineTask getTask() {
        return deadlineTask;
    }

    @Override
    public CommandResult execute(Model model) {
        assert model != null;
        model.addDeadlineTask(deadlineTask);
        return new CommandResult(String.format(MESSAGE_SUCCESS, deadlineTask.getName(),
                                               StringUtil.localDateTimeToPrettyString(deadlineTask.getDue())));
    }

}


text:
package test;

import dagger2.Module;
import dagger2.Provides;

@Module
final class DependedModule {
  @Provides
  String provideGreeting() {
    return "Hello world!";
  }
}


text:
//
//  CMSearchView.m
//  CMSearchBar
//
//  Created by 23 on 2017/1/18.
//  Copyright © 2017年 23. All rights reserved.
//

#import "CMSearchView.h"
#import "CMSearchBar.h"

@interface CMSearchView() <UITextFieldDelegate>

@property(nonatomic,weak) CMSearchBar *searchBar;

@end

@implementation CMSearchView
{
    CGFloat _margin;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self customUI];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self customUI];
}

- (void)customUI
{
    //设置边距
    _margin = 10;

    //设置背景
    self.backgroundColor = [UIColor colorWithRed:246/255.0 green:246/255.0 blue:246/255.0 alpha:246/255.0];

    //设置搜索条
    CMSearchBar *searchBar = [[CMSearchBar alloc]init];
    searchBar.delegate = self;
    searchBar.enablesReturnKeyAutomatically = YES;
    searchBar.returnKeyType = UIReturnKeySearch;
    [searchBar addTarget:self action:@selector(searchBarEditingDidBegin) forControlEvents:UIControlEventEditingDidBegin];
    [searchBar addTarget:self action:@selector(searchBarTextChange) forControlEvents:UIControlEventEditingChanged];
    [self addSubview:searchBar];
    self.searchBar = searchBar;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat w = self.frame.size.width;
    CGFloat h = self.frame.size.height;
    self.searchBar.frame = CGRectMake(_margin, _margin, w - 2 * _margin, h - 2 * _margin);
}

#pragma mark - 事件监听
- (void)searchBarEditingDidBegin
{
    if ([self.delegate respondsToSelector:@selector(searchView:didSearchBarEditingDidBegin:)]) {
        [self.delegate searchView:self didSearchBarEditingDidBegin:self.searchBar];
    }
}

- (void)searchBarTextChange
{
    if ([self.delegate respondsToSelector:@selector(searchView:didSearchBarTextChanged:)]) {
        [self.delegate searchView:self didSearchBarTextChanged:self.searchBar];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([self.delegate respondsToSelector:@selector(searchView:didSearchBarReturnKeyClicked:keyword:)]) {
        [self.delegate searchView:self didSearchBarReturnKeyClicked:self.searchBar keyword:textField.text];
    }
    return YES;
}

- (void)setType:(CMSearchViewType)type
{
    _type = type;

    if (type == CMSearchViewTypeNormal) {
        self.searchBar.enabled = YES;
    }else {
        self.searchBar.enabled = NO;
    }

}

#pragma mark - 工具方法
/**获取输入焦点*/
- (void)getInputPoint
{
    [self.searchBar becomeFirstResponder];
}

/**失去输入焦点*/
- (void)resignInputPoint
{
    [self.searchBar resignFirstResponder];
    [self resignFirstResponder];
}

/**设置占位符*/
- (void)setupPlaceholder:(NSString *)placeholder
{
    self.searchBar.placeholder = placeholder;
}

/**设置搜索框关键字*/
- (void)setupSearchKeyword:(NSString *)keyword
{
    self.searchBar.text = keyword;
}

@end


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Shopify SDK for Unity: Shopify.Unity.Blog Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Shopify SDK for Unity

Shopify

Unity

Blog

Public Member Functions |
List of all members

Shopify.Unity.Blog Class Reference

An online store blog.
 More...

Inheritance diagram for Shopify.Unity.Blog:

  <map id="Shopify.Unity.Blog_map" name="Shopify.Unity.Blog_map">
<area href="class_shopify_1_1_unity_1_1_s_d_k_1_1_abstract_response.html" alt="Shopify.Unity.SDK.AbstractResponse" shape="rect" coords="0,0,222,24"/>
<area href="interface_shopify_1_1_unity_1_1_node.html" title="An object with an ID to support global identification." alt="Shopify.Unity.Node" shape="rect" coords="464,0,686,24"/>
  </map>

Public Member Functions

 	Blog (Dictionary< string, object > dataJSON)

 	Accepts deserialized json data.  Will further parse passed in data.  More...

Article 	articleByHandle (string alias=null)

 	Find an article by its handle.  More...

ArticleConnection 	articles (string alias=null)

 	List of the blog's articles.  More...

List< ArticleAuthor > 	authors ()

 	The authors who have contributed to the blog.  More...

string 	handle ()

 	A human-friendly unique string for the Blog automatically generated from its title.  More...

string 	id ()

 	Globally unique identifier.  More...

string 	title ()

 	The blogs's title.  More...

string 	url ()

 	The url pointing to the blog accessible from the web.  More...

object 	Clone ()

Additional Inherited Members

 Protected Member Functions inherited from Shopify.Unity.SDK.AbstractResponse

T 	Get< T > (string field, string alias=null)

 Protected Attributes inherited from Shopify.Unity.SDK.AbstractResponse

Dictionary< string, object > 	Data

 Properties inherited from Shopify.Unity.SDK.AbstractResponse

Dictionary< string, object > 	DataJSON [get, protected set]

Detailed Description

An online store blog.

Constructor & Destructor Documentation

◆ Blog()

          Shopify.Unity.Blog.Blog
          (
          Dictionary< string, object >
          dataJSON	)

inline

Accepts deserialized json data.  Will further parse passed in data.

Parameters

dataJSON	Deserialized JSON data for Blog

Member Function Documentation

◆ articleByHandle()

          Article Shopify.Unity.Blog.articleByHandle
          (
          string
          alias = null	)

inline

Find an article by its handle.

Parameters

alias	If the original field queried was queried using an alias, then pass the matching string.

◆ articles()

          ArticleConnection Shopify.Unity.Blog.articles
          (
          string
          alias = null	)

inline

List of the blog's articles.

Parameters

alias	If the original field queried was queried using an alias, then pass the matching string.

◆ authors()

          List<ArticleAuthor> Shopify.Unity.Blog.authors
          (
          	)

inline

The authors who have contributed to the blog.

◆ handle()

          string Shopify.Unity.Blog.handle
          (
          	)

inline

A human-friendly unique string for the Blog automatically generated from its title.

◆ id()

          string Shopify.Unity.Blog.id
          (
          	)

inline

Globally unique identifier.

Implements Shopify.Unity.Node.

◆ title()

          string Shopify.Unity.Blog.title
          (
          	)

inline

The blogs's title.

◆ url()

          string Shopify.Unity.Blog.url
          (
          	)

inline

The url pointing to the blog accessible from the web.

The documentation for this class was generated from the following file:

Assets/Shopify/Unity/Generated/Blog.cs

<address class="footer">

</address>


text:
<?php

namespace actsmart\actsmart\Actuators\WebChat\Form;

class WebChatFormTextElement extends WebChatFormElement
{
    /**
     * @return array
     */
    public function getData()
    {
        return parent::getData() + [
            'element_type' => 'text'
        ];
    }
}


text:
/**
 * @file autoPlay command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

exports.exec = async (Bastion, message) => {
  if (!message.guild.music.enabled) {
    if (Bastion.user.id === '267035345537728512') {
      return Bastion.emit('error', '', Bastion.i18n.error(message.guild.language, 'musicDisabledPublic'), message.channel);
    }
    return Bastion.emit('error', '', Bastion.i18n.error(message.guild.language, 'musicDisabled'), message.channel);
  }

  let guildModel = await Bastion.database.models.guild.findOne({
    attributes: [ 'musicAutoPlay' ],
    where: {
      guildID: message.guild.id
    }
  });

  let enabled, color, autoPlayStatus;
  if (guildModel.dataValues.musicAutoPlay) {
    enabled = false;
    color = Bastion.colors.RED;
    autoPlayStatus = Bastion.i18n.info(message.guild.language, 'disableMusicAutoPlay', message.author.tag);
  }
  else {
    enabled = true;
    color = Bastion.colors.GREEN;
    autoPlayStatus = Bastion.i18n.info(message.guild.language, 'enableMusicAutoPlay', message.author.tag);
  }

  await Bastion.database.models.guild.update({
    musicAutoPlay: enabled
  },
  {
    where: {
      guildID: message.guild.id
    },
    fields: [ 'musicAutoPlay' ]
  });

  await message.channel.send({
    embed: {
      color: color,
      description: autoPlayStatus
    }
  }).catch(e => {
    Bastion.log.error(e);
  });
};

exports.config = {
  aliases: [],
  enabled: true
};

exports.help = {
  name: 'autoPlay',
  description: 'Toggles auto playing of music.',
  botPermission: '',
  userTextPermission: 'MANAGE_GUILD',
  userVoicePermission: '',
  usage: 'autoPlay',
  example: []
};


text:
package com.clemble.test.random.constructor;

import static com.google.common.base.Preconditions.checkNotNull;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.function.Supplier;

import com.clemble.test.reflection.ReflectionUtils;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;

/**
 * Simple abstraction to keep track of registered PropertySetters.
 *
 * @author Anton Oparin
 *
 */
final public class ClassPropertySetterRegistry {

    /**
     * Registered PropertySetters collection
     */
    final private SortedSet<ClassPropertySetter<?>> propertySelectors = new TreeSet<ClassPropertySetter<?>>(ClassPropertySetter.COMPARE_PRESENTATION_TYPE);

    /**
     * Registered abstract PropertySetters collection
     */
    final private Set<AbstractPropertySetter<?>> abstractPropertySelectors = new HashSet<AbstractPropertySetter<?>>();

    /**
     * Registers specified Property in PropertySelectors list.
     *
     * @param propertySelector
     *            PropertySelector to add.
     */
    public void addSpecificProperties(ClassPropertySetter<?> propertySelector) {
        propertySelectors.remove(propertySelector);
        propertySelectors.add(propertySelector);
    }

    /**
     * Retrieves Collection of applicable PropertySetters from the List.
     *
     * @param applicableClass
     *            Class on which register happens.
     * @return Collection of PropertySetters applicable to the provided Class.
     */
    public Collection<ClassPropertySetter<?>> getApplicableProperties(final ClassAccessWrapper<?> applicableClass) {
        // Step 1. Filter all properties
        Collection<ClassPropertySetter<?>> applicableSelectors = Collections2.filter(propertySelectors, new Predicate<ClassPropertySetter<?>>() {
            @Override
            public boolean apply(ClassPropertySetter<?> selector) {
                return applicableClass.canReplace(selector.getAffectedClass());
            }
        });
        // Step 2. Filter all abstract properties
        for (AbstractPropertySetter<?> abstractProperty: abstractPropertySelectors) {
            if(abstractProperty.isApplicable(applicableClass)) {
                ClassPropertySetter<?> propertySetter = constructSetter(applicableClass.getSourceClass(), abstractProperty.getName(), abstractProperty.getValueGenerator());
                if(propertySetter != null)
                    applicableSelectors.add(propertySetter);
            }
        }
        // Step 3. Returning result set to the
        List<ClassPropertySetter<?>> sortedSelectors = new ArrayList<ClassPropertySetter<?>>(applicableSelectors);
        return sortedSelectors;
    }

    /**
     * Registers {@link java.util.concurrent.Callable} for specified field/method in the Class, all subClasses will use this register as well.
     *
     * @param searchClass
     *            Class to search.
     * @param name
     *            field/method name
     * @param valueGenerator
     *            {@link Callable} to use.
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public <T> void register(final Class<?> searchClass, final String name, final Supplier<T> valueGenerator) {
        if ((searchClass.getModifiers() & (Modifier.ABSTRACT | Modifier.INTERFACE)) > 0) {
            abstractPropertySelectors.add(new AbstractPropertySetter(searchClass, name, valueGenerator));
        } else {
            addSpecificProperties(constructSetter(searchClass, name, valueGenerator));
        }
    }

    private <T> ClassPropertySetter<T> constructSetter(final Class<?> searchClass, final String name, final Supplier<T> valueGenerator) {
        final String possibleName = name.toLowerCase();
        final ClassAccessWrapper<?> wrapper = ClassAccessWrapper.createAllMethodsAccessor(searchClass);
        final Field possibleField = ReflectionUtils.findField(wrapper, possibleName);
        final Method possibleMethod = ReflectionUtils.findSetMethod(wrapper, possibleName);

        ClassPropertySetter<T> propertySetter = ClassPropertySetter.create(wrapper, possibleField, possibleMethod, valueGenerator);

        return propertySetter;
    }

    public static class AbstractPropertySetter<T> {
        final private Class<?> searchClass;
        final private String name;
        final private Supplier<T> valueGenerator;

        public AbstractPropertySetter(Class<?> searchClass, String name, Supplier
                <T> valueGenerator) {
            assert (searchClass.getModifiers() & (Modifier.ABSTRACT | Modifier.INTERFACE)) > 0;
            this.searchClass = checkNotNull(searchClass);
            this.name = checkNotNull(name);
            this.valueGenerator = checkNotNull(valueGenerator);
        }

        public boolean isApplicable(final ClassAccessWrapper<?> applicableClass) {
            return searchClass.isAssignableFrom(applicableClass.getSourceClass());
        }

        public String getName() {
            return name;
        }

        public Supplier<T> getValueGenerator() {
            return valueGenerator;
        }
    }

}


text:
{% extends 'base.html' %}
{% from 'navbar.html' import navbar %}
{% from 'common.html' import decimal_field_vertical %}

{% block navbar %}
{{ navbar(processdata) }}
{% endblock %}

{% block script %}
<link rel="stylesheet" href="/static/jqwidgets/jqwidgets/styles/jqx.base.css" type="text/css"/>

{% endblock %}

{% block main %}

          Überblick

            <form class="form" method="post">
              {{ form.hidden_tag() }}
              {{ decimal_field_vertical(form.setpoint, '°C') }}
            </form>

          Aktuelles Rezept:{% if current_receipe %} {{ current_receipe.name }}{% endif %}
          <button class="btn btn-primary pull-right btn-xs">Run</button>

      {% if current_receipe %}

          Schritt
          Temperatur
          Dauer

        {% for step in current_receipe.steps %}

          {{ step.name }}
          {{ step.setpoint }} °C
          {{ step.duration }} Min.

        {% endfor %}

      {% endif %}

 Verlauf

{% endblock %}


text:
package org.adligo.fabricate.models.fabricate;

import org.adligo.fabricate.common.system.FabricateDefaults;
import org.adligo.fabricate.xml.io_v1.fabricate_v1_0.JavaType;

public class JavaSettings implements I_JavaSettings {
  private final String xms_;
  private final String xmx_;
  private final int threads_;

  public JavaSettings(I_JavaSettings other) {
    threads_ = other.getThreads();
    xms_ = other.getXms();
    xmx_ = other.getXmx();
  }

  public JavaSettings(JavaType java) {
    this(new JavaSettingsMutant(java));
  }

  /* (non-Javadoc)
   * @see org.adligo.fabricate.models.fabricate.I_JavaSettings#getThreads()
   */
  @Override
  public int getThreads() {
    if (threads_ == 0) {
      return FabricateDefaults.JAVA_THREADS;
    }
    return threads_;
  }

  /* (non-Javadoc)
   * @see org.adligo.fabricate.models.fabricate.I_JavaSettings#getXmx()
   */
  @Override
  public String getXms() {
    if (xms_ == null) {
      return FabricateDefaults.JAVA_XMS_DEFAULT;
    }
    return xms_;
  }

  public String getXmx() {
    if (xmx_ == null) {
      return FabricateDefaults.JAVA_XMX_DEFAULT;
    }
    return xmx_;
  }

}


text:
#timer code to calculate how long processes take to run
class Stopwatch
  @@start_time = 0
  @@elapsed_time = 0
  @@average_times = []
  #method that counts how long a block takes to run
  def timed(&block)
    @@start_time = Time.now
    Thread.new(&block).join
    @@elapsed_time = Time.now - @@start_time
    @@average_times.push(@@elapsed_time)
  end
  #return average time of mulitple executions
  def average
    return @@average_times.inject(:+).to_f / @@average_times.size
  end

  #method that takes an input block and executes exec_num of times
  def execute(exec_num, &block)
    exec_num.times do timed(&block)
    end
  end
end

#example usage to illustrate the effeciency of symbol lookups versus string lookup

ta = Stopwatch.new
ta.execute(1000) {10000.times {:foo.equal? :foo }}
puts "the average time was #{ta.average}"
tb = Stopwatch.new
tb.execute(1000) {10000.times {"foo".equal? "foo"}}
puts "the average time was #{tb.average}"


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CTS.W._150501.Models.Domain.Model.Client.ContactUs;
using CTS.Com.Domain.Helper;
using CTS.W._150501.Models.Domain.Object.Client.Main;
using CTS.W._150501.Models.Domain.Dao.Client;
using CTS.Data.APLocales.Domain.Utils;
using CTS.Data.Domain.Constants;
using CTS.Web.Com.Domain.Helper;
using CTS.W._150501.Models.Domain.Common.Constants;
using CTS.Data.APStorageFiles.Domain.Utils;
using CTS.Com.Domain.Constants;
using CTS.Com.Domain.Exceptions;
using CTS.Com.Domain.Model;
using CTS.Data.MACompanyInfos.Domain.Utils;
using CTS.Data.APSEOInfos.Domain.Utils;
using CTS.W._150501.Models.Resources.Strings;

namespace CTS.W._150501.Models.Domain.Logic.Client.ContactUs
{
    /// <summary>
    /// InitLogic
    /// </summary>
    public class SendMailLogic
    {
        #region Execute Method
        /// <summary>
        /// Xử lý init.
        /// </summary>
        /// <param name="inputObject">DataModel</param>
        /// <returns>DataModel</returns>
        public SendMailDataModel Execute(SendMailDataModel inputObject)
        {
            // Kiểm tra thông tin
            Check(inputObject);
            // Lấy thông tin
            var resultObject = SendInfo(inputObject);
            // Kết quả trả về
            return resultObject;
        }
        #endregion

        #region Private Method
        /// <summary>
        /// Kiểm tra thông tin.
        /// </summary>
        /// <param name="inputObject">DataModel</param>
        private void Check(SendMailDataModel inputObject)
        {

        }

        /// <summary>
        /// Lấy thông tin.
        /// </summary>
        /// <param name="inputObject">DataModel</param>
        /// <returns>DataModel</returns>
        private SendMailDataModel SendInfo(SendMailDataModel inputObject)
        {
            // Khởi tạo biến cục bộ
            var getResult = new SendMailDataModel();
            var companyCom = new CompanyCom();
            // Map dữ liệu
            DataHelper.CopyObject(inputObject, getResult);
            // Lấy thông tin dữ liệu
            var fileTemplate = FileHelper.ToString(PageHelper.MapPath("/stg/tmpl/email/contact-us.html"));
            var emailAddress = companyCom.GetString(WebContextHelper.LocaleCd, W150501Logics.CD_INFO_CD_EMAIL_ADDRESS, false);
            var hostEmailAddress = companyCom.GetString(WebContextHelper.LocaleCd, W150501Logics.CD_INFO_CD_EMAIL_HOST, false);
            var subject = Names.CLN_CONTACT_00001;
            var body = new StringBuilder(fileTemplate);
            body.Replace("{Name}", inputObject.Name);
            body.Replace("{Phone}", inputObject.Phone);
            body.Replace("{Email}", inputObject.Email);
            body.Replace("{Description}", inputObject.Description);
            // Tiến hành send mail
            MailHelper.SendMail(inputObject.Email, emailAddress, subject, body.ToString(), hostEmailAddress);
            // Kết quả trả về
            return getResult;
        }
        #endregion
    }
}


text:
| Name              | Contact Information | Areas of Expertise  | Group Affiliations     |
| ----------------- |:-------------------:| -------------------:| ---------------------: |
| Lorena Mesa       | me@lorenamesa.com   | CFP, Code of Conduct| PyLadies Chicago, PSF	 |
| David Wolever     | wolever@pycon.ca  / https://twitter.com/wolever   | Green Room, AV, FA, starting from scratch | PyCon Canada, PyCon |
|                   |            		  |      			    |						 |
|                   |               	  |     			    |						 |

#####User Groups

| Name              | Contact Information 		| Location           |
| ----------------- |:------------------------:	| ------------------:|
| Chicago Python    | https://twitter.com/chipy | Chicago, IL USA    |
| Flask-NYC         | organizers@bigapplepy.org | New York, NY USA   |
| Learn Python NYC  | organizers@bigapplepy.org | New York, NY USA   |
| NYC Python        | organizers@bigapplepy.org | New York, NY USA   |
| Python Toronto    | https://twitter.com/pythontoronto | Toronto, CA |
|                   |            		        |      			     |
|                   |               	        |     			     |

#####Conferences

| Name              | Contact Information 		                   | Location            |
| ----------------- |:--------------------------------------------:| ------------------: |
| PyGotham          | organizers@pygotham.org                      | New York, NY USA    |
| PyOhio    		| https://pyohio.org 		                   | Cleveland, OH USA   |
| PyCaribbean       | http://pycaribbean.com/                      | Bayamon, Puerto Rico|
| PyCon Jamaica     | https://www.pythonjam.org.jm/conference-2016 | Kingston, Jamaica   |
| PyCon Canada      | https://pycon.ca                             | Montréal, Canada    |

[Add your name](https://github.com/wolever/pycon_organizers_manual/blob/master/regional_information/north_america.md)!


text:
<TITLE>Review for One False Move (1991)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

One False Move (1991)

reviewed by
Frank Maloney

                              ONE FALSE MOVE
                       A film review by Frank Maloney
                        Copyright 1992 Frank Maloney

     ONE FALSE MOVE is a film directed by Carl Franklin, from a script
by Billy Bob Thornton and Tom Epperson.  It stars Cynda Williams, Bill
Paxton, Michael Beach, and Bill Bob Thornton.  Rated R, for violence,
strong language.

     ONE FALSE MOVE is a quirky and surprising thriller.  It begins with
a scene of horrifying brutality and violence.  One thinks that he or she
has seen this before and knows what is going to follow: vengeance, cops
and druggies, mayhem and high-speed car chases.  But even at the
beginning one knows he or she is in for something different, if just
because of the camerawork that makes one's skin creep.  And then a
sudden change of pace and place, with some comedy thrown in, and the
disorientation is complete.  This is not going to be a routine Hollywood
formula film.

     By the time the film comes to its conclusion, it has widened its
aims and taken charge of a surprisingly broad territory.  Racism,
justice, abuses of all sorts, prejudices, the gap between rural and
urban, all these are fresh as the last headline.  The story is sharp as
a crease, powerfully told, with plenty of twists and turns to keep
anyone off balance.

     The story, by the way, or at least the script, was co-written by
one of the actors, Billy Bob Thornton, who plays a white-trash coke head
who is barely under control at the best of times.  He and his co-writer
Tom Epperson provided a script full of taut writing, tight plotting,
full of energy and discipline.

     The other actors are equally up to the demands of the script as
Thornton.  Cynda William as Fantasia is the touch point, the pivot, of
the story.  It's her mysterious, ambiguous role in the story that
provides the most interest.  She is the worst of the worst, yet driven
by the tenderest of emotions.  She's elegant, beautiful, treacherous,
passive, possessed by more demons that would seem possible to pack into
her small frame.

     Michael Beach is the third member of this particular menage.  An
ex-con with a genius IQ, a passing resemblance to Malcom X, and a taste
for knifework.  He's cold and focused and very scary.

     The cops include Jim Metzler as Dud Cole and Earl Billings as John
McFeely, two LAPD officers who find they have to work with the hickish
Dale "Hurricane" Dixon, played by Bill Paxton.  This is more Paxton's
movie, more Dixon's story, than anyone else's, although the script tries
to fool you into dismissing him as a swaggering rube.  And he is due for
some come-uppances, some course corrections for his life.  At first he
appears irritating, foolish, headstrong, childishly self-involved,
mostly harmless even if thoughtlessly racist and casually abusive of his
powers.  His wife (Natalie Canerday) puts her quiet wisdom on display
when she sums him up with: "Dale doesn't know any better -- he watches
TV.  I read nonfiction."

     Paxton may play Hurricane a little too broadly at first, but in the
latter parts of the film his characterization takes on depth, dimension,
color, and complexity.

     A word of praise should also go to the musical score by Peter
Haycock and Derek Holt and to the photography of James L. Carter.

     Finally, let me say something briefly about the director, Carl
Franklin.  He has managed to give us a portrait of life on both sides of
the color line that is probably unique.  He finds the contact point
between human folly and inhuman crime.  He lets one of the characters
speak a line that rings loud since the LA riots: "Looking guilty is
being guilty for black people."  But he puts it in the mouth of Fantasia
after she has fully joined in her companions crimes.  He is a very
assured director, and I await with pleasure his next film.

     I high recommend ONE FALSE MOVE even at full price.

--
Frank Richard Aloysius Jude Maloney
.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('mapdata', '0049_altitude_area_ramp'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='altitudearea',
            name='maxx',
        ),
        migrations.RemoveField(
            model_name='altitudearea',
            name='maxy',
        ),
        migrations.RemoveField(
            model_name='altitudearea',
            name='minx',
        ),
        migrations.RemoveField(
            model_name='altitudearea',
            name='miny',
        ),
        migrations.RemoveField(
            model_name='altitudemarker',
            name='maxx',
        ),
        migrations.RemoveField(
            model_name='altitudemarker',
            name='maxy',
        ),
        migrations.RemoveField(
            model_name='altitudemarker',
            name='minx',
        ),
        migrations.RemoveField(
            model_name='altitudemarker',
            name='miny',
        ),
        migrations.RemoveField(
            model_name='area',
            name='maxx',
        ),
        migrations.RemoveField(
            model_name='area',
            name='maxy',
        ),
        migrations.RemoveField(
            model_name='area',
            name='minx',
        ),
        migrations.RemoveField(
            model_name='area',
            name='miny',
        ),
        migrations.RemoveField(
            model_name='building',
            name='maxx',
        ),
        migrations.RemoveField(
            model_name='building',
            name='maxy',
        ),
        migrations.RemoveField(
            model_name='building',
            name='minx',
        ),
        migrations.RemoveField(
            model_name='building',
            name='miny',
        ),
        migrations.RemoveField(
            model_name='column',
            name='maxx',
        ),
        migrations.RemoveField(
            model_name='column',
            name='maxy',
        ),
        migrations.RemoveField(
            model_name='column',
            name='minx',
        ),
        migrations.RemoveField(
            model_name='column',
            name='miny',
        ),
        migrations.RemoveField(
            model_name='door',
            name='maxx',
        ),
        migrations.RemoveField(
            model_name='door',
            name='maxy',
        ),
        migrations.RemoveField(
            model_name='door',
            name='minx',
        ),
        migrations.RemoveField(
            model_name='door',
            name='miny',
        ),
        migrations.RemoveField(
            model_name='graphnode',
            name='maxx',
        ),
        migrations.RemoveField(
            model_name='graphnode',
            name='maxy',
        ),
        migrations.RemoveField(
            model_name='graphnode',
            name='minx',
        ),
        migrations.RemoveField(
            model_name='graphnode',
            name='miny',
        ),
        migrations.RemoveField(
            model_name='hole',
            name='maxx',
        ),
        migrations.RemoveField(
            model_name='hole',
            name='maxy',
        ),
        migrations.RemoveField(
            model_name='hole',
            name='minx',
        ),
        migrations.RemoveField(
            model_name='hole',
            name='miny',
        ),
        migrations.RemoveField(
            model_name='lineobstacle',
            name='maxx',
        ),
        migrations.RemoveField(
            model_name='lineobstacle',
            name='maxy',
        ),
        migrations.RemoveField(
            model_name='lineobstacle',
            name='minx',
        ),
        migrations.RemoveField(
            model_name='lineobstacle',
            name='miny',
        ),
        migrations.RemoveField(
            model_name='obstacle',
            name='maxx',
        ),
        migrations.RemoveField(
            model_name='obstacle',
            name='maxy',
        ),
        migrations.RemoveField(
            model_name='obstacle',
            name='minx',
        ),
        migrations.RemoveField(
            model_name='obstacle',
            name='miny',
        ),
        migrations.RemoveField(
            model_name='poi',
            name='maxx',
        ),
        migrations.RemoveField(
            model_name='poi',
            name='maxy',
        ),
        migrations.RemoveField(
            model_name='poi',
            name='minx',
        ),
        migrations.RemoveField(
            model_name='poi',
            name='miny',
        ),
        migrations.RemoveField(
            model_name='ramp',
            name='maxx',
        ),
        migrations.RemoveField(
            model_name='ramp',
            name='maxy',
        ),
        migrations.RemoveField(
            model_name='ramp',
            name='minx',
        ),
        migrations.RemoveField(
            model_name='ramp',
            name='miny',
        ),
        migrations.RemoveField(
            model_name='space',
            name='maxx',
        ),
        migrations.RemoveField(
            model_name='space',
            name='maxy',
        ),
        migrations.RemoveField(
            model_name='space',
            name='minx',
        ),
        migrations.RemoveField(
            model_name='space',
            name='miny',
        ),
        migrations.RemoveField(
            model_name='stair',
            name='maxx',
        ),
        migrations.RemoveField(
            model_name='stair',
            name='maxy',
        ),
        migrations.RemoveField(
            model_name='stair',
            name='minx',
        ),
        migrations.RemoveField(
            model_name='stair',
            name='miny',
        ),
    ]


text:
import React, { Component } from 'react';
import {connect} from 'react-redux';
import Modal from 'react-modal';

import { logIn, closeModal } from '../../actions';

const Login = ({onLogin, onCancel, errorMessage}) => {
  let username, password;
  let handleKeyPress = e => {
    if (e.charCode == 13) {
      onLogin(username.value, password.value);
    }
  }
  return (
    <Modal isOpen={true} contentLabel="Login">

Username:
        <input
          type="text"
          ref={node => username = node}
          placeholder="Username"
          autoFocus
          onKeyPress={handleKeyPress}/>

Password:
        <input
          type="password"
          ref={node => password = node}
          placeholder="Password"
          onKeyPress={handleKeyPress}/>

      {
        errorMessage ?
{errorMessage}
 : null
      }

        <button onClick={() => onLogin(username.value, password.value)} >Login</button>
        <button onClick={() => onCancel()}>Cancel</button>

    </Modal>
  );
};

let mapStateToProps = state => ({
  errorMessage: state.modal.data.error
});

let mapDispatchToProps = dispatch => ({
  onLogin(username, password) {
    dispatch(logIn(username, password, closeModal()));
  },
  onCancel() {
    dispatch(closeModal());
  }
});

let LoginModal = connect(
  mapStateToProps,
  mapDispatchToProps
)(Login);

export default LoginModal;


text:
function graph_job_enumerator(param_file_dir,param_list_file, graph_list_file,...
                                edge_truth_token, edge_truth_server,...
                                node_truth_token, node_truth_server,...
                                varargin)
% graph_job_enumerator Create listfile for all graphs that need to be
%                       created and evaluated
%
% TODO: add notes
%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% (c) [2014] The Johns Hopkins University / Applied Physics Laboratory All Rights Reserved. Contact the JHU/APL Office of Technology Transfer for any additional rights.  www.jhuapl.edu/ott
%
% 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.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    %% Collect all input data
    % columns - nodes: server,token,args
    % rows - edges: server,token,args
    edge_data{1,1} = edge_truth_server;
    edge_data{1,2} = edge_truth_token;
    edge_data{1,3} = [];
    node_data{1,1} = node_truth_server;
    node_data{1,2} = node_truth_token;
    node_data{1,3} = [];
    for ii = 1:length(varargin)
        data = load(varargin{ii});
        if strcmpi(data.edge_or_node,'node') == 1
            % Node algorithm
            % Go through all the tokens and collect info
            for jj = 1:length(data.token_list)
                node_data{size(node_data,1) + 1,1} = data.server_url;
                node_data{size(node_data,1),2} = data.token_list{jj};

                paramMap = [];
                cnt = 1;
                for kk = 1:2:size(data.args,2)
                    vals = data.args{kk+1};
                    if isa(vals,'cell')
                        % cell/string based parameter value
                        paramMap = sprintf('%s%s:%s,',paramMap,data.args{kk},vals{data.set_inds(jj,cnt)});
                    else
                        % number based parameter value
                        paramMap = sprintf('%s%s:%s,',paramMap,data.args{kk},num2str(vals(data.set_inds(jj,cnt))));
                    end
                    cnt = cnt + 1;
                end
                paramMap = paramMap(1:end-1);

                node_data{size(node_data,1),3} = paramMap;
            end
        else
            % Edge algorithm
            % Go through all the tokens and collect info
            for jj = 1:length(data.token_list)
                edge_data{size(edge_data,1) + 1,1} = data.server_url;
                edge_data{size(edge_data,1),2} = data.token_list{jj};

                paramMap = [];
                cnt = 1;
                for kk = 1:2:size(data.args,2)
                    vals = data.args{kk+1};
                    if isa(vals,'cell')
                        % cell/string based parameter value
                        paramMap = sprintf('%s%s:%s,',paramMap,data.args{kk},vals{data.set_inds(jj,cnt)});
                    else
                        % number based parameter value
                        paramMap = sprintf('%s%s:%s,',paramMap,data.args{kk},num2str(vals(data.set_inds(jj,cnt))));
                    end
                    cnt = cnt + 1;
                end
                paramMap = paramMap(1:end-1);

                edge_data{size(edge_data,1),3} = paramMap;
            end
        end
    end

    %% Compute Cell Indicies
    [d1,d2] = meshgrid(1:size(edge_data,1), 1:size(node_data,1));
    cell_inds = [d1(:) d2(:)];

    %% Write out job param data files
    mkdir(param_file_dir);

    param_files = cell(size(cell_inds,1),1);
    graph_job_str = cell(size(cell_inds,1),1);
    for ii = 1:size(cell_inds,1)
        row = cell_inds(ii,1);
        column = cell_inds(ii,2);
        edge_params = edge_data{row,3}; %#ok<NASGU>
        node_params = node_data{column,3}; %#ok<NASGU>
        edge_server = edge_data{row,1};
        edge_token =  edge_data{row,2};
        node_server = node_data{column,1};
        node_token = node_data{column,2};

        % Write out data to be used during report gen
        job_param_filename = fullfile(param_file_dir,...
                                        sprintf('r%d_c%d.mat',row,column));
        param_files{ii} = job_param_filename;
        save(job_param_filename,'row','column','edge_params','node_params',...
            'edge_server','edge_token','node_server','node_token');

        % Create strings for the list file needed by Graph Gen to run all
        % the "cells" in the table
        graph_job_str{ii} = sprintf('%s,%s,%s,%s',edge_token,edge_server,...
                                        node_token,node_server);
    end

    %% Write out job param data list file
    fid = fopen(param_list_file,'wt');
    try
        for ii = 1:size(cell_inds,1)
            fprintf(fid,'%s\n',param_files{ii});
        end
    catch ME
        fclose(fid);
        rethrow(ME);
    end

    fclose(fid);

    %% Write graph gen list file
    fid = fopen(graph_list_file,'wt');
    try
        for ii = 1:size(graph_job_str,1)
            fprintf(fid,'%s\n',graph_job_str{ii});
        end
    catch ME
        fclose(fid);
        rethrow(ME);
    end
    fclose(fid);
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Overs. Kongel. Danske Vidensk. Selsk. Forh. Medlemmers Arbeider 1854:173. 1854

#### Original name
null

### Remarks
null


text:
RSpec.describe Superstructure::ArgumentErrorBuilder do
  let(:builder) { described_class.new }

  describe "#error?" do
    subject { builder.error? }

    context "when at least one error has been added" do
      before do
        builder.add_error(:missing_params, :hello)
      end

      it { should be_truthy }
    end

    context "when no errors have been added" do
      it { should be_falsy }
    end
  end

  it "builds an ArgumentError with all of the added errors" do
    builder.add_error(:extra_params, :alpha)
    builder.add_errors(:missing_params, [:beta, :charlie])

    expect(builder.build).to have_attributes(
      extra_params: [:alpha],
      missing_params: [:beta, :charlie],
      shadowed_params: []
    )
  end
end


text:
*WARNING*: Under active development

This package provides an implementation of the `PROV Data Model <http://www.w3.org/TR/prov-dm/>`_ in Python. It contains a number of sub-modules:

* prov.model: In-memory classes for PROV assertions. `ProvBundle.JSONEncoder` and `ProvBundle.JSONDecoder` provide JSON serialisation and deserialisation for a `ProvBundle` in the `PROV-JSON representation <http://www.w3.org/Submission/prov-json/>`_. In addition, the `prov.model.graph` module exports PROV documents into graphical formats (e.g. PDF, PNG, SVG).

* prov.persistence: A Django app for storing and loading `ProvBundle` instances to/from databases using Django ORM

* prov.tracking: a logging-like module to facilitate tracking provenance in Python programs

See `prov/model/test/examples.py <https://github.com/trungdong/prov/blob/master/prov/model/test/examples.py>`_ for example usages.

Deployment: The package was used to build `ProvStore <https://provenance.ecs.soton.ac.uk/store/>`_, a repository for provenance documents.


text:
#ifndef STATE_HPP
#define STATE_HPP

#include <SFML/Graphics/Drawable.hpp>
#include <SFML/System/Time.hpp>
#include <SFML/Window/Event.hpp>

#include "game.hpp"

class Game;

class State
{

    public:
        State(Game& t_engine)
            : m_engine(t_engine)
        {
        }

    public:
        virtual void pause() = 0;
        virtual void resume() = 0;

        virtual void handleEvent(const sf::Event& t_event) = 0;

        virtual void update(const sf::Time& t_elapsedTime) = 0;

        virtual void display(sf::RenderWindow& t_window) = 0;

    protected:
        Game& m_engine;
};

#endif // STATE_HPP


text:
var mongo = require('mongodb')
  , db;

exports.init = function(ctx, callback) {
  var settings = ctx.settings;
  mongo.Db.connect('mongodb://' + settings.db.host + ':' + settings.db.port + '/' + settings.db.name, {auto_reconnect: true}, function(err, handler) {
    if (err === null) {
      console.log('setupDB: OK');
      db = handler;
      ctx.db = exports;
    }
    callback(err);
  });
};

exports.findAll = function(collection, callback) {
  db.collection(collection, function(err, collectionHandler) {
    if (err)
      callback(err, null);
    collectionHandler.find().toArray(function(err, items) {
      callback(err, items);
    });
  });
};

exports.findById = function(collection, id, callback) {
  db.collection(collection, function(err, collectionHandler) {
    if (err)
      callback(err, null);
    collectionHandler.find({ '_id': id }, function(err, document) {
      callback(err, document);
    });
  });
};

exports.insert = function(collection, document, callback) {
  db.collection(collection, function(err, collectionHandler) {
    if (err)
      callback(err, null);
    collectionHandler.insert(document, { safe: true }, function(err, result) {
      callback(err, result);
    });
  });
};

exports.update = function(collection, document, callback) {
  db.collection(collection, function(err, collectionHandler) {
    if (err)
      callback(err, null);
    collectionHandler.update({ '_id': document._id }, document, { safe: true }, function(err, result) {
      callback(err, result);
    });
  });
};

exports.deleteById = function(collection, id, callback) {
  db.collection(collection, function(err, collectionHandler) {
    if (err)
      callback(err, null);
    collectionHandler.remove({ '_id': id }, { safe: true }, function(err, result) {
      callback(err, result);
    });
  });
};

exports.deleteAll = function(collection, callback) {
  db.collection(collection, function(err, collectionHandler) {
    if (err)
      callback(err, null);
    collectionHandler.remove(null, { safe: true }, function(err, result) {
      callback(err, result);
    });
  });
};


text:
import unittest
import numpy as np
from inference_pass_test import InferencePassTest
import paddle.fluid as fluid
import paddle.fluid.core as core
from paddle.fluid.core import PassVersionChecker
from paddle.fluid.core import AnalysisConfig

class TRTReshapeTest(InferencePassTest):
    def setUp(self):
        self.bs = 1
        self.input_shape = [16, 3, 8]
        self.reshape = [-1, 4, 4, 24]
        self.data_shape = [
            self.bs,
            self.input_shape[0],
            self.input_shape[1],
            self.input_shape[2],
        ]
        with fluid.program_guard(self.main_program, self.startup_program):
            data = fluid.data(
                name='data', shape=self.data_shape, dtype='float32'
            )
            reshape_out = self.append_reshape(data, self.reshape)
            out = fluid.layers.batch_norm(reshape_out, is_test=True)
        self.feeds = {
            'data': np.random.random(self.data_shape).astype('float32'),
        }
        self.enable_trt = True
        self.trt_parameters = TRTReshapeTest.TensorRTParam(
            1 << 30, self.bs, 1, AnalysisConfig.Precision.Float32, False, False
        )
        self.fetch_list = [out]

    def append_reshape(self, data, reshape):
        return fluid.layers.reshape(data, reshape)

    def test_check_output(self):
        if core.is_compiled_with_cuda():
            use_gpu = True
            self.check_output_with_option(use_gpu)
            self.assertTrue(
                PassVersionChecker.IsCompatible('tensorrt_subgraph_pass')
            )

class TRTReshapeTest1(TRTReshapeTest):
    def setUp(self):
        self.bs = 2
        self.input_shape = [23, 13, 12]
        self.reshape = [2, 0, -1, 6]
        self.data_shape = [
            self.bs,
            self.input_shape[0],
            self.input_shape[1],
            self.input_shape[2],
        ]
        with fluid.program_guard(self.main_program, self.startup_program):
            data = fluid.data(
                name='data', shape=self.data_shape, dtype='float32'
            )
            reshape_out = self.append_reshape(data, self.reshape)
            out = fluid.layers.batch_norm(reshape_out, is_test=True)
        self.feeds = {
            'data': np.random.random(self.data_shape).astype('float32'),
        }
        self.enable_trt = True
        self.trt_parameters = TRTReshapeTest.TensorRTParam(
            1 << 30, self.bs, 1, AnalysisConfig.Precision.Float32, False, False
        )
        self.fetch_list = [out]

class TRTReshapeTest2(TRTReshapeTest):
    def setUp(self):
        self.bs = 2
        self.input_shape = [23, 13, 12]
        self.reshape = [2, 0, -1, 6]
        self.data_shape = [
            self.bs,
            self.input_shape[0],
            self.input_shape[1],
            self.input_shape[2],
        ]
        with fluid.program_guard(self.main_program, self.startup_program):
            data = fluid.data(
                name='data', shape=self.data_shape, dtype='float32'
            )
            reshape_out = fluid.layers.reshape(x=data, shape=self.reshape)
            out = fluid.layers.batch_norm(reshape_out, is_test=True)
        self.feeds = {
            'data': np.random.random(self.data_shape).astype('float32')
        }
        self.enable_trt = True
        self.trt_parameters = TRTReshapeTest.TensorRTParam(
            1 << 30, self.bs, 1, AnalysisConfig.Precision.Float32, False, False
        )
        self.fetch_list = [out]

class TRTReshapeTest3(TRTReshapeTest):
    def setUp(self):
        self.bs = 1
        self.input_shape = [7, 16, 27]
        self.reshape = [1, 8, 14, 0]
        self.data_shape = [
            self.bs,
            self.input_shape[0],
            self.input_shape[1],
            self.input_shape[2],
        ]
        with fluid.program_guard(self.main_program, self.startup_program):
            data = fluid.data(
                name='data', shape=self.data_shape, dtype='float32'
            )
            bn_out = fluid.layers.batch_norm(data, is_test=True)
            out = self.append_reshape(bn_out, self.reshape)
        self.feeds = {
            'data': np.random.random(self.data_shape).astype('float32'),
        }
        self.enable_trt = True
        self.trt_parameters = TRTReshapeTest.TensorRTParam(
            1 << 30, self.bs, 1, AnalysisConfig.Precision.Float32, False, False
        )
        '''
        self.dynamic_shape_params = TRTReshapeTest.DynamicShapeParam({
            'data': [1, 3, 8, 8]
        }, {'data': [5, 100, 100, 100]}, {'data': [1, 3, 16, 16]}, False)
        '''
        self.fetch_list = [out]

if __name__ == "__main__":
    unittest.main()


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using AutoRest.Core.Logging;
using AutoRest.Core.Properties;
using AutoRest.Swagger.Validation.Core;
using AutoRest.Swagger.Model;

namespace AutoRest.Swagger.Validation
{
    public class OperationDescriptionRequired : TypedRule<Operation>
    {
        /// <summary>
        /// This rule fails if the description is null and the reference is null (since the reference could have a description)
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public override bool IsValid(Operation entity)
            => entity == null || entity.Description != null;

        /// <summary>
        /// The template message for this Rule.
        /// </summary>
        /// <remarks>
        /// This may contain placeholders '{0}' for parameterized messages.
        /// </remarks>
        public override string MessageTemplate => Resources.MissingDescription;

        /// <summary>
        /// The severity of this message (ie, debug/info/warning/error/fatal, etc)
        /// </summary>
        public override Category Severity => Category.Warning;
    }
}


text:
package org.svip.pool.db;

import org.svip.util.proxy.ProxyFactory;
import org.svip.util.proxy.impl.AdviceImpl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Blues
 * @version 1.0
 * Created on 2014/8/24
 */
public class ConnPool {

    /*
     4> when time out, auto close needless conn
     5> log
     7*> produce singleton for pool manager according to config
     8> one transaction a conn
     9>  Before exit system close all conn
     10> check conn is valid
     */
    private List<Connection> free;
    private List<Connection> active;
    private PoolParam param;

    public ConnPool(PoolParam param) {
        this.param = param;
        this.init();
    }

    public synchronized Connection getConnection() throws Exception {
        if (active.size() >= param.getMaxiNum()) {
            Thread.sleep(param.getWaitTime());
        }
        return this.getValidConnection(free.size() <= 0 && active.size() < param.getMaxiNum());
    }

    public void close(Connection con) throws SQLException {
        if (active.remove(con) && free.size() < param.getMiniNum()) {
            free.add(con);
        } else {
            throw new DbPoolException("Can not remove con from active.");
        }
    }

    private Connection getValidConnection(boolean isAdd) throws SQLException {
        Connection con = null;
        if (isAdd) {
            con = this.getConnectionProxy();
        } else {
            if (free.size() > 0) {
                con = free.remove(0);
            } else {
                return con;
            }
        }
        if (con.isValid(param.getTimeout())) {
            active.add(con);
            return con;
        }
        return this.getValidConnection(isAdd);
    }

    private void init() {
        try {
            free = new LinkedList<Connection>();
            active = new LinkedList<Connection>();
            Class.forName(param.getDriver());
            for (int i = 0; i < param.getMiniNum(); i++) {
                free.add(this.getConnectionProxy());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Connection getConnectionProxy() throws SQLException {
        Connection con = DriverManager.getConnection(param.getUrl(), param.getUsername(), param.getPassword());
        if (con != null) {
            return (Connection) ProxyFactory.getProxy(con, new AdviceImpl());
        }
        return con;
    }
}


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

<title>E-Index</title>
<meta name="date" content="2017-02-26">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I K L M N O P Q R S T U V W _

E

endAction(String, int) - Method in class kariminf.faris.process.ston.FarisParse

endActionHandler(String, Verb, Set<Adverb>) - Method in class kariminf.faris.process.Generator

This is called when the action ends (all its components have been processed

endActionHandler(String, Verb, Set<Adverb>) - Method in class kariminf.faris.process.ston.StonGenerator

endActionRelativeHandler(String) - Method in class kariminf.faris.process.Generator

endActionRelativeHandler(String) - Method in class kariminf.faris.process.ston.StonGenerator

endActions(boolean) - Method in class kariminf.faris.process.ston.FarisParse

endAgents() - Method in class kariminf.faris.process.ston.FarisParse

endAgentsHandler(String) - Method in class kariminf.faris.process.Generator

This is called to mark the end of current action's agents enumeration

endAgentsHandler(String) - Method in class kariminf.faris.process.ston.StonGenerator

endComparison(String, List<Integer>) - Method in class kariminf.faris.process.ston.FarisParse

endDisjunctionHandler() - Method in class kariminf.faris.process.Generator

This is called when the disjunction of elements is over, and to start a new disjunction
 if there is any

endDisjunctionHandler() - Method in class kariminf.faris.process.ston.StonGenerator

endMindProcessing(QuantSubstance) - Method in class kariminf.faris.process.Generator

endPlaceHandler(Relation.Adpositional, Adverb) - Method in class kariminf.faris.process.Generator

endPlaceHandler(Relation.Adpositional, Adverb) - Method in class kariminf.faris.process.ston.StonGenerator

endPRelatives() - Method in class kariminf.faris.process.ston.FarisParse

endRelative(String) - Method in class kariminf.faris.process.ston.FarisParse

endRole(String, int) - Method in class kariminf.faris.process.ston.FarisParse

endSentence(String) - Method in class kariminf.faris.process.ston.FarisParse

endStateHandler(String, String) - Method in class kariminf.faris.process.Generator

endStateHandler(String, String) - Method in class kariminf.faris.process.ston.StonGenerator

endSubstanceHandler(String, Noun) - Method in class kariminf.faris.process.Generator

This marks the end of a substance processing

endSubstanceHandler(String, Noun) - Method in class kariminf.faris.process.ston.StonGenerator

endSubstanceRelativeHandler(String) - Method in class kariminf.faris.process.Generator

endSubstanceRelativeHandler(String) - Method in class kariminf.faris.process.ston.StonGenerator

endThemes() - Method in class kariminf.faris.process.ston.FarisParse

endThemesHandler(String) - Method in class kariminf.faris.process.Generator

This is called to mark the end of current action's themes enumeration

endThemesHandler(String) - Method in class kariminf.faris.process.ston.StonGenerator

endTimeHandler(Relation.Adpositional, Adverb, LocalDateTime) - Method in class kariminf.faris.process.Generator

endTimeHandler(Relation.Adpositional, Adverb, LocalDateTime) - Method in class kariminf.faris.process.ston.StonGenerator

equals(Object) - Method in class kariminf.faris.knowledge.Thought

equals(Object) - Method in class kariminf.faris.linguistic.Noun

equals(Object) - Method in class kariminf.faris.linguistic.POS

equals(Object) - Method in class kariminf.faris.linguistic.ProperNoun

equals(Object) - Method in class kariminf.faris.philosophical.Action

equals(Object) - Method in class kariminf.faris.philosophical.Substance

A B C D E F G H I K L M N O P Q R S T U V W _

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
The *Yard* framework paginates **index**'s `QuerySet`, `ValueSet`, *list* and *generator* based responses.

```python
from yard import resources

class FooResource(resources.Resource):

    # default configuration
    class Pagination:
        offset_parameter = 'offset'
        results_per_page = {
            'parameter': 'results',
            'default': 25,
            'limit': 50,
        }
```

In order to deactivate the pagination you need to do as follows:

```python
from yard import resources

class FooResource(resources.Resource):

    # default configuration
    class Pagination:
        no_pagination = True
```

## Pagination Options

### no_pagination

    no_pagination = True

- disable pagination in the resource.
- defaults to `False`

### offset_parameter

    offset_parameter = 'offset'

- name of the parameter for the offset number.
- defaults to *offset*.

### results_per\_page

    results_per_page = {
        'parameter': 'limit',
        'default': 50,
        'limit': 100,
    }

- **default**: default number of results per each page. Defaults to *25*.
- **parameter**: name of the parameter for the number of results. Defaults to *results*.
- **limit**: maximum number of results per each page allowed. Defaults to *50*.


text:
static NSString *const UUID_Service                = @"00008000-60B2-21F8-BCE3-94EEA697F98C";
static NSString *const UUID_Characteristic_Command = @"00008001-60B2-21F8-BCE3-94EEA697F98C"; // write
static NSString *const UUID_Characteristic_Notify  = @"00008002-60B2-21F8-BCE3-94EEA697F98C"; // notify
static NSString *const UUID_Characteristic_BulkOut = @"00008003-60B2-21F8-BCE3-94EEA697F98C"; // write
static NSString *const UUID_Characteristic_BulkIn  = @"00008004-60B2-21F8-BCE3-94EEA697F98C"; // notify

@implementation JumaDeviceConstant

#pragma mark - service

+ (CBUUID *)serviceUUID {
    static CBUUID *serviceUUID = nil;
    if (!serviceUUID) {
        serviceUUID = [CBUUID UUIDWithString:UUID_Service];
    }
    return serviceUUID;
}

+ (NSArray *)services {
    static NSArray *services = nil;
    if (!services) {
        services = @[ [self serviceUUID] ];
    }
    return services;
}

#pragma mark - characteristic

+ (CBUUID *)commandCharacteristicUUID {
    static CBUUID *commandCharacteristicUUID = nil;
    if (!commandCharacteristicUUID) {
        commandCharacteristicUUID = [CBUUID UUIDWithString:UUID_Characteristic_Command];
    }
    return commandCharacteristicUUID;

}
+ (CBUUID *)notifyCharacteristicUUID {
    static CBUUID *notifyCharacteristicUUID = nil;
    if (!notifyCharacteristicUUID) {
        notifyCharacteristicUUID = [CBUUID UUIDWithString:UUID_Characteristic_Notify];
    }
    return notifyCharacteristicUUID;
}
+ (CBUUID *)bulkOutCharacteristicUUID {
    static CBUUID *bulkOutCharacteristicUUID = nil;
    if (!bulkOutCharacteristicUUID) {
        bulkOutCharacteristicUUID = [CBUUID UUIDWithString:UUID_Characteristic_BulkOut];
    }
    return bulkOutCharacteristicUUID;
}

+ (NSArray *)characteristics {
    static NSArray *characteristics = nil;
    if (!characteristics) {
        characteristics = @[ [self commandCharacteristicUUID],
                             [self notifyCharacteristicUUID],
                             [self bulkOutCharacteristicUUID] ];
    }
    return characteristics;
}

@end


text:
plugin_name = python-plugin
publish_bucket = cloudbees-clickstack
publish_repo = testing
publish_url = s3://$(publish_bucket)/$(publish_repo)/

deps =

pkg_files = README LICENSE setup functions

include plugin.mk


text:
<?php
include_once('./includes/functions.php');
/**
*
*/
class Model_User{

    //user id
    var $user_id;
    //firstname
    var $user_firstname;
    //lastname
    var $user_lastname;
    //email
    var $user_email;
    //password
    var $user_password;
    //user_picture
    var $user_picture;
    //user query
    var $user_query;
    //query status
    var $query_status;
    //user details
    var $user_details;
    //key
    var $thekey;

    //constructor
    function __construct(){
        $this->query_status = true;
        $this->user_details = null;
        $this->user_query = null;
        $this->thekey = "mhbjhjhjkjjkogjrbg093ti";

    }

    //destructor
    function __destruct(){

    }

     //function to create an instance of a new user
     function create_newuser($user_firstname, $user_lastname, $user_email, $user_password, $user_picture){
        $newuser = new Model_User();
        $newuser->user_id = generate_user_id();
        $newuser->user_firstname = $user_firstname;
        $newuser->user_lastname = $user_lastname;
        $newuser->user_email = $user_email;
        $newuser->user_password = $user_password;
        $newuser->user_picture = $user_picture;

    }

    //function to add user to user table
    function add_user($conn, $user_id, $user_firstname, $user_lastname, $user_email, $user_password, $user_picture){
        //encrypt password here
        $user_password = encrypt($user_password, $this->thekey);
        //encrypt email
        $user_email = encrypt($user_email, $this->thekey);
        $this->user_query_status = true;
        $this->user_query = mysqli_query($conn, "INSERT INTO users VALUES('$user_id', '$user_firstname', '$user_lastname',
         '$user_email', '$user_password', 'file_get_contents($user_picture)')");
        /*$this->user_query = mysqli_query($conn, "CALL add_user('$user_id', '$user_firstname', '$user_lastname',
         '$user_email', '$user_password', 'file_get_contents($user_picture)')");*/
        return ($this->user_query != null);
    }

    //function to check if user owns pass
    function confirm_password($conn, $user_email, $user_password){
        //encrypt user's mail
        $user_email = encrypt($user_email, $this->thekey);
        //encrypt user's password
        $user_password = encrypt($user_password, $this->thekey);
        //echo $user_password;

            $this->user_query = mysqli_query($conn, "SELECT * FROM users WHERE user_email='$user_email' AND user_password='$user_password'");//return wanted values
            $row = mysqli_fetch_array($this->user_query, MYSQLI_ASSOC);
            $numrows = mysqli_num_rows($this->user_query);
            $this->user_details = $row;
            return $numrows;
    }

    //function to activate user
    function activate_user($conn, $user_id){
        $this->user_query_status = true;
        $this->user_query = mysql_query($conn, "UPDATE users SET user_status='activated' WHERE user_id='$user_id");
        if ($this->user_query == null) {
            $this->user_query_status = false;
            //prompt user activation went wrong
            exit();
        }
    }

    //function to get user details after signing in
    function  get_user_details(){
        return $this->user_details;
    }

    //function to change email  :: update email
    function change_user_email($conn, $user_id, $user_old_email, $user_new_email, $user_password){
        $this->user_query_status = true;
        if ($this->confirm_password($conn, $user_old_email, $user_password) == true) {
            $this->user_query = mysqli_connect($conn, "UPDATE users SET user_email='$user_email' WHERE user_id='$user_id'");
            //$this->user_query = mysqli_query($conn, "CALL change_user_email('$user_new_email', '$user_id'");
            if ($this->user_query == null) {
                $this->user_query_status = false;
            }
        }
    }

    //function to change profile picture
    function change_user_profile_picture($conn, $user_id, $user_picture){
        $this->user_query_status = true;
        $this->user_query = mysqli_connect($conn, "UPDATE users SET user_picture='$user_picture' WHERE user_id='$user_id'");
        //$this->user_query = mysqli_connect($conn, "CALL change_user_picture($user_picture, '$id')");
        if ($this->user_query == null) {
            $this->user_query_status = false;
            exit();
        }
    }

    //function to change user's names
    function change_user_names($conn, $user_id, $user_new_firstname, $user_new_lastname){
        $this->user_query_status = true;
        $this->user_query = mysqli_connect($conn, "UPDATE users SET user_firstname='$user_new_firstname',
         user_lastname='$user_lastname' WHERE user_id='$user_id'");
       // $this->user_query = mysqli_query($conn, "CALL change_user_names('$user_new_firstname', '$user_new_lastname')");
        if ($this->user_query == null) {
            $this->user_query_status = false;
        }
    }

    //function to change user's password
    function change_user_password($conn, $user_id, $user_new_password, $user_old_password){
        $this->user_query_status = true;
        if ($this->confirm_password($conn, $user_email, $user_old_password) == true) {
            $this->user_query = mysqli_connect($conn, "UPDATE users SET user_password='$user_new_password' WHERE user_id='$user_id'");
            //$this->user_query = mysqli_query($conn, "CALL change_user_password('$user_new_password', $user_id')");
            if ($this->user_query == null) {
                $this->user_query_status = false;
            }
        }
    }

}

?>


text:
package br.com.valdineireis.v4labs.validators;

import br.com.caelum.vraptor.validator.Validator;
import br.com.valdineireis.v4labs.dao.UsuarioDAO;
import br.com.valdineireis.v4labs.factory.MessageFactory;

import javax.inject.Inject;

public class EmailValidator {

    private UsuarioDAO users;
    private Validator validator;
    private MessageFactory messageFactory;

    @Deprecated
    public EmailValidator() {
    }

    @Inject
    public EmailValidator(Validator validator, UsuarioDAO users, MessageFactory messageFactory) {
        this.users = users;
        this.validator = validator;
        this.messageFactory = messageFactory;
    }

    public boolean validate(String email) {
        if (users.contemUsuarioComLogin(email)) {
            validator.add(messageFactory.build("error", "user.errors.email.used"));
        }
        if (email == null) {
            validator.add(messageFactory.build("error", "user.errors.email.required"));
        }

        return !validator.hasErrors();
    }
}


text:
function [CODES, CODEBOOKS, DISTORTIONS, R] = AQ_pipeline( ...
    X, NWORDS, NITS, N, V )
%AQ_PIPELINE Quantizes X according to the algorithm proposed by Babenko and
%Lempitsky at CVPR 14.
%
% [CODES, CODEBOOKS, DISTORTIONS] = AQ_PIPELINE( X, NWORDS, NITS, N, V )
%
% Input
%   X      : d-by-n matrix. Each column is a datapoint to encode.
%   NWORDS : M-long vector. It has as many entries as codebooks are
%            desired. The entries specify the number of codewords to use
%            for each codebook.
%   NITS   : Integer. Number of iterations to run the optimization for.
%   N      : Integer. Beam search depth.
%   V      : Booleam. Whether to print progress. Defaults to false.
%
% Output
%   CODES       : numel(NWORDS)-by-n matrix. X encoded.
%   CODEBOOKS   : numel(NWORDS)-long cell array. Each entry is a learned
%                 subcodebook.
%   DISTORTIONS : NITS+1-long vector. The first entry contains the
%                 distorition after initialization. Entry i+1 contains the
%                 distortion after iteration i;
%   R           : d-by-d orthogonal matrix. The rotation of the data.
%                 If the number of codebooks, M <= 4, then this will be the
%                 identity. If M > 4 then this will correspond to the
%                 preprocessing of OPQ.

% --
% Julieta.

if nargin < 5,
    V = false;
end

NITQ_OPQ = 100;

% If we are asked for more than 4 codebooks then do APQ.
if numel( NWORDS ) > 4,
    [CODES, CODEBOOKS, DISTORTIONS, R] = AQPQ_pipeline( ...
        X, NWORDS, NITQ_OPQ, NITS, N, V );
    return
else
    R = eye( size(X,1) );
end

%% Create space for the output.
DISTORTIONS = zeros( NITS+1, 1 );

%% Initialize at random.
[CODES, CODEBOOKS] = AQ_initialize_random( X, NWORDS );

qerror         = get_qerror( X, CODES, CODEBOOKS );
DISTORTIONS(1) = qerror;

if V, fprintf('Error after initialization  is %e.\n', qerror); end;

%% Iterate between encoding and updating codebooks.
for i = 1:NITS,

    if V, fprintf('=== Iteration %d / %d. ===\n', i, NITS); end

    if V, fprintf('Encoding... '); tic; end
    CODES  = AQ_encoding(X, CODEBOOKS, N, V > 1);
    qerror = get_qerror( X, CODES, CODEBOOKS );
    if V, fprintf('done in %.2f seconds. Qerror is %e\n', toc, qerror); end

    if V, fprintf('Updating codebooks... '); tic; end
    CODEBOOKS = AQ_update_codebooks( X, CODES, CODEBOOKS );
    qerror    = get_qerror( X, CODES, CODEBOOKS );
    if V, fprintf('done in %.2f seconds. Qerror is %e\n', toc, qerror); end

    DISTORTIONS( i+1 ) = qerror;

end

end


text:
"""The tests for the rmvtransport platform."""
import unittest
from unittest.mock import patch
import datetime

from homeassistant.setup import setup_component

from tests.common import get_test_home_assistant

VALID_CONFIG_MINIMAL = {'sensor': {'platform': 'rmvtransport',
                                   'next_departure': [{'station': '3000010'}]}}

VALID_CONFIG_NAME = {'sensor': {
    'platform': 'rmvtransport',
    'next_departure': [
        {
            'station': '3000010',
            'name': 'My Station',
        }
        ]}}

VALID_CONFIG_MISC = {'sensor': {
    'platform': 'rmvtransport',
    'next_departure': [
        {
            'station': '3000010',
            'lines': [21, 'S8'],
            'max_journeys': 2,
            'time_offset': 10
        }
        ]}}

VALID_CONFIG_DEST = {'sensor': {
    'platform': 'rmvtransport',
    'next_departure': [
        {
            'station': '3000010',
            'destinations': ['Frankfurt (Main) Flughafen Regionalbahnhof',
                             'Frankfurt (Main) Stadion']
        }
        ]}}

def get_departuresMock(stationId, maxJourneys,
                       products):  # pylint: disable=invalid-name
    """Mock rmvtransport departures loading."""
    data = {'station': 'Frankfurt (Main) Hauptbahnhof',
            'stationId': '3000010', 'filter': '11111111111', 'journeys': [
                {'product': 'Tram', 'number': 12, 'trainId': '1123456',
                 'direction': 'Frankfurt (Main) Hugo-Junkers-Straße/Schleife',
                 'departure_time': datetime.datetime(2018, 8, 6, 14, 21),
                 'minutes': 7, 'delay': 3, 'stops': [
                     'Frankfurt (Main) Willy-Brandt-Platz',
                     'Frankfurt (Main) Römer/Paulskirche',
                     'Frankfurt (Main) Börneplatz',
                     'Frankfurt (Main) Konstablerwache',
                     'Frankfurt (Main) Bornheim Mitte',
                     'Frankfurt (Main) Saalburg-/Wittelsbacherallee',
                     'Frankfurt (Main) Eissporthalle/Festplatz',
                     'Frankfurt (Main) Hugo-Junkers-Straße/Schleife'],
                 'info': None, 'info_long': None,
                 'icon': 'https://products/32_pic.png'},
                {'product': 'Bus', 'number': 21, 'trainId': '1234567',
                 'direction': 'Frankfurt (Main) Hugo-Junkers-Straße/Schleife',
                 'departure_time': datetime.datetime(2018, 8, 6, 14, 22),
                 'minutes': 8, 'delay': 1, 'stops': [
                     'Frankfurt (Main) Weser-/Münchener Straße',
                     'Frankfurt (Main) Hugo-Junkers-Straße/Schleife'],
                 'info': None, 'info_long': None,
                 'icon': 'https://products/32_pic.png'},
                {'product': 'Bus', 'number': 12, 'trainId': '1234568',
                 'direction': 'Frankfurt (Main) Hugo-Junkers-Straße/Schleife',
                 'departure_time': datetime.datetime(2018, 8, 6, 14, 25),
                 'minutes': 11, 'delay': 1, 'stops': [
                     'Frankfurt (Main) Stadion'],
                 'info': None, 'info_long': None,
                 'icon': 'https://products/32_pic.png'},
                {'product': 'Bus', 'number': 21, 'trainId': '1234569',
                 'direction': 'Frankfurt (Main) Hugo-Junkers-Straße/Schleife',
                 'departure_time': datetime.datetime(2018, 8, 6, 14, 25),
                 'minutes': 11, 'delay': 1, 'stops': [],
                 'info': None, 'info_long': None,
                 'icon': 'https://products/32_pic.png'},
                {'product': 'Bus', 'number': 12, 'trainId': '1234570',
                 'direction': 'Frankfurt (Main) Hugo-Junkers-Straße/Schleife',
                 'departure_time': datetime.datetime(2018, 8, 6, 14, 25),
                 'minutes': 11, 'delay': 1, 'stops': [],
                 'info': None, 'info_long': None,
                 'icon': 'https://products/32_pic.png'},
                {'product': 'Bus', 'number': 21, 'trainId': '1234571',
                 'direction': 'Frankfurt (Main) Hugo-Junkers-Straße/Schleife',
                 'departure_time': datetime.datetime(2018, 8, 6, 14, 25),
                 'minutes': 11, 'delay': 1, 'stops': [],
                 'info': None, 'info_long': None,
                 'icon': 'https://products/32_pic.png'}
                ]}
    return data

def get_errDeparturesMock(stationId, maxJourneys,
                          products):  # pylint: disable=invalid-name
    """Mock rmvtransport departures erroneous loading."""
    raise ValueError

class TestRMVtransportSensor(unittest.TestCase):
    """Test the rmvtransport sensor."""

    def setUp(self):
        """Set up things to run when tests begin."""
        self.hass = get_test_home_assistant()
        self.config = VALID_CONFIG_MINIMAL
        self.reference = {}
        self.entities = []

    def tearDown(self):
        """Stop everything that was started."""
        self.hass.stop()

    @patch('RMVtransport.RMVtransport.get_departures',
           side_effect=get_departuresMock)
    def test_rmvtransport_min_config(self, mock_get_departures):
        """Test minimal rmvtransport configuration."""
        assert setup_component(self.hass, 'sensor', VALID_CONFIG_MINIMAL)
        state = self.hass.states.get('sensor.frankfurt_main_hauptbahnhof')
        self.assertEqual(state.state, '7')
        self.assertEqual(state.attributes['departure_time'],
                         datetime.datetime(2018, 8, 6, 14, 21))
        self.assertEqual(state.attributes['direction'],
                         'Frankfurt (Main) Hugo-Junkers-Straße/Schleife')
        self.assertEqual(state.attributes['product'], 'Tram')
        self.assertEqual(state.attributes['line'], 12)
        self.assertEqual(state.attributes['icon'], 'mdi:tram')
        self.assertEqual(state.attributes['friendly_name'],
                         'Frankfurt (Main) Hauptbahnhof')

    @patch('RMVtransport.RMVtransport.get_departures',
           side_effect=get_departuresMock)
    def test_rmvtransport_name_config(self, mock_get_departures):
        """Test custom name configuration."""
        assert setup_component(self.hass, 'sensor', VALID_CONFIG_NAME)
        state = self.hass.states.get('sensor.my_station')
        self.assertEqual(state.attributes['friendly_name'], 'My Station')

    @patch('RMVtransport.RMVtransport.get_departures',
           side_effect=get_errDeparturesMock)
    def test_rmvtransport_err_config(self, mock_get_departures):
        """Test erroneous rmvtransport configuration."""
        assert setup_component(self.hass, 'sensor', VALID_CONFIG_MINIMAL)

    @patch('RMVtransport.RMVtransport.get_departures',
           side_effect=get_departuresMock)
    def test_rmvtransport_misc_config(self, mock_get_departures):
        """Test misc configuration."""
        assert setup_component(self.hass, 'sensor', VALID_CONFIG_MISC)
        state = self.hass.states.get('sensor.frankfurt_main_hauptbahnhof')
        self.assertEqual(state.attributes['friendly_name'],
                         'Frankfurt (Main) Hauptbahnhof')
        self.assertEqual(state.attributes['line'], 21)

    @patch('RMVtransport.RMVtransport.get_departures',
           side_effect=get_departuresMock)
    def test_rmvtransport_dest_config(self, mock_get_departures):
        """Test misc configuration."""
        assert setup_component(self.hass, 'sensor', VALID_CONFIG_DEST)
        state = self.hass.states.get('sensor.frankfurt_main_hauptbahnhof')
        self.assertEqual(state.state, '11')
        self.assertEqual(state.attributes['direction'],
                         'Frankfurt (Main) Hugo-Junkers-Straße/Schleife')
        self.assertEqual(state.attributes['line'], 12)
        self.assertEqual(state.attributes['minutes'], 11)
        self.assertEqual(state.attributes['departure_time'],
                         datetime.datetime(2018, 8, 6, 14, 25))


text:
import * as ts from 'typescript';

import {AbsoluteFsPath} from '../../file_system';
import {DependencyTracker} from '../api';

/**
 * An implementation of the `DependencyTracker` dependency graph API.
 *
 * The `FileDependencyGraph`'s primary job is to determine whether a given file has "logically"
 * changed, given the set of physical changes (direct changes to files on disk).
 *
 * A file is logically changed if at least one of three conditions is met:
 *
 * 1. The file itself has physically changed.
 * 2. One of its dependencies has physically changed.
 * 3. One of its resource dependencies has physically changed.
 */
export class FileDependencyGraph<T extends {fileName: string} = ts.SourceFile> implements
    DependencyTracker<T> {
  private nodes = new Map<T, FileNode>();

  addDependency(from: T, on: T): void {
    this.nodeFor(from).dependsOn.add(on.fileName);
  }

  addResourceDependency(from: T, resource: AbsoluteFsPath): void {
    this.nodeFor(from).usesResources.add(resource);
  }

  addTransitiveDependency(from: T, on: T): void {
    const nodeFrom = this.nodeFor(from);
    nodeFrom.dependsOn.add(on.fileName);

    const nodeOn = this.nodeFor(on);
    for (const dep of nodeOn.dependsOn) {
      nodeFrom.dependsOn.add(dep);
    }
  }

  addTransitiveResources(from: T, resourcesOf: T): void {
    const nodeFrom = this.nodeFor(from);
    const nodeOn = this.nodeFor(resourcesOf);
    for (const dep of nodeOn.usesResources) {
      nodeFrom.usesResources.add(dep);
    }
  }

  isStale(sf: T, changedTsPaths: Set<string>, changedResources: Set<AbsoluteFsPath>): boolean {
    return isLogicallyChanged(sf, this.nodeFor(sf), changedTsPaths, EMPTY_SET, changedResources);
  }

  /**
   * Update the current dependency graph from a previous one, incorporating a set of physical
   * changes.
   *
   * This method performs two tasks:
   *
   * 1. For files which have not logically changed, their dependencies from `previous` are added to
   *    `this` graph.
   * 2. For files which have logically changed, they're added to a set of logically changed files
   *    which is eventually returned.
   *
   * In essence, for build `n`, this method performs:
   *
   * G(n) + L(n) = G(n - 1) + P(n)
   *
   * where:
   *
   * G(n) = the dependency graph of build `n`
   * L(n) = the logically changed files from build n - 1 to build n.
   * P(n) = the physically changed files from build n - 1 to build n.
   */
  updateWithPhysicalChanges(
      previous: FileDependencyGraph<T>, changedTsPaths: Set<string>, deletedTsPaths: Set<string>,
      changedResources: Set<AbsoluteFsPath>): Set<string> {
    const logicallyChanged = new Set<string>();

    for (const sf of previous.nodes.keys()) {
      const node = previous.nodeFor(sf);
      if (isLogicallyChanged(sf, node, changedTsPaths, deletedTsPaths, changedResources)) {
        logicallyChanged.add(sf.fileName);
      } else if (!deletedTsPaths.has(sf.fileName)) {
        this.nodes.set(sf, {
          dependsOn: new Set(node.dependsOn),
          usesResources: new Set(node.usesResources),
        });
      }
    }

    return logicallyChanged;
  }

  private nodeFor(sf: T): FileNode {
    if (!this.nodes.has(sf)) {
      this.nodes.set(sf, {
        dependsOn: new Set<string>(),
        usesResources: new Set<AbsoluteFsPath>(),
      });
    }
    return this.nodes.get(sf)!;
  }
}

/**
 * Determine whether `sf` has logically changed, given its dependencies and the set of physically
 * changed files and resources.
 */
function isLogicallyChanged<T extends {fileName: string}>(
    sf: T, node: FileNode, changedTsPaths: ReadonlySet<string>, deletedTsPaths: ReadonlySet<string>,
    changedResources: ReadonlySet<AbsoluteFsPath>): boolean {
  // A file is logically changed if it has physically changed itself (including being deleted).
  if (changedTsPaths.has(sf.fileName) || deletedTsPaths.has(sf.fileName)) {
    return true;
  }

  // A file is logically changed if one of its dependencies has physically changed.
  for (const dep of node.dependsOn) {
    if (changedTsPaths.has(dep) || deletedTsPaths.has(dep)) {
      return true;
    }
  }

  // A file is logically changed if one of its resources has physically changed.
  for (const dep of node.usesResources) {
    if (changedResources.has(dep)) {
      return true;
    }
  }
  return false;
}

interface FileNode {
  dependsOn: Set<string>;
  usesResources: Set<AbsoluteFsPath>;
}

const EMPTY_SET: ReadonlySet<any> = new Set<any>();


text:
// Production steps of ECMA-262, Edition 6, 22.1.2.1
// es6-ified by @alexsasharegan
if (!Array.from) {
    Array.from = (function() {
        const toStr = Object.prototype.toString
        const isCallable = fn => typeof fn === "function" || toStr.call(fn) === "[object Function]"
        const toInteger = value => {
            const number = Number(value)
            if (isNaN(number)) {
                return 0
            }
            if (number === 0 || !isFinite(number)) {
                return number
            }
            return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number))
        }
        const maxSafeInteger = Math.pow(2, 53) - 1
        const toLength = value => Math.min(Math.max(toInteger(value), 0), maxSafeInteger)

        // The length property of the from method is 1.
        return function from(arrayLike /*, mapFn, thisArg */) {
            // 1. Let C be the this value.
            const C = this

            // 2. Let items be ToObject(arrayLike).
            const items = Object(arrayLike)

            // 3. ReturnIfAbrupt(items).
            if (arrayLike == null) {
                throw new TypeError("Array.from requires an array-like object - not null or undefined")
            }

            // 4. If mapfn is undefined, then let mapping be false.
            const mapFn = arguments.length > 1 ? arguments[1] : void undefined
            let T

            if (typeof mapFn !== "undefined") {
                // 5. else
                // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
                if (!isCallable(mapFn)) {
                    throw new TypeError("Array.from: when provided, the second argument must be a function")
                }

                // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
                if (arguments.length > 2) {
                    T = arguments[2]
                }
            }

            // 10. Let lenValue be Get(items, "length").
            // 11. Let len be ToLength(lenValue).
            const len = toLength(items.length)

            // 13. If IsConstructor(C) is true, then
            // 13. a. Let A be the result of calling the [[Construct]] internal method
            // of C with an argument list containing the single item len.
            // 14. a. Else, Let A be ArrayCreate(len).
            let A = isCallable(C) ? Object(new C(len)) : new Array(len)

            // 16. Let k be 0.
            let k = 0
            // 17. Repeat, while k < len… (also steps a - h)
            let kValue
            while (k < len) {
                kValue = items[k]
                if (mapFn) {
                    A[k] = typeof T === "undefined" ? mapFn(kValue, k) : mapFn.call(T, kValue, k)
                } else {
                    A[k] = kValue
                }
                k += 1
            }
            // 18. Let putStatus be Put(A, "length", len, true).
            A.length = len
            // 20. Return A.
            return A
        }
    })()
}

if (!Array.isArray) {
    Array.isArray = arg => Object.prototype.toString.call(arg) === "[object Array]"
}

// Static
export const from = Array.from
export const isArray = Array.isArray

// Instance
export const arrayIncludes = (array, value) => array.indexOf(value) !== -1