text:
Imports System.ComponentModel
Imports SoftLogik.Win.UI

Namespace Reporting
    Public Class SPReportManager

        Private Shared WithEvents _reportViewer As SPReportViewer = Nothing
        Private Shared WithEvents _reportSettings As SPReportSettings = Nothing
        Private Shared _MdiParent As Form = Nothing

        Private Shared ReadOnly Property Viewer() As SPReportViewer
            Get
                If _reportViewer Is Nothing Then _reportViewer = New SPReportViewer
                If _reportViewer.IsDisposed Then _reportViewer = New SPReportViewer
                Return _reportViewer
            End Get
        End Property
        Public Shared ReadOnly Property Settings() As SPReportSettings
            Get
                If _reportSettings Is Nothing Then _reportSettings = New SPReportSettings
                If _reportSettings.IsDisposed Then _reportSettings = New SPReportSettings
                Return _reportSettings
            End Get
        End Property

        Public Shared WriteOnly Property MdiParent() As Form
            Set(ByVal value As Form)
                _MdiParent = value
            End Set
        End Property

        <Description("Load and Show a Report a specified Report File in the Customized Report Viewer.")> _
        Public Shared Sub ShowReport(ByVal ReportFile As String)
            With Settings
                .MdiParent = _MdiParent
                .ViewerForm = Viewer
                .Show()
            End With
        End Sub

        <Description("Load and Print a Report a specified Report File.")> _
        Public Shared Sub PrintReport(ByVal ReportFile As String)
            Viewer.MdiParent = _MdiParent
            With Settings
                .MdiParent = _MdiParent
                .ViewerForm = Viewer
            End With
        End Sub

    End Class
End Namespace


text:
package at.renehollander.transactionmanager.manager;

import at.renehollander.transactionmanager.Callback;
import at.renehollander.transactionmanager.Maps;
import com.corundumstudio.socketio.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Manager implements AuthorizationListener {

    private static Logger LOG = LoggerFactory.getLogger(Manager.class);

    private Map<String, SocketIOClient> clients;
    private SocketIOServer server;

    public Manager(int port) {

        clients = new HashMap<>();

        Configuration config = new Configuration();
        config.setPort(port);
        config.getSocketConfig().setReuseAddress(true);
        config.setAuthorizationListener(this);
        server = new SocketIOServer(config);

        server.addConnectListener(this::onConnect);
        server.addDisconnectListener(this::onDisconnect);

        server.start();
    }

    public void onConnect(SocketIOClient client) {
        String name = client.getHandshakeData().getUrlParams().get("name").get(0);
        client.set("name", name);
        clients.put(name, client);
        LOG.info("Client " + name + " connected!");
    }

    public void execute(int timeout, String statement, Callback.NoParamsWithStringError callback) {
        Lock lock = new ReentrantLock();
        Set<SocketIOClient> clients = fetch();
        List<String> exceptions = new ArrayList<>();
        AtomicBoolean triggered = new AtomicBoolean(false);
        server.getBroadcastOperations().sendEvent("execute", Maps.of("timeout", timeout, "statement", statement), new BroadcastAckCallback<Map>(Map.class, timeout) {
            public void onClientSuccess(SocketIOClient client, Map resultMap) {
                lock.lock();
                LOG.info("Recieved response from " + client.get("name"));
                Map<String, Object> result = resultMap;
                if (result == null) result = new HashMap<>();
                clients.remove(client);
                if (result.containsKey("error")) {
                    LOG.error("client " + client.get("name") + " responded with an exception: " + result.get("error"));
                    exceptions.add("client " + client.get("name") + " responded with an exception: " + result.get("error"));
                } else {
                    LOG.info("client " + client.get("name") + " response after " + statement + " was ok");
                }
                rollbackOrCommitCheck(clients, exceptions, timeout, callback, triggered);
                lock.unlock();
            }

            public void onClientTimeout(SocketIOClient client) {
                lock.lock();
                clients.remove(client);
                LOG.error("client " + client.get("name") + " timed out");
                exceptions.add("client " + client.get("name") + " timed out");
                rollbackOrCommitCheck(clients, exceptions, timeout, callback, triggered);
                lock.unlock();
            }
        });
        clients.forEach((client) -> {
            LOG.info("Sent Statement \"" + statement + "\" to " + client.get("name"));
        });
    }

    private synchronized void rollbackOrCommitCheck(Set<SocketIOClient> clients, List<String> exceptions, int timeout, Callback.NoParamsWithStringError callback, AtomicBoolean triggered) {
        if (!triggered.get() && clients.isEmpty()) {
            triggered.set(true);
            if (!exceptions.isEmpty()) {
                LOG.info("Executing Rollback on all stations");
                rollback(timeout, callback, exceptions);
            } else if (exceptions.isEmpty()) {
                LOG.info("Executing Commit on all stations");
                commit(timeout, callback, exceptions);
            }
        }
    }

    private synchronized void callbackCheck(Set<SocketIOClient> clients, List<String> exceptions, Callback.NoParamsWithStringError callback, AtomicBoolean triggered, List<String> prev) {
        if (!triggered.get() && clients.isEmpty()) {
            triggered.set(true);
            if (exceptions.isEmpty()) {
                callback.execute(prev.isEmpty() ? null : prev.toArray(new String[prev.size()]));
            } else if (!exceptions.isEmpty()) {
                List<String> all = new ArrayList<>(exceptions);
                all.addAll(prev);
                callback.execute(all.toArray(new String[all.size()]));
            }
        }
    }

    private void rollback(int timeout, Callback.NoParamsWithStringError callback, List<String> prev) {
        Lock lock = new ReentrantLock();
        Set<SocketIOClient> clients = fetch();
        List<String> exceptions = new ArrayList<>();
        AtomicBoolean triggered = new AtomicBoolean(false);
        server.getBroadcastOperations().sendEvent("rollback", null, new BroadcastAckCallback<Map>(Map.class, timeout) {
            public void onClientSuccess(SocketIOClient client, Map resultMap) {
                lock.lock();
                Map<String, Object> result = resultMap;
                if (result == null) result = new HashMap<>();
                clients.remove(client);
                if (result.containsKey("error")) {
                    LOG.error("client " + client.get("name") + " responded with an exception while rolling back: " + result.get("error"));
                    exceptions.add("client " + client.get("name") + " responded with an exception while rolling back: " + result.get("error"));
                } else {
                    LOG.info("client " + client.get("name") + " response after rollback was ok");
                }
                callbackCheck(clients, exceptions, callback, triggered, prev);
                lock.unlock();
            }

            public void onClientTimeout(SocketIOClient client) {
                lock.lock();
                clients.remove(client);
                exceptions.add("client " + client.get("name") + " timed out while rolling back");
                LOG.error("client " + client.get("name") + " timed out while rolling back");
                callbackCheck(clients, exceptions, callback, triggered, prev);
                lock.unlock();
            }
        });
    }

    private void commit(int timeout, Callback.NoParamsWithStringError callback, List<String> prev) {
        Lock lock = new ReentrantLock();
        Set<SocketIOClient> clients = fetch();
        List<String> exceptions = new ArrayList<>();
        AtomicBoolean triggered = new AtomicBoolean(false);
        server.getBroadcastOperations().sendEvent("commit", null, new BroadcastAckCallback<Map>(Map.class, timeout) {
            public void onClientSuccess(SocketIOClient client, Map resultMap) {
                lock.lock();
                Map<String, Object> result = resultMap;
                if (result == null) result = new HashMap<>();
                clients.remove(client);
                if (result.containsKey("error")) {
                    exceptions.add("client " + client.get("name") + " responded with an exception while committing: " + result.get("error"));
                    LOG.error("client " + client.get("name") + " responded with an exception while committing: " + result.get("error"));
                } else {
                    LOG.info("client " + client.get("name") + " response after commit was ok");
                }
                callbackCheck(clients, exceptions, callback, triggered, prev);
                lock.unlock();
            }

            public void onClientTimeout(SocketIOClient client) {
                lock.lock();
                clients.remove(client);
                exceptions.add("client " + client.get("name") + " timed out while committing");
                LOG.error("client " + client.get("name") + " timed out while committing");
                callbackCheck(clients, exceptions, callback, triggered, prev);
                lock.unlock();
            }
        });
    }

    public void onDisconnect(SocketIOClient client) {
        clients.remove(client.get("name"));
        LOG.info("Client " + client.get("name") + " disconnected!");
    }

    public boolean isAuthorized(HandshakeData data) {
        String name = data.getUrlParams().get("name").get(0);
        return !(name == null || name.isEmpty()) && !clients.containsKey(name);
    }

    private Set<SocketIOClient> fetch() {
        return new HashSet<>(server.getAllClients());
    }

}

redpajama_set_name: RedPajamaGithub


text:
package Zeno410Utils;

import net.minecraft.util.ChunkCoordinates;

/**
 *
 * @author Zeno410
 */
public class PlaneLocation {
    public final int x;
    public final int z;

    public PlaneLocation(int _x, int _z) {
        x = _x;
        z = _z;
    }

    public PlaneLocation(ChunkCoordinates coordinates) {
        this(coordinates.posX,coordinates.posZ);
    }

    public float distance(PlaneLocation location) {
        return ((float)(x-location.x))*((float)(x-location.x))+
                ((float)(z-location.z))*((float)(z-location.z));
    }

    public <Type extends Provider> Type closest(Iterable<Type> choices) {
        Type result = null;
        float bestDistance = Float.MAX_VALUE;
        float distance;

        for (Type tested: choices) {
            distance = this.distance(tested.planeLocation());
            if (distance<bestDistance) {
                result = tested;
            }
        }
        return result;
    }

    public abstract class Provider {
        abstract public PlaneLocation planeLocation();
    }
    @Override
    public int hashCode() {
        int hash = 7;
        hash = 71 * hash + this.x;
        hash = 71 * hash + this.z;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final PlaneLocation other = (PlaneLocation) obj;
        if (this.x != other.x) {
            return false;
        }
        if (this.z != other.z) {
            return false;
        }
        return true;
    }
}


text:
<?php

/**
 * Developer: alkis_stamos
 * Date: 4/5/2015
 * Time: 8:51 PM
 * Projections
 */

namespace Nuad\Graph;
/**
 * Metadata class to represent a single property of a graph object.
 *
 * Class Property
 * @package Nuad\Graph
 */
class Property
{
    /**
     * Const to determine if the Property type is string
     *
     * @var string
     */
    public static $_STRING_TYPE = 'S';
    /**
     * Const to determine if the Property type is integer
     *
     * @var string
     */
    public static $_INTEGER_TYPE = 'I';
    /**
     * Const to determine if the Property type is boolean
     *
     * @var string
     */
    public static $_BOOLEAN_TYPE = 'B';
    /**
     * Const to determine if the Property type is array
     *
     * @var string
     */
    public static $_ARRAY_TYPE = 'A';
    /**
     * Const to determine if the Property type is float or double
     *
     * @var string
     */
    public static $_DOUBLE_TYPE = 'D';
    /**
     * The type of the property can either be complex (for objects/lists of objects) or flat for simple types.
     *
     * @var Type
     */
    public $type;

    /**
     * Creates an empty property with the given graph Type
     *
     * @param Type $type
     */
    protected final function __construct(Type $type)
    {
        $this->type = $type;
    }
}


text:
package com.digitalpetri.opcua.stack.core.types.enumerated;

import com.digitalpetri.opcua.stack.core.serialization.DelegateRegistry;
import com.digitalpetri.opcua.stack.core.serialization.UaDecoder;
import com.digitalpetri.opcua.stack.core.serialization.UaEncoder;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.digitalpetri.opcua.stack.core.serialization.UaEnumeration;

public enum ServerState implements UaEnumeration {

    Running(0),
    Failed(1),
    NoConfiguration(2),
    Suspended(3),
    Shutdown(4),
    Test(5),
    CommunicationFault(6),
    Unknown(7);

    private final int value;

    private ServerState(int value) {
        this.value = value;
    }

    @Override
    public int getValue() {
        return value;
    }

    private static final ImmutableMap<Integer, ServerState> VALUES;

    static {
        Builder<Integer, ServerState> builder = ImmutableMap.builder();
        for (ServerState e : values()) {
            builder.put(e.getValue(), e);
        }
        VALUES = builder.build();
    }

    public static ServerState from(Integer value) {
        if (value == null) return null;
        return VALUES.getOrDefault(value, null);
    }

    public static void encode(ServerState serverState, UaEncoder encoder) {
        encoder.encodeInt32(null, serverState.getValue());
    }

    public static ServerState decode(UaDecoder decoder) {
        int value = decoder.decodeInt32(null);

        return VALUES.getOrDefault(value, null);
    }

    static {
        DelegateRegistry.registerEncoder(ServerState::encode, ServerState.class);
        DelegateRegistry.registerDecoder(ServerState::decode, ServerState.class);
    }

}


text:
namespace extensions {
class Extension;
}

namespace net {
class URLRequest;
}

namespace performance_monitor {
class Database;

// PerformanceMonitor is a tool which will allow the user to view information
// about Chrome's performance over a period of time. It will gather statistics
// pertaining to performance-oriented areas (e.g. CPU usage, memory usage, and
// network usage) and will also store information about significant events which
// are related to performance, either being indicative (e.g. crashes) or
// potentially causal (e.g. extension installation/uninstallation).
//
// Thread Safety: PerformanceMonitor lives on multiple threads. When interacting
// with the Database, PerformanceMonitor acts on a background thread (which has
// the sequence guaranteed by a token, Database::kDatabaseSequenceToken). At
// other times, the PerformanceMonitor will act on the appropriate thread for
// the task (for instance, gathering statistics about CPU and memory usage
// is done on the background thread, but most notifications occur on the UI
// thread).
class PerformanceMonitor : public content::NotificationObserver {
 public:
  struct PerformanceDataForIOThread {
    PerformanceDataForIOThread();

    uint64 network_bytes_read;
  };

  typedef std::map<base::ProcessHandle,
                   linked_ptr<base::ProcessMetrics> > MetricsMap;

  // Set the path which the PerformanceMonitor should use for the database files
  // constructed. This must be done prior to the initialization of the
  // PerformanceMonitor. Returns true on success, false on failure (failure
  // likely indicates that PerformanceMonitor has already been started at the
  // time of the call).
  bool SetDatabasePath(const FilePath& path);

  // Returns the current PerformanceMonitor instance if one exists; otherwise
  // constructs a new PerformanceMonitor.
  static PerformanceMonitor* GetInstance();

  // Begins the initialization process for the PerformanceMonitor in order to
  // start collecting data.
  void Start();

  // Inform PerformanceMonitor that bytes have been read; if these came across
  // the network (and PerformanceMonitor is initialized), then increment the
  // count accordingly.
  void BytesReadOnIOThread(const net::URLRequest& request, const int bytes);

  // content::NotificationObserver
  // Wait for various notifications; insert events into the database upon
  // occurance.
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE;

  Database* database() { return database_.get(); }
  FilePath database_path() { return database_path_; }
  static bool initialized() { return initialized_; }

 private:
  friend struct DefaultSingletonTraits<PerformanceMonitor>;
  friend class PerformanceMonitorBrowserTest;
  FRIEND_TEST_ALL_PREFIXES(PerformanceMonitorUncleanExitBrowserTest,
                           OneProfileUncleanExit);
  FRIEND_TEST_ALL_PREFIXES(PerformanceMonitorUncleanExitBrowserTest,
                           TwoProfileUncleanExit);
  FRIEND_TEST_ALL_PREFIXES(PerformanceMonitorBrowserTest, NetworkBytesRead);

  PerformanceMonitor();
  virtual ~PerformanceMonitor();

  // Perform any additional initialization which must be performed on a
  // background thread (e.g. constructing the database).
  void InitOnBackgroundThread();

  void FinishInit();

  // Register for the appropriate notifications as a NotificationObserver.
  void RegisterForNotifications();

  // Checks for whether the previous profiles closed uncleanly; this method
  // should only be called once per run in order to avoid duplication of events
  // (exceptions made for testing purposes where we construct the environment).
  void CheckForUncleanExits();

  // Find the last active time for the profile and insert the event into the
  // database.
  void AddUncleanExitEventOnBackgroundThread(const std::string& profile_name);

  // Check the previous Chrome version from the Database and determine if
  // it has been updated. If it has, insert an event in the database.
  void CheckForVersionUpdateOnBackgroundThread();

  // Wrapper function for inserting events into the database.
  void AddEvent(scoped_ptr<Event> event);

  void AddEventOnBackgroundThread(scoped_ptr<Event> event);

  // Since Database::AddMetric() is overloaded, base::Bind() does not work and
  // we need a helper function.
  void AddMetricOnBackgroundThread(const Metric& metric);

  // Notify any listeners that PerformanceMonitor has finished the initializing.
  void NotifyInitialized();

  // Perform any collections that are done on a timed basis.
  void DoTimedCollections();

  // Update the database record of the last time the active profiles were
  // running; this is used in determining when an unclean exit occurred.
  void UpdateLiveProfiles();
  void UpdateLiveProfilesHelper(
      scoped_ptr<std::set<std::string> > active_profiles, std::string time);

  // Gathers CPU usage and memory usage of all Chrome processes in order to.
  void GatherStatisticsOnBackgroundThread();

  // Gathers the CPU usage of every Chrome process that has been running since
  // the last call to GatherStatistics().
  void GatherCPUUsageOnBackgroundThread();

  // Gathers the memory usage of every process in the current list of processes.
  void GatherMemoryUsageOnBackgroundThread();

  // Updates the ProcessMetrics map with the current list of processes.
  void UpdateMetricsMapOnBackgroundThread();

  // Generate an appropriate ExtensionEvent for an extension-related occurrance
  // and insert it in the database.
  void AddExtensionEvent(EventType type,
                         const extensions::Extension* extension);

  // Generate an appropriate RendererFailure for a renderer crash and insert it
  // in the database.
  void AddRendererClosedEvent(
      content::RenderProcessHost* host,
      const content::RenderProcessHost::RendererClosedDetails& details);

  // Called on the IO thread, this will call InsertIOData on the background
  // thread with a copy of the PerformanceDataForIOThread object to prevent
  // any possible race conditions.
  void CallInsertIOData();

  // Insert the collected IO data into the database.
  void InsertIOData(
      const PerformanceDataForIOThread& performance_data_for_io_thread);

  // The store for all performance data that must be gathered from the IO
  // thread.
  PerformanceDataForIOThread performance_data_for_io_thread_;

  // The location at which the database files are stored; if empty, the database
  // will default to '<user_data_dir>/performance_monitor_dbs'.
  FilePath database_path_;

  scoped_ptr<Database> database_;

  // A map of currently running ProcessHandles to ProcessMetrics.
  scoped_ptr<MetricsMap> metrics_map_;

  // The timer to signal PerformanceMonitor to perform its timed collections.
  base::RepeatingTimer<PerformanceMonitor> timer_;

  content::NotificationRegistrar registrar_;

  // A flag indicating whether or not PerformanceMonitor is initialized. Any
  // external sources accessing PerformanceMonitor should either wait for
  // the PERFORMANCE_MONITOR_INITIALIZED notification or should check this
  // flag.
  static bool initialized_;

  DISALLOW_COPY_AND_ASSIGN(PerformanceMonitor);
};

}  // namespace performance_monitor

#endif  // CHROME_BROWSER_PERFORMANCE_MONITOR_PERFORMANCE_MONITOR_H_


text:
package com.sksamuel.scapegoat.inspections

import com.sksamuel.scapegoat.{ Levels, Inspection, InspectionContext, Inspector }

/** @author Stephen Samuel */
class VarClosure extends Inspection {

  override def inspector(context: InspectionContext): Inspector = new Inspector(context) {

    import context.global._

    override def postTyperTraverser = Some apply new context.Traverser {

      private def capturesVar(tree: Tree): Unit = tree match {
        case Block(stmt, expr) => (stmt :+ expr).foreach(capturesVar)
        case Apply(Select(_, _), args) =>
          args.filter(_.symbol != null)
            .foreach(arg => if (arg.symbol.isMethod && arg.symbol.isGetter && !arg.symbol.isStable) {
              context.warn("VarClosure",
                tree.pos,
                Levels.Warning,
                "Closing over a var can lead to subtle bugs: " + tree.toString().take(500),
                VarClosure.this)
            })
        case _ =>
      }

      override def inspect(tree: Tree): Unit = {
        tree match {
          case Function(List(ValDef(_, _, _, _)), body) => capturesVar(body)
          case _                                        => continue(tree)
        }
      }
    }
  }
}


text:
//
//  YQCategoryForFoundation.h
//  Demo
//
//  Created by maygolf on 16/11/7.
//  Copyright © 2016年 yiquan. All rights reserved.
//

#ifndef YQCategoryForFoundation_h
#define YQCategoryForFoundation_h

#import "NSObject+YQObject.h"
#import "NSObject+YQCoder.h"
#import "NSArray+YQCategory.h"
#import "NSDictionary+YQCategory.h"
#import "NSString+YQCategory.h"
#import "NSString+YQURL.h"
#import "NSDate+YQCategory.h"

#endif /* YQCategoryForFoundation_h */


text:
package com.greengrowapps.ggarest.streams;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public interface StreamConverter {
    void writeToOutputStream(String string, OutputStream outputStream) throws IOException;
    String readFromInputStream(InputStream inputStream) throws IOException;
    int getContentLength(String stringBody);
}


text:
//======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package gov.nih.nci.caarray.domain.array;

import gov.nih.nci.cabio.domain.ExonArrayReporter;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.OneToOne;

import org.hibernate.annotations.Cascade;

/**
 *
 */
@Entity
@DiscriminatorValue("EXON")
public class ExonProbeAnnotation extends AbstractProbeAnnotation {

    private static final long serialVersionUID = 1L;

    private Long start;
    private Long stop;
    private String strand;
    private String uniprotId;
    private ExonArrayReporter exonArrayReporter;
    private Gene gene;

    /**
     * @return the exonArrayReporter
     */
    @OneToOne
    @Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
    public ExonArrayReporter getExonArrayReporter() {
        return exonArrayReporter;
    }
    /**
     * @param exonArrayReporter the exonArrayReporter to set
     */
    public void setExonArrayReporter(ExonArrayReporter exonArrayReporter) {
        this.exonArrayReporter = exonArrayReporter;
    }
     /**
     * @return the start
     */
    public Long getStart() {
        return start;
    }
    /**
     * @param start the start to set
     */
    public void setStart(Long start) {
        this.start = start;
    }
    /**
     * @return the stop
     */
    public Long getStop() {
        return stop;
    }
    /**
     * @param stop the stop to set
     */
    public void setStop(Long stop) {
        this.stop = stop;
    }
    /**
     * @return the strand
     */
    public String getStrand() {
        return strand;
    }
    /**
     * @param strand the strand to set
     */
    public void setStrand(String strand) {
        this.strand = strand;
    }
    /**
     * @return the swissprotId
     */
    public String getUniprotId() {
        return uniprotId;
    }
    /**
     * @param swissprotId the swissprotId to set
     */
    public void setUniprotId(String swissprotId) {
        this.uniprotId = swissprotId;
    }

    /**
     * @return the gene
     */
    @OneToOne
    @Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
    public Gene getGene() {
        return gene;
    }

    /**
     * @param gene the gene to set
     */
    public void setGene(Gene gene) {
        this.gene = gene;
    }

}


text:
package mesosphere.marathon.core.externalvolume

import com.wix.accord.Validator
import mesosphere.marathon.state.ExternalVolume
trait ExternalVolumes

object ExternalVolumes {
  def validExternalVolume: Validator[ExternalVolume] = ???
}


text:
package com.strobel.reflection;

import com.strobel.core.ArrayUtilities;
import com.strobel.util.TypeUtils;

import java.util.Set;

/**
 * @author Mike Strobel
 */
public abstract class Binder {
    static boolean compareMethodSignatureAndName(final MethodBase m1, final MethodBase m2) {
        final ParameterList p1 = m1.getParameters();
        final ParameterList p2 = m2.getParameters();

        if (p1.size() != p2.size()) {
            return false;
        }

        for (int i = 0, n = p1.size(); i < n; i++) {
            if (!TypeUtils.areEquivalent(p1.get(i).getParameterType(), p2.get(i).getParameterType())) {
                return false;
            }
        }

        return true;
    }

    static int getHierarchyDepth(final Type t) {
        int depth = 0;

        Type currentType = t;
        do {
            depth++;
            currentType = currentType.getBaseType();
        } while (currentType != null);

        return depth;
    }

    static MethodBase findMostDerivedNewSlotMethod(final MethodBase[] match, final int cMatches) {
        int deepestHierarchy = 0;
        MethodBase methodWithDeepestHierarchy = null;

        for (int i = 0; i < cMatches; i++) {
            // Calculate the depth of the hierarchy of the declaring type of the
            // current method.
            final int currentHierarchyDepth = getHierarchyDepth(match[i].getDeclaringType());

            // The two methods have the same name, signature, and hierarchy depth.
            // This can only happen if at least one is vararg or generic.
            if (currentHierarchyDepth == deepestHierarchy) {
                throw Error.ambiguousMatch();
            }

            // Check to see if this method is on the most derived class.
            if (currentHierarchyDepth > deepestHierarchy) {
                deepestHierarchy = currentHierarchyDepth;
                methodWithDeepestHierarchy = match[i];
            }
        }

        return methodWithDeepestHierarchy;
    }

    public abstract MethodBase selectMethod(final Set<BindingFlags> bindingFlags, final MethodBase[] matches, final Type[] parameterTypes);
}

@SuppressWarnings("ConstantConditions")
final class DefaultBinder extends Binder {
    @Override
    public MethodBase selectMethod(final Set<BindingFlags> bindingFlags, final MethodBase[] matches, final Type[] types) {
        if (ArrayUtilities.isNullOrEmpty(matches)) {
            return null;
        }

        final MethodBase[] candidates = matches.clone();

        //
        // Find all the methods that can be described by the parameter types.
        // Remove all of them that cannot.
        //

        int stop;
        int currentIndex = 0;

        for (int i = 0, n = candidates.length; i < n; i++) {
            final MethodBase candidate = candidates[i];
            final ParameterList parameters = candidate.getParameters();
            final int parameterCount = parameters.size();
            final boolean isVarArgs = candidate.getCallingConvention() == CallingConvention.VarArgs;

            if (parameterCount != types.length && !isVarArgs) {
                continue;
            }

            for (stop = 0; stop < Math.min(parameterCount,  types.length); stop++) {
                final Type parameterType = parameters.get(stop).getParameterType();

                if (parameterType == types[stop] || parameterType == Types.Object) {
                    continue;
                }

                if (parameterType.isAssignableFrom(types[stop])) {
                    continue;
                }

                if (!isVarArgs || stop != parameterCount - 1) {
                    break;
                }

                if (!parameterType.getElementType().isAssignableFrom(types[stop])) {
                    break;
                }
            }

            if (stop == parameterCount ||
                stop == parameterCount - 1 && isVarArgs) {

                candidates[currentIndex++] = candidate;
            }
        }

        if (currentIndex == 0) {
            return null;
        }

        if (currentIndex == 1) {
            return candidates[0];
        }

        // Walk all of the methods looking the most specific method to invoke
        int currentMin = 0;
        boolean ambiguous = false;

        final int[] parameterOrder = new int[types.length];

        for (int i = 0, n = types.length; i < n; i++) {
            parameterOrder[i] = i;
        }

        for (int i = 1; i < currentIndex; i++) {
            final MethodBase m1 = candidates[currentMin];
            final MethodBase m2 = candidates[i];

            final Type<?> varArgType1;
            final Type<?> varArgType2;

            if (m1.getCallingConvention() == CallingConvention.VarArgs) {
                final TypeList pt1 = m1.getParameters().getParameterTypes();
                varArgType1 = pt1.get(pt1.size() - 1).getElementType();
            }
            else {
                varArgType1 = null;
            }

            if (m2.getCallingConvention() == CallingConvention.VarArgs) {
                final TypeList pt2 = m2.getParameters().getParameterTypes();
                varArgType2 = pt2.get(pt2.size() - 1).getElementType();
            }
            else {
                varArgType2 = null;
            }

            final int newMin = findMostSpecificMethod(
                m1,
                parameterOrder,
                varArgType1,
                candidates[i],
                parameterOrder,
                varArgType2,
                types,
                null
            );

            if (newMin == 0) {
                ambiguous = true;
            }
            else {
                if (newMin == 2) {
                    ambiguous = false;
                    currentMin = i;
                }
            }
        }
        if (ambiguous) {
            throw Error.ambiguousMatch();
        }

        return candidates[currentMin];
    }

    private static int findMostSpecificMethod(
        final MethodBase m1,
        final int[] varArgOrder1,
        final Type varArgArrayType1,
        final MethodBase m2,
        final int[] varArgOrder2,
        final Type varArgArrayType2,
        final Type[] types,
        final Object[] args) {

        //
        // Find the most specific method based on the parameters.
        //
        final int result = findMostSpecific(
            m1.getParameters(),
            varArgOrder1,
            varArgArrayType1,
            m2.getParameters(),
            varArgOrder2,
            varArgArrayType2,
            types,
            args
        );

        //
        // If the match was not ambiguous then return the result.
        //
        if (result != 0) {
            return result;
        }

        //
        // Check to see if the methods have the exact same name and signature.
        //
        if (compareMethodSignatureAndName(m1, m2)) {
            //
            // Determine the depth of the declaring types for both methods.
            //
            final int hierarchyDepth1 = getHierarchyDepth(m1.getDeclaringType());
            final int hierarchyDepth2 = getHierarchyDepth(m2.getDeclaringType());

            //
            // The most derived method is the most specific one.
            //
            if (hierarchyDepth1 == hierarchyDepth2) {
                return 0;
            }
            else if (hierarchyDepth1 < hierarchyDepth2) {
                return 2;
            }
            else {
                return 1;
            }
        }

        //
        // The match is ambiguous.
        //
        return 0;
    }

    private static int findMostSpecific(
        final ParameterList p1,
        final int[] varArgOrder1,
        final Type varArgArrayType1,
        final ParameterList p2,
        final int[] varArgOrder2,
        final Type varArgArrayType2,
        final Type[] types,
        final Object[] args) {
        //
        // A method using varargs is always less specific than one not using varargs.
        //
        if (varArgArrayType1 != null && varArgArrayType2 == null) {
            return 2;
        }
        if (varArgArrayType2 != null && varArgArrayType1 == null) {
            return 1;
        }

        //
        // Now either p1 and p2 both use params or neither does.
        //

        boolean p1Less = false;
        boolean p2Less = false;

        for (int i = 0, n = types.length; i < n; i++) {
            if (args != null && args[i] == Missing.Value) {
                continue;
            }

            final Type c1;
            final Type c2;

            //
            //  If a vararg array is present, then either
            //      the user re-ordered the parameters, in which case
            //          the argument to the vararg array is either an array
            //              in which case the params is conceptually ignored and so varArgArrayType1 == null
            //          or the argument to the vararg array is a single element
            //              in which case varArgOrder[i] == p1.Length - 1 for that element
            //      or the user did not re-order the parameters in which case
            //          the varArgOrder array could contain indexes larger than p.Length - 1 (see VSW 577286)
            //          so any index >= p.Length - 1 is being put in the vararg array
            //

            if (varArgArrayType1 != null && varArgOrder1[i] >= p1.size() - 1) {
                c1 = varArgArrayType1;
            }
            else {
                c1 = p1.get(varArgOrder1[i]).getParameterType();
            }

            if (varArgArrayType2 != null && varArgOrder2[i] >= p2.size() - 1) {
                c2 = varArgArrayType2;
            }
            else {
                c2 = p2.get(varArgOrder2[i]).getParameterType();
            }

            if (c1 == c2) {
                continue;
            }

            switch (findMostSpecificType(c1, c2, types[i])) {
                case 0:
                    return 0;
                case 1:
                    p1Less = true;
                    break;
                case 2:
                    p2Less = true;
                    break;
            }
        }

        // Two way p1Less and p2Less can be equal.  All the arguments are the
        //  same they both equal false, otherwise there were things that both
        //  were the most specific type on....
        if (p1Less == p2Less) {
            // if we cannot tell which is a better match based on parameter types (p1Less == p2Less),
            // let's see which one has the most matches without using the params array (the longer one wins).
            if (!p1Less && args != null) {
                if (p1.size() > p2.size()) {
                    return 1;
                }
                else if (p2.size() > p1.size()) {
                    return 2;
                }
            }

            return 0;
        }
        else {
            return p1Less ? 1 : 2;
        }
    }

    private static int findMostSpecificType(final Type c1, final Type c2, final Type t) {
        //
        // If the two types are exact move on...
        //
        if (TypeUtils.areEquivalent(c1, c2)) {
            return 0;
        }

        if (TypeUtils.areEquivalent(c1, t)) {
            return 1;
        }

        if (TypeUtils.areEquivalent(c2, t)) {
            return 2;
        }

        final boolean c1FromC2 = c1.isAssignableFrom(c2);
        final boolean c2FromC1 = c2.isAssignableFrom(c1);

        if (c1FromC2 == c2FromC1) {
            return 0;
        }

        return c1FromC2 ? 2 : 1;
    }
}


text:
package com.microsoft.office365;

import java.util.Locale;

import android.os.Build;

import com.microsoft.office365.http.FroyoHttpConnection;
import com.microsoft.office365.http.HttpConnection;
import com.microsoft.office365.http.JavaHttpConnection;

/**
 * Platform specific classes and operations
 */
public class Platform {
	static boolean mPlatformVerified = false;
	static boolean mIsAndroid = false;

	/**
	 * Creates an adequate HttpConnection for the current platform
	 * @param logger Logger to use with the connection
	 * @return An HttpConnection
	 */
	public static HttpConnection createHttpConnection() {
		if (isAndroid() && Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO) {
			return new FroyoHttpConnection();
		} else {
			return new JavaHttpConnection();
		}
	}

	/**
	 * Indicates if the current platform is Android
	 */
	public static boolean isAndroid() {

		if (!mPlatformVerified) {
			String runtime = System.getProperty("java.runtime.name").toLowerCase(Locale.getDefault());

			if (runtime.contains("android")) {
				mIsAndroid = true;
			} else {
				mIsAndroid = false;
			}

			mPlatformVerified = true;
		}

		return mIsAndroid;
	}

	/**
     * Generates the User-Agent
     */
    public static String getUserAgent() {
        String osName;

        if (isAndroid()) {
            osName = "Android API" + Build.VERSION.SDK_INT;
        } else {
            osName = System.getProperty("os.name").toLowerCase(Locale.getDefault());
        }
        String userAgent = String.format("Office (lang=Java; os=%s; version=1.0)", osName);

        return userAgent;
    }
}


text:
@interface DMAliasesPreferencesViewController : DMPreferencesViewController <NSTableViewDataSource, NSTableViewDelegate>

@end


text:
///////////////////////////////////////////////////////////////////////////////
// @file         : ToolBar.js                                                //
// @summary      : ToolBar flow types                                        //
// @version      : 0.0.1                                                     //
// @project      : tickelr                                                   //
// @description  :                                                           //
// @author       : Benjamin Maggi                                            //
// @email        : benjaminmaggi@gmail.com                                   //
// @date         : 07 Sep 2017                                               //
// @license:     : MIT                                                       //
// ------------------------------------------------------------------------- //
//                                                                           //
// Copyright 2017 Benjamin Maggi <benjaminmaggi@gmail.com>                   //
//                                                                           //
//                                                                           //
// License:                                                                  //
// Permission is hereby granted, free of charge, to any person obtaining a   //
// copy of this software and associated documentation files                  //
// (the "Software"), to deal in the Software without restriction, including  //
// without limitation the rights to use, copy, modify, merge, publish,       //
// distribute, sublicense, and/or sell copies of the Software, and to permit //
// persons to whom the Software is furnished to do so, subject to the        //
// following conditions:                                                     //
//                                                                           //
// The above copyright notice and this permission notice shall be included   //
// in all copies or substantial portions of the Software.                    //
//                                                                           //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS   //
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF                //
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.    //
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY      //
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,      //
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE         //
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                    //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

import type { Action } from './Action';

export const PlayerActionKeys = {
  /* HTML5 Audio */
  SET_CONTEXT: 'SET_CONTEXT',
  SET_ANALYZER: 'SET_ANALYZER',
  SET_WAVESURFER: 'SET_WAVESURFER',
  /* Media Properties */
  SET_DURATION: 'SET_DURATION',
  /* Playback Status */
  SET_CURRENT_TIME: 'SET_CURRENT_TIME',
  /* Events */
  SET_SEEK: 'SET_SEEK',
  SET_LOADING: 'SET_LOADING',
  SET_FINISHED: 'SET_FINISHED',
  SET_PLAYING: 'SET_PLAYING',
  SET_READY: 'SET_READY',
  /* Methods */
  SET_VOLUME: 'SET_VOLUME',
  SET_MUTE: 'SET_MUTE',
  SET_STOP: 'SET_STOP',
  SET_PAUSE: 'SET_PAUSE',
  SET_PLAYPAUSE: 'SET_PLAYPAUSE',
  TOGGLE_MUTE: 'TOGGLE_MUTE',
  SEEK_TO: 'SEEK_TO',
  ERROR: 'ERROR',
};

export type PlayerActions =
  | Action<typeof PlayerActionKeys.SET_CONTEXT, any>
  | Action<typeof PlayerActionKeys.SET_ANALYZER, any>
  | Action<typeof PlayerActionKeys.SET_WAVESURFER, any>
  | Action<typeof PlayerActionKeys.SET_DURATION, number>
  | Action<typeof PlayerActionKeys.SET_CURRENT_TIME, number>
  | Action<typeof PlayerActionKeys.SET_SEEK, number>
  | Action<typeof PlayerActionKeys.SET_VOLUME, number>
  | Action<typeof PlayerActionKeys.SET_MUTE, boolean>
  | Action<typeof PlayerActionKeys.SET_LOADING, number>
  | Action<typeof PlayerActionKeys.SET_FINISHED, boolean>
  | Action<typeof PlayerActionKeys.SET_PLAYING, any>
  | Action<typeof PlayerActionKeys.SET_STOP, boolean>
  | Action<typeof PlayerActionKeys.SET_PAUSE, boolean>
  | Action<typeof PlayerActionKeys.SET_PLAYPAUSE, any>
  | Action<typeof PlayerActionKeys.SET_READY, boolean>
  | Action<typeof PlayerActionKeys.TOGGLE_MUTE, void>
  | Action<typeof PlayerActionKeys.SEEK_TO, number>
  | Action<typeof PlayerActionKeys.ERROR, string>
  ;


text:
package org.reasm;

import java.util.Iterator;
import java.util.NoSuchElementException;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;

import org.reasm.source.SourceLocation;

/**
 * A generator of {@link AssemblyStepLocation} objects.
 *
 * @author Francis Gagné
 */
final class AssemblyStepLocationGenerator implements Iterator<AssemblyStepLocation> {

    @Nonnull
    private final Iterable<SourceLocation> sourceLocationIterable;
    @CheckForNull
    private final AssemblyStepIterationController iterationController;
    @CheckForNull
    private final AssemblyStepLocation parentAssemblyStepLocation;
    private final boolean transparentParent;

    @CheckForNull
    private Iterator<SourceLocation> sourceLocationIterator;
    private long iterationNumber;

    /**
     * Initializes a new AssemblyStepLocationGenerator.
     *
     * @param sourceLocationIterable
     *            an {@link Iterable} of {@link SourceLocation} objects
     * @param iterationController
     *            a {@link AssemblyStepIterationController} indicating whether to perform a new iteration when the end of
     *            sourceLocationIterable is reached
     * @param parentAssemblyStepLocation
     *            the parent assembly step location of the {@link AssemblyStepLocation} objects produced by this iterator
     */
    AssemblyStepLocationGenerator(@Nonnull Iterable<SourceLocation> sourceLocationIterable,
            @CheckForNull AssemblyStepIterationController iterationController,
            @CheckForNull AssemblyStepLocation parentAssemblyStepLocation, boolean transparentParent) {
        this.sourceLocationIterable = sourceLocationIterable;
        this.iterationController = iterationController;
        this.parentAssemblyStepLocation = parentAssemblyStepLocation;
        this.transparentParent = transparentParent;

        if (iterationController == null) {
            this.sourceLocationIterator = this.sourceLocationIterable.iterator();
        }
    }

    @Override
    public final boolean hasNext() {
        for (;;) {
            if (this.sourceLocationIterator != null && this.sourceLocationIterator.hasNext()) {
                return true;
            }

            this.sourceLocationIterator = null;
            if (this.iterationController == null || !this.iterationController.hasNextIteration()) {
                return false;
            }

            this.iterationNumber++;
            this.sourceLocationIterator = this.sourceLocationIterable.iterator();
        }
    }

    @Override
    public final AssemblyStepLocation next() {
        if (!this.hasNext()) {
            throw new NoSuchElementException();
        }

        final Iterator<SourceLocation> sourceLocationIterator = this.sourceLocationIterator;
        assert sourceLocationIterator != null;
        return new AssemblyStepLocation(sourceLocationIterator.next(), this.iterationNumber, this.parentAssemblyStepLocation,
                this.transparentParent);
    }

    @Override
    public final void remove() {
        throw new UnsupportedOperationException();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Dexiom.EPPlusExporter.Extensions;
using Dexiom.EPPlusExporter.Helpers;
using Dexiom.EPPlusExporter.Interfaces;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using OfficeOpenXml.Table;

namespace Dexiom.EPPlusExporter
{
    public abstract class TableExporter<T> : IExporter, ITableOutput, ITableOutputCustomization<T>
        where T : class
    {
        private readonly List<KeyValuePair<string, Action<ColumnConfiguration>>> _columnAlterations = new List<KeyValuePair<string, Action<ColumnConfiguration>>>();
        private readonly List<Action<ExcelRange>> _tableCustomizations = new List<Action<ExcelRange>>();

        #region Abstract
        protected abstract ExcelRange AddWorksheet(ExcelPackage package);
        #endregion

        #region Public Functions
        public ExcelPackage CreateExcelPackage()
        {
            var retVal = new ExcelPackage();
            var excelRange = AddWorksheet(retVal);
            if (excelRange == null)
                return null;

            //apply table customizations
            foreach (var tableCustomization in _tableCustomizations)
                tableCustomization(excelRange);

            return retVal;
        }

        public ExcelWorksheet AppendToExcelPackage(ExcelPackage package)
        {
            if (package == null)
                throw new ArgumentNullException(nameof(package));

            var excelRange = AddWorksheet(package);
            if (excelRange == null)
                return null;

            //apply table customizations
            foreach (var tableCustomization in _tableCustomizations)
                tableCustomization(excelRange);

            return excelRange.Worksheet;
        }
        #endregion

        #region ITableOutputCustomization<T>

        public TableExporter<T> Configure<TProperty>(Expression<Func<T, TProperty>> properties, Action<ColumnConfiguration> column) => Configure(PropertyNames.For(properties), column);
        public TableExporter<T> Configure(IEnumerable<string> propertyNames, Action<ColumnConfiguration> column)
        {
            foreach (var propName in propertyNames)
                _columnAlterations.Add(new KeyValuePair<string, Action<ColumnConfiguration>>(propName, column));

            return this;
        }

        public TableExporter<T> CustomizeTable(Action<ExcelRange> applyCustomization)
        {
            _tableCustomizations.Add(applyCustomization);
            return this;
        }

        public TableExporter<T> StyleFor<TProperty>(Expression<Func<T, TProperty>> properties, Action<ExcelStyle> setStyle) => StyleFor(PropertyNames.For(properties), setStyle);
        public TableExporter<T> StyleFor(IEnumerable<string> propertyNames, Action<ExcelStyle> setStyle) => Configure(propertyNames, c => c.Content.SetStyle = setStyle);

        public TableExporter<T> HeaderStyleFor<TProperty>(Expression<Func<T, TProperty>> properties, Action<ExcelStyle> setStyle) => HeaderStyleFor(PropertyNames.For(properties), setStyle);
        public TableExporter<T> HeaderStyleFor(IEnumerable<string> propertyNames, Action<ExcelStyle> setStyle) => Configure(propertyNames, c => c.Header.SetStyle = setStyle);

        public TableExporter<T> NumberFormatFor<TProperty>(Expression<Func<T, TProperty>> properties, string numberFormat) => NumberFormatFor(PropertyNames.For(properties), numberFormat);
        public TableExporter<T> NumberFormatFor(IEnumerable<string> propertyNames, string numberFormat) => Configure(propertyNames, c => c.Content.NumberFormat = numberFormat);

        public TableExporter<T> Display<TProperty>(Expression<Func<T, TProperty>> properties) => Display(PropertyNames.For(properties));
        public TableExporter<T> Display(IEnumerable<string> propertyNames)
        {
            if (DisplayedProperties == null)
                DisplayedProperties = new HashSet<string>();

            foreach (var propName in propertyNames)
                DisplayedProperties.Add(propName);

            return this;
        }

        public TableExporter<T> Ignore<TProperty>(Expression<Func<T, TProperty>> properties) => Ignore(PropertyNames.For(properties));
        public TableExporter<T> Ignore(IEnumerable<string> propertyNames)
        {
            foreach (var propName in propertyNames)
                IgnoredProperties.Add(propName);

            return this;
        }

        public TableExporter<T> DefaultNumberFormat(Type type, string numberFormat)
        {
            DefaultNumberFormats.AddOrUpdate(type, numberFormat);
            return this;
        }

        public TableExporter<T> TextFormatFor<TProperty>(Expression<Func<T, TProperty>> properties, string format) => TextFormatFor(PropertyNames.For(properties), format);
        public TableExporter<T> TextFormatFor(IEnumerable<string> propertyNames, string format)
        {
            foreach (var propName in propertyNames)
                TextFormats.AddOrUpdate(propName, format);

            return this;
        }

        public TableExporter<T> ConditionalStyleFor<TProperty>(Expression<Func<T, TProperty>> properties, Action<T, ExcelStyle> setStyle) => ConditionalStyleFor(PropertyNames.For(properties), setStyle);
        public TableExporter<T> ConditionalStyleFor(IEnumerable<string> propertyNames, Action<T, ExcelStyle> setStyle)
        {
            foreach (var propName in propertyNames)
                ConditionalStyles.AddOrUpdate(propName, setStyle);

            return this;
        }

        public TableExporter<T> FormulaFor<TProperty>(Expression<Func<T, TProperty>> properties, Func<T, object, string> formulaFormat) => FormulaFor(PropertyNames.For(properties), formulaFormat);
        public TableExporter<T> FormulaFor(IEnumerable<string> propertyNames, Func<T, object, string> formulaFormat)
        {
            foreach (var propName in propertyNames)
                Formulas.AddOrUpdate(propName, formulaFormat);

            return this;
        }
        #endregion

        #region Protected
        protected Dictionary<string, string> TextFormats { get; } = new Dictionary<string, string>();

        protected HashSet<string> DisplayedProperties { get; private set; }

        protected HashSet<string> IgnoredProperties { get; } = new HashSet<string>();

        protected Dictionary<string, Action<T, ExcelStyle>> ConditionalStyles { get; } = new Dictionary<string, Action<T, ExcelStyle>>();

        protected Dictionary<string, Func<T, object, string>> Formulas { get; } = new Dictionary<string, Func<T, object, string>>();

        protected Dictionary<Type, string> DefaultNumberFormats { get; } = new Dictionary<Type, string>
        {
            { typeof(DateTime), "yyyy-MM-dd HH:mm:ss" },
            { typeof(DateTime?), "yyyy-MM-dd HH:mm:ss" }
        };

        protected object GetPropertyValue(PropertyInfo property, object item)
        {
#if NET4
            var value = property.GetValue(item, null);
#else
            var value = property.GetValue(item);
#endif
            return ApplyTextFormat(property.Name, value);
        }

        protected object ApplyTextFormat(string propertyName, object value)
        {
            if (value != null && TextFormats.ContainsKey(propertyName))
                return string.Format(TextFormats[propertyName], value);

            return value;
        }

        protected Dictionary<string, ColumnConfiguration> GetColumnConfigurations(IEnumerable<string> columnNames)
        {
            var retVal = new Dictionary<string, ColumnConfiguration>();
            foreach (var colName in columnNames)
            {
                var newConfig = new ColumnConfiguration();

                //apply all the alterations to the column definition
                var alterations = _columnAlterations.Where(n => n.Key == colName);
                foreach (var alteration in alterations)
                    alteration.Value(newConfig);

                retVal.Add(colName, newConfig);
            }

            return retVal;
        }
        #endregion

        #region Properties

        public string WorksheetName { get; set; } = "Data";

        public TableStyles TableStyle { get; set; } = TableStyles.None;

        public bool AutoFitColumns { get; set; } = true;

        #endregion

    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<article id="1145">
	<title>Neighborhood Information CentersA Study and Some Proposals	</title>
	<author>Kahn, A.J.	</author>
	<text>
		  Our point of departure is a study of the feasibility and desirability
		of adapting the British Citizens' Advice Bureau (CAB) plan to the
		United States, carried out with the financial support and cooperation
		of the Ford Foundation.
		  We conclude that the British CAB pattern, while creative, richly
		implicative and a major source of valuable guidance, if merely duplicated
		would not make the optimum contribution to the current American scene.
		  We find overwhelming evidence that new information, advice, referral
		provision are necessary.  Localities need and want Neighborhood Information
		Centers (NIC's).
		  We find promising beginnings and a number of attractive possibilities
		emerging out of the somewhat different efforts by a number of federal
		agencies, local government and local voluntary groups.  However, no one
		of these provides auspices for all the needed functions in accord with
		qualities which we find to be essential.
	</text>
</article>


text: SELECT t2.* FROM t1 JOIN t2 USING(a) WHERE x='0001ffffffffffff'


text:
package com.android.i18n.addressinput;

import android.app.ProgressDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.i18n.addressinput.common.AddressField.WidthType;

/**
 * Base class for customizing widgets for address input.
 * <p>
 * Clients can optionally override this class and pass it to {@link AddressWidget} the constructor.
 * This will be invoked by the widget to create UI components that provide consistent look-and-feel
 * with other UI components clients might use alongside the address widget.
 */
public class AddressWidgetUiComponentProvider {
  protected Context context;
  protected LayoutInflater inflater;

  public AddressWidgetUiComponentProvider(Context context) {
    this.context = context;
    this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  }

  /**
   * Creates a label, e.g. "State", for an address input field.
   *
   * @param label the label of the address input field
   * @param widthType {@link WidthType} of the field
   * @return a custom {@link TextView} created for the field
   */
  protected TextView createUiLabel(CharSequence label, WidthType widthType) {
    TextView textView = (TextView) inflater.inflate(R.layout.address_textview, null, false);
    textView.setText(label);
    return textView;
  }

  /**
   * See {@link #createUiLabel(CharSequence, WidthType)}.
   *
   * @param isEditField whether the field is an edit field (as opposed to spinner)
   */
  protected TextView createUiLabel(CharSequence label, WidthType widthType, boolean isEditField) {
    return createUiLabel(label, widthType);
  }

  /**
   * Creates a text input view for an address input field.
   *
   * @param widthType {@link WidthType} of the field
   * @return a custom {@link EditText} created for the field
   */
  protected EditText createUiTextField(WidthType widthType) {
    return (EditText) inflater.inflate(R.layout.address_edittext, null, false);
  }

  /**
   * Creates a {@link Spinner} for a input field that uses UI picker.
   *
   * @param widthType {@link WidthType} of the field
   * @return a custom {@link Spinner} created for the field
   */
  protected Spinner createUiPickerSpinner(WidthType widthType) {
    return (Spinner) inflater.inflate(R.layout.address_spinner, null, false);
  }

  /**
   * Creates an {@link AutoCompleteTextView} for an input field that uses autocomplete.
   *
   * @param widthType {@link WidthType} of the field
   * @return a custom {@link AutoCompleteTextView} created for the field
   */
  protected AutoCompleteTextView createUiAutoCompleteTextField(WidthType widthType) {
    return (AutoCompleteTextView)
        inflater.inflate(R.layout.address_autocomplete_textview, null, false);
  }

  /**
   * Creates an {@link ViewGroup} for an input field that uses autocomplete. Subclass
   * should provide an implementation if
   * {@link AddressWidget#setUseLayoutWrapperForTextFields(boolean)} is called with true.
   * If subclass does not override this method, a default LinearLayout wrapper will be used.
   * The return ViewGroup must have a AutoCompleteTextView descendant with id
   * address_autocomplete_text_view.
   *
   * @param widthType {@link WidthType} of the field
   * @param fieldText the label for the text field
   * @return a custom {@link ViewGroup} created for the field
   */
  protected ViewGroup createUiAutoCompleteViewGroup(WidthType widthType, String fieldText) {
    return (ViewGroup)
        inflater.inflate(R.layout.address_autocomplete_view_group, null, false);
  }

  /**
   * Creates an {@link ArrayAdapter} to work with the custom {@link Spinner} of a input field that
   * uses UI picker.
   *
   * @param widthType {@link WidthType} of the field
   * @return a custom {@link ArrayAdapter} for the field
   */
  protected ArrayAdapter<String> createUiPickerAdapter(WidthType widthType) {
    ArrayAdapter<String> adapter =
        new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    return adapter;
  }

  /** Gets an activity indicator to show that a task is in progress. */
  protected ProgressDialog getUiActivityIndicatorView() {
    return new ProgressDialog(context);
  }
}


text:
<?php

namespace Alchemy\Zippy\Tests\Resource\Teleporter;

use Alchemy\Zippy\Tests\TestCase;

class TeleporterTestCase extends TestCase
{
    public function provideContexts()
    {
        if (!is_dir(__DIR__ . '/context-test')) {
            mkdir (__DIR__ . '/context-test');
        }

        return array(
            array(__DIR__),
            array(__DIR__ . '/context-test')
        );
    }
}


text:
package cucumber.api.formatter;

/**
 * Interface for Formatters that need to know if the Runtime is strict.
 */
public interface StrictAware extends Formatter {
    /**
     * When set to strict the formatter should indicate failure for undefined and pending steps
     *
     * @param strict true iff the runtime is in strict mode
     */
    void setStrict(boolean strict);
}


text:
package com.google.ads.googleads.v10.services;

public final class AdServiceProto {
  private AdServiceProto() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistryLite registry) {
  }

  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions(
        (com.google.protobuf.ExtensionRegistryLite) registry);
  }
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v10_services_GetAdRequest_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v10_services_GetAdRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v10_services_MutateAdsRequest_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v10_services_MutateAdsRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v10_services_AdOperation_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v10_services_AdOperation_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v10_services_MutateAdsResponse_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v10_services_MutateAdsResponse_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v10_services_MutateAdResult_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v10_services_MutateAdResult_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static  com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\n2google/ads/googleads/v10/services/ad_s" +
      "ervice.proto\022!google.ads.googleads.v10.s" +
      "ervices\032,google/ads/googleads/v10/common" +
      "/policy.proto\032:google/ads/googleads/v10/" +
      "enums/response_content_type.proto\032+googl" +
      "e/ads/googleads/v10/resources/ad.proto\032\034" +
      "google/api/annotations.proto\032\027google/api" +
      "/client.proto\032\037google/api/field_behavior" +
      ".proto\032\031google/api/resource.proto\032 googl" +
      "e/protobuf/field_mask.proto\032\027google/rpc/" +
      "status.proto\"J\n\014GetAdRequest\022:\n\rresource" +
      "_name\030\001 \001(\tB#\340A\002\372A\035\n\033googleads.googleapi" +
      "s.com/Ad\"\221\002\n\020MutateAdsRequest\022\030\n\013custome" +
      "r_id\030\001 \001(\tB\003\340A\002\022G\n\noperations\030\002 \003(\0132..go" +
      "ogle.ads.googleads.v10.services.AdOperat" +
      "ionB\003\340A\002\022\027\n\017partial_failure\030\004 \001(\010\022j\n\025res" +
      "ponse_content_type\030\005 \001(\0162K.google.ads.go" +
      "ogleads.v10.enums.ResponseContentTypeEnu" +
      "m.ResponseContentType\022\025\n\rvalidate_only\030\003" +
      " \001(\010\"\346\001\n\013AdOperation\022/\n\013update_mask\030\002 \001(" +
      "\0132\032.google.protobuf.FieldMask\022_\n\033policy_" +
      "validation_parameter\030\003 \001(\0132:.google.ads." +
      "googleads.v10.common.PolicyValidationPar" +
      "ameter\0228\n\006update\030\001 \001(\0132&.google.ads.goog" +
      "leads.v10.resources.AdH\000B\013\n\toperation\"\212\001" +
      "\n\021MutateAdsResponse\0221\n\025partial_failure_e" +
      "rror\030\003 \001(\0132\022.google.rpc.Status\022B\n\007result" +
      "s\030\002 \003(\01321.google.ads.googleads.v10.servi" +
      "ces.MutateAdResult\"}\n\016MutateAdResult\0227\n\r" +
      "resource_name\030\001 \001(\tB \372A\035\n\033googleads.goog" +
      "leapis.com/Ad\0222\n\002ad\030\002 \001(\0132&.google.ads.g" +
      "oogleads.v10.resources.Ad2\275\003\n\tAdService\022" +
      "\240\001\n\005GetAd\022/.google.ads.googleads.v10.ser" +
      "vices.GetAdRequest\032&.google.ads.googlead" +
      "s.v10.resources.Ad\">\202\323\344\223\002(\022&/v10/{resour" +
      "ce_name=customers/*/ads/*}\332A\rresource_na" +
      "me\022\305\001\n\tMutateAds\0223.google.ads.googleads." +
      "v10.services.MutateAdsRequest\0324.google.a" +
      "ds.googleads.v10.services.MutateAdsRespo" +
      "nse\"M\202\323\344\223\002.\")/v10/customers/{customer_id" +
      "=*}/ads:mutate:\001*\332A\026customer_id,operatio" +
      "ns\032E\312A\030googleads.googleapis.com\322A\'https:" +
      "//www.googleapis.com/auth/adwordsB\372\001\n%co" +
      "m.google.ads.googleads.v10.servicesB\016AdS" +
      "erviceProtoP\001ZIgoogle.golang.org/genprot" +
      "o/googleapis/ads/googleads/v10/services;" +
      "services\242\002\003GAA\252\002!Google.Ads.GoogleAds.V1" +
      "0.Services\312\002!Google\\Ads\\GoogleAds\\V10\\Se" +
      "rvices\352\002%Google::Ads::GoogleAds::V10::Se" +
      "rvicesb\006proto3"
    };
    descriptor = com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
          com.google.ads.googleads.v10.common.PolicyProto.getDescriptor(),
          com.google.ads.googleads.v10.enums.ResponseContentTypeProto.getDescriptor(),
          com.google.ads.googleads.v10.resources.AdProto.getDescriptor(),
          com.google.api.AnnotationsProto.getDescriptor(),
          com.google.api.ClientProto.getDescriptor(),
          com.google.api.FieldBehaviorProto.getDescriptor(),
          com.google.api.ResourceProto.getDescriptor(),
          com.google.protobuf.FieldMaskProto.getDescriptor(),
          com.google.rpc.StatusProto.getDescriptor(),
        });
    internal_static_google_ads_googleads_v10_services_GetAdRequest_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_google_ads_googleads_v10_services_GetAdRequest_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v10_services_GetAdRequest_descriptor,
        new java.lang.String[] { "ResourceName", });
    internal_static_google_ads_googleads_v10_services_MutateAdsRequest_descriptor =
      getDescriptor().getMessageTypes().get(1);
    internal_static_google_ads_googleads_v10_services_MutateAdsRequest_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v10_services_MutateAdsRequest_descriptor,
        new java.lang.String[] { "CustomerId", "Operations", "PartialFailure", "ResponseContentType", "ValidateOnly", });
    internal_static_google_ads_googleads_v10_services_AdOperation_descriptor =
      getDescriptor().getMessageTypes().get(2);
    internal_static_google_ads_googleads_v10_services_AdOperation_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v10_services_AdOperation_descriptor,
        new java.lang.String[] { "UpdateMask", "PolicyValidationParameter", "Update", "Operation", });
    internal_static_google_ads_googleads_v10_services_MutateAdsResponse_descriptor =
      getDescriptor().getMessageTypes().get(3);
    internal_static_google_ads_googleads_v10_services_MutateAdsResponse_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v10_services_MutateAdsResponse_descriptor,
        new java.lang.String[] { "PartialFailureError", "Results", });
    internal_static_google_ads_googleads_v10_services_MutateAdResult_descriptor =
      getDescriptor().getMessageTypes().get(4);
    internal_static_google_ads_googleads_v10_services_MutateAdResult_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v10_services_MutateAdResult_descriptor,
        new java.lang.String[] { "ResourceName", "Ad", });
    com.google.protobuf.ExtensionRegistry registry =
        com.google.protobuf.ExtensionRegistry.newInstance();
    registry.add(com.google.api.ClientProto.defaultHost);
    registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
    registry.add(com.google.api.AnnotationsProto.http);
    registry.add(com.google.api.ClientProto.methodSignature);
    registry.add(com.google.api.ClientProto.oauthScopes);
    registry.add(com.google.api.ResourceProto.resourceReference);
    com.google.protobuf.Descriptors.FileDescriptor
        .internalUpdateFileDescriptor(descriptor, registry);
    com.google.ads.googleads.v10.common.PolicyProto.getDescriptor();
    com.google.ads.googleads.v10.enums.ResponseContentTypeProto.getDescriptor();
    com.google.ads.googleads.v10.resources.AdProto.getDescriptor();
    com.google.api.AnnotationsProto.getDescriptor();
    com.google.api.ClientProto.getDescriptor();
    com.google.api.FieldBehaviorProto.getDescriptor();
    com.google.api.ResourceProto.getDescriptor();
    com.google.protobuf.FieldMaskProto.getDescriptor();
    com.google.rpc.StatusProto.getDescriptor();
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
<?php
/**
 * Example presents error handling for updateProblem() API method
*/

use SphereEngine\Api\ProblemsClientV4;
use SphereEngine\Api\SphereEngineResponseException;

// require library
require_once('../../../../vendor/autoload.php');

// define access parameters
$accessToken = '<access_token>';
$endpoint = '<endpoint>';

// initialization
$client = new ProblemsClientV4($accessToken, $endpoint);

// API usage
$problemId = 42;
$newProblemName = 'New example problem name';

try {
    $response = $client->updateProblem($problemId, $newProblemName);
} catch (SphereEngineResponseException $e) {
    if ($e->getCode() == 401) {
        echo 'Invalid access token';
    } elseif ($e->getCode() == 403) {
        echo 'Access to the problem is forbidden';
    } elseif ($e->getCode() == 404) {
        echo 'Problem does not exist';
    } elseif ($e->getCode() == 400) {
        echo 'Error code: '.$e->getErrorCode().', details available in the message: ' . $e->getMessage();
    }
}


text:
from __future__ import division
import os, os.path
import sys
import pandas as pd
import numpy as np

sys.path.append('/home/will/HIVReportGen/AnalysisCode/')
sys.path.append('/home/will/PySeqUtils/')
sys.path.append('/home/will/PatientPicker/')
import LoadingTools
#os.chdir('/home/will/HIVVariation/')

# <codecell>

store = pd.HDFStore('/home/will/HIVReportGen/Data/SplitRedcap/2013-01-16/EntireCohort.hdf')
redcap_data = store['redcap']
seq_data = store['seq_data']

t = redcap_data['Event Name'].dropna().apply(lambda x: x.split(' - ')[0])
t.unique()
redcap_data['VisitNum'] = redcap_data['Patient visit number'].combine_first(t)
redcap_data['VisitNum'][redcap_data['VisitNum']=='A03'] = 'R03'

# <codecell>

fields = ['Patient ID', 'VisitNum', 'Date of visit']
data = redcap_data[fields].rename(columns = {'Date of visit':'Date'})

# <headingcell level=2>

# Data Description

# <markdowncell>

# Here I define my return or not-return patients. In this case I'm defining every patient that _actually_ returned as True and every patient that has been more the 365\*2 days since thier last visit (using 1/16/2013 as the 'current date') as False. If its been less then two years the I exclude that visit from the analysis.

# <codecell>

from datetime import datetime
def get_diff_days(inser):
    return np.diff(inser)/(1e9*60*60*24)

def get_visit_diffs(inpat):

    nvisit = pd.DataFrame({
                        'Date':[datetime(2013,1,16)],
                        'VisitNum':['RN']
                        })

    ndata = pd.concat([inpat, nvisit], axis = 0, ignore_index=True)
    ndata.sort('Date', inplace=True)
    ndata['DiffDate'] = pd.rolling_apply(ndata['Date'], 2, get_diff_days)
    return ndata.set_index('VisitNum').drop('Patient ID', axis = 1)

odata = data.groupby('Patient ID').apply(get_visit_diffs).dropna()
print odata.head(n=30)

# <codecell>

from scipy.stats import norm
cohort_level_data = odata.groupby(level=1)['DiffDate'].agg({'std':'std',
                                                            'mean':'mean',
                                                            'count':'count'})
print cohort_level_data

# <markdowncell>

# Above is a table of the average times between visits. This only includes patients that _actually returned_ for the R0X visit. You can see that for the first few visits the average is well above the 6-month goal but it levels out around R05.
#

# <headingcell level=2>

# Prediction

# <markdowncell>

# Here I'm builing a cohort-level 'Surivial Function'. In this case I'm using mean and std from between-visit times for all patients at each visit. I'm assuming a Gaussian Distribution. Then I build a Patient-Level 'Survival Function' based on thier between-visit times. For patients with less than 3 visits I built a SF from all patients.

# <codecell>

cohort_norm = {}
for key, row in cohort_level_data.iterrows():
    cohort_norm[key] = norm(loc = row['mean'], scale = row['std'])

# <codecell>

pat_mu = odata['DiffDate'].drop('RN', axis=0, level=1).mean()
pat_std = odata['DiffDate'].drop('RN', axis=0, level=1).std()

def add_sf_data(inpat):
    if len(inpat) > 3:
        mu = inpat['DiffDate'].mean()
        st = inpat['DiffDate'].std()
        obj = norm(loc=mu, scale=st)
    else:
        obj = norm(loc=pat_mu, scale=pat_std)

    inpat['CohortSF'] = np.nan
    inpat['PatSF'] = np.nan
    inpat['Returned'] = True
    inpat['Returned'].iloc[-1] = np.nan if inpat['DiffDate'].iloc[-1] < 365*2 else False

    for key, row in inpat.iterrows():
        inpat['CohortSF'].ix[key] = cohort_norm[key[1]].sf(row['DiffDate'])
        inpat['PatSF'].ix[key] = obj.sf(row['DiffDate'])
    return inpat

ndata = odata.groupby(level=0).apply(add_sf_data)
print ndata[['DiffDate', 'CohortSF', 'PatSF', 'Returned']].head(n = 30)

# <markdowncell>

# Guessing at how to combine these two Survival Functions is difficult. As such I'm using the SKLearn package to build a DecisionTree and a Naive-Bayes predictor using ONLY THESE PARAMETERS. This has the advantage of not directly biasing any future selection from these results. I'm also comparing this to a simple DummyClassifier which will guess that all patients return.

# <codecell>

from sklearn.metrics import auc_score, zero_one_loss, roc_curve
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.cross_validation import cross_val_score, Bootstrap
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.ensemble import AdaBoostClassifier
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression

X = ndata.dropna()[['CohortSF', 'PatSF']].values
y = ndata.dropna()['Returned'].values

# <codecell>

import matplotlib.pyplot as plt
from collections import defaultdict

classifiers = [(DecisionTreeClassifier(), 'DecisionTree', 'r'),
               (GaussianNB(), 'NaiveBayes', 'g'),
               (AdaBoostClassifier(), 'Adaboost', 'c'),
               (LogisticRegression(), 'Logistic', 'k'),
               (DummyClassifier(), 'Dummy', 'b')]
plt.figure(figsize = (10,10))

losses = defaultdict(float)
nreps = 5
for train, test in Bootstrap(len(y), nreps):

    for pred, name, color in classifiers:
        fitted = pred.fit(X[train, :], y[train])
        pred_y = fitted.predict_proba(X[test, :])
        fpr, tpr, _ = roc_curve(y[test], pred_y[:,1])
        plt.plot(fpr, tpr, color, label=name)
        losses[name] += zero_one_loss(y[test], fitted.predict(X[test, :]))/nreps

plt.xlabel('False-Positive-Rate')
plt.ylabel('True-Positve-Rate')
plt.legend(['DecisionTree', 'NaiveBayes', 'Adaboost', 'Logistic', 'Dummy'], 'lower right');

# <markdowncell>

# The ROC curve is a commno method to look at the effectiveness of a classifier. It measures the trade-off between True-Positves and False-Negatives. The larger the Area Under the Curve the better the score. A random coin flip would have an area of 0.5 (the blue line).

# <codecell>

scores = numpy.array([losses[name] for name in ['DecisionTree', 'NaiveBayes', 'Adaboost', 'Logistic', 'Dummy']])
plt.bar([1, 2, 3,4,5], scores, width = 0.5)
plt.ylabel('%Miss-classified')
plt.xticks([1.25,2.25,3.25,4.25,5.25], ['DecisionTree', 'NaiveBayes', 'Adaboost', 'Logistic', 'Dummy']);

# <markdowncell>

# This graph shows the effectiveness of each of the three methods. The y-axis represents the fraction of miss-classified samples (averaged over 5 trials). We can see that the DecisionTree has only a 3% likelihood of mis-classifying a patient as return or not return. We can use this classifier to prioritize which patients we call for return visits.

# <codecell>

def expand_sf_data(inpat):
    dates = pd.date_range('1/1/2013', periods = 30, freq = 'M')
    if len(inpat) > 3:
        mu = inpat['DiffDate'].mean()
        st = inpat['DiffDate'].std()
        obj = norm(loc=mu, scale=st)
    else:
        obj = norm(loc=pat_mu, scale=pat_std)

    outdata = pd.DataFrame(columns = ['CohortSF', 'PatSF', 'LastVisit', 'DiffDays'],
                           index = pd.Index(dates, name = 'Date'))

    try:
        ldate = inpat.iloc[-2]['Date']
        lvisit = inpat.index[-2][1]
    except IndexError:
        lvisit = 'R01'
        ldate = inpat.iloc[0]['Date']

    outdata['LastVisit'] = lvisit

    for date in dates:

        diff_date = (date - ldate).days

        outdata.ix[date]['CohortSF'] = cohort_norm[lvisit].sf(diff_date)
        outdata.ix[date]['PatSF'] = obj.sf(diff_date)
        outdata.ix[date]['DiffDays'] = diff_date

    return outdata

edata = odata.groupby(level=0).apply(expand_sf_data)

# <codecell>

X = ndata.dropna()[['CohortSF', 'PatSF']].values
y = ndata.dropna()['Returned'].values
predictor = AdaBoostClassifier().fit(X,y)

edata['LikelyReturn'] = predictor.predict(edata[['CohortSF', 'PatSF']].values)

# <codecell>

date_count = edata.groupby(level = 'Date')['LikelyReturn'].sum()
date_count.plot(figsize=(15,10))
plt.title('Returnable Cohort Size')
plt.xlabel('Starting Date')
plt.ylabel('Patients Likely To Return')

# <codecell>

print date_count.diff().mean(), 'Patients lost per month wasted!'

# <markdowncell>

# The above figure shows the number of patients that are predicted to return if called given a particular starting date. We can see that the longer we wait the less patients we can keep for 'longitudinal' natures. From this graph we can estimate that we lose ~1.5 patients per week that we don't start!

# <headingcell level=2>

# Make Call-Back Sheets

# <markdowncell>

# Here I want to make a set of sheets for the clinic to use to re-call patients. For each month I'll make a list (sorted by likelihood) of patients who are likely to return. I'll also mark which patients have 3+ which should be seen by the neurologist.

# <codecell>

pred_pat_data = edata.swaplevel(0, 1)
pred_pat_data['ProbReturn'] = predictor.predict_proba(pred_pat_data[['CohortSF', 'PatSF']].values)[:,1]

out_file = '/home/will/RedcapQC/CallbackPats/HIV_DrexelMed_GeneticAnalysisCohort_recall_list.xlsx'
writer = pd.ExcelWriter(out_file)
sheet_name = '%i-%i'
for tdate, rows in pred_pat_data.groupby(level=0):

    if tdate > datetime.now():
        srows = rows.sort(['ProbReturn', 'LastVisit'], ascending=False)
        srows['Neuro'] = ''
        srows['Neuro'][srows['LastVisit']>='R03'] = 'Prefered Neuropsych visit'
        rem_days = srows['DiffDays'] % 180
        month_mask = (rem_days < 31)

        tmp = srows[['Neuro']][month_mask].reset_index()
        print tdate, month_mask.sum()
        ndate = tdate.to_datetime()
        tmp[['Patient ID', 'Neuro']].to_excel(writer,
                                              sheet_name % (ndate.year, ndate.month),
                                              index=False)
writer.save()

# <codecell>

pd.DataFrame().to_excel?

# <codecell>

pd.DataFrame().to_excel

# <codecell>

tmp[['Patient ID', 'Neuro']].to_excel

# <codecell>

data['Date'].map(lambda x: x.month).value_counts()

# <codecell>


text:
namespace remoting {

namespace protocol {
class ClipboardEvent;
}  // namespace protocol

class Clipboard {
 public:
  virtual ~Clipboard() {};

  // Initialises any objects needed to read from or write to the clipboard.
  // This method must be called on the desktop thread.
  virtual void Start() = 0;

  // Destroys any objects initialised by Start().
  // This method must be called on the desktop thread.
  virtual void Stop() = 0;

  // Writes an item to the clipboard.
  // This method must be called on the desktop thread, after Start().
  virtual void InjectClipboardEvent(const protocol::ClipboardEvent& event) = 0;

  static scoped_ptr<Clipboard> Create();
};

}  // namespace remoting

#endif  // REMOTING_HOST_CLIPBOARD_H_


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.s4game</groupId>
	<artifactId>oa</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.3.RELEASE</version>
	</parent>
	<name>oa</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>com.github.pagehelper</groupId>
				<artifactId>pagehelper-spring-boot-starter</artifactId>
				<version>1.1.1</version>
			</dependency>

			<dependency>
				<groupId>com.mangofactory</groupId>
				<artifactId>swagger-springmvc</artifactId>
				<version>1.0.0</version>
			</dependency>
			<dependency>
				<groupId>org.apache.commons</groupId>
				<artifactId>commons-lang3</artifactId>
				<version>3.4</version>
			</dependency>
			<dependency>
				<groupId>junit</groupId>
				<artifactId>junit</artifactId>
				<version>4.12</version>
				<scope>test</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<modules>
		<module>oa-manager</module>
		<module>oa-common</module>
	</modules>
</project>


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />

  <title>File: LICENSE [RemoteApp]</title>

  <link type="text/css" media="screen" href="../../rdoc.css" rel="stylesheet" />

          Home
          Classes
          Methods

Files

LICENSE

Rakefile

xbmc-client-LICENSE

IUI_LICENSE.txt

LICENSE

NOTICE

rhoconfig.txt

rholog.txt

Class Index

        <form action="#" method="get" accept-charset="utf-8" class="initially-hidden">
        <fieldset>
          <legend>Quicksearch</legend>
          <input type="text" name="quicksearch" value=""
            class="quicksearch-field" />
        </fieldset>
        </form>

ApiV4

ApiV4::Application

ApiV4::Input

ApiV4::Playback

ApiV4::Playlist

ApiV4::VideoLibrary

Api

Api::V2

Api::V4

ApiV2

ApiV2::Playback

ApiV2::VideoLibrary

XbmcConnect

XbmcConnect::Command

AppApplication

Application4

ApplicationHelper

BarcodeScanController

BrowserHelper

CommandsController

CommandsHelper

Control2

Control4

Controls

ControlsController

DownloadHelper

ErrorHelper

GeoController

GeoHelper

Input4

MethodHelper

MoreController

Movie

MovieController

MovieHelper

ObjHelper

Object

Playlist4

PlaylistController

PlaylistHelper

Product

ProductController

ProductHelper

SpecRunner

SpecRunnerController

TempClass

TvEpisodeHelper

TvSeasonHelper

TvShowHelper

Tvepisode

TvepisodeController

Tvseason

TvseasonController

Tvshow

TvshowController

VideoLibrary2

VideoLibrary4

XbmcAppHelper

XbmcConfig

XbmcConfigController

XbmcConfigHelper

XbmcController

No matching classes.

         Apache License
   Version 2.0, January 2004
http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

Definitions.

"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by the
copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all other
entities that control, are controlled by, or are under common control with
that entity. For the purposes of this definition, "control" means (i) the
power, direct or indirect, to cause the direction or management of such
entity, whether by contract or otherwise, or (ii) ownership of fifty
percent (50%) or more of the outstanding shares, or (iii) beneficial
ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.

"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation source,
and configuration files.

"Object" form shall mean any form resulting from mechanical transformation
or translation of a Source form, including but not limited to compiled
object code, generated documentation, and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License,
as indicated by a copyright notice that is included in or attached to the
work (an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived
from) the Work and for which the editorial revisions, annotations,
elaborations, or other modifications represent, as a whole, an original
work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind
by name) to the interfaces of, the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including the original
version of the Work and any modifications or additions to that Work or
Derivative Works thereof, that is intentionally submitted to Licensor for
inclusion in the Work by the copyright owner or by an individual or Legal
Entity authorized to submit on behalf of the copyright owner. For the
purposes of this definition, "submitted" means any form of electronic,
verbal, or written communication sent to the Licensor or its
representatives, including but not limited to communication on electronic
mailing lists, source code control systems, and issue tracking systems that
are managed by, or on behalf of, the Licensor for the purpose of discussing
and improving the Work, but excluding communication that is conspicuously
marked or otherwise designated in writing by the copyright owner as "Not a
Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity on
behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.

Grant of Copyright License. Subject to the terms and conditions of this
License, each Contributor hereby grants to You a perpetual, worldwide,
non-exclusive, no-charge, royalty-free, irrevocable copyright license to
reproduce, prepare Derivative Works of, publicly display, publicly perform,
sublicense, and distribute the Work and such Derivative Works in Source or
Object form.

Grant of Patent License. Subject to the terms and conditions of this
License, each Contributor hereby grants to You a perpetual, worldwide,
non-exclusive, no-charge, royalty-free, irrevocable (except as stated in
this section) patent license to make, have made, use, offer to sell, sell,
import, and otherwise transfer the Work, where such license applies only to
those patent claims licensable by such Contributor that are necessarily
infringed by their Contribution(s) alone or by combination of their
Contribution(s) with the Work to which such Contribution(s) was submitted.
If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or
contributory patent infringement, then any patent licenses granted to You
under this License for that Work shall terminate as of the date such
litigation is filed.

Redistribution. You may reproduce and distribute copies of the Work or
Derivative Works thereof in any medium, with or without modifications, and
in Source or Object form, provided that You
meet the following conditions:

(a) You must give any other recipients of the Work or

Derivative Works a copy of this License; and

(b) You must cause any modified files to carry prominent notices

stating that You changed the files; and

© You must retain, in the Source form of any Derivative Works

that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and

(d) If the Work includes a "NOTICE" text file as part of its

distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.

You may add Your own copyright statement to Your modifications and may
provide additional or different license terms and conditions for use,
reproduction, or distribution of Your modifications, or for any such
Derivative Works as a whole, provided Your use, reproduction, and
distribution of the Work otherwise complies with the conditions stated in
this License.

Submission of Contributions. Unless You explicitly state otherwise, any
Contribution intentionally submitted for inclusion in the Work by You to
the Licensor shall be under the terms and conditions of this License,
without any additional terms or conditions. Notwithstanding the above,
nothing herein shall supersede or modify the terms of any separate license
agreement you may have executed with Licensor regarding such Contributions.

Trademarks. This License does not grant permission to use the trade names,
trademarks, service marks, or product names of the Licensor, except as
required for reasonable and customary use in describing the origin of the
Work and reproducing the content of the NOTICE file.

Disclaimer of Warranty. Unless required by applicable law or agreed to in
writing, Licensor provides the Work (and each Contributor provides its
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied, including, without limitation, any
warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or
FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for
determining the appropriateness of using or redistributing the Work and
assume any risks associated with Your exercise of permissions under this
License.

Limitation of Liability. In no event and under no legal theory, whether in
tort (including negligence), contract, or otherwise, unless required by
applicable law (such as deliberate and grossly negligent acts) or agreed to
in writing, shall any Contributor be liable to You for damages, including
any direct, indirect, special, incidental, or consequential damages of any
character arising as a result of this License or out of the use or
inability to use the Work (including but not limited to damages for loss of
goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor has been
advised of the possibility of such damages.

Accepting Warranty or Additional Liability. While redistributing the Work
or Derivative Works thereof, You may choose to offer, and charge a fee for,
acceptance of support, warranty, indemnity, or other liability obligations
and/or rights consistent with this License. However, in accepting such
obligations, You may act only on Your own behalf and on Your sole
responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any
liability incurred by, or claims asserted against, such Contributor by
reason of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!)  The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.

[Validate]

Generated with the Darkfish
      Rdoc Generator 2.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;

namespace Controls.Toolkit
{
    public class EdgePanel : Grid
    {
        public EdgePanel()
        {

        }
    }
}


text:
package org.jetbrains.idea.maven.indices;

public class MavenProjectIndicesManagerTest extends MavenIndicesTestCase {
  private MavenIndicesTestFixture myIndicesFixture;

  @Override
  protected void setUp() throws Exception {
    super.setUp();
    myIndicesFixture = new MavenIndicesTestFixture(myDir.toPath(), myProject);
    myIndicesFixture.setUp();
  }

  @Override
  protected void tearDown() throws Exception {
    try {
      myIndicesFixture.tearDown();
    }
    catch (Throwable e) {
      addSuppressedException(e);
    }
    finally {
      super.tearDown();
    }
  }
}