text:
module VagrantPlugins
  module DCOS
    class ProvisionerConfig < Vagrant.plugin(2, :config)
      attr_accessor :install_method
      attr_accessor :max_install_threads
      attr_accessor :machine_types
      attr_accessor :config_template_path

      def initialize
        super
        @install_method = UNSET_VALUE
        @max_install_threads = UNSET_VALUE
        @machine_types = UNSET_VALUE
        @config_template_path = UNSET_VALUE
      end

      def finalize!
        # defaults after merging
        @install_method = :ssh_pull if @install_method == UNSET_VALUE
        @max_install_threads = 4 if @max_install_threads == UNSET_VALUE
        @machine_types = {} if @machine_types == UNSET_VALUE
        @config_template_path = 'etc/config-1.6.yaml' if @config_template_path == UNSET_VALUE
      end

      # The validation method is given a machine object, since validation is done for each machine that Vagrant is managing
      def validate(_machine)
        errors = _detected_errors

        install_methods = [:web, :ssh_pull, :ssh_push]
        unless install_methods.include?(@install_method.to_sym)
          errors << "Invalid config: install_method must be one of #{install_methods}"
        end

        unless @max_install_threads > 0
          errors << 'Invalid config: max_install_threads must be greater than zero'
        end

        # Validate required fields
        required_fields = [
          :machine_types,
          :config_template_path
        ]
        required_fields.each do |field_name|
          value = send(field_name.to_sym)
          if value.nil? || value.empty? || value == UNSET_VALUE
            errors << "Invalid config: #{field_name} is required"
          end
        end

        return { 'dcos' => errors } unless errors.empty?

        # Validate required files
        required_file_fields = [
          :config_template_path
        ]
        required_file_fields.each do |field_name|
          file_path = send(field_name.to_sym)
          unless File.file?(file_path)
            errors << "Invalid config: #{field_name} file not found: '#{file_path}' - Ensure that the file exists or reconfigure its location"
          end
        end

        { 'dcos_install' => errors }
      end
    end
  end
end


text:
package org.tokalac.logging.modules.config;

import java.util.Enumeration;
import java.util.Properties;

/**
 * Abstract Class for Module Configurations
 * Created by Erol TOKALACOGLU on 31/05/15.
 * Version 1.0
 * Param <V>
 */
public abstract class AbstractConfigurator implements Configurator {

    private static String path;

    /**
     * Return the local path of configuration file
     * @author Erol TOKALACOGLU
     * @param NONE
     * @return File path
     */
    public String getConfigFilePath() {
        return path;
    }

    /**
     * Set the local file path
     * @author Erol TOKALACOGLU
     * @param Local file path
     * @return NONE
     */
    public void setConfigFilePath(String path) {
        AbstractConfigurator.path = path;
    }

    public abstract Properties getSettings();

    public abstract Enumeration<?> getKeys();

}

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace MicrosoftGraph.Model
{
    /// <summary>
    /// Room
    /// </summary>
    [Serializable]
    public class Room
    {
        /// <summary>
        /// Room name
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// Room email
        /// </summary>
        public string Address { get; set; }

        /// <summary>
        /// Custom ToString method that returns room name
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return Name;
        }
    }
}


text:
using System.Windows;

namespace Xamarin.Wcf.Views
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}


text:
package com.backtype.hadoop;

import com.backtype.hadoop.FileCopyInputFormat.FileCopyArgs;
import com.backtype.hadoop.formats.RecordInputStream;
import com.backtype.hadoop.formats.RecordOutputStream;
import com.backtype.hadoop.formats.RecordStreamFactory;
import com.backtype.support.Utils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapred.lib.NullOutputFormat;

import java.io.IOException;

public class Coercer {
    private static final String FACTIN_ARG = "coercer_stream_factin_arg";
    private static final String FACTOUT_ARG = "coercer_stream_factout_arg";

    private static Thread shutdownHook;
    private static RunningJob job = null;

    public static void coerce(String source, String dest, int renameMode, PathLister lister, RecordStreamFactory factin, RecordStreamFactory factout) throws IOException {
        coerce(source, dest, renameMode, lister, factin, factout, "");
    }

    public static void coerce(String qualSource, String qualDest, int renameMode, PathLister lister, RecordStreamFactory factin, RecordStreamFactory factout, String extensionOnRename) throws IOException {
        coerce(qualSource, qualDest, renameMode, lister, factin, factout, extensionOnRename, new Configuration());
    }

    public static void coerce(String qualSource, String qualDest, int renameMode, PathLister lister, RecordStreamFactory factin, RecordStreamFactory factout, String extensionOnRename, Configuration configuration) throws IOException {
        if(!Utils.hasScheme(qualSource) || !Utils.hasScheme(qualDest))
            throw new IllegalArgumentException("source and dest must have schemes " + qualSource + " " + qualDest);

        FileCopyArgs args = new FileCopyArgs(qualSource, qualDest, renameMode, lister, extensionOnRename);
        JobConf conf = new JobConf(configuration, Coercer.class);
        Utils.setObject(conf, FileCopyInputFormat.ARGS, args);
        Utils.setObject(conf, FACTIN_ARG, factin);
        Utils.setObject(conf, FACTOUT_ARG, factout);

        conf.setJobName("Coercer: " + qualSource + " -> " + qualDest);

        conf.setInputFormat(FileCopyInputFormat.class);
        conf.setOutputFormat(NullOutputFormat.class);
        conf.setMapperClass(CoercerMapper.class);

        conf.setSpeculativeExecution(false);

        conf.setNumReduceTasks(0);

        conf.setOutputKeyClass(NullWritable.class);
        conf.setOutputValueClass(NullWritable.class);

        try {
            registerShutdownHook();
            job = new JobClient(conf).submitJob(conf);
            while(!job.isComplete()) {
                Thread.sleep(100);
            }

            if(!job.isSuccessful()) throw new IOException("Coercer failed");
            deregisterShutdownHook();
        } catch(IOException e) {
            IOException ret = new IOException("Coercer failed");
            ret.initCause(e);
            throw ret;
        } catch(InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static void registerShutdownHook() {
        shutdownHook = new Thread()
        {
            @Override
            public void run()
            {
                try {
                    if(job != null)
                        job.killJob();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        Runtime.getRuntime().addShutdownHook( shutdownHook );
    }

    private static void deregisterShutdownHook()
    {
        Runtime.getRuntime().removeShutdownHook( shutdownHook );
    }

    public static class CoercerMapper extends AbstractFileCopyMapper {

        RecordStreamFactory factin;
        RecordStreamFactory factout;

        @Override
        protected void copyFile(FileSystem fsSource, Path source, FileSystem fsDest, Path target, Reporter reporter) throws IOException {
            RecordInputStream fin = factin.getInputStream(fsSource, source);
            RecordOutputStream fout = factout.getOutputStream(fsDest, target);

            try {
                byte[] record;
                int bytes = 0;
                while((record = fin.readRawRecord()) != null) {
                    fout.writeRaw(record);
                    bytes+=record.length;
                    if(bytes >= 1000000) { //every 1 MB of data report progress so we don't time out on large files
                        bytes = 0;
                        reporter.progress();
                    }
                }
            } finally {
                fin.close();
            }
            //don't complete files that aren't done yet. prevents partial files from being written
            fout.close();
        }

        @Override
        public void configure(JobConf job) {
            super.configure(job);
            factin = (RecordStreamFactory) Utils.getObject(job, FACTIN_ARG);
            factout = (RecordStreamFactory) Utils.getObject(job, FACTOUT_ARG);
        }
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto

namespace Google\Cloud\Compute\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Contains output only fields. Use this sub-message for all output fields set on ResourcePolicy. The internal structure of this "status" field should mimic the structure of ResourcePolicy proto specification.
 *
 * Generated from protobuf message google.cloud.compute.v1.ResourcePolicyResourceStatus
 */
class ResourcePolicyResourceStatus extends \Google\Protobuf\Internal\Message
{
    /**
     * [Output Only] Specifies a set of output values reffering to the instance_schedule_policy system status. This field should have the same name as corresponding policy field.
     *
     * Generated from protobuf field optional .google.cloud.compute.v1.ResourcePolicyResourceStatusInstanceSchedulePolicyStatus instance_schedule_policy = 344877104;
     */
    private $instance_schedule_policy = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type \Google\Cloud\Compute\V1\ResourcePolicyResourceStatusInstanceSchedulePolicyStatus $instance_schedule_policy
     *           [Output Only] Specifies a set of output values reffering to the instance_schedule_policy system status. This field should have the same name as corresponding policy field.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Compute\V1\Compute::initOnce();
        parent::__construct($data);
    }

    /**
     * [Output Only] Specifies a set of output values reffering to the instance_schedule_policy system status. This field should have the same name as corresponding policy field.
     *
     * Generated from protobuf field optional .google.cloud.compute.v1.ResourcePolicyResourceStatusInstanceSchedulePolicyStatus instance_schedule_policy = 344877104;
     * @return \Google\Cloud\Compute\V1\ResourcePolicyResourceStatusInstanceSchedulePolicyStatus|null
     */
    public function getInstanceSchedulePolicy()
    {
        return $this->instance_schedule_policy;
    }

    public function hasInstanceSchedulePolicy()
    {
        return isset($this->instance_schedule_policy);
    }

    public function clearInstanceSchedulePolicy()
    {
        unset($this->instance_schedule_policy);
    }

    /**
     * [Output Only] Specifies a set of output values reffering to the instance_schedule_policy system status. This field should have the same name as corresponding policy field.
     *
     * Generated from protobuf field optional .google.cloud.compute.v1.ResourcePolicyResourceStatusInstanceSchedulePolicyStatus instance_schedule_policy = 344877104;
     * @param \Google\Cloud\Compute\V1\ResourcePolicyResourceStatusInstanceSchedulePolicyStatus $var
     * @return $this
     */
    public function setInstanceSchedulePolicy($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Compute\V1\ResourcePolicyResourceStatusInstanceSchedulePolicyStatus::class);
        $this->instance_schedule_policy = $var;

        return $this;
    }

}


text:
=begin
  1. create a program for a kind of die (with letters, not numbers)
  2. note that its input will be an array of strings
  3. define a variable that functions throughout the whole program, assigned to the sides of the die
    a. the number of sides depends on the length of the input array
  4. create an action that the program will execute to randomize the strings
    a. create a variable that returns a random number between 0 and the length of the array
    b. assign the randomized number to access that index of the array
    c. return the string at that index

=end

# Initial Solution
=begin
class Die

  def initialize(labels)
    @sides = labels.length
    @labels = labels

    unless @sides > 0
      raise ArgumentError.new("Your die needs more than 0 sides!")
    end
  end

  def sides
    return @sides
  end

  def roll
    puts "Rolling die..."

    unless @sides > 1
      p @labels[0]
    end

    index_length = @sides - 1

    index = rand(0..index_length)

    letter = @labels[index]

    puts "You rolled a #{letter} on your #{@sides}-symboled die."

    p letter
  end
end
=end

# Refactored Solution

class Die
  def initialize(labels)
    @sides = labels.length
    @labels = labels

    unless @sides > 0
      raise ArgumentError.new("Your die needs more than 0 sides!")
    end
  end

  def sides
    @sides
  end

  def roll
    puts "Rolling die..."

    p @labels.sample

  end
end

# Reflection
=begin
What were the main differences between this die class and the last one you created
 in terms of implementation? Did you need to change much logic to get this to work?
In this die class, the random number had to apply to an array element, not
directly to a Fixnum. That meant the code needed a little more coaxing to return
the suitable random element than it had needed to return a random number in a
range. More or less, I had to move the random number generator range from the
number of sides to the number of array indices (starting with 0).

What does this exercise teach you about making code that is easily changeable or modifiable?
Having a template to work from is far simpler than not, certainly. And finding a
 refactor-friendly method makes altering the code far easier; I was able to test
 the different effects of .shuffle and .sample quickly after I implemented them.

What new methods did you learn when working on this challenge, if any?
I learned about .shuffle and I used .sample. In my research, I found it
interesting that .shuffle takes more time to complete than .sample, since
.shuffle randomizesthe entire array, whereas .sample plucks one random number
 from the index.

What concepts about classes were you able to solidify in this challenge?
The scope of instance variables was ironed out more; I think it strange that
the argument/s in the initialize constructor aren't automatically instance
variables, since those are the main inputs that would be modified in Class
methods. I also clarified the correct use of driver code when testing classes;
in the first challenge I didn't quite have a feel for the .new constructor,
and I want to learn a little more about it.

=end


text:
package com.lantopia.libjava.state;

/**
 * @author Mark McKenna %ltmark.denis.mckenna@gmail.com>
 * @version 0.1
 * @since 01/02/14
 */
public final class States {
    private States() { }

    public static State.Builder stateBuilder() { return new State.Builder(); }
}


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.

title: deviceready
---

# deviceready

Das Ereignis wird ausgelöst, wenn Cordova vollständig geladen ist.

    document.addEventListener("deviceready", yourCallbackFunction, false);

## Details

Dieses Ereignis ist wesentlich für jede Anwendung. Es signalisiert, dass Cordovas Gerät APIs geladen haben und bereit sind, zugreifen.

Cordova besteht aus zwei Codebasen: native und JavaScript. Während der native Code lädt, zeigt eine benutzerdefinierte Lade-Bild. JavaScript lädt jedoch nur wenn das DOM geladen. Dies bedeutet, dass die Web-app möglicherweise eine Cordova JavaScript-Funktion nennen darf, bevor der entsprechende systemeigene Code verfügbar ist.

Das `deviceready` -Ereignis wird ausgelöst, sobald Cordova vollständig geladen hat. Einmal können das Ereignis ausgelöst, Sie sicher Cordova-APIs aufrufen. Anwendungen in der Regel fügen Sie einen Ereignis-Listener mit `document.addEventListener` sobald das HTML-Dokument DOM geladen hat.

Das `deviceready` Ereignis verhält sich etwas anders als von anderen. Ein Ereignishandler registriert nach der `deviceready` -Ereignis ausgelöst hat die Callback-Funktion aufgerufen, sofort.

## Unterstützte Plattformen

*   Amazon Fire OS
*   Android
*   BlackBerry 10
*   iOS
*   Tizen
*   Windows Phone 8
*   Windows 8

## Kurzes Beispiel

    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {
        // Now safe to use device APIs
    }

## Vollständiges Beispiel

    <!DOCTYPE html>
    <html>
      <head>
        <title>Device Ready Example</title>

        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">

        // Wait for device API libraries to load
        //
        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }

        // device APIs are available
        //
        function onDeviceReady() {
            // Now safe to use device APIs
        }

        </script>
      </head>
      <body onload="onLoad()">
      </body>
    </html>


text:
import ReducedAction from 'reduced-actions-redux';
import {createUnresolvedAction as UA} from '../UnresolvedAction';

module.exports = [
    {
        name: 'FETCH_SERVERS',
        dependencies: ['servers'],
        resolver: function (action, dispatch){
            this.servers.find().then(d => {
                let all_server = d.data.map(s => Object.assign({id: s._id}, s));
                dispatch(new ReducedAction(
                    action.type,
                    'servers.all_servers',
                    all_server
                ));
            }).catch(e => {
                dispatch(UA('ERROR', e));
            });
        }
    },
    {
        name: 'ADD_SERVER',
        dependencies: ['servers'],
        resolver: function (action, dispatch){
            this.servers.create(action.context)
                .then(s => {
                    dispatch(new ReducedAction(
                        action.type,
                        'servers.all_servers',
                        all => [...all, Object.assign({id: s._id}, s)]
                    ))
                })
                .catch(e => {
                    if (e.name == 'BadRequest'){
                        e.name = 'NewServerCreationFailed';
                    }
                    dispatch(UA('ERROR', e));
                });
        }
    },
    {
        name: 'UPDATE_SERVER',
        dependencies: ['servers'],
        resolver: function (action, dispatch){
            this.servers.patch(action.context.id, action.context.data)
                .then(s => {
                    dispatch(new ReducedAction(
                        action.type,
                        `servers.all_servers[${s._id}]`,
                        Object.assign({id: s._id}, s)
                    ))
                })
                .catch(e => {
                    if (e.name == 'BadRequest'){
                        e.name = 'ServerUpdateFailed';
                    }
                    dispatch(UA('ERROR', e));
                });
        }
    },
    {
        name: 'ADD_SERVER_LOG',
        dependencies: ['servers'],
        resolver: function (action, dispatch){
            const server_id =  action.context.server.id;
            const patch = {
                logs: [
                    ...action.context.server.logs,
                    {
                        name: action.context.name,
                        path: action.context.path,
                    }
                ]
            };
            this.servers.patch(server_id, patch)
                .then(s => {
                    dispatch(new ReducedAction(
                        action.type,
                        `servers.all_servers[${server_id}].logs`,
                        s.logs
                    ))
                })
                .catch(e => {
                    dispatch(UA('ERROR', e));
                });
        }
    },
    {
        name: 'REMOVE_SERVER_LOG',
        dependencies: ['servers'],
        resolver: function (action, dispatch){
            const server_id =  action.context.server.id;
            const patch = {
                logs: action.context.server.logs.filter(l => l._id != action.context.log_id),
            };
            this.servers.patch(server_id, patch)
                .then(s => {
                    dispatch(new ReducedAction(
                        action.type,
                        `servers.all_servers[${server_id}].logs`,
                        s.logs
                    ))
                })
                .catch(e => {
                    dispatch(UA('ERROR', e));
                });
        }
    },
    {
        name: 'DELETE_SERVER',
        dependencies: ['servers', 'changePathAction'],
        resolver: function (action, dispatch){
            let server_id = action.context;
            this.servers.remove(server_id)
                .then(s => {
                    dispatch(this.changePathAction('/dashboard'));
                    dispatch(new ReducedAction(
                        action.type,
                        'servers.all_servers',
                        all => all.filter(s => s.id != server_id)
                    ));
                })
                .catch(e => {
                    dispatch(UA('ERROR', e));
                });
        }
    },
    {
        name: 'CHECK_SERVER_CONNECTION',
        dependencies: ['servers'],
        resolver: function (action, dispatch){
            let server_id = action.context;
            this.servers.get(server_id, {query:{checkifconnected: true}})
                .then(con => {
                    dispatch(new ReducedAction(
                        'UPDATE_SERVER_CONNECTION_CHECK',
                        `servers.all_servers[${server_id}]`,
                        s => Object.assign({ }, s, {connection_check: con})
                    ));
                })
                .catch(e => {
                    dispatch(UA('ERROR', e));
                });
        }
    },

    {
        name: 'SERVER_EDIT_SELECT',
        dependencies: ['changePathAction'],
        resolver: function (action, dispatch){
            const server_id = action.context;
            dispatch(this.changePathAction('/dashboard/edit/' + server_id));
        }
    },
    {
        name: 'SERVER_MONITORING_SELECT',
        dependencies: ['changePathAction'],
        resolver: function (action, dispatch){
            const server_id = action.context;
            dispatch(this.changePathAction('/dashboard/monitor/' + server_id));
        }
    },
    {
        name: 'SERVER_NEW_SELECT',
        dependencies: ['changePathAction'],
        resolver: function (action, dispatch){
            dispatch(this.changePathAction('/dashboard/new'));
        }
    },
    {
        name: 'SERVER_DASHBOARD_SELECT',
        dependencies: ['changePathAction'],
        resolver: function (action, dispatch){
            dispatch(this.changePathAction('/dashboard'));
        }
    }

];


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.apache.taverna.server.master.localworker (Apache Taverna Server 3.1.0-incubating API)</title>
<meta name="date" content="2018-01-18">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

org.apache.taverna.server.master.localworker

Interfaces

IdAwareForkRunFactory.MetaFactory

Classes

AbstractRemoteRunFactory

ForkRunFactory

IdAwareForkRunFactory

LocalWorkerFactory

LocalWorkerState


text:
<?php namespace Phprest\Service\RequestFilter\Contract\Sort;

interface ParseStrategy
{
    /**
     * @param string $input
     *
     * @return \Phprest\Service\RequestFilter\DataStructure\Sort
     */
    public function parse($input);
}


text:
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Mail;

namespace VelocityMail.Service
{
    /// <summary>
    /// A testable thread-safe implementation of <see cref="VelocityMailService"/> that captures e-mails
    /// to <see cref="SentMessages"/> and <see cref="RawMessages"/> rather than actually sending them.
    /// </summary>
    public class TestableVelocityMailService : VelocityMailService
    {
        /// <inheritdoc/>
        public TestableVelocityMailService(VelocityMailOptions options) : base(options)
        {
        }

        private readonly ConcurrentQueue<MailMessage> _sentMessages = new ConcurrentQueue<MailMessage>();
        private readonly ConcurrentQueue<VelocityMailMessage> _rawMessages = new ConcurrentQueue<VelocityMailMessage>();

        /// <summary>
        /// Gets the collection of sent <see cref="MailMessage"/> messages.
        /// </summary>
        public MailMessage[] SentMessages { get => _sentMessages.ToArray(); }

        /// <summary>
        /// Gets the collection of sent <see cref="VelocityMailMessage"/> messages before
        /// processing and converting to a <see cref="MailMessage"/>.
        /// </summary>
        public VelocityMailMessage[] RawMessages { get => _rawMessages.ToArray(); }

        /// <summary>
        /// Clears (deletes) all sent messages.
        /// </summary>
        public void ClearMessages()
        {
            // NOTE: .NetStandard 2.0 does not contain `Clear()`. That first appears in 2.1.
            while (_rawMessages.TryDequeue(out _)) { };
            while (_sentMessages.TryDequeue(out _)) { };
        }

        /// <inheritdoc/>
        public override void Send(VelocityMailMessage msg)
        {
            var mailMessage = msg.GetMailMessage(Engine, true);
            _sentMessages.Enqueue(mailMessage);
            _rawMessages.Enqueue(msg);
        }
    }
}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

  <title> | Tyler </title>
  <meta name="viewport" content="width=device-width,initial-scale=1">

  <link rel="shortcut icon" href="http://gravatar.com/avatar/9f5734a7063a4c48139f4999f3100167
?s=16">
  <link rel="stylesheet" href="http://tybenz.com/css/reset.css">
  <link rel="stylesheet" href="http://tybenz.com/css/mobile.css">
  <link rel="stylesheet" href="http://tybenz.com/css/desktop.css" media="(min-width:40em)">
  <link rel="stylesheet" href="http://tybenz.com/css/pygments.css">
  <link href='http://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700|Ubuntu:300,500,300italic,500italic|Ubuntu+Condensed' rel='stylesheet' type='text/css'>

Dolphin Rape Is Real

Blog

About

Projects

Home

Docs

Download

© Moms Demand Action


text:
@interface BNGMainViewController : NSViewController

- (BOOL)uploadFile:(PFFile *)file
              name:(NSString *)fileName
              type:(NSString *)fileType;

@end


text:
package be.fluid_it.mvn.cd.x.freeze.replace;

import be.fluid_it.mvn.cd.x.freeze.mapping.DefaultArtifactFreezeMapping;
import be.fluid_it.mvn.cd.x.freeze.model.GroupIdArtifactIdVersion;
import be.fluid_it.mvn.cd.x.freeze.pom.SamplePom_ArtifactInheritsVersion;
import be.fluid_it.mvn.cd.x.freeze.pom.SamplePom_Library;
import be.fluid_it.mvn.cd.x.freeze.resolve.FrozenArtifactResolver;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.junit.Assert;
import org.junit.Test;

import java.io.*;

public class PomFreezerTest {
    @Test
    public void freezePom_ArtifactInheritsVersion() {
        FrozenArtifactResolver frozenArtifactResolverDummy = new FrozenArtifactResolver() {
            @Override
            public GroupIdArtifactIdVersion getLatestFrozenVersion(GroupIdArtifactIdVersion snapshotGroupIdArtifactIdVersion) {
                if (SamplePom_ArtifactInheritsVersion.parentGroupIdArtifactIdVersion().equals(snapshotGroupIdArtifactIdVersion)) {
                    return SamplePom_ArtifactInheritsVersion.frozenParentGroupIdArtifactIdVersion();
                } else if (SamplePom_ArtifactInheritsVersion.libraryGroupIdArtifactIdVersion().equals(snapshotGroupIdArtifactIdVersion)) {
                    return SamplePom_ArtifactInheritsVersion.frozenLibraryGroupIdArtifactIdVersion();
                }
                throw new IllegalStateException("Not expected groupIdArtifactIdVersionPrefix : " + snapshotGroupIdArtifactIdVersion);
            }

            @Override
            public boolean artifactInheritsVersionFromParent() {
                return true;
            }

            @Override
            public String artifactFrozenVersion() {
                return SamplePom_ArtifactInheritsVersion.FROZEN_VERSION;
            }
        };

        ByteArrayOutputStream pomOutputStream = new ByteArrayOutputStream();
        new DefaultPomFreezer(frozenArtifactResolverDummy, SamplePom_ArtifactInheritsVersion.fakedStamper(), new ConsoleLogger()).freeze(SamplePom_ArtifactInheritsVersion.asStream(), pomOutputStream);
        String pomContent = pomOutputStream.toString();
        System.out.print(pomContent);
        Assert.assertTrue(pomContent.contains("<version>" + SamplePom_ArtifactInheritsVersion.FROZEN_VERSION + "</version>"));
        Assert.assertTrue(pomContent.contains("<version>" + SamplePom_ArtifactInheritsVersion.LIBRARY_FROZEN_VERSION + "</version>"));
    }

    @Test
    public void freezePom() {
        FrozenArtifactResolver frozenArtifactResolverDummy = new FrozenArtifactResolver() {
            @Override
            public GroupIdArtifactIdVersion getLatestFrozenVersion(GroupIdArtifactIdVersion snapshotGroupIdArtifactIdVersion) {
                if (SamplePom_ArtifactInheritsVersion.parentGroupIdArtifactIdVersion().equals(snapshotGroupIdArtifactIdVersion)) {
                    return SamplePom_ArtifactInheritsVersion.frozenParentGroupIdArtifactIdVersion();
                } else if (SamplePom_ArtifactInheritsVersion.groupIdArtifactIdVersion().equals(snapshotGroupIdArtifactIdVersion)) {
                    return SamplePom_ArtifactInheritsVersion.frozenGroupIdArtifactIdVersion();
                } else if (SamplePom_ArtifactInheritsVersion.libraryGroupIdArtifactIdVersion().equals(snapshotGroupIdArtifactIdVersion)) {
                    return SamplePom_ArtifactInheritsVersion.frozenLibraryGroupIdArtifactIdVersion();
                }
                throw new IllegalStateException("Not expected groupIdArtifactIdVersionPrefix : " + snapshotGroupIdArtifactIdVersion);
            }

            @Override
            public boolean artifactInheritsVersionFromParent() {
                return false;
            }

            @Override
            public String artifactFrozenVersion() {
                return SamplePom_ArtifactInheritsVersion.FROZEN_VERSION;
            }
        };

        ByteArrayOutputStream pomOutputStream = new ByteArrayOutputStream();
        new DefaultPomFreezer(frozenArtifactResolverDummy, SamplePom_ArtifactInheritsVersion.fakedStamper(), new ConsoleLogger()).freeze(SamplePom_Library.asStream(), pomOutputStream);
        String pomContent = pomOutputStream.toString();
        System.out.print(pomContent);
        Assert.assertTrue(pomContent.contains("<version>" + SamplePom_ArtifactInheritsVersion.FROZEN_VERSION + "</version>"));
        Assert.assertTrue(pomContent.contains("<version>" + SamplePom_ArtifactInheritsVersion.LIBRARY_FROZEN_VERSION + "</version>"));
    }

}


text:
package org.basex.query.expr.path;

import static org.basex.query.QueryError.*;

import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.iter.*;
import org.basex.query.util.list.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.value.type.*;
import org.basex.query.var.*;
import org.basex.util.*;
import org.basex.util.hash.*;

/**
 * Mixed path expression.
 *
 * @author BaseX Team 2005-22, BSD License
 * @author Christian Gruen
 */
public final class MixedPath extends Path {
  /**
   * Constructor.
   * @param info input info
   * @param root root expression; can be a {@code null} reference
   * @param steps axis steps
   */
  MixedPath(final InputInfo info, final Expr root, final Expr... steps) {
    super(info, AtomType.ITEM, root, steps);
  }

  @Override
  public Iter iter(final QueryContext qc) throws QueryException {
    final Value rt = root != null ? root.value(qc) : ctxValue(qc);
    Iter iter = rt.iter(qc);
    long size = iter.size();

    final QueryFocus focus = qc.focus, qf = new QueryFocus();
    qc.focus = qf;
    try {
      // loop through all expressions
      final int sl = steps.length;
      for(int s = 0; s < sl; s++) {
        // set context position and size
        qf.size = size;
        qf.pos = 0;

        // loop through all input items; cache nodes and items
        final ANodeBuilder nodes = new ANodeBuilder();
        final ValueBuilder items = new ValueBuilder(qc);
        final Expr step = steps[s];
        for(Item item; (item = iter.next()) != null;) {
          if(!(item instanceof ANode)) throw PATHNODE_X_X_X.get(info, step, item.type, item);
          qf.value = item;
          qf.pos++;
          // loop through all resulting items
          final Iter ir = step.iter(qc);
          for(Item it; (it = qc.next(ir)) != null;) {
            if(it instanceof ANode) nodes.add((ANode) it);
            else items.add(it);
          }
        }

        final Value value = items.value(step);
        if(value.isEmpty()) {
          // all results are nodes: create new iterator
          iter = nodes.value(step).iter();
        } else {
          // raise error if this is not the final result
          if(s + 1 < sl)
            throw PATHNODE_X_X_X.get(info, steps[s + 1], value.itemAt(0).type, value.itemAt(0));
          // result contains non-nodes: raise error if result any contains nodes
          if(!nodes.isEmpty()) throw MIXEDRESULTS.get(info);
          iter = value.iter();
        }
        size = iter.size();
      }
    } finally {
      qc.focus = focus;
    }
    return iter;
  }

  @Override
  public boolean ddo() {
    return seqType().type instanceof NodeType;
  }

  @Override
  public Value value(final QueryContext qc) throws QueryException {
    return iter(qc).value(qc, this);
  }

  @Override
  public boolean vacuous() {
    return steps[steps.length - 1].vacuous();
  }

  @Override
  public Expr copy(final CompileContext cc, final IntObjMap<Var> vm) {
    return copyType(new MixedPath(info, root == null ? null : root.copy(cc, vm),
        Arr.copyAll(cc, vm, steps)));
  }
}


text:
namespace Charity.Data.Repositories
{
    using System;
    using System.Linq;
    using Charity.Data.Common;
    using Charity.Data.Common.Repositories;
    using Charity.Data.Models;

    public class FoodRequestRepository : DeletableEntityRepository<FoodRequest>, IFoodRequestRepository
    {
        public FoodRequestRepository(IApplicationDbContext context)
            : base(context)
        {
        }
    }
}


text:
package jp.sourceforge.ea2ddl.dao.cbean.cq.ciq;

import org.seasar.dbflute.cbean.*;
import org.seasar.dbflute.cbean.ckey.*;
import org.seasar.dbflute.cbean.coption.ConditionOption;
import org.seasar.dbflute.cbean.cvalue.ConditionValue;
import org.seasar.dbflute.cbean.sqlclause.SqlClause;
import jp.sourceforge.ea2ddl.dao.cbean.*;
import jp.sourceforge.ea2ddl.dao.cbean.cq.bs.*;
import jp.sourceforge.ea2ddl.dao.cbean.cq.*;

/**
 * The condition-inline-query of t_operation.
 * @author DBFlute(AutoGenerator)
 */
public class TOperationCIQ extends AbstractBsTOperationCQ {

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    protected BsTOperationCQ _myCQ;

    // ===================================================================================
    //                                                                         Constructor
    //                                                                         ===========
    public TOperationCIQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel, BsTOperationCQ myCQ) {
        super(childQuery, sqlClause, aliasName, nestLevel);
        _myCQ = myCQ;
        _foreignPropertyName = _myCQ.getForeignPropertyName();// Accept foreign property name.
        _relationPath = _myCQ.getRelationPath();// Accept relation path.
    }

    // ===================================================================================
    //                                                             Override about Register
    //                                                             =======================
    @Override
    protected void reflectRelationOnUnionQuery(ConditionQuery baseQueryAsSuper, ConditionQuery unionQueryAsSuper) {
        throw new UnsupportedOperationException("InlineQuery must not need UNION method: " + baseQueryAsSuper + " : " + unionQueryAsSuper);
    }

    @Override
    protected void setupConditionValueAndRegisterWhereClause(ConditionKey k, Object v, ConditionValue cv, String col) {
        regIQ(k, v, cv, col);
    }

    @Override
    protected void setupConditionValueAndRegisterWhereClause(ConditionKey k, Object v, ConditionValue cv, String col, ConditionOption op) {
        regIQ(k, v, cv, col, op);
    }

    @Override
    protected void registerWhereClause(String whereClause) {
        registerInlineWhereClause(whereClause);
    }

    @Override
    protected String getInScopeSubQueryRealColumnName(String columnName) {
        if (_onClauseInline) {
            throw new UnsupportedOperationException("InScopeSubQuery of on-clause is unsupported");
        }
        return _onClauseInline ? getRealAliasName() + "." + columnName : columnName;
    }

    @Override
    protected void registerExistsSubQuery(ConditionQuery subQuery
            , String columnName, String relatedColumnName, String propertyName) {
        throw new UnsupportedOperationException("Sorry! ExistsSubQuery at inline view is unsupported. So please use InScopeSubQyery.");
    }

    // ===================================================================================
    //                                                                Override about Query
    //                                                                ====================
    protected ConditionValue getCValueOperationid() {
        return _myCQ.getOperationid();
    }
    public String keepOperationid_InScopeSubQuery_TOperationparamsList(TOperationparamsCQ subQuery) {
        return _myCQ.keepOperationid_InScopeSubQuery_TOperationparamsList(subQuery);
    }
    public String keepOperationid_NotInScopeSubQuery_TOperationparamsList(TOperationparamsCQ subQuery) {
        return _myCQ.keepOperationid_NotInScopeSubQuery_TOperationparamsList(subQuery);
    }
    public String keepOperationid_ExistsSubQuery_TOperationparamsList(TOperationparamsCQ subQuery) {
        throw new UnsupportedOperationException("ExistsSubQuery at inline() is unsupported! Sorry!");
    }
    public String keepOperationid_NotExistsSubQuery_TOperationparamsList(TOperationparamsCQ subQuery) {
        throw new UnsupportedOperationException("NotExistsSubQuery at inline() is unsupported! Sorry!");
    }
    public String keepOperationid_SpecifyDerivedReferrer_TOperationparamsList(TOperationparamsCQ subQuery) {
        throw new UnsupportedOperationException("(Specify)DerivedReferrer at inline() is unsupported! Sorry!");
    }
    public String keepOperationid_QueryDerivedReferrer_TOperationparamsList(TOperationparamsCQ subQuery) {
        throw new UnsupportedOperationException("(Query)DerivedReferrer at inline() is unsupported! Sorry!");
    }
    public String keepOperationid_QueryDerivedReferrer_TOperationparamsListParameter(Object parameterValue) {
        throw new UnsupportedOperationException("(Query)DerivedReferrer at inline() is unsupported! Sorry!");
    }
    protected ConditionValue getCValueObjectId() {
        return _myCQ.getObjectId();
    }
    protected ConditionValue getCValueName() {
        return _myCQ.getName();
    }
    public String keepName_InScopeSubQuery_TConnectorBySourceroleList(TConnectorCQ subQuery) {
        return _myCQ.keepName_InScopeSubQuery_TConnectorBySourceroleList(subQuery);
    }
    public String keepName_InScopeSubQuery_TConnectorByDestroleList(TConnectorCQ subQuery) {
        return _myCQ.keepName_InScopeSubQuery_TConnectorByDestroleList(subQuery);
    }
    public String keepName_NotInScopeSubQuery_TConnectorBySourceroleList(TConnectorCQ subQuery) {
        return _myCQ.keepName_NotInScopeSubQuery_TConnectorBySourceroleList(subQuery);
    }
    public String keepName_NotInScopeSubQuery_TConnectorByDestroleList(TConnectorCQ subQuery) {
        return _myCQ.keepName_NotInScopeSubQuery_TConnectorByDestroleList(subQuery);
    }
    public String keepName_ExistsSubQuery_TConnectorBySourceroleList(TConnectorCQ subQuery) {
        throw new UnsupportedOperationException("ExistsSubQuery at inline() is unsupported! Sorry!");
    }
    public String keepName_ExistsSubQuery_TConnectorByDestroleList(TConnectorCQ subQuery) {
        throw new UnsupportedOperationException("ExistsSubQuery at inline() is unsupported! Sorry!");
    }
    public String keepName_NotExistsSubQuery_TConnectorBySourceroleList(TConnectorCQ subQuery) {
        throw new UnsupportedOperationException("NotExistsSubQuery at inline() is unsupported! Sorry!");
    }
    public String keepName_NotExistsSubQuery_TConnectorByDestroleList(TConnectorCQ subQuery) {
        throw new UnsupportedOperationException("NotExistsSubQuery at inline() is unsupported! Sorry!");
    }
    public String keepName_SpecifyDerivedReferrer_TConnectorBySourceroleList(TConnectorCQ subQuery) {
        throw new UnsupportedOperationException("(Specify)DerivedReferrer at inline() is unsupported! Sorry!");
    }
    public String keepName_SpecifyDerivedReferrer_TConnectorByDestroleList(TConnectorCQ subQuery) {
        throw new UnsupportedOperationException("(Specify)DerivedReferrer at inline() is unsupported! Sorry!");
    }
    public String keepName_QueryDerivedReferrer_TConnectorBySourceroleList(TConnectorCQ subQuery) {
        throw new UnsupportedOperationException("(Query)DerivedReferrer at inline() is unsupported! Sorry!");
    }
    public String keepName_QueryDerivedReferrer_TConnectorBySourceroleListParameter(Object parameterValue) {
        throw new UnsupportedOperationException("(Query)DerivedReferrer at inline() is unsupported! Sorry!");
    }
    public String keepName_QueryDerivedReferrer_TConnectorByDestroleList(TConnectorCQ subQuery) {
        throw new UnsupportedOperationException("(Query)DerivedReferrer at inline() is unsupported! Sorry!");
    }
    public String keepName_QueryDerivedReferrer_TConnectorByDestroleListParameter(Object parameterValue) {
        throw new UnsupportedOperationException("(Query)DerivedReferrer at inline() is unsupported! Sorry!");
    }
    protected ConditionValue getCValueScope() {
        return _myCQ.getScope();
    }
    protected ConditionValue getCValueType() {
        return _myCQ.getType();
    }
    protected ConditionValue getCValueReturnarray() {
        return _myCQ.getReturnarray();
    }
    protected ConditionValue getCValueStereotype() {
        return _myCQ.getStereotype();
    }
    protected ConditionValue getCValueIsstatic() {
        return _myCQ.getIsstatic();
    }
    protected ConditionValue getCValueConcurrency() {
        return _myCQ.getConcurrency();
    }
    protected ConditionValue getCValueNotes() {
        return _myCQ.getNotes();
    }
    protected ConditionValue getCValueBehaviour() {
        return _myCQ.getBehaviour();
    }
    protected ConditionValue getCValueGenoption() {
        return _myCQ.getGenoption();
    }
    protected ConditionValue getCValuePos() {
        return _myCQ.getPos();
    }
    protected ConditionValue getCValueStyle() {
        return _myCQ.getStyle();
    }
    protected ConditionValue getCValuePure() {
        return _myCQ.getPure();
    }
    protected ConditionValue getCValueClassifier() {
        return _myCQ.getClassifier();
    }
    protected ConditionValue getCValueCode() {
        return _myCQ.getCode();
    }
    protected ConditionValue getCValueIsroot() {
        return _myCQ.getIsroot();
    }
    protected ConditionValue getCValueIsleaf() {
        return _myCQ.getIsleaf();
    }
    protected ConditionValue getCValueIsquery() {
        return _myCQ.getIsquery();
    }
    protected ConditionValue getCValueStateflags() {
        return _myCQ.getStateflags();
    }
    protected ConditionValue getCValueEaGuid() {
        return _myCQ.getEaGuid();
    }
    protected ConditionValue getCValueStyleex() {
        return _myCQ.getStyleex();
    }

    // ===================================================================================
    //                                                                     Scalar SubQuery
    //                                                                     ===============
    public String keepScalarSubQuery(TOperationCQ subQuery) {
        throw new UnsupportedOperationException("ScalarSubQuery at inline() is unsupported! Sorry!");
    }

    // ===================================================================================
    //                                                             MySelf InScope SubQuery
    //                                                             =======================
    public String keepMyselfInScopeSubQuery(TOperationCQ subQuery) {
        throw new UnsupportedOperationException("MyselfInScopeSubQuery at inline() is unsupported! Sorry!");
    }

    // ===================================================================================
    //                                                                       Very Internal
    //                                                                       =============
    // Very Internal (for Suppressing Warn about 'Not Use Import')
    String xiCB() { return TOperationCB.class.getName(); }
    String xiCQ() { return TOperationCQ.class.getName(); }
}


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

I'm a Research Engineer, currently working in London. My technical interests are mainly around machine learning, reinforcement learning, and robotics.

### Contact me

[osushkov@gmail.com](mailto:osushkov@gmail.com)


text:
import urllib2
from bs4 import BeautifulSoup

def command_pubivisat(bot, user, channel, args):
	"""Fetches todays pub quizzes for Tampere from pubivisat.fi"""
	url = "http://pubivisat.fi/tampere"

	f = urllib2.urlopen(url)
	d = f.read()
	f.close()

	bs = BeautifulSoup(d)
	data = bs.find('table', {'class': 'quiz_list'}).find('tbody').findAll('tr')

	quizzes = []
	for row in data:
		name = row.find('a').string
		time = row.findAll('td')[1].string

		quizzes.append("%s: %s" % (str(name), str(time)))

	output = ' | '.join(reversed(quizzes))
	return(bot.say(channel, output))


text:
package com.guidewire.editor.devtools.smartcopy;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;

public class ClipboardUtil {

  public static void copyToClipboard(String text) {
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    StringSelection data = new StringSelection(text);
    clipboard.setContents(data, data);
  }

}


text:
/* globals YoastACFAnalysisConfig */
module.exports = YoastACFAnalysisConfig;


text:
package processor

import (
	"context"
	"log"
	"net/http"
	"time"
)

var r = &Registry{}

// Registry stores all the processors known to this application
type Registry struct {
	ps []Processor
}

func (r *Registry) register(p Processor) {
	r.ps = append(r.ps, p)
}

// List the registered processors
func (r *Registry) List() []Processor {
	return r.ps
}

// Get the processor registry
func Get() *Registry {
	return r
}

// Register a new processor
func Register(p Processor) {
	log.Printf("Registering the processor %s", p)
	r.register(p)
}

// GetOutcome for the given request, stopping after the first non-neutral outcome
func GetOutcome(req *http.Request) Outcome {
	timeout := 50 * time.Millisecond
	ctx, cancel := context.WithTimeout(req.Context(), timeout)

	for _, p := range Get().List() {
		o, err := p.Process(req.WithContext(ctx))
		if err != nil {
			log.Printf("registry: %s", err)
		}

		if o != NEUTRAL {
			log.Printf("outcome: %d", o)
			cancel()
			return o
		}
	}

	cancel()
	return NEUTRAL
}


text:
package uk.co.buildergenerator.testmodel;

public class ArrayOfPrimitiveIntsPropertyWithSetArrayMethod {

    private int[] ints;

    public int[] getInts() {
        return ints;
    }

    public void setInts(int[] ints) {
        this.ints = ints;
    }
}


text:
yum_repository 'test9' do
  source 'custom_template.erb'
  description 'a test'
  baseurl 'http://drop.the.baseurl.biz'
  enabled false
  action :create
end


text:
---
title: "removeEventListener and this"
path: "/removeeventlistener-and-this/"
date: "2017-01-17T14:46:20.000Z"
date_updated:   2017-01-19T11:04:25.000Z
tags: JavaScript, DOM
---

Have you ever tried to call `removeEventListener` on a previously attached element and couldn't remove it? Did you maybe try to pass a function to `addEventListener` that is bound to another context?

The context of the callback that we are passing to `addEventListener` is the same as the event.currentTarget when is being called. The problem is that when we bind the callback to another object, we can't remove it afterward.

Lets see an example:

```js
let element = document.createElement('button');

let callback = function (e) {
  console.assert(e.currentTarget === this);
}

element.addEventListener('click', callback);

element.dispatchEvent(new Event('click'));
```

In the example above, the assertion inside the callback is always going to be true. Great? Great. But that's not the case. Consider something like this:

```js
let Button = function () {
  this.el = document.createElement('button');
  this.addEvents();
}

Button.prototype.addEvents = function () {
  this.el.addEventListener('click', this.clickHandler.bind(this));
}

Button.prototype.clickHandler = function () {
  /* do something with this */
}
```

Great! I am trying to model my Button element and I need the event handlers to bind to the model itself.

Now let's try to remove the attached handler.

```js
let Button = function () {

  this.el = document.createElement('button');
  this.addEvents();
}

Button.prototype.addEvents = function () {
  this.el.addEventListener('click', this.clickHandler.bind(this));
}

Button.prototype.removeEvents = function () {
  this.el.removeEventListener('click', this.clickHandler);
}

Button.prototype.clickHandler = function () {
  /* do something with this */
}
```

The above won't work. Meaning that the `removeEventListener` won't actually remove the attached event handler. It will simply skip it. (And certainly if we bind again at the `removeEventListener` won't work). See, bind returns always a new function while `removeEventListener` and `addEventListener` second parameter must refer to the same function object.

So what do we do when we need to remove our attached event handlers at some point at runtime? Meet `handleEvent`, the default function that JavaScript looks for when tries to find a handler that has been attached to an event.

```js
let Button = function () {

  this.el = document.createElement('button');
  this.addEvents();
}

Button.prototype.addEvents = function () {
  this.el.addEventListener('click', this);
}

Button.prototype.removeEvents = function () {
  this.el.removeEventListener('click', this);
}

Button.prototype.handleEvent = function (e) {
  switch(e.type) {
    case 'click': {
     this.clickHandler(e);
    }
  }
}

Button.prototype.clickHandler = function () {
  /* do something with this */
}
```

Note how I pass only `this` to the `addEventListener`/`removeEventListener` functions.  `addEventListener` accepts objects as well. This way, JavaScript will look for the `handleEvent` function and call it with the event passed.

This way we are able to remove the event listeners while `this` inside `clickHandler` is correctly set to the `Button` class.

Another possible solution would be to keep a reference to the binded function and then remove that.

```js
let Button = function () {

  this.el = document.createElement('button');
  this.clickHandler = this.clickHandler.bind(this);
  this.addEvents();
}

Button.prototype.addEvents = function () {
  this.el.addEventListener('click', this.clickHandler);
}

Button.prototype.removeEvents = function () {
  this.el.removeEventListener('click', this.clickHandler);
}

Button.prototype.clickHandler = function () {
  /* do something with this */
}
```

I still like the `handleEvent` function because I keep my event handlers in a single place and I don't pollute the constructor with meaningless bindings.

All of the above behaves exactly the same way using the class keyword of ES6.

Have you ever run into a similar situation? What did you do? Leave me a comment! :)


text:
<?php
namespace fay\core;

use fay\core\FBase;

class Response extends FBase{
	/**
	 * HTTP状态码
	 */
	public static $httpStatuses = array(
		100 => 'Continue',
		101 => 'Switching Protocols',
		102 => 'Processing',
		118 => 'Connection timed out',
		200 => 'OK',
		201 => 'Created',
		202 => 'Accepted',
		203 => 'Non-Authoritative',
		204 => 'No Content',
		205 => 'Reset Content',
		206 => 'Partial Content',
		207 => 'Multi-Status',
		208 => 'Already Reported',
		210 => 'Content Different',
		226 => 'IM Used',
		300 => 'Multiple Choices',
		301 => 'Moved Permanently',
		302 => 'Found',
		303 => 'See Other',
		304 => 'Not Modified',
		305 => 'Use Proxy',
		306 => 'Reserved',
		307 => 'Temporary Redirect',
		308 => 'Permanent Redirect',
		310 => 'Too many Redirect',
		400 => 'Bad Request',
		401 => 'Unauthorized',
		402 => 'Payment Required',
		403 => 'Forbidden',
		404 => 'Not Found',
		405 => 'Method Not Allowed',
		406 => 'Not Acceptable',
		407 => 'Proxy Authentication Required',
		408 => 'Request Time-out',
		409 => 'Conflict',
		410 => 'Gone',
		411 => 'Length Required',
		412 => 'Precondition Failed',
		413 => 'Request Entity Too Large',
		414 => 'Request-URI Too Long',
		415 => 'Unsupported Media Type',
		416 => 'Requested range unsatisfiable',
		417 => 'Expectation failed',
		418 => 'I\'m a teapot',
		422 => 'Unprocessable entity',
		423 => 'Locked',
		424 => 'Method failure',
		425 => 'Unordered Collection',
		426 => 'Upgrade Required',
		428 => 'Precondition Required',
		429 => 'Too Many Requests',
		431 => 'Request Header Fields Too Large',
		449 => 'Retry With',
		450 => 'Blocked by Windows Parental Controls',
		500 => 'Internal Server Error',
		501 => 'Not Implemented',
		502 => 'Bad Gateway ou Proxy Error',
		503 => 'Service Unavailable',
		504 => 'Gateway Time-out',
		505 => 'HTTP Version not supported',
		507 => 'Insufficient storage',
		508 => 'Loop Detected',
		509 => 'Bandwidth Limit Exceeded',
		510 => 'Not Extended',
		511 => 'Network Authentication Required',
	);

	/**
	 * 发送一个http头
	 * @param int $code
	 * @param string $text
	 */
	public static function setStatusHeader($code = 200, $text = ''){
		if ($code == '' OR ! is_numeric($code)){
			throw new HttpException('Status codes must be numeric', 500);
		}

		if (isset(self::$httpStatuses[$code]) AND $text == ''){
			$text = self::$httpStatuses[$code];
		}

		if ($text == ''){
			throw new HttpException('No status text available.  Please check your status code number or supply your own message text.', 500);
		}

		$server_protocol = (isset($_SERVER['SERVER_PROTOCOL'])) ? $_SERVER['SERVER_PROTOCOL'] : FALSE;

		if (substr(php_sapi_name(), 0, 3) == 'cgi'){
			header("Status: {$code} {$text}", TRUE);
		}elseif ($server_protocol == 'HTTP/1.1' OR $server_protocol == 'HTTP/1.0'){
			header($server_protocol." {$code} {$text}", TRUE, $code);
		}else{
			header("HTTP/1.1 {$code} {$text}", TRUE, $code);
		}
	}

	/**
	 * 页面跳转
	 * @param string $uri
	 * @param array $params
	 */
	public static function redirect($uri = null, $params = array(), $url_rewrite = true){
		if($uri === null){
			header('location:'.\F::app()->view->url(null));
		}else{
			header('location:'.\F::app()->view->url($uri, $params, $url_rewrite));
		}
		die;
	}

	/**
	 * 返回上一页
	 */
	public static function goback(){
		if(isset($_SERVER['HTTP_REFERER'])){
			header('location:'.$_SERVER['HTTP_REFERER']);
		}else{
			echo '<script>history.go(-1);</script>';
		}
		die;
	}

	/**
	 * 在非显示性页面调用此方法输出。
	 * 若为ajax访问,则返回json
	 * 若是浏览器访问,则设置flash后跳转
	 * @param string $status 状态success, error
	 * @param array|string $data
	 * @param bool|array $redirect 跳转地址,若为false且是浏览器访问,则返回上一页
	 */
	public static function output($status = 'error', $data = array(), $redirect = false){
		if(!is_array($data)){
			$data = array(
				'message'=>$data,
			);
		}
		if(\F::app()->input->isAjaxRequest()){
			echo json_encode(array(
				'status'=>$status == 'success' ? 1 : 0,
			)+$data);
			die;
		}else{
			if(!empty($data['message'])){
				//若设置了空 的message,则不发flash
				\F::app()->flash->set($data['message'], $status);
			}else if($status == 'success'){
				\F::app()->flash->set('操作成功', $status);
			}else{
				\F::app()->flash->set('操作失败', $status);
			}

			if($redirect === false){
				self::goback();
			}else{
				if(is_array($redirect)){
					$redirect = \F::app()->view->url($redirect[0],
						empty($redirect[1]) ? array() : $redirect[1],
						isset($redirect[2]) && $redirect[2] === false ? false : true);
				}
				header('location:'.$redirect);
				die;
			}
		}
	}

	/**
	 * 用一个单页来做信息提示,并在$delay时间后跳转
	 * @param unknown $message 信息
	 * @param number $delay 停留时间
	 * @param string $redirect 跳转的url,默认为回到上一页
	 */
	public static function jump($message, $status = 'success', $redirect = false, $delay = 3){
		if(!$redirect && !empty($_SERVER['HTTP_REFERER'])){
			$redirect = $_SERVER['HTTP_REFERER'];
		}
		\F::app()->view->renderPartial('common/jump', array(
			'redirect'=>$redirect,
			'status'=>$status,
			'message'=>$message,
			'delay'=>$delay,
		));
		die;
	}
}


text:
class JsTestsController < ActionController::Base
  helper_method :tests, :test

  def index
  end

  def show
  end

private
  def tests
    @tests ||= TestRailsJs.tests do |tests, path|
      asset_path = Pathname(path)
      tests.map do |test|
        { :asset => Pathname(test).relative_path_from(asset_path).sub_ext('').to_s,
          :path => Pathname(test).relative_path_from(Rails.root) }
      end
    end
  end

  def test
    params[:id]
  end
end


text:
@interface YLWebViewController ()
@property(nonatomic, strong) WKWebView *webView;
@end

@implementation YLWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (WKWebView *)webView
{
    if(!_webView) {
        _webView = self.configeWebView;
        [self.view addSubview:_webView];
    }
    return _webView;
}

- (WKWebView *)configeWebView
{
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    webView.navigationDelegate = self;
    return webView;
}

- (void)clearWebCache
{
    NSArray * types = @[WKWebsiteDataTypeMemoryCache, WKWebsiteDataTypeDiskCache];
    NSSet *websiteDataTypes = [NSSet setWithArray:types];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];

    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
    }];
}

- (void)setUrlStr:(NSString *)urlStr
{
    _urlStr = urlStr;
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
}

- (void)setHtmlString:(NSString *)htmlString
{
    _htmlString = htmlString;
    [self.webView loadHTMLString:_htmlString baseURL:nil];
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation
{
    __weak typeof(YLWebViewController *)wekeSelf = self;
    [webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable title, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            __strong typeof(YLWebViewController *)self = wekeSelf;
            self.title = title;
        });
    }];
}
@end


text:
version: v0.36.5
category: API
title: 'Ipc Main'
source_url: 'https://github.com/atom/electron/blob/master/docs/api/ipc-main.md'
---

# ipcMain

The `ipcMain` module is an instance of the
[EventEmitter](https://nodejs.org/api/events.html) class. When used in the main
process, it handles asynchronous and synchronous messages sent from a renderer
process (web page). Messages sent from a renderer will be emitted to this
module.

## Sending Messages

It is also possible to send messages from the main process to the renderer
process, see [webContents.send](http://electron.atom.io/docs/v0.36.5/api/web-contents#webcontentssendchannel-arg1-arg2-) for more information.

* When sending a message, the event name is the `channel`.
* To reply a synchronous message, you need to set `event.returnValue`.
* To send an asynchronous back to the sender, you can use
  `event.sender.send(...)`.

An example of sending and handling messages between the render and main
processes:

```javascript
// In main process.
const ipcMain = require('electron').ipcMain;
ipcMain.on('asynchronous-message', function(event, arg) {
  console.log(arg);  // prints "ping"
  event.sender.send('asynchronous-reply', 'pong');
});

ipcMain.on('synchronous-message', function(event, arg) {
  console.log(arg);  // prints "ping"
  event.returnValue = 'pong';
});
```

```javascript
// In renderer process (web page).
const ipcRenderer = require('electron').ipcRenderer;
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong"

ipcRenderer.on('asynchronous-reply', function(event, arg) {
  console.log(arg); // prints "pong"
});
ipcRenderer.send('asynchronous-message', 'ping');
```

## Listening for Messages

The `ipcMain` module has the following method to listen for events:

### `ipcMain.on(channel, callback)`

* `channel` String - The event name.
* `callback` Function

When the event occurs the `callback` is called with an `event` object and
arbitrary arguments.

### `ipcMain.removeListener(channel, callback)`

* `channel` String - The event name.
* `callback` Function - The reference to the same function that you used for
  `ipcMain.on(channel, callback)`

Once done listening for messages, if you no longer want to activate this
callback and for whatever reason can't merely stop sending messages on the
channel, this function will remove the callback handler for the specified
channel.

### `ipcMain.removeAllListeners(channel)`

* `channel` String - The event name.

This removes *all* handlers to this ipc channel.

### `ipcMain.once(channel, callback)`

Use this in place of `ipcMain.on()` to fire handlers meant to occur only once,
as in, they won't be activated after one call of `callback`

## IPC Event

The `event` object passed to the `callback` has the following methods:

### `event.returnValue`

Set this to the value to be returned in a synchronous message.

### `event.sender`

Returns the `webContents` that sent the message, you can call
`event.sender.send` to reply to the asynchronous message, see
[webContents.send](http://electron.atom.io/docs/v0.36.5/api/web-contents#webcontentssendchannel-arg1-arg2-) for more information.


text:
package com.hotdocs.cloud;

/**
 * Interview format options
 */
public enum InterviewFormat {
    JavaScript, Silverlight, Unspecified
}


text:
#ifndef XSIMD_ALIGNED_ALLOCATOR_HPP
#define XSIMD_ALIGNED_ALLOCATOR_HPP

#include "../config/xsimd_arch.hpp"

#include <algorithm>
#include <utility>
#ifdef _WIN32
#include <malloc.h>
#else
#include <cstdlib>
#endif

#include <cassert>

namespace xsimd
{

    /**
     * @class aligned_allocator
     * @brief Allocator for aligned memory
     *
     * The aligned_allocator class template is an allocator that
     * performs memory allocation aligned by the specified value.
     *
     * @tparam T type of objects to allocate.
     * @tparam Align alignment in bytes.
     */
    template <class T, size_t Align=default_arch::alignment()>
    class aligned_allocator
    {
    public:

        using value_type = T;
        using pointer = T*;
        using const_pointer = const T*;
        using reference = T&;
        using const_reference = const T&;
        using size_type = size_t;
        using difference_type = ptrdiff_t;

        static constexpr size_t alignment = Align;

        template <class U>
        struct rebind
        {
            using other = aligned_allocator<U, Align>;
        };

        aligned_allocator() noexcept;
        aligned_allocator(const aligned_allocator& rhs) noexcept;

        template <class U>
        aligned_allocator(const aligned_allocator<U, Align>& rhs) noexcept;

        ~aligned_allocator();

        pointer address(reference) noexcept;
        const_pointer address(const_reference) const noexcept;

        pointer allocate(size_type n, const void* hint = 0);
        void deallocate(pointer p, size_type n);

        size_type max_size() const noexcept;
        size_type size_max() const noexcept;

        template <class U, class... Args>
        void construct(U* p, Args&&... args);

        template <class U>
        void destroy(U* p);
    };

    template <class T1, size_t Align1, class T2, size_t Align2>
    bool operator==(const aligned_allocator<T1, Align1>& lhs,
                    const aligned_allocator<T2, Align2>& rhs) noexcept;

    template <class T1, size_t Align1, class T2, size_t Align2>
    bool operator!=(const aligned_allocator<T1, Align1>& lhs,
                    const aligned_allocator<T2, Align2>& rhs) noexcept;

    void* aligned_malloc(size_t size, size_t alignment);
    void aligned_free(void* ptr);

    template <class T>
    size_t get_alignment_offset(const T* p, size_t size, size_t block_size);

    /************************************
     * aligned_allocator implementation *
     ************************************/

    /**
     * Default constructor.
     */
    template <class T, size_t A>
    inline aligned_allocator<T, A>::aligned_allocator() noexcept
    {
    }

    /**
     * Copy constructor.
     */
    template <class T, size_t A>
    inline aligned_allocator<T, A>::aligned_allocator(const aligned_allocator&) noexcept
    {
    }

    /**
     * Extended copy constructor.
     */
    template <class T, size_t A>
    template <class U>
    inline aligned_allocator<T, A>::aligned_allocator(const aligned_allocator<U, A>&) noexcept
    {
    }

    /**
     * Destructor.
     */
    template <class T, size_t A>
    inline aligned_allocator<T, A>::~aligned_allocator()
    {
    }

    /**
     * Returns the actual address of \c r even in presence of overloaded \c operator&.
     * @param r the object to acquire address of.
     * @return the actual address of \c r.
     */
    template <class T, size_t A>
    inline auto
    aligned_allocator<T, A>::address(reference r) noexcept -> pointer
    {
        return &r;
    }

    /**
     * Returns the actual address of \c r even in presence of overloaded \c operator&.
     * @param r the object to acquire address of.
     * @return the actual address of \c r.
     */
    template <class T, size_t A>
    inline auto
    aligned_allocator<T, A>::address(const_reference r) const noexcept -> const_pointer
    {
        return &r;
    }

    /**
     * Allocates <tt>n * sizeof(T)</tt> bytes of uninitialized memory, aligned by \c A.
     * The alignment may require some extra memory allocation.
     * @param n the number of objects to allocate storage for.
     * @param hint unused parameter provided for standard compliance.
     * @return a pointer to the first byte of a memory block suitably aligned and sufficient to
     * hold an array of \c n objects of type \c T.
     */
    template <class T, size_t A>
    inline auto
    aligned_allocator<T, A>::allocate(size_type n, const void*) -> pointer
    {
        pointer res = reinterpret_cast<pointer>(aligned_malloc(sizeof(T) * n, A));
        if (res == nullptr)
            throw std::bad_alloc();
        return res;
    }

    /**
     * Deallocates the storage referenced by the pointer p, which must be a pointer obtained by
     * an earlier call to allocate(). The argument \c n must be equal to the first argument of the call
     * to allocate() that originally produced \c p; otherwise, the behavior is undefined.
     * @param p pointer obtained from allocate().
     * @param n number of objects earlier passed to allocate().
     */
    template <class T, size_t A>
    inline void aligned_allocator<T, A>::deallocate(pointer p, size_type)
    {
        aligned_free(p);
    }

    /**
     * Returns the maximum theoretically possible value of \c n, for which the
     * call allocate(n, 0) could succeed.
     * @return the maximum supported allocated size.
     */
    template <class T, size_t A>
    inline auto
    aligned_allocator<T, A>::max_size() const noexcept -> size_type
    {
        return size_type(-1) / sizeof(T);
    }

    /**
     * This method is deprecated, use max_size() instead
     */
    template <class T, size_t A>
    inline auto
    aligned_allocator<T, A>::size_max() const noexcept -> size_type
    {
        return size_type(-1) / sizeof(T);
    }

    /**
     * Constructs an object of type \c T in allocated uninitialized memory
     * pointed to by \c p, using placement-new.
     * @param p pointer to allocated uninitialized memory.
     * @param args the constructor arguments to use.
     */
    template <class T, size_t A>
    template <class U, class... Args>
    inline void aligned_allocator<T, A>::construct(U* p, Args&&... args)
    {
        new ((void*)p) U(std::forward<Args>(args)...);
    }

    /**
     * Calls the destructor of the object pointed to by \c p.
     * @param p pointer to the object that is going to be destroyed.
     */
    template <class T, size_t A>
    template <class U>
    inline void aligned_allocator<T, A>::destroy(U* p)
    {
        p->~U();
    }

    /**
     * @defgroup allocator_comparison Comparison operators
     */

    /**
     * @ingroup allocator_comparison
     * Compares two aligned memory allocator for equality. Since allocators
     * are stateless, return \c true iff <tt>A1 == A2</tt>.
     * @param lhs aligned_allocator to compare.
     * @param rhs aligned_allocator to compare.
     * @return true if the allocators have the same alignment.
     */
    template <class T1, size_t A1, class T2, size_t A2>
    inline bool operator==(const aligned_allocator<T1, A1>& lhs,
                           const aligned_allocator<T2, A2>& rhs) noexcept
    {
        return lhs.alignment == rhs.alignment;
    }

    /**
    * @ingroup allocator_comparison
     * Compares two aligned memory allocator for inequality. Since allocators
     * are stateless, return \c true iff <tt>A1 != A2</tt>.
     * @param lhs aligned_allocator to compare.
     * @param rhs aligned_allocator to compare.
     * @return true if the allocators have different alignments.
     */
    template <class T1, size_t A1, class T2, size_t A2>
    inline bool operator!=(const aligned_allocator<T1, A1>& lhs,
                           const aligned_allocator<T2, A2>& rhs) noexcept
    {
        return !(lhs == rhs);
    }

    /****************************************
     * aligned malloc / free implementation *
     ****************************************/

    namespace detail
    {
        inline void* xaligned_malloc(size_t size, size_t alignment)
        {
            assert(((alignment & (alignment - 1)) == 0) && "alignment must be a power of two");
            assert((alignment >= sizeof(void*)) && "alignment must be at least the size of a pointer");
            void* res = nullptr;
#ifdef _WIN32
            res = _aligned_malloc(size, alignment);
#else
            if(posix_memalign(&res, alignment, size) != 0)
            {
                res = nullptr;
            }
#endif
            return res;
        }

        inline void xaligned_free(void* ptr)
        {
#ifdef _WIN32
            _aligned_free(ptr);
#else
            free(ptr);
#endif
        }
    }

    inline void* aligned_malloc(size_t size, size_t alignment)
    {
        return detail::xaligned_malloc(size, alignment);
    }

    inline void aligned_free(void* ptr)
    {
        detail::xaligned_free(ptr);
    }

    template <class T>
    inline size_t get_alignment_offset(const T* p, size_t size, size_t block_size)
    {
        // size_t block_size = simd_traits<T>::size;
        if (block_size == 1)
        {
            // The simd_block consists of exactly one scalar so that all
            // elements of the array
            // are "well" aligned.
            return 0;
        }
        else if (size_t(p) & (sizeof(T) - 1))
        {
            // The array is not aligned to the size of a single element, so that
            // no element
            // of the array is well aligned
            return size;
        }
        else
        {
            size_t block_mask = block_size - 1;
            return std::min<size_t>(
                (block_size - ((size_t(p) / sizeof(T)) & block_mask)) & block_mask,
                size);
        }
    }

    template<class T, class A=default_arch>
    using default_allocator = typename std::conditional<A::requires_alignment(),
              aligned_allocator<T, A::alignment()>,
              std::allocator<T>
            >::type;
}

#endif


text:
<?php namespace App\Repositories;

use Prettus\Repository\Eloquent\BaseRepository;

abstract class ExtendedRepository extends BaseRepository
{
    public function includeRelations($relations)
    {
        $this->presenter->parseIncludes($relations);

        return $this;
    }

    public function parserResult($result)
    {
        return parent::parserResult($result);
    }
}


text:
"""Support for Xiaomi Yeelight WiFi color bulb."""
from __future__ import annotations

import asyncio
import logging

from yeelight import BulbException
from yeelight.aio import KEY_CONNECTED

from homeassistant.const import CONF_ID, CONF_NAME
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.event import async_call_later

from .const import (
    ACTIVE_COLOR_FLOWING,
    ACTIVE_MODE_NIGHTLIGHT,
    DATA_UPDATED,
    STATE_CHANGE_TIME,
    UPDATE_REQUEST_PROPERTIES,
)
from .scanner import YeelightScanner

_LOGGER = logging.getLogger(__name__)

@callback
def async_format_model(model: str) -> str:
    """Generate a more human readable model."""
    return model.replace("_", " ").title()

@callback
def async_format_id(id_: str) -> str:
    """Generate a more human readable id."""
    return hex(int(id_, 16)) if id_ else "None"

@callback
def async_format_model_id(model: str, id_: str) -> str:
    """Generate a more human readable name."""
    return f"{async_format_model(model)} {async_format_id(id_)}"

@callback
def _async_unique_name(capabilities: dict) -> str:
    """Generate name from capabilities."""
    model_id = async_format_model_id(capabilities["model"], capabilities["id"])
    return f"Yeelight {model_id}"

def update_needs_bg_power_workaround(data):
    """Check if a push update needs the bg_power workaround.

    Some devices will push the incorrect state for bg_power.

    To work around this any time we are pushed an update
    with bg_power, we force poll state which will be correct.
    """
    return "bg_power" in data

class YeelightDevice:
    """Represents single Yeelight device."""

    def __init__(self, hass, host, config, bulb):
        """Initialize device."""
        self._hass = hass
        self._config = config
        self._host = host
        self._bulb_device = bulb
        self.capabilities = {}
        self._device_type = None
        self._available = True
        self._initialized = False
        self._name = None

    @property
    def bulb(self):
        """Return bulb device."""
        return self._bulb_device

    @property
    def name(self):
        """Return the name of the device if any."""
        return self._name

    @property
    def config(self):
        """Return device config."""
        return self._config

    @property
    def host(self):
        """Return hostname."""
        return self._host

    @property
    def available(self):
        """Return true is device is available."""
        return self._available

    @callback
    def async_mark_unavailable(self):
        """Set unavailable on api call failure due to a network issue."""
        self._available = False

    @property
    def model(self):
        """Return configured/autodetected device model."""
        return self._bulb_device.model or self.capabilities.get("model")

    @property
    def fw_version(self):
        """Return the firmware version."""
        return self.capabilities.get("fw_ver")

    @property
    def is_nightlight_supported(self) -> bool:
        """
        Return true / false if nightlight is supported.

        Uses brightness as it appears to be supported in both ceiling and other lights.
        """
        return self._nightlight_brightness is not None

    @property
    def is_nightlight_enabled(self) -> bool:
        """Return true / false if nightlight is currently enabled."""
        # Only ceiling lights have active_mode, from SDK docs:
        # active_mode 0: daylight mode / 1: moonlight mode (ceiling light only)
        if self._active_mode is not None:
            return int(self._active_mode) == ACTIVE_MODE_NIGHTLIGHT

        if self._nightlight_brightness is not None:
            return int(self._nightlight_brightness) > 0

        return False

    @property
    def is_color_flow_enabled(self) -> bool:
        """Return true / false if color flow is currently running."""
        return self._color_flow and int(self._color_flow) == ACTIVE_COLOR_FLOWING

    @property
    def _active_mode(self):
        return self.bulb.last_properties.get("active_mode")

    @property
    def _color_flow(self):
        return self.bulb.last_properties.get("flowing")

    @property
    def _nightlight_brightness(self):
        return self.bulb.last_properties.get("nl_br")

    @property
    def type(self):
        """Return bulb type."""
        if not self._device_type:
            self._device_type = self.bulb.bulb_type

        return self._device_type

    async def _async_update_properties(self):
        """Read new properties from the device."""
        try:
            await self.bulb.async_get_properties(UPDATE_REQUEST_PROPERTIES)
            self._available = True
            if not self._initialized:
                self._initialized = True
        except OSError as ex:
            if self._available:  # just inform once
                _LOGGER.error(
                    "Unable to update device %s, %s: %s", self._host, self.name, ex
                )
            self._available = False
        except asyncio.TimeoutError as ex:
            _LOGGER.debug(
                "timed out while trying to update device %s, %s: %s",
                self._host,
                self.name,
                ex,
            )
        except BulbException as ex:
            _LOGGER.debug(
                "Unable to update device %s, %s: %s", self._host, self.name, ex
            )

    async def async_setup(self):
        """Fetch capabilities and setup name if available."""
        scanner = YeelightScanner.async_get(self._hass)
        self.capabilities = await scanner.async_get_capabilities(self._host) or {}
        if self.capabilities:
            self._bulb_device.set_capabilities(self.capabilities)
        if name := self._config.get(CONF_NAME):
            # Override default name when name is set in config
            self._name = name
        elif self.capabilities:
            # Generate name from model and id when capabilities is available
            self._name = _async_unique_name(self.capabilities)
        elif self.model and (id_ := self._config.get(CONF_ID)):
            self._name = f"Yeelight {async_format_model_id(self.model, id_)}"
        else:
            self._name = self._host  # Default name is host

    async def async_update(self, force=False):
        """Update device properties and send data updated signal."""
        if not force and self._initialized and self._available:
            # No need to poll unless force, already connected
            return
        await self._async_update_properties()
        async_dispatcher_send(self._hass, DATA_UPDATED.format(self._host))

    async def _async_forced_update(self, _now):
        """Call a forced update."""
        await self.async_update(True)

    @callback
    def async_update_callback(self, data):
        """Update push from device."""
        _LOGGER.debug("Received callback: %s", data)
        was_available = self._available
        self._available = data.get(KEY_CONNECTED, True)
        if update_needs_bg_power_workaround(data) or (
            not was_available and self._available
        ):
            # On reconnect the properties may be out of sync
            #
            # If the device drops the connection right away, we do not want to
            # do a property resync via async_update since its about
            # to be called when async_setup_entry reaches the end of the
            # function
            #
            async_call_later(self._hass, STATE_CHANGE_TIME, self._async_forced_update)
        async_dispatcher_send(self._hass, DATA_UPDATED.format(self._host))


text:
buzzlr is a Tumblr browser written in Swift. This was done for the [Yahoo Mobile Developer Conference Hackathon 2015](http://www.hackathon.io/yahoo-hackathon) in NY.

### Licensing
buzzlr is licensed under [the MIT License](https://github.com/duliodenis/buzzlr/blob/master/LICENSE).

### Support or Contact
Visit [ddApps.co](http://ddapps.co) to see more.


text:
package com.opengamma.web.analytics.blotter;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.joda.beans.Bean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaBean;
import org.joda.beans.MetaProperty;
import org.joda.beans.PropertyDefinition;
import org.joda.convert.StringConvert;
import org.json.JSONObject;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.util.ArgumentChecker;

/**
 * TODO can this be deleted?
 * TODO how should read-only properties be handled? I guess it depends on the use case of the data
 */
// TODO do this as HTML, easier to consume
/* package */ class JsonBeanStructureVisitor implements BeanVisitor<JSONObject> {

  private static final Map<Class<?>, String> s_types = Maps.newHashMap();
  private static final String NUMBER = "number";
  private static final String BOOLEAN = "boolean";
  private static final String STRING = "string";

  static {
    s_types.put(Double.TYPE, NUMBER);
    s_types.put(Double.class, NUMBER);
    s_types.put(Float.TYPE, NUMBER);
    s_types.put(Float.class, NUMBER);
    s_types.put(Long.TYPE, NUMBER);
    s_types.put(Long.class, NUMBER);
    s_types.put(Short.TYPE, NUMBER);
    s_types.put(Short.class, NUMBER);
    s_types.put(Integer.TYPE, NUMBER);
    s_types.put(Integer.class, NUMBER);
    s_types.put(Byte.TYPE, NUMBER);
    s_types.put(Byte.class, NUMBER);
    s_types.put(BigDecimal.class, NUMBER);
    s_types.put(Boolean.TYPE, BOOLEAN);
    s_types.put(Boolean.class, BOOLEAN);
    s_types.put(Character.TYPE, STRING);
    s_types.put(Character.class, STRING);
    s_types.put(String.class, STRING);
  }

  private final Map<String, Object> _json = Maps.newHashMap();
  private final BeanHierarchy _beanHierarchy;
  private final StringConvert _stringConvert;

  /* package */ JsonBeanStructureVisitor(Set<MetaBean> metaBeans) {
    ArgumentChecker.notNull(metaBeans, "metaBeans");
    _beanHierarchy = new BeanHierarchy(metaBeans);
    // TODO parameter for this
    _stringConvert = JodaBeanUtils.stringConverter();
  }

  @Override
  public void visitMetaBean(MetaBean metaBean) {
    // TODO configurable field name
    _json.clear();
    _json.put("type", metaBean.beanType().getSimpleName());
  }

  @Override
  public void visitBeanProperty(MetaProperty<?> property, BeanTraverser traverser) {
    Set<Class<? extends Bean>> argumentTypes = _beanHierarchy.subtypes(property.propertyType());
    if (argumentTypes.isEmpty()) {
      throw new OpenGammaRuntimeException("No bean types are available to satisfy property " + property);
    }
    List<String> beanTypeNames = Lists.newArrayListWithCapacity(argumentTypes.size());
    for (Class<? extends Bean> argumentType : argumentTypes) {
      beanTypeNames.add(argumentType.getSimpleName());
    }
    _json.put(property.name(), optional(property, StringUtils.join(beanTypeNames, "|")));
  }

  @Override
  public void visitCollectionProperty(MetaProperty<?> property, BeanTraverser traverser) {
    _json.put(property.name(), arrayType(property));
  }

  @Override
  public void visitSetProperty(MetaProperty<?> property, BeanTraverser traverser) {
    _json.put(property.name(), arrayType(property));
  }

  @Override
  public void visitListProperty(MetaProperty<?> property, BeanTraverser traverser) {
    _json.put(property.name(), arrayType(property));
  }

  @Override
  public void visitMapProperty(MetaProperty<?> property, BeanTraverser traverser) {
    Class<? extends Bean> beanType = property.metaBean().beanType();
    Class<?> keyType = JodaBeanUtils.mapKeyType(property, beanType);
    Class<?> valueType = JodaBeanUtils.mapValueType(property, beanType);
    _json.put(property.name(), optional(property,  "{" + typeFor(keyType) + ":" + typeFor(valueType) + "}"));
  }

  @Override
  public void visitProperty(MetaProperty<?> property, BeanTraverser traverser) {
    _json.put(property.name(), optional(property, typeFor(property)));
  }

  private static String optional(MetaProperty<?> property, String type) {
    if (nullable(property)) {
      return type + "?";
    } else {
      return type;
    }
  }

  @Override
  public JSONObject finish() {
    return new JSONObject(_json);
  }

  private String arrayType(MetaProperty<?> property) {
    return optional(property, "[" + typeFor(property.propertyType()) + "]");
  }

  private String typeFor(MetaProperty<?> property) {
    return typeFor(property.propertyType());
  }

  private String typeFor(Class<?> type) {
    String typeName = s_types.get(type);
    if (typeName != null) {
      return typeName;
    } else {
      try {
        _stringConvert.findConverter(type);
        return STRING;
      } catch (Exception e) {
        throw new OpenGammaRuntimeException("No type mapping found for class " + type.getName(), e);
      }
    }
  }

  private static boolean nullable(MetaProperty<?> property) {
    if (property.propertyType().isPrimitive()) {
      return false;
    } else {
      PropertyDefinition definitionAnnotation = property.annotation(PropertyDefinition.class);
      return !definitionAnnotation.validate().equals("notNull");
    }
  }
}


text:
module Api::Controllers::Tasks
  class Index
    include Api::Action
    include JSONAPI::Hanami::Action

    def call(params)
      self.data = tasks_repository.for_list(params[:list_id])
      self.status = 200
    end

    def tasks_repository
      @tasks_repository ||= TaskRepository.new
    end
  end
end


text:
package soundgates.diagram.edit.parts;

import org.eclipse.draw2d.Connection;
import org.eclipse.draw2d.PolylineDecoration;
import org.eclipse.draw2d.RotatableDecoration;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ConnectionNodeEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ITreeBranchEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.draw2d.ui.figures.PolylineConnectionEx;
import org.eclipse.gmf.runtime.notation.View;

import soundgates.diagram.edit.policies.Link2ItemSemanticEditPolicy;

/**
 * @generated NOT
 */
public class Link2EditPart extends ConnectionAbstractEditPart {

	/**
	 * @generated
	 */
	public static final int VISUAL_ID = 4002;

	/**
	 * @generated
	 */
	public Link2EditPart(View view) {
		super(view);
	}

	/**
	 * @generated
	 */
	protected void createDefaultEditPolicies() {
		super.createDefaultEditPolicies();
		installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE,
				new Link2ItemSemanticEditPolicy());
	}

	/**
	 * Creates figure for this edit part.
	 *
	 * Body of this method does not depend on settings in generation model
	 * so you may safely remove <i>generated</i> tag and modify it.
	 *
	 * @generated
	 */

	protected Connection createConnectionFigure() {
		return new CompositeSoundComponentLinksFigure();
	}

	/**
	 * @generated
	 */
	public CompositeSoundComponentLinksFigure getPrimaryShape() {
		return (CompositeSoundComponentLinksFigure) getFigure();
	}

	/**
	 * @generated
	 */
	public class CompositeSoundComponentLinksFigure extends
			PolylineConnectionEx {

		/**
		 * @generated
		 */
		public CompositeSoundComponentLinksFigure() {

			setTargetDecoration(createTargetDecoration());
		}

		/**
		 * @generated
		 */
		private RotatableDecoration createTargetDecoration() {
			PolylineDecoration df = new PolylineDecoration();
			return df;
		}

	}

}


text:
package Maths;

import org.junit.Test;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.fail;

/**
 * Created with IntelliJ IDEA.
 * User: sebastianzillessen
 * Date: 10.11.13
 * Time: 12:17
 * To change this template use File | Settings | File Templates.
 */
public class ArrayMathsTest {

    double d = 0.00001;

    @Test
    public void testIntToDouble() {
        assertEquals(1.0, ArrayMaths.intToDouble(new int[]{1})[0]);
        assertEquals(1.0, ArrayMaths.intToDouble(new int[]{1, 2, 3})[0]);
        assertEquals(2.0, ArrayMaths.intToDouble(new int[]{1, 2, 3})[1]);
        assertEquals(3.0, ArrayMaths.intToDouble(new int[]{1, 2, 3})[2]);
    }

    @Test
    public void testDiffMax() {
        double[] a = new double[]{3, 9, 1, 2};
        double[] b = new double[]{2, -9, 2, 4};
        assertEquals(18, ArrayMaths.diffMax(a, b), 0.0);
    }

    @Test
    public void testDiffMaxFail() {
        double[] a = new double[]{3, 9, 1, 2};
        double[] b = new double[]{2, -9, 2};
        try{
            ArrayMaths.diffMax(a,b);
            fail();
        }
        catch(Exception e){

        }
    }

}