text:
package com.bob.digcsdn.adapters;

import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bob.digcsdn.R;
import com.bob.digcsdn.models.Comment;
import com.bob.digcsdn.utils.Constants;
import com.bob.digcsdn.utils.ImageLoading;

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

/**
 * Created by bob on 15-6-16.
 */
public class CommentAdapter extends BaseAdapter {
    private ViewHolder holder;//视图容器
    private LayoutInflater layoutInflater;//布局加载器
    private Context context;
    private List<Comment> list;//资源列表
    private String replyText;
    private ImageLoading imageLoader;

    public CommentAdapter(Context context){
        super();
        layoutInflater= layoutInflater.from(context);
        list= new ArrayList<>();
        imageLoader= ImageLoading.getInstance();
    }
    public void setList(List<Comment> list) {
        this.list = list;
    }

    public void addList(List<Comment> list) {
        this.list.addAll(list);
    }

    public void clearList() {
        this.list.clear();
    }

    public List<Comment> getList() {
        return list;
    }

    public void removeItem(int position) {
        if (list.size() > 0) {
            list.remove(position);
        }
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {//0~size-1
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Comment item = list.get(position);
        if (null== convertView) {
            holder = new ViewHolder();
            switch (item.getType()) {
                case Constants.DEF_COMMENT_TYPE.PARENT:
                    convertView = layoutInflater.inflate(R.layout.comment_item, null);
                    holder.name = (TextView) convertView.findViewById(R.id.name);//用户名
                    holder.content = (TextView) convertView.findViewById(R.id.content);//评论内容
                    holder.date = (TextView) convertView.findViewById(R.id.date);
                    holder.replyCount = (TextView) convertView.findViewById(R.id.replyCount);
                    holder.userFace = (ImageView) convertView.findViewById(R.id.userface);
                    break;
                case Constants.DEF_COMMENT_TYPE.CHILD:
                    convertView = layoutInflater.inflate(R.layout.comment_child_item, null);
                    holder.name = (TextView) convertView.findViewById(R.id.name);//用户名
                    holder.content = (TextView) convertView.findViewById(R.id.content);//评论内容
                    holder.date = (TextView) convertView.findViewById(R.id.date);
                    break;
            }
            convertView.setTag(holder);
        } else holder = (ViewHolder) convertView.getTag();

        if (null != item) {
            switch (item.getType()) {
                case Constants.DEF_COMMENT_TYPE.PARENT:
                    holder.name.setText(item.getUsername());
                    holder.content.setText(Html.fromHtml(item.getContent()));//使用formHtml格式化文本内容
                    holder.date.setText(item.getPostTime());
                    imageLoader.loadImage(item.getUserface(), holder.userFace, R.drawable.csdn, R.drawable.ic_default);// 显示头像
                    break;
                case Constants.DEF_COMMENT_TYPE.CHILD://评论不显示头像
                    holder.name.setText(item.getUsername());
                    replyText = item.getContent().replace("[reply]", "【");
                    replyText = replyText.replace("[/reply]", "】");
                    holder.content.setText(Html.fromHtml(replyText));
                    holder.date.setText(item.getPostTime());
                    break;

            }
        }
        return convertView;
    }

    private class ViewHolder {
        TextView id;
        TextView date;//评论日期
        TextView name;//用户名称
        TextView content;//评论内容
        ImageView userFace;//用户头像
        TextView replyCount;//评论回复数量,貌似并没有什么卵用
    }
}


text:
package druzy.littleframe;

import java.beans.PropertyChangeEvent;

import druzy.mvc.AbstractModel;

public class DoYouWantModel extends AbstractModel {

	private Runnable ok=null;
	private Runnable cancel=new Runnable(){
		public void run(){
			setExit(true);
		}
	};
	private boolean exit=false;

	public DoYouWantModel(Runnable ok) {
		super();
		this.ok=ok;
	}

	public DoYouWantModel(Runnable ok, Runnable cancel){
		this(ok);
		this.cancel=cancel;
	}

	public boolean isExit() {
		return exit;
	}

	public void setExit(boolean exit) {
		boolean old=this.exit;
		this.exit = exit;
		firePropertyChange(new PropertyChangeEvent(this,"exit",old,exit));
	}

	public Runnable getOk() {
		return ok;
	}

	public void setOk(Runnable ok) {
		Runnable old=this.ok;
		this.ok = ok;
		firePropertyChange(new PropertyChangeEvent(this,"ok",old,ok));
	}

	public Runnable getCancel() {
		return cancel;
	}

	public void setCancel(Runnable cancel) {
		Runnable old=this.cancel;
		this.cancel = cancel;
		firePropertyChange(new PropertyChangeEvent(this,"cancel",old,cancel));
	}

}

redpajama_set_name: RedPajamaGithub


text:
class Course::CoursesComponent < SimpleDelegator
  include Course::ControllerComponentHost::Component

  def sidebar_items
    admin_sidebar_items + settings_sidebar_items
  end

  private

  def admin_sidebar_items
    return [] unless can?(:manage, current_course)

    [
      {
        title: t('layouts.course_admin.title'),
        type: :admin,
        weight: 4,
        path: course_admin_path(current_course)
      }
    ]
  end

  def settings_sidebar_items
    [
      settings_index_item,
      settings_components_item,
      settings_sidebar_item
    ]
  end

  def settings_index_item
    {
      title: t('layouts.course_admin.title'),
      type: :settings,
      weight: 1,
      path: course_admin_path(current_course)
    }
  end

  def settings_components_item
    {
      title: t('layouts.course_admin.component_settings.title'),
      type: :settings,
      weight: 2,
      path: course_admin_components_path(current_course)
    }
  end

  def settings_sidebar_item
    {
      title: t('layouts.course_admin.sidebar_settings.title'),
      type: :settings,
      weight: 3,
      path: course_admin_sidebar_path(current_course)
    }
  end
end


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('candidates', '0004_auto_20150724_0407'),
        ('questions', '0002_remove_choice_checked'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='choice',
            name='question',
        ),
        migrations.DeleteModel(
            name='Choice',
        ),
    ]


text:
package com.intellij.openapi.util;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ShutDownTracker implements Runnable {
  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.ShutDownTracker");
  private final List<Thread> myThreads = new ArrayList<Thread>();
  private final LinkedList<Thread> myShutdownThreads = new LinkedList<Thread>();
  private final LinkedList<Runnable> myShutdownTasks = new LinkedList<Runnable>();
  private volatile boolean myIsShutdownHookRunning = false;

  private ShutDownTracker() {
    //noinspection HardCodedStringLiteral
    Runtime.getRuntime().addShutdownHook(new Thread(this, "Shutdown tracker"));
  }

  private static class ShutDownTrackerHolder {
    private static final ShutDownTracker ourInstance = new ShutDownTracker();
  }

  @NotNull
  public static ShutDownTracker getInstance() {
    return ShutDownTrackerHolder.ourInstance;
  }

  public static boolean isShutdownHookRunning() {
    return getInstance().myIsShutdownHookRunning;
  }

  @Override
  public void run() {
    myIsShutdownHookRunning = true;

    ensureStopperThreadsFinished();

    for (Runnable task = removeLast(myShutdownTasks); task != null; task = removeLast(myShutdownTasks)) {
      //  task can change myShutdownTasks
      try {
        task.run();
      }
      catch (Throwable e) {
        LOG.error(e);
      }
    }

    for (Thread thread = removeLast(myShutdownThreads); thread != null; thread = removeLast(myShutdownThreads)) {
      thread.start();
      try {
        thread.join();
      }
      catch (InterruptedException ignored) {
      }
    }
  }

  public final void ensureStopperThreadsFinished() {
    Thread[] threads = getStopperThreads();
    final long started = System.currentTimeMillis();
    while (threads.length > 0) {
      Thread thread = threads[0];
      if (!thread.isAlive()) {
        if (isRegistered(thread)) {
          LOG.error("Thread '" + thread.getName() + "' did not unregister itself from ShutDownTracker.");
          unregisterStopperThread(thread);
        }
      }
      else {
        final long totalTimeWaited = System.currentTimeMillis() - started;
        if (totalTimeWaited > 3000) {
          // okay, we are waiting fo too long already, lets stop everyone:
          // in some cases, stopper thread may try to run readAction while we are shutting down (under a writeAction) and deadlock.
          thread.interrupt();
        }

        try {
          thread.join(100);
        }
        catch (InterruptedException ignored) {
        }
      }
      threads = getStopperThreads();
    }
  }

  private synchronized boolean isRegistered(@NotNull Thread thread) {
    return myThreads.contains(thread);
  }

  @NotNull
  private synchronized Thread[] getStopperThreads() {
    return myThreads.toArray(new Thread[myThreads.size()]);
  }

  public synchronized void registerStopperThread(@NotNull Thread thread) {
    myThreads.add(thread);
  }

  public synchronized void unregisterStopperThread(@NotNull Thread thread) {
    myThreads.remove(thread);
  }

  public synchronized void registerShutdownThread(@NotNull Thread thread) {
    myShutdownThreads.addLast(thread);
  }

  public synchronized void registerShutdownThread(int index, @NotNull Thread thread) {
    myShutdownThreads.add(index, thread);
  }

  public synchronized void registerShutdownTask(@NotNull Runnable task) {
    myShutdownTasks.addLast(task);
  }

  public synchronized void unregisterShutdownTask(@NotNull Runnable task) {
    myShutdownTasks.remove(task);
  }

  private synchronized <T> T removeLast(@NotNull LinkedList<T> list) {
    return list.isEmpty()? null : list.removeLast();
  }

  public static void invokeAndWait(boolean returnOnTimeout, boolean runInEdt, @NotNull final Runnable runnable) {
    if (!runInEdt) {
      if (returnOnTimeout) {
        final Semaphore semaphore = new Semaphore();
        semaphore.down();
        new Thread(new Runnable() {
          @Override
          public void run() {
            runnable.run();
            semaphore.up();
          }
        },"shutdown tracker invoker").start();
        semaphore.waitFor(1000);
      }
      else {
        runnable.run();
      }
      return;
    }

    if (returnOnTimeout) {
      final Semaphore semaphore = new Semaphore();
      semaphore.down();
      SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
          runnable.run();
          semaphore.up();
        }
      });
      semaphore.waitFor(1000);
      return;
    }

    try {
      UIUtil.invokeAndWaitIfNeeded(runnable);
    }
    catch (Exception e) {
      LOG.error(e);
    }
  }
}


text:
import { temporaryDir } from './helpers';

const tmp = temporaryDir();

tmp.copy('./README.md', './README-tmp.md');
tmp.copy('./CHANGELOG.md', './CHANGELOG-tmp.md');
tmp.copy('./CONTRIBUTING.md', './CONTRIBUTING-tmp.md');

tmp.remove('./README.md');
tmp.remove('./CHANGELOG.md');
tmp.remove('./CONTRIBUTING.md');


text:
<?php defined('SYSPATH') or die('No direct script access.');

require_once MODPATH . 'kodwoo/classes/kohana/kodwoo/internal/template.php';
class Kodwoo_Internal_Template extends Kohana_Kodwoo_Internal_Template { }


text:
@implementation LNBookLinkSource
MJCodingImplementation

- (BOOL)isEqual:(LNBookLinkSource *)object
{
    return [self._id isEqualToString:object._id];
}

@end


text:
import math
import numpy as np
import cv2

from scipy.signal import savgol_filter

class ModelConfig:

    def __init__(self, num_segments, min_angle, max_angle, num_angles, tail_length, tail_detection, prune_retention, test_width, draw_width, auto_detect_tail_length):

        self.min_angle = min_angle # Minimum angle for each segment (relative to previous segment)
        self.max_angle = max_angle # Maximum angle for each segment
        self.num_models_per_segment = num_angles # Number of angles to try for each segment

        self.prune_freq = 1 # When constructing the model, segment interval at which the model pruning function is called. Lower numbers are faster
        self.max_num_models_to_keep = prune_retention # Number of models retained after each round of pruning

        segment_height = int(tail_length / num_segments)
        self.segment_heights = [segment_height] * num_segments # Length must match num_segments
        self.segment_widths = [test_width] * num_segments # Used for constructing and testing straight-line models. Length must match num_segment

        self.num_segments = num_segments

        self.smoothed_segment_width = draw_width # Used for drawing the final smoothed version of the tail curve

        self.tail_offset = 30 # Distance in pixels from the head point to the tail model start point

        self.rotated_img_size = 200 # Size of the internal image of the rotated fish

        self.tail_point_detection_algorithm = tail_detection

        # Auto-detect tail length settings
        self.auto_detect_tail_length = auto_detect_tail_length
        if auto_detect_tail_length:
            # Override number of segments with a high number
            # Tail end will be detected automatically before this is reached and model generation will be stopped at that point
            self.num_segments = 20
            self.segment_heights = [5] * self.num_segments
            self.segment_widths  = [2] * self.num_segments
            self.segment_score_improvement_threshold = 250 # Amount by which a segment must improve the model score to be considered valid. If 'num_fail_segments' segments in a row are considered invalid, no further segments are added to that model
            self.num_fail_segments = 2 # Number of continuous segments which fail to meet the threshold improvement score for model generation to stop
            self.min_segments = 5 # Minimum number of segments in the model - There will be at least this many segments, even if the failing criteria is reached

class MaskCanvas:

    def __init__(self, canvas_width, canvas_height):
        self.canvas = np.zeros((canvas_width, canvas_height), np.uint8)
        self.points = []
        self.scores = [0]
        self.angle_offset = 0

    def add_point(self, point):
        self.points.append(point)

    def last_point(self):
        return self.points[-1] if len(self.points) > 0 else None

    def last_score(self):
        return self.scores[-1]

    def score_improvement(self, n):
        if len(self.scores) < n + 1:
            return 0
        return self.scores[-1 * n] - self.scores[-1 * (n+1)]

def getOrientation(frame, config):

    th_val = 1

    ret, binary_img = cv2.threshold(frame, th_val, 255, cv2.THRESH_BINARY)
    contours, hierarchy = cv2.findContours(binary_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]

    # Sort contours by area
    contours.sort(key=lambda ar: cv2.contourArea(ar))

    largest_contour = contours[-1]

    [vx, vy, x, y] = cv2.fitLine(largest_contour, cv2.DIST_L2, 0, 0.01, 0.01)
    line_angle = math.atan2(vy, vx)
    line_angle_degrees = math.degrees(line_angle)

    angle = line_angle_degrees + 90

    x, y, w, h = cv2.boundingRect(largest_contour)

    img_cropped = frame[y:y+h, x:x+w]

    rotated_img, actual_angle = rotateFishImage(img_cropped, angle, config)

    return rotated_img, actual_angle

def rotateFishImage(img, angle_degrees, config):

    input_image = np.zeros((config.rotated_img_size, config.rotated_img_size), np.uint8)

    y_mid = config.rotated_img_size // 2
    def _get_range(l):
        bot = math.floor(y_mid - l/2)
        top = math.floor(y_mid + l/2)
        return bot, top

    h_ran, w_ran = list(map(_get_range, img.shape))
    input_image[h_ran[0]:h_ran[1], w_ran[0]:w_ran[1]] = img

    rows, cols = input_image.shape
    center = (rows//2, cols//2)

    M = cv2.getRotationMatrix2D(center, angle_degrees, 1.0)
    rotated_img = cv2.warpAffine(input_image, M, (cols, rows))

    img_top = rotated_img[0:y_mid, 0:config.rotated_img_size]
    img_bottom = rotated_img[y_mid:config.rotated_img_size, 0:config.rotated_img_size]

    # Use valid pixel count to determine which half contains the head

    top_area = len(img_top[img_top != 0])
    bottom_area = len(img_bottom[img_bottom != 0])

    head_half = img_top if bottom_area < top_area else img_bottom

    # Find rotation angle again, this time only using the head half

    contours, hierarchy = cv2.findContours(head_half.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]
    contours.sort(key=lambda ar: ar.size)
    largest_contour = contours[-1]

    [vx, vy, x, y] = cv2.fitLine(largest_contour, cv2.DIST_L2, 0, 0.01, 0.01)
    line_angle = math.atan2(vy, vx)
    line_angle_degrees = (math.degrees(line_angle) + 90) % 360

    final_angle = (angle_degrees + line_angle_degrees) % 360

    rows, cols = input_image.shape[:2]
    center = (rows/2, cols/2)
    M = cv2.getRotationMatrix2D(center, final_angle, 1.0)
    rotated_output_img = cv2.warpAffine(input_image, M, (cols, rows))

    # Check again whether the image is rotated 180 degrees, and correct if necessary

    img_top = rotated_output_img[0:y_mid, 0:config.rotated_img_size]
    img_bottom = rotated_output_img[y_mid:config.rotated_img_size, 0:config.rotated_img_size]

    top_area = len(img_top[img_top != 0])
    bottom_area = len(img_bottom[img_bottom != 0])

    if bottom_area > top_area:
        correction_angle = 180
        M = cv2.getRotationMatrix2D(center, correction_angle, 1.0)
        rotated_output_img = cv2.warpAffine(rotated_output_img, M, (cols, rows))
        final_angle = (final_angle + correction_angle) % 360

    return rotated_output_img, final_angle

def getHeadMask(frame):

    th_val = 1

    ret, img_thresh = cv2.threshold(frame, th_val, 255, cv2.THRESH_BINARY)

    # Remove excess noise by drawing only the largest contour

    head_mask = np.zeros((img_thresh.shape[0], img_thresh.shape[1]), np.uint8)

    contours, hierarchy = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]
    contours.sort(key=lambda ar: ar.size)
    head_contour = contours[-1]

    cv2.drawContours(head_mask, [head_contour], 0, 255, cv2.FILLED)

    return head_mask

def getHeadPoint(rotated_img, angle):

    theta = math.radians(- angle)

    img_binary = np.zeros(rotated_img.shape, np.uint8)
    contours, hierarchy = cv2.findContours(rotated_img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]
    contours.sort(key=lambda ar: ar.size)
    largest_contour = contours[-1]
    cv2.drawContours(img_binary, [largest_contour], 0, 255, cv2.FILLED)

    valid_pixels = np.nonzero(img_binary)

    x = valid_pixels[1]
    y = valid_pixels[0]

    head_x = x[np.argmin(y)]
    head_y = np.min(y)

    w, h = rotated_img.shape[:2]
    center_x = w / 2
    center_y = h / 2

    hypot = math.hypot(center_x - head_x, center_y - head_y)

    rotated_head_x = center_x - (hypot * math.sin(theta))
    rotated_head_y = center_y - (hypot * math.cos(theta))

    return rotated_head_x, rotated_head_y

def getTailStartPoint(head_mask, head_point, config):

	# Calculate the angle from the head point to the contour center
	# Then, 'walk' down the line from the head point to the contour center point a set length

    contours, hierarchy = cv2.findContours(head_mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]
    contour = contours[-1]

    # Get contour center
    contour_moments = cv2.moments(contour)
    contour_center_x = int(contour_moments['m10'] / contour_moments['m00'])
    contour_center_y = int(contour_moments['m01'] / contour_moments['m00'])

    head_x = head_point[0]
    head_y = head_point[1]

    head_contour_center_angle = math.atan2(contour_center_y - head_y, contour_center_x - head_x)

    head_x = head_point[0]
    head_y = head_point[1]

    # Calculate tail start point
    tail_start_x = head_x + config.tail_offset * math.cos(head_contour_center_angle)
    tail_start_y = head_y + config.tail_offset * math.sin(head_contour_center_angle)

    return (int(tail_start_x), int(tail_start_y))

def getModelMasks(head_mask, base_angle, frame, head_point, config):

    # Generate the test image used for scoring models
    test_image = getTestImage(frame, head_mask, head_point, base_angle, config)

    # Create starting object
    initial_canvas = MaskCanvas(head_mask.shape[0], head_mask.shape[1])

    # Add tail starting point
    initial_point = getTailStartPoint(head_mask, head_point, config)
    initial_canvas.add_point(initial_point)

    # Set base angle
    initial_canvas.angle_offset = -base_angle

    canvas_set = [initial_canvas]
    output_canvas_set = drawModelSegments(canvas_set, config.num_segments, test_image, config)

    return output_canvas_set

def getTestImage(frame, head_mask, head_point, angle, config):

    # Remove the head from the test image using a triangular mask, so it doesn't interfere with tail model scoring

    center_x, center_y = getTailStartPoint(head_mask, head_point, config)

    triangle_length = 100

    t0_angle_radians = math.radians(angle)
    t0_x = center_x + triangle_length * math.sin(t0_angle_radians)
    t0_y = center_y - triangle_length * math.cos(t0_angle_radians)

    t1_angle_radians = math.radians(angle - 90)
    t1_x = center_x + triangle_length * math.sin(t1_angle_radians)
    t1_y = center_y - triangle_length * math.cos(t1_angle_radians)

    t2_angle_radians = math.radians(angle + 90)
    t2_x = center_x + triangle_length * math.sin(t2_angle_radians)
    t2_y = center_y - triangle_length * math.cos(t2_angle_radians)

    triangle_points = np.array([(t0_x, t0_y), (t1_x, t1_y), (t2_x, t2_y)]).astype('int32')

    test_image = frame.copy()
    cv2.fillConvexPoly(test_image, triangle_points, 0)

    return test_image

def drawModelSegments(canvas_set, num_segments, test_image, config):

    angle_increment = (config.max_angle - config.min_angle) / config.num_models_per_segment

    output_set = []

    for canvas in canvas_set:

        for i in range(0, config.num_models_per_segment + 1):

            # Calculate segment rotation angle
            rotation_angle = config.min_angle + (i * angle_increment)

            # Draw line on canvas

            new_canvas = MaskCanvas(0, 0)
            new_canvas.canvas = canvas.canvas.copy()
            new_canvas.points = list(canvas.points)
            new_canvas.angle_offset = canvas.angle_offset
            new_canvas.scores = list(canvas.scores)

            segment_width = config.segment_widths[-num_segments]
            segment_height = config.segment_heights[-num_segments]

            canvas_with_segment = drawSegmentOnCanvas(new_canvas, rotation_angle, segment_width, segment_height)

            # Add canvas to output set
            output_set.append(canvas_with_segment)

    # Prune the models with the lowest scores
    if num_segments % config.prune_freq == 0:
        end_generation, output_set = pruneModels(test_image, output_set, config.max_num_models_to_keep, config)

    # If auto-detect tail length is enabled, check for 'end model generation' flag
    if config.auto_detect_tail_length:
        if end_generation is True and num_segments < config.num_segments - config.min_segments:
            i = len(output_set[0].points) - config.num_fail_segments # Remove the final failing segments
            output_set[0].points = output_set[0].points[0:i]
            return output_set

    # Call the function recursively until all segments have been drawn on the canvases
    if num_segments > 1:
        return drawModelSegments(output_set, num_segments - 1, test_image, config)
    else:
        return output_set

def drawSegmentOnCanvas(canvas, angle, segment_width, segment_height):

    # Take into account previous angles
    adjusted_angle = angle + canvas.angle_offset

    # Convert angle from degrees to radians
    angle_radians = math.radians(adjusted_angle)

    # Calculate position of next point
    pt_x = canvas.last_point()[0] + segment_height * math.sin(angle_radians)
    pt_y = canvas.last_point()[1] + segment_height * math.cos(angle_radians)
    pt = (int(pt_x), int(pt_y))

    # Draw line connecting points
    cv2.line(canvas.canvas, canvas.last_point(), pt, 255, thickness=segment_width, lineType=cv2.LINE_AA)

    # Add the new point to the MaskCanvas object's list of points
    canvas.add_point(pt)

    # Update 'angle_offset' on the MaskCanvas object
    canvas.angle_offset += angle

    return canvas

def pruneModels(test_image, canvas_set, max_num_models_to_keep, config):

    for canvas in canvas_set:
        score = scoreModel(canvas, test_image)
        canvas.scores.append(score)

    # Order canvas list by scores
    canvas_set.sort(key=lambda c: c.last_score())

    # Remove all masks except the ones with the top scores
    keep_num = max_num_models_to_keep if len(canvas_set) > max_num_models_to_keep else len(canvas_set)
    pruned_set = canvas_set[-keep_num:]

    # Return the pruned set of models if tail length auto-detection is off
    if config.auto_detect_tail_length == False:
        return False, pruned_set

    # Otherwise, decide whether to continue adding segments to the models or not

    best_canvas = canvas_set[-1]

    # If the set continuous number of segments fail to meet the threshold improvement score,
    # signal that the model should stop being generated (ie. no further segments should be added, and the final
    # failing x segments should be removed from the model)

    end_generation = False
    for x in range(1, config.num_fail_segments + 1):

        if best_canvas.score_improvement(x) > config.segment_score_improvement_threshold:
            break

        if x == config.num_fail_segments:
            end_generation = True

    return end_generation, pruned_set

def scoreModel(canvas, test_image):

    # Find pixels in the test image which overlap with the model
    masked_img = cv2.bitwise_and(test_image, test_image, mask=canvas.canvas)

    # Get non-zero pixels
    valid_pixels = masked_img[masked_img != 0]

    # Adjust pixel values so that darker pixels will score higher than lighter pixels (as fish is darker than the background)
    adjusted_vals = 256 - valid_pixels

    # Calculate score
    score = int(cv2.sumElems(adjusted_vals)[0])

    return score

def smoothMaskModel(mask_canvas, config):

    points = mask_canvas.points

    points = np.array(points)
    points = points.astype(int)

    x = points[:, 0]
    y = points[:, 1]

    window_length = len(y)

    if window_length % 2 == 0:
        window_length -= 1

    polyorder = 3
    yhat = savgol_filter(y, window_length, polyorder)

    output_points = []
    for a, b in zip(x, yhat):
        new_point = [a, b]
        output_points.append(new_point)
    output_points = np.array(output_points)
    output_points = output_points.astype(int)

    mask = np.zeros(mask_canvas.canvas.shape, np.uint8)
    cv2.polylines(mask, [output_points], False, 255, thickness=config.smoothed_segment_width)

    return mask, output_points

def getCombinationMask(head_mask, tail_mask):

    combination_mask = cv2.add(head_mask, tail_mask)

    return combination_mask

def cleanMask(mask):

    # Apply closing to smooth the edges of the mask

    kernel_size = 5
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size))  # Circle

    mask_closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

    return mask_closing

def getZebrafishMask(frame, config):

    # Get orientated image and rotation angle
    rotated_img, angle = getOrientation(frame, config)

    # Get head mask
    head_mask = getHeadMask(frame)

    # Get head point
    head_point = getHeadPoint(rotated_img, angle)

    # Get model masks
    model_masks = getModelMasks(head_mask, angle, frame, head_point, config)

    # Get best mask
    test_image = getTestImage(frame, head_mask, head_point, angle, config)
    _, mask_set = pruneModels(test_image, model_masks, 1, config)
    best_mask = mask_set[0]

    # Smooth the best mask
    smoothed_mask, smoothed_points = smoothMaskModel(best_mask, config)

    # Get combination mask
    combination_mask = getCombinationMask(head_mask, smoothed_mask)

    # Clean mask
    cleaned_mask = cleanMask(combination_mask)

    worm_mask = cleaned_mask.copy()

    contours, hierarchy = cv2.findContours(cleaned_mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]

    if len(contours) == 0:
        output = None

    else:
        # Remove nesting from contour
        worm_cnt = contours[0]
        worm_cnt = np.vstack(worm_cnt).squeeze()

        # Return None values if contour too small
        if len(worm_cnt) < 3:
            output = None
        else:
            cnt_area = cv2.contourArea(worm_cnt)
            output = worm_mask, worm_cnt, cnt_area, \
                   cleaned_mask, head_point, smoothed_points

    if output is None:
        return [None]*6
    else:
        return output


text:
var fs = require("fs");
var through = require("through");
var JSONStream = require("JSONStream");
var csv = require("csv-streamify");
var yr = require("../yearrange");

var stream = fs.createReadStream(__dirname + "/date-styles.csv");
var out = fs.createWriteStream(__dirname + "/date-tests.json");

var csvStream = csv({
    delimiter: "\t",
    quote: "|",
    objectMode: true,
    columns: true
});

stream
    .pipe(csvStream)
    .pipe(through(function(data) {
        var date = yr.parse(data.Example);
        if (date.start) {
            this.queue(date);
        }
    }))
    .pipe(JSONStream.stringify())
    .pipe(out);


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Fun & Useful Backbone extensions, yaaaay</title>
    <link rel="stylesheet" href="bower_components/qunit/qunit/qunit.css">


text:
package com.phone1000.chayu.adapters;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;

import java.util.List;

/**
 * Created by Administrator on 2016/11/27 0027.
 */
public class TeaCommFragmentAdapter extends FragmentPagerAdapter{

    private static final String TAG = TeaCommFragmentAdapter.class.getSimpleName();
    private List<Fragment> data;

    public TeaCommFragmentAdapter(FragmentManager fm,List<Fragment> data) {
        super(fm);
        this.data = data;
    }

    @Override
    public Fragment getItem(int position) {
        //Log.e(TAG, "getItem: "+data.get(position) );
        return data.get(position);
    }

    @Override
    public int getCount() {
        //Log.e(TAG, "getCount: "+data.size()+"");
        return data.size();
    }
}


text:
"""Misspellings.

---
layout:     post
source:     The Wall Street Journal
source_url: http://on.wsj.com/1rksm8k
title:      misspellings
date:       2014-06-10 12:31:19
categories: writing
---

Points out misspellings.

"""
from proselint.tools import memoize, preferred_forms_check

@memoize
def check(text):
    """Suggest the preferred forms."""
    err = "wsj.athletes"
    msg = "Misspelling of athlete's name. '{}' is the preferred form."

    misspellings = [
        ["Dwyane Wade",         ["Dwayne Wade"]],
        ["Miikka Kiprusoff",    ["Mikka Kiprusoff"]],
        ["Mark Buehrle",        ["Mark Buerhle"]],
        ["Skylar Diggins",      ["Skyler Diggins"]],
        ["Agnieszka Radwanska", ["Agnieska Radwanska"]],
        ["J.J. Redick",         ["J.J. Reddick"]],
        ["Manny Pacquiao",      ["Manny Packquaio"]],
        ["Antawn Jamison",      ["Antwan Jamison"]],
        ["Cal Ripken",          ["Cal Ripkin"]],
        ["Jhonny Peralta",      ["Johnny Peralta"]],
        ["Monta Ellis",         ["Monte Ellis"]],
        ["Alex Rodriguez",      ["Alex Rodriquez"]],
        ["Mark Teixeira",       ["Mark Texeira"]],
        ["Brett Favre",         ["Brett Farve"]],
        ["Torii Hunter",        ["Tori Hunter"]],
        ["Stephen Curry",       ["Stephon Curry"]],
        ["Mike Krzyzewski",     ["Mike Kryzewski"]],
    ]

    return preferred_forms_check(text, misspellings, err, msg)


text:
/**
# webrtc

webrtc configuration with localStorage persistence
*/
/* global console, localStorage */

import b8r from '../source/b8r.js'
import { isElectron } from '../lib/runtime-environment.js'

const settingsPath = 'webrtc-devices.settings'
const listeners = []
const { desktopCapturer } = isElectron ? require('electron') : { desktopCapturer: false }

if (!navigator.mediaDevices) {
  throw new Error('navigator.mediaDevices not found; webrtc not supported')
}

const addListener = listener => listeners.indexOf(listener) === -1 && listeners.push(listener)

const removeListener = listener => {
  for (let i = listeners.length - 1; i >= 0; i--) {
    if (listeners[i] === listener) {
      listeners.splice(i, 1)
    }
  }
}

b8r.set('webrtc-devices', {
  settings: JSON.parse(localStorage.getItem(settingsPath) || '{}')
})

const defaultLabels = {
  videoinput: 'Default Camera',
  audioinput: 'Default Microphone'
}

const sortDevices = ds => ds.sort((a, b) =>
  // Since we include desktop sources (windows and screens), this is a more friendly order than the
  // arbitrary way they come back from enumerateDevices()
  //
  // Could go wrong if there's more than one device called 'Default' in a given list, but that
  // shouldn't happen in practice and it wouldn't be a big deal anyway.
  //
  a.label === 'Default' ? -1
    : b.label === 'Default' ? 1
      : a.type === b.type ? (a.label || '').localeCompare(b.label)
        : (a.type || '').localeCompare(b.type)
)

let firstLoad = true

const updateMediaDevices = desktopSources => {
  navigator.mediaDevices.enumerateDevices()
    .then(
      devices => {
        const type = 'local'
        const sources = {
          audioinput: [],
          videoinput: [],
          audiooutput: []
        // There appears to be no such thing as "videooutput" - I suppose you're supposed to assume
        // you're not in a headless environment
        }
        const settings = b8r.get(settingsPath)
        devices.forEach(device => {
          sources[device.kind] = sources[device.kind] || []
          const { label, deviceId, groupId } = device
          sources[device.kind].push({
            label: label || defaultLabels[device.kind],
            deviceId,
            groupId,
            type
          }
          )
        })

        if (sources.videoinput.length === 0) {
        // This is a fake video source so that we know there is no camera on this machine. s
          sources.videoinput.push({ deviceId: null, label: 'no camera', type: 'local' })
        }

        desktopSources.forEach(source => sources.videoinput.push(source))

        for (const k in sources) { sortDevices(sources[k]) }

        // clear device settings if device no longer present
        if (
          settings.videoinput &&
        sources.videoinput &&
        !sources.videoinput.find(device => device.deviceId === settings.videoinput)
        ) {
          settings.videoinput = null
        }
        if (
          settings.audioinput &&
        sources.audioinput &&
        !sources.audioinput.find(device => device.deviceId === settings.audioinput)
        ) {
          settings.audioinput = null
        }

        if (!settings.audioinput && sources.audioinput.length) {
        // Until we implement BOT-609, the only audio sources will be microphones, so switching to
        // default makes sense when one gets unplugged.
          settings.audioinput = sources.audioinput[0].deviceId
        }
        if (firstLoad) {
        // Set video defaults only on first load to avoid the creepy unexpected behavior of, for
        // example, automatically publishing your camera when you close a window you were sharing.
        //
        // Refine when we implement BOT-612
          if (!settings.videoinput && sources.videoinput.length) {
            settings.videoinput = sources.videoinput[0].deviceId
          }
        }
        firstLoad = false
        b8r.set('webrtc-devices.sources',
        // For screensharing, force source list to update in settings screen when a window title
        // changes, but the deviceId remains the same. This happens, for example, when you switch
        // tabs in your browser.
          null)
        b8r.set('webrtc-devices.sources', sources)
        const webrtcDevices = b8r.get('webrtc-devices')
        listeners.forEach(listener => listener('devices', webrtcDevices))
      }
    )
}

const update = () => {
  if (desktopCapturer) {
    desktopCapturer.getSources({ types: ['window', 'screen'] }, (desktopError, desktopSources) => {
      const sources = []
      desktopSources.forEach(source => {
        sources.push({
          label: source.name,
          deviceId: source.id,
          type: source.id.split(':')[0],
          groupId: '',
          thumbnail: source.thumbnail.toDataURL() || undefined
        })
      })
      updateMediaDevices(sources)
    })
  } else {
    updateMediaDevices([])
  }
}

const saveSettings = b8r.debounce(
  () => {
    console.log('saving webrtc-devices.settings')
    listeners.forEach(listener => listener('settings', b8r.get(settingsPath)))

    // We don't to set defaults to an ephemeral device
    const videoId = b8r.get(settingsPath).videoinput
    const videoInput = b8r.get(`webrtc-devices.sources.videoinput[deviceId=${videoId}]`) ||
                       b8r.get('webrtc-devices.sources.videoinput[type=local]')
    const audioId = b8r.get(settingsPath).audioinput
    const audioInput = b8r.get(`webrtc-devices.sources.audioinput[deviceId=${audioId}]`) ||
                       b8r.get('webrtc-devices.sources.audioinput[type=local]')

    if (videoInput && videoInput.type === 'local' && audioInput && audioInput.type === 'local') {
      b8r.set(`${settingsPath}.videoinput`, videoInput.deviceId)
      b8r.set(`${settingsPath}.audioinput`, audioInput.deviceId)
      localStorage.setItem(settingsPath, b8r.getJSON(settingsPath))
    }
  },
  100
)

b8r.observe('webrtc-devices.settings', saveSettings)

if (navigator.mediaDevices.addEventListener) {
  navigator.mediaDevices.addEventListener('devicechange', update)
} else if (navigator.mediaDevices) {
  navigator.ondevicechange = update
}

update()

export {
  update,
  addListener,
  removeListener
}


text:
<?php

namespace GeekHub\SpaceBlogBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class PageController extends Controller
{
    /**
     * @param Request $request
     *
     * @return Response.
     */
    public function indexAction(Request $request)
    {
        $postsQuery = $this->getDoctrine()
            ->getRepository('SpaceBlogBundle:Post')
            ->findAllQuery();

        $paginatorCurrentPageNumber = (int) abs($request->query->get('page'));
        $paginator = $this->get('space_blog.pagination');
        $paginatedPosts = $paginator->paginate($paginatorCurrentPageNumber, $postsQuery, 'posts');

        return $this->render('SpaceBlogBundle:Page:index.html.twig', [
            'posts' => $paginatedPosts,
        ]);
    }

    /**
     * @return Response
     */
    public function siteMapAction()
    {
        $this->get('white_october_breadcrumbs')
            ->addItem("home", $this->get("router")->generate("space_blog_homepage"))
            ->addItem("sitemap", $this->get("router")->generate("space_blog_sitemap"))
        ;
        $categoriesTree = $this->get('space_blog.tree')->category();

        return $this->render('SpaceBlogBundle:Page:site_map.html.twig', [
            'categories_tree' => $categoriesTree,
        ]);
    }
}


text:
import React from 'react';
import classnames from 'classnames';

import './Calendar.css';

import {
  DEFAULT_CURRENT_DATE,
  language,
  getMonthFormatted,
  monthGenegrator,
} from './util';

export default React.createClass({

  propTypes: {
    assignedMonth: React.PropTypes.string,
    assignedYear: React.PropTypes.string,
    selectedDate: React.PropTypes.object,
    availableDate: React.PropTypes.shape({
      from: React.PropTypes.object, // Date instance
      to: React.PropTypes.object, // Date instance
    }),
    highlightDates: React.PropTypes.arrayOf(React.PropTypes.object),
    onChange: React.PropTypes.func,
  },

  getDefaultProps() {
    return {
      onChange: () => {},
      onHover: () => {},
      selectedDate: undefined,
      highlightDates: [],
    };
  },

  getInitialState() {
    return {
      currentDate: DEFAULT_CURRENT_DATE,
      today: new Date(),
    };
  },

  componentWillMount() {
    this.setCurrentDateFromProps(this.props);
  },

  componentWillReceiveProps(nextProps) {
    if (
      nextProps.assignedYear !== this.props.assignedYear ||
      nextProps.assignedMonth !== this.props.assignedMonth
    ) {
      this.setCurrentDateFromProps(nextProps);
    }
  },

  setCurrentDateFromProps(props) {
    const targetMonth = parseInt(props.assignedMonth, 10);
    const targetYear = parseInt(props.assignedYear, 10);

    if (!isNaN(targetMonth) && !isNaN(targetYear) && targetMonth >= 0 && targetMonth < 13) {
      this.setState({ currentDate: new Date(targetYear, targetMonth - 1, 1) });
    }
  },

  goPrevMonth() {
    const newCurrentDate = new Date(this.state.currentDate);
    newCurrentDate.setMonth(this.state.currentDate.getMonth() - 1, 1);
    this.setState({
      currentDate: newCurrentDate,
    });
  },

  goNextMonth() {
    const newCurrentDate = new Date(this.state.currentDate);
    newCurrentDate.setMonth(this.state.currentDate.getMonth() + 1, 1);
    this.setState({
      currentDate: newCurrentDate,
    });
  },

  selectDayEvent(dateObj) {
    const selectedDateObj = {
      year: this.state.currentDate.getFullYear(),
      month: this.state.currentDate.getMonth(),
      day: dateObj.date,
      fullDate: dateObj.fullDate,
    };
    this.props.onChange(selectedDateObj);
  },

  hoverDayEvent(dateObj) {
    if (dateObj) {
      const selectedDateObj = {
        year: this.state.currentDate.getFullYear(),
        month: this.state.currentDate.getMonth(),
        day: dateObj.date,
        fullDate: dateObj.fullDate,
      };
      this.props.onHover(selectedDateObj);
    } else {
      this.props.onHover(null);
    }
  },

  render() {
    const { state, props } = this;
    const {
      currentDate,
      today,
    } = state;

    const {
      selectedDate,
      availableDate,
      highlightDates,
    } = props;

    const monthObj = monthGenegrator(availableDate, highlightDates)(currentDate, today);

    const selectedDateObj = selectedDate ? {
      day: selectedDate.getDate(),
      month: selectedDate.getMonth(),
      year: selectedDate.getFullYear(),
    } : null;

    const $month = monthObj.map((week, i) => {
      const $week = week.map((day, j) => {
        const dateCx = classnames({
          'cal-month-day': true,
          'cal-day-outmonth': day.outmonth,
          'cal-day-weekend': day.day === 6 || day.day === 7,
          'cal-day-today': day.isToday,
          notAvailable: !day.available,
          selected: selectedDateObj &&
            selectedDateObj.day === day.date &&
            selectedDateObj.month === currentDate.getMonth() &&
            selectedDateObj.year === currentDate.getFullYear() &&
            !day.outmonth,
          highlighted: day.highlighted,
        });
        return (

this.selectDayEvent(day)}
              onMouseEnter={()=>this.hoverDayEvent(day)}
            >
              {day.date}

        );
      });
      return (

          {$week}

      );
    });

    return (

            <svg
              className="arrow-left arrow-icon"
              x="0px" y="0px"
              width="14px" height="14px"
              viewBox="0 0 199.404 199.404"
            >
              <g>
                <polygon points="135.412,0 35.709,99.702 135.412,199.404 163.695,171.119 92.277,99.702 163.695,28.285" />
              </g>
            </svg>

            {getMonthFormatted(currentDate)}    {currentDate.getFullYear()}

            <svg
              className="arrow-right arrow-icon"
              x="0px" y="0px"
              width="14px" height="14px"
              viewBox="0 0 199.404 199.404"
            >
              <g>
                <polygon points="63.993,199.404 163.695,99.702 63.993,0 35.709,28.285 107.127,99.702 35.709,171.119" />
              </g>
            </svg>

{language.d1}

{language.d2}

{language.d3}

{language.d4}

{language.d5}

{language.d6}

{language.d0}

          {$month}

    );
  },
});


text:
<?php

/**
 * @category   Zend
 * @package    Zend_Application
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Application
{
    /**
     * Autoloader to use
     *
     * @var Zend_Loader_Autoloader
     */
    protected $_autoloader;

    /**
     * Bootstrap
     *
     * @var Zend_Application_Bootstrap_BootstrapAbstract
     */
    protected $_bootstrap;

    /**
     * Application environment
     *
     * @var string
     */
    protected $_environment;

    /**
     * Options for Zend_Application
     *
     * @var array
     */
    protected $_options = array();

    /**
     * Constructor
     *
     * Initialize application. Potentially initializes include_paths, PHP
     * settings, and bootstrap class.
     *
     * @param  string                   $environment
     * @param  string|array|Zend_Config $options String path to configuration file, or array/Zend_Config of configuration options
     * @throws Zend_Application_Exception When invalid options are provided
     * @return void
     */
    public function __construct($environment, $options = null)
    {
        $this->_environment = (string) $environment;

        require_once 'Zend/Loader/Autoloader.php';
        $this->_autoloader = Zend_Loader_Autoloader::getInstance();

        if (null !== $options) {
            if (is_string($options)) {
                $options = $this->_loadConfig($options);
            } elseif ($options instanceof Zend_Config) {
                $options = $options->toArray();
            } elseif (!is_array($options)) {
                throw new Zend_Application_Exception('Invalid options provided; must be location of config file, a config object, or an array');
            }

            $this->setOptions($options);
        }
    }

    /**
     * Retrieve current environment
     *
     * @return string
     */
    public function getEnvironment()
    {
        return $this->_environment;
    }

    /**
     * Retrieve autoloader instance
     *
     * @return Zend_Loader_Autoloader
     */
    public function getAutoloader()
    {
        return $this->_autoloader;
    }

    /**
     * Set application options
     *
     * @param  array $options
     * @throws Zend_Application_Exception When no bootstrap path is provided
     * @throws Zend_Application_Exception When invalid bootstrap information are provided
     * @return Zend_Application
     */
    public function setOptions(array $options)
    {
        $options = array_change_key_case($options, CASE_LOWER);

        if (!empty($options['config'])) {
            $options += $this->_loadConfig($options['config']);
        }

        $this->_options = $options;

        if (!empty($options['phpsettings'])) {
            $this->setPhpSettings($options['phpsettings']);
        }

        if (!empty($options['includepaths'])) {
            $this->setIncludePaths($options['includepaths']);
        }

        if (!empty($options['autoloadernamespaces'])) {
            $this->setAutoloaderNamespaces($options['autoloadernamespaces']);
        }

        if (!empty($options['bootstrap'])) {
            $bootstrap = $options['bootstrap'];

            if (is_string($bootstrap)) {
                $this->setBootstrap($bootstrap);
            } elseif (is_array($bootstrap)) {
                if (empty($bootstrap['path'])) {
                    throw new Zend_Application_Exception('No bootstrap path provided');
                }

                $path  = $bootstrap['path'];
                $class = null;

                if (!empty($bootstrap['class'])) {
                    $class = $bootstrap['class'];
                }

                $this->setBootstrap($path, $class);
            } else {
                throw new Zend_Application_Exception('Invalid bootstrap information provided');
            }
        }

        return $this;
    }

    /**
     * Retrieve application options (for caching)
     *
     * @return array
     */
    public function getOptions()
    {
        return $this->_options;
    }

    /**
     * Is an option present?
     *
     * @param  string $key
     * @return bool
     */
    public function hasOption($key)
    {
        return array_key_exists($key, $this->_options);
    }

    /**
     * Retrieve a single option
     *
     * @param  string $key
     * @return mixed
     */
    public function getOption($key)
    {
        if ($this->hasOption($key)) {
            return $this->_options[$key];
        }
        return null;
    }

    /**
     * Set PHP configuration settings
     *
     * @param  array $settings
     * @param  string $prefix Key prefix to prepend to array values (used to map . separated INI values)
     * @return Zend_Application
     */
    public function setPhpSettings(array $settings, $prefix = '')
    {
        foreach ($settings as $key => $value) {
            $key = empty($prefix) ? $key : $prefix . $key;
            if (is_scalar($value)) {
                ini_set($key, $value);
            } elseif (is_array($value)) {
                $this->setPhpSettings($value, $key . '.');
            }
        }

        return $this;
    }

    /**
     * Set include path
     *
     * @param  array $paths
     * @return Zend_Application
     */
    public function setIncludePaths(array $paths)
    {
        $path = implode(PATH_SEPARATOR, $paths);
        set_include_path($path . PATH_SEPARATOR . get_include_path());
        return $this;
    }

    /**
     * Set autoloader namespaces
     *
     * @param  array $namespaces
     * @return Zend_Application
     */
    public function setAutoloaderNamespaces(array $namespaces)
    {
        $autoloader = $this->getAutoloader();

        foreach ($namespaces as $namespace) {
            $autoloader->registerNamespace($namespace);
        }

        return $this;
    }

    /**
     * Set bootstrap path/class
     *
     * @param  string $path
     * @param  string $class
     * @return Zend_Application
     */
    public function setBootstrap($path, $class = null)
    {
        // setOptions() can potentially send a null value; specify default
        // here
        if (null === $class) {
            $class = 'Bootstrap';
        }

        require_once $path;
        $this->_bootstrap = new $class($this);

        return $this;
    }

    /**
     * Get bootstrap object
     *
     * @return Zend_Application_Bootstrap_BootstrapAbstract
     */
    public function getBootstrap()
    {
        if (null === $this->_bootstrap) {
            $this->_bootstrap = new Zend_Application_Bootstrap_Bootstrap($this);
        }
        return $this->_bootstrap;
    }

    /**
     * Bootstrap application
     *
     * @return Zend_Application
     */
    public function bootstrap()
    {
        $this->getBootstrap()->bootstrap();
        return $this;
    }

    /**
     * Run the application
     *
     * @return void
     */
    public function run()
    {
        $this->getBootstrap()->run();
    }

    /**
     * Load configuration file of options
     *
     * @param  string $file
     * @throws Zend_Application_Exception When invalid configuration file is provided
     * @return array
     */
    protected function _loadConfig($file)
    {
        $environment = $this->getEnvironment();
        $suffix      = strtolower(pathinfo($file, PATHINFO_EXTENSION));

        switch ($suffix) {
            case 'ini':
                $config = new Zend_Config_Ini($file, $environment);
                break;

            case 'xml':
                $config = new Zend_Config_Xml($file, $environment);
                break;

            case 'php':
            case 'inc':
                $config = include $file;
                if (!is_array($config)) {
                    throw new Zend_Application_Exception('Invalid configuration file provided; PHP file does not return array value');
                }
                return $config;
                break;

            default:
                throw new Zend_Application_Exception('Invalid configuration file provided; unknown config type');
        }

        return $config->toArray();
    }
}


text:
"""
Provides classes for the analysis of dynamical systems and time series based
on recurrence plots, including measures of recurrence quantification
analysis (RQA) and recurrence network analysis.
"""

# array object and fast numerics
import numpy as np

from .. import Network
from .joint_recurrence_plot import JointRecurrencePlot

#
#  Class definitions
#

class JointRecurrenceNetwork(JointRecurrencePlot, Network):

    """
    Class JointRecurrenceNetwork for generating and quantitatively analyzing
    joint recurrence networks.

    For a joint recurrence network, time series x and y need to have the same
    length! Formally, nodes are identified with sampling points in time, while
    an undirected link (i,j) is introduced if x at time i is recurrent to x at
    time j and also y at time i is recurrent to y at time j. Self-loops are
    excluded in this undirected network representation.

    More information on the theory and applications of joint recurrence
    networks can be found in [Feldhoff2013]_.

    **Examples:**

     - Create an instance of JointRecurrenceNetwork with a fixed recurrence
       threshold and without embedding::

           JointRecurrenceNetwork(x, y, threshold=(0.1,0.2))

     - Create an instance of JointRecurrenceNetwork with a fixed recurrence
       threshold in units of STD and without embedding::

           JointRecurrenceNetwork(x, y, threshold_std=(0.03,0.05))

     - Create an instance of JointRecurrenceNetwork at a fixed recurrence rate
       and using time delay embedding::

           JointRecurrenceNetwork(
               x, y, dim=(3,5), tau=(2,1),
               recurrence_rate=(0.05,0.04)).recurrence_rate()
    """

    #
    #  Internal methods
    #

    def __init__(self, x, y, metric=("supremum", "supremum"),
                 normalize=False, lag=0, silence_level=0, **kwds):
        """
        Initialize an instance of JointRecurrenceNetwork.

        .. note::
           For a joint recurrence network, time series x and y need to have the
           same length!

        Creates an embedding of the given time series x and y, calculates a
        joint recurrence plot from the embedding and then creates a Network
        object from the joint recurrence plot, interpreting the joint
        recurrence matrix as the adjacency matrix of an undirected complex
        network.

        Either recurrence thresholds ``threshold``/``threshold_std`` or
        recurrence rates ``recurrence_rate`` have to be given as keyword
        arguments.

        Embedding is only supported for scalar time series. If embedding
        dimension ``dim`` and delay ``tau`` are **both** given as keyword
        arguments, embedding is applied. Multidimensional time series are
        processed as is by default.

        :type x: 2D Numpy array (time, dimension)
        :arg x: The time series x to be analyzed, can be scalar or
            multi-dimensional.
        :type y: 2D Numpy array (time, dimension)
        :arg y: The time series y to be analyzed, can be scalar or
            multi-dimensional.
        :type metric: tuple of string
        :arg metric: The metric for measuring distances in phase space
            ("manhattan", "euclidean", "supremum").  Give separately for each
            time series.
        :type normalize: tuple of bool
        :arg normalize: Decide whether to normalize the time series to zero
            mean and unit standard deviation. Give separately for each time
            series.
        :arg number lag: To create a delayed version of the JRP.
        :arg number silence_level: Inverse level of verbosity of the object.
        :type threshold: tuple of number
        :keyword threshold: The recurrence threshold keyword for generating the
            recurrence plot using a fixed threshold.  Give separately for each
            time series.
        :type threshold_std: tuple of number
        :keyword threshold_std: The recurrence threshold keyword for generating
            the recurrence plot using a fixed threshold in units of the time
            series' STD. Give separately for each time series.
        :type recurrence_rate: tuple of number
        :keyword recurrence_rate: The recurrence rate keyword for generating
            the recurrence plot using a fixed recurrence rate. Give separately
            for each time series.
        :type dim: tuple of number
        :keyword dim: The embedding dimension. Give separately for each time
            series.
        :type tau: tuple of number
        :keyword tau: The embedding delay. Give separately for each time
            series.
        """
        #  Check for consistency
        if np.abs(lag) < x.shape[0]:
            if x.shape[0] == y.shape[0]:
                #  Initialize the underlying RecurrencePlot object
                JointRecurrencePlot.__init__(self, x, y, metric, normalize,
                                             lag, silence_level, **kwds)

                #  Set diagonal of JR to zero to avoid self-loops in the joint
                #  recurrence network
                A = self.JR - np.eye((self.N-np.abs(lag)), dtype="int8")

                #  Create a Network object interpreting the recurrence matrix
                #  as the graph adjacency matrix. Joint recurrence networks
                #  are undirected by definition.
                Network.__init__(self, A, directed=False,
                                 silence_level=silence_level)
            else:
                raise ValueError(
                    "Both time series x and y need to have the same length!")
        else:
            raise ValueError(
                "Delay value (lag) must not exceed length of time series!")

    def __str__(self):
        """
        Returns a string representation.
        """
        return 'JointRecurrenceNetwork:\n%s\n%s' % (
            JointRecurrencePlot.__str__(self), Network.__str__(self))

    def clear_cache(self):
        """
        Clean up memory by deleting information that can be recalculated from
        basic data.

        Extends the clean up methods of the parent classes.
        """
        #  Call clean up of RecurrencePlot
        JointRecurrencePlot.clear_cache(self)
        #  Call clean up of Network
        Network.clear_cache(self)

    #
    #  Methods to handle recurrence networks
    #
    def set_fixed_threshold(self, threshold):
        """
        Create a joint recurrence network at fixed thresholds.

        :type threshold: tuple of number
        :arg threshold: The threshold. Give for each time series separately.
        """
        #  Set fixed threshold on recurrence plot level
        JointRecurrencePlot.set_fixed_threshold(self, threshold)

        #  Set diagonal of JR to zero to avoid self-loops in the joint
        #  recurrence network
        A = self.JR.copy()
        A.flat[::self.N+1] = 0

        #  Create a Network object interpreting the recurrence matrix as the
        #  graph adjacency matrix. Joint recurrence networks are undirected by
        #  definition.
        Network.__init__(self, A, directed=False,
                         silence_level=self.silence_level)

    def set_fixed_threshold_std(self, threshold_std):
        """
        Create a joint recurrence network at fixed thresholds in units of the
        standard deviation of the time series.

        :type threshold_std: tuple of number
        :arg threshold_std: The threshold in units of standard deviation. Give
            for each time series separately.
        """
        #  Set fixed threshold on recurrence plot level
        JointRecurrencePlot.set_fixed_threshold_std(self, threshold_std)

        #  Set diagonal of JR to zero to avoid self-loops in the joint
        #  recurrence network
        A = self.JR.copy()
        A.flat[::self.N+1] = 0

        #  Create a Network object interpreting the recurrence matrix as the
        #  graph adjacency matrix. Joint recurrence networks are undirected by
        #  definition.
        Network.__init__(self, A, directed=False,
                         silence_level=self.silence_level)

    def set_fixed_recurrence_rate(self, density):
        """
        Create a joint recurrence network at fixed link densities (recurrence
        rates).

        :type density: tuple of number
        :arg density: The link density / recurrence rate. Give for each time
            series separately.
        """
        #  Set fixed recurrence rate on recurrence plot level
        JointRecurrencePlot.set_fixed_recurrence_rate(self, density)

        #  Set diagonal of JR to zero to avoid self-loops in the joint
        #  recurrence network
        A = self.JR.copy()
        A.flat[::self.N+1] = 0

        #  Create a Network object interpreting the recurrence matrix as the
        #  graph adjacency matrix. Joint recurrence networks are undirected by
        #  definition.
        Network.__init__(self, A, directed=False,
                         silence_level=self.silence_level)


text:
.. _utils:

Utilities
=========

These functions have been implemented to help users use the core Rambutan model. They consist mostly of data converters. For example, one can convert a FastA file to a one-hot encoded numpy array using the fasta_to_dense function, or calculation the insulation score of a predicted or real contact map using the insulation_score function.

API Reference
-------------

.. automodule:: rambutan.utils
	:members:
	:inherited-members:


text:
using Google.Api.Ads.Common.Util.Reports;
using Google.Api.Ads.Dfp.Lib;
using Google.Api.Ads.Dfp.v201502;
using Google.Api.Ads.Dfp.Util.v201502;

using System;

namespace Google.Api.Ads.Dfp.Examples.CSharp.v201502 {
  /// <summary>
  /// This code example runs a reach report. The report is saved to the specified file path.
  ///
  /// Tags: ReportService.runReportJob
  /// </summary>
  class RunReachReport : SampleBase {
    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example runs a reach report. The report is saved to the specified " +
            "file path.";
      }
    }

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      SampleBase codeExample = new RunReachReport();
      Console.WriteLine(codeExample.Description);
      codeExample.Run(new DfpUser());
    }

    /// <summary>
    /// Run the code example.
    /// </summary>
    /// <param name="user">The DFP user object running the code example.</param>
    public override void Run(DfpUser user) {
      ReportService reportService = (ReportService) user.GetService(
          DfpService.v201502.ReportService);

      // Set the file path where the report will be saved.
      String filePath = _T("INSERT_FILE_PATH_HERE");

      // Create report job.
      ReportJob reportJob = new ReportJob();

      // Create report query.
      ReportQuery reportQuery = new ReportQuery();
      reportQuery.dateRangeType = DateRangeType.REACH_LIFETIME;
      reportQuery.dimensions = new Dimension[] {Dimension.LINE_ITEM_ID, Dimension.LINE_ITEM_NAME};
      reportQuery.columns = new Column[] {Column.REACH_FREQUENCY, Column.REACH_AVERAGE_REVENUE,
          Column.REACH};
      reportJob.reportQuery = reportQuery;

      try {
        // Run report.
        reportJob = reportService.runReportJob(reportJob);

        ReportUtilities reportUtilities = new ReportUtilities(reportService, reportJob.id);

        // Set download options.
        ReportDownloadOptions options = new ReportDownloadOptions();
        options.exportFormat = ExportFormat.CSV_DUMP;
        options.useGzipCompression = true;
        reportUtilities.reportDownloadOptions = options;

        // Download the report.
        using (ReportResponse reportResponse = reportUtilities.GetResponse()) {
          reportResponse.Save(filePath);
        }
        Console.WriteLine("Report saved to \"{0}\".", filePath);

      } catch (Exception ex) {
        Console.WriteLine("Failed to run delivery report. Exception says \"{0}\"",
            ex.Message);
      }
    }
  }
}


text:
namespace YandexDnsAPI.Enums
{
    public static class ErrorStates
    {
        public static string Unknown = "unknown";
        public static string NoToken = "no_token";
        public static string NoDomain = "no_domain";
        public static string NoIp = "no_ip";
        public static string BadDomain = "bad_domain";
        public static string Prohibited = "prohibited";
        public static string BadToken = "bad_token";
        public static string BadLogin = "bad_login";
        public static string BadPassword = "bad_passwd";
        public static string NoAuth = "no_auth";
        public static string NotAllowed = "not_allowed";
        public static string Blocked = "blocked";
        public static string Occupied = "occupied";
        public static string DomainLimitReached = "domain_limit_reached";
        public static string NoReply = "no_reply";
    }
}


text:
<?php

/**
 * Created by PhpStorm.
 * User: ksv
 * Date: 22.12.16
 * Time: 16:04
 */

namespace CatalogOfPhpPatterns\ServiceLayer\Services;

use CatalogOfPhpPatterns\ServiceLayer\Interfaces\IConcreteRepository;

/**
 * Class ConcreteService
 * @package CatalogOfPhpPatterns\ServiceLayer\Services
 */
class ConcreteService extends GenericService
{
    /**
     * @var IConcreteRepository|null
     */
    protected $repository = null;

    /**
     * ConcreteService constructor
     * @param IConcreteRepository $repository
     */
    public function __construct(IConcreteRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * @return string
     */
    public function helloWorld()
    {
        return sprintf("%s, %s!", $this->repository->foo(), $this->repository->bar());
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <!-- Basics -->
    <groupId>something</groupId>
  <artifactId>maven-sortpom-sorter</artifactId>
        <?sortpom ignore?>
      <!-- \$1 $1 $1 \n  -->
        <?sortpom resume?>
    <version>1.0</version>
  <packaging>jar</packaging>
  <name>SortPom Sorter</name>
  <description>The sorting functionality</description>

  <dependencies>
    <dependency>
      <groupId>org.jdom</groupId>
      <artifactId>jdom</artifactId>
      <version>1.1.3</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
        <?sortpom ignore?>
      <version>4.11</version><!--$NO-MVN-MAN-VER$ -->
        <?sortpom resume?>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
        <?sortpom ignore?>
      <version>2.1</version><!--$NO-MVN-MAN-VER$ -->
        <?sortpom resume?>
    </dependency>

    <!-- Test dependencies -->
    <dependency>
      <groupId>com.google.code.reflection-utils</groupId>
      <artifactId>reflection-utils</artifactId>
      <version>0.0.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

</project>


text:
[![Build Status](https://travis-ci.org/ericmdev/essentials.dockerfile.svg?branch=master)](https://travis-ci.org/ericmdev/essentials.dockerfile)

**Dockerfile** of [Debian](https://www.debian.org/) essentials:

- nano

*Requirements*
- [Docker](https://www.docker.com/)

*Base Docker Image*
- [debian:jessie](https://hub.docker.com/_/debian/)

*Docker Pull Command*
- `docker pull ericmdev/essentials`

### Usage

Build the image.

    $ make

Run the interactive container.

    $ make run

*See the `Makefile` for more options.


text:
/
#if (defined(__NEWLIB__))
#define LIBSTUB_SYS_WRITE _swiwrite
#else // __REDLIB__
#define LIBSTUB_SYS_WRITE __write
#endif
int LIBSTUB_SYS_WRITE (int, char *, int);

/*
 * consoleprint() -  provides a "print string to console" function that uses
 * the CodeRed semihosting debug channel functionality. Because this can
 * send a full string in one operation, rather than a single character (as
 * using printf will) this will provide faster prints to the console.
 *
 * Input - pointer to zero-terminated character string
 * Returns 0 if successful
 *
 * Note that in order to consoleprint() to actually display to the console,
 * the semihosting interface using stdout must have been setup. The easiest
 * way to do this is to call printf() once at the start of your application
 */
int consoleprint(char *cpstring)
{
	 int slen, res;
	 // Calculate length of string
	 slen = strlen (cpstring);
	 // Call function to carry out semihosting "SYS_WRITE" operation
	 res = LIBSTUB_SYS_WRITE (0, cpstring,slen);	// Note that '0' represents stdout
	 return res;
}


text:
package jp.gr.java_conf.jyukon.detabu;

import android.content.Context;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

@Module(library = true)
public class RequestManagerModule {
    private Context mApplicationContext;

    public RequestManagerModule(DetabuApplication application) {
        this.mApplicationContext = application.getApplicationContext();
    }

    @Provides
    @Singleton
    RequestManager provideRequestManager() {
        return new RequestManager(mApplicationContext);
    }
}


text:
<?php

namespace osCommerce\OM\Core\Site\Website\SQL\Newsletter;

use osCommerce\OM\Core\Registry;

class SaveSubscription
{
    public static function execute(array $data): bool
    {
        $OSCOM_PDO = Registry::get('PDO');

        return $OSCOM_PDO->save('website_newsletters_subscribers', [
            'sub_key' => $data['key'],
            'list_id' => $data['list_id'],
            'email' => $data['email'],
            'name' => $data['name'],
            'optin_time' => $data['optin_time'],
            'optin_ip' => $data['optin_ip'],
            'confirm_ip' => $data['ip_address']
        ]) === 1;
    }
}


text:
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.zone_hvac_forced_air_units import ZoneHvacUnitVentilator

log = logging.getLogger(__name__)

class TestZoneHvacUnitVentilator(unittest.TestCase):

    def setUp(self):
        self.fd, self.path = tempfile.mkstemp()

    def tearDown(self):
        os.remove(self.path)

    def test_create_zonehvacunitventilator(self):

        pyidf.validation_level = ValidationLevel.error

        obj = ZoneHvacUnitVentilator()
        # alpha
        var_name = "Name"
        obj.name = var_name
        # object-list
        var_availability_schedule_name = "object-list|Availability Schedule Name"
        obj.availability_schedule_name = var_availability_schedule_name
        # real
        var_maximum_supply_air_flow_rate = 0.0001
        obj.maximum_supply_air_flow_rate = var_maximum_supply_air_flow_rate
        # alpha
        var_outdoor_air_control_type = "FixedAmount"
        obj.outdoor_air_control_type = var_outdoor_air_control_type
        # real
        var_minimum_outdoor_air_flow_rate = 0.0
        obj.minimum_outdoor_air_flow_rate = var_minimum_outdoor_air_flow_rate
        # object-list
        var_minimum_outdoor_air_schedule_name = "object-list|Minimum Outdoor Air Schedule Name"
        obj.minimum_outdoor_air_schedule_name = var_minimum_outdoor_air_schedule_name
        # real
        var_maximum_outdoor_air_flow_rate = 0.0
        obj.maximum_outdoor_air_flow_rate = var_maximum_outdoor_air_flow_rate
        # object-list
        var_maximum_outdoor_air_fraction_or_temperature_schedule_name = "object-list|Maximum Outdoor Air Fraction or Temperature Schedule Name"
        obj.maximum_outdoor_air_fraction_or_temperature_schedule_name = var_maximum_outdoor_air_fraction_or_temperature_schedule_name
        # node
        var_air_inlet_node_name = "node|Air Inlet Node Name"
        obj.air_inlet_node_name = var_air_inlet_node_name
        # node
        var_air_outlet_node_name = "node|Air Outlet Node Name"
        obj.air_outlet_node_name = var_air_outlet_node_name
        # node
        var_outdoor_air_node_name = "node|Outdoor Air Node Name"
        obj.outdoor_air_node_name = var_outdoor_air_node_name
        # node
        var_exhaust_air_node_name = "node|Exhaust Air Node Name"
        obj.exhaust_air_node_name = var_exhaust_air_node_name
        # node
        var_mixed_air_node_name = "node|Mixed Air Node Name"
        obj.mixed_air_node_name = var_mixed_air_node_name
        # alpha
        var_supply_air_fan_object_type = "Fan:OnOff"
        obj.supply_air_fan_object_type = var_supply_air_fan_object_type
        # object-list
        var_supply_air_fan_name = "object-list|Supply Air Fan Name"
        obj.supply_air_fan_name = var_supply_air_fan_name
        # alpha
        var_coil_option = "None"
        obj.coil_option = var_coil_option
        # object-list
        var_supply_air_fan_operating_mode_schedule_name = "object-list|Supply Air Fan Operating Mode Schedule Name"
        obj.supply_air_fan_operating_mode_schedule_name = var_supply_air_fan_operating_mode_schedule_name
        # alpha
        var_heating_coil_object_type = "Coil:Heating:Water"
        obj.heating_coil_object_type = var_heating_coil_object_type
        # object-list
        var_heating_coil_name = "object-list|Heating Coil Name"
        obj.heating_coil_name = var_heating_coil_name
        # real
        var_heating_convergence_tolerance = 0.0001
        obj.heating_convergence_tolerance = var_heating_convergence_tolerance
        # alpha
        var_cooling_coil_object_type = "Coil:Cooling:Water"
        obj.cooling_coil_object_type = var_cooling_coil_object_type
        # object-list
        var_cooling_coil_name = "object-list|Cooling Coil Name"
        obj.cooling_coil_name = var_cooling_coil_name
        # real
        var_cooling_convergence_tolerance = 0.0001
        obj.cooling_convergence_tolerance = var_cooling_convergence_tolerance
        # object-list
        var_availability_manager_list_name = "object-list|Availability Manager List Name"
        obj.availability_manager_list_name = var_availability_manager_list_name
        # object-list
        var_design_specification_zonehvac_sizing_object_name = "object-list|Design Specification ZoneHVAC Sizing Object Name"
        obj.design_specification_zonehvac_sizing_object_name = var_design_specification_zonehvac_sizing_object_name

        idf = IDF()
        idf.add(obj)
        idf.save(self.path, check=False)

        with open(self.path, mode='r') as f:
            for line in f:
                log.debug(line.strip())

        idf2 = IDF(self.path)
        self.assertEqual(idf2.zonehvacunitventilators[0].name, var_name)
        self.assertEqual(idf2.zonehvacunitventilators[0].availability_schedule_name, var_availability_schedule_name)
        self.assertAlmostEqual(idf2.zonehvacunitventilators[0].maximum_supply_air_flow_rate, var_maximum_supply_air_flow_rate)
        self.assertEqual(idf2.zonehvacunitventilators[0].outdoor_air_control_type, var_outdoor_air_control_type)
        self.assertAlmostEqual(idf2.zonehvacunitventilators[0].minimum_outdoor_air_flow_rate, var_minimum_outdoor_air_flow_rate)
        self.assertEqual(idf2.zonehvacunitventilators[0].minimum_outdoor_air_schedule_name, var_minimum_outdoor_air_schedule_name)
        self.assertAlmostEqual(idf2.zonehvacunitventilators[0].maximum_outdoor_air_flow_rate, var_maximum_outdoor_air_flow_rate)
        self.assertEqual(idf2.zonehvacunitventilators[0].maximum_outdoor_air_fraction_or_temperature_schedule_name, var_maximum_outdoor_air_fraction_or_temperature_schedule_name)
        self.assertEqual(idf2.zonehvacunitventilators[0].air_inlet_node_name, var_air_inlet_node_name)
        self.assertEqual(idf2.zonehvacunitventilators[0].air_outlet_node_name, var_air_outlet_node_name)
        self.assertEqual(idf2.zonehvacunitventilators[0].outdoor_air_node_name, var_outdoor_air_node_name)
        self.assertEqual(idf2.zonehvacunitventilators[0].exhaust_air_node_name, var_exhaust_air_node_name)
        self.assertEqual(idf2.zonehvacunitventilators[0].mixed_air_node_name, var_mixed_air_node_name)
        self.assertEqual(idf2.zonehvacunitventilators[0].supply_air_fan_object_type, var_supply_air_fan_object_type)
        self.assertEqual(idf2.zonehvacunitventilators[0].supply_air_fan_name, var_supply_air_fan_name)
        self.assertEqual(idf2.zonehvacunitventilators[0].coil_option, var_coil_option)
        self.assertEqual(idf2.zonehvacunitventilators[0].supply_air_fan_operating_mode_schedule_name, var_supply_air_fan_operating_mode_schedule_name)
        self.assertEqual(idf2.zonehvacunitventilators[0].heating_coil_object_type, var_heating_coil_object_type)
        self.assertEqual(idf2.zonehvacunitventilators[0].heating_coil_name, var_heating_coil_name)
        self.assertAlmostEqual(idf2.zonehvacunitventilators[0].heating_convergence_tolerance, var_heating_convergence_tolerance)
        self.assertEqual(idf2.zonehvacunitventilators[0].cooling_coil_object_type, var_cooling_coil_object_type)
        self.assertEqual(idf2.zonehvacunitventilators[0].cooling_coil_name, var_cooling_coil_name)
        self.assertAlmostEqual(idf2.zonehvacunitventilators[0].cooling_convergence_tolerance, var_cooling_convergence_tolerance)
        self.assertEqual(idf2.zonehvacunitventilators[0].availability_manager_list_name, var_availability_manager_list_name)
        self.assertEqual(idf2.zonehvacunitventilators[0].design_specification_zonehvac_sizing_object_name, var_design_specification_zonehvac_sizing_object_name)


text:
package com.sxt.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sxt.inter.dto.LocalUserDto;
import com.sxt.controller.AbstractGeneralController;
import com.sxt.util.SingleOnline;

public class LoginFilter extends AbstractGeneralController implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// 获得在下面代码中要用的request,response,session对象xx
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        HttpSession session = servletRequest.getSession();
        servletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
        LocalUserDto localUserDto = super.getLocalUser(servletRequest);
        if(localUserDto!=null){
        	String ip=super.getRemoteAddr(servletRequest);
        	if (!SingleOnline.isValidUser(localUserDto.getUid(), session.getId()+"-"+ip)) {
                session.invalidate();
                response.getWriter().write("<script language='javascript'>alert('您的账户已在其它地点登录!');location.href='../login.jsp'</script>");
            }else{
            	chain.doFilter(servletRequest, servletResponse);
            }
        }else{
        	chain.doFilter(servletRequest, servletResponse);
        }
    }

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}


text:
import cms.models.fields
import django.db.models.deletion
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ("cms", "0020_old_tree_cleanup"),
        ("djangocms_blog", "0037_auto_20190806_0743"),
    ]

    operations = [
        migrations.AddField(
            model_name="post",
            name="media",
            field=cms.models.fields.PlaceholderField(
                editable=False,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="media",
                slotname="media",
                to="cms.Placeholder",
            ),
        ),
    ]


text:
package com.alibaba.cobar.loader;

import org.junit.Test;

/**
 * @author xianmao.hexm 2011-1-21
 */
public class SchemaLoaderTest {

    @Test
    public void testSchemaLoader() {
        new SchemaLoader();
    }

}


text:
layout: post
title: "próba ataku na Moldoveanu"
date: 2013-09-24 19:00:00
category: wyjazdy
tags: [wakacje, autostop, rumunia, góry, moldoveanu]

description: "Chwilowo przerwę cykl o wakacyjnej wyprawie autostopowej i opiszę mój ostatni wyjazd w rumuńskie góry, który odbył się w dniach 16-22. września. Będąc dokładnym wyjazd odbył się w celu zdobycia najwyższego szczytu Rumunii, który miałem odwiedzić podczas wakacyjnej wyprawy. Chodzi oczywiście o szczyt Moldoveanu (2544 m n.p.m.) leżący w Górach Fogaraskich."
excerpt: "/assets/images/2013/35-gory.jpg"

---

{% include JB/setup %}

Chwilowo przerwę cykl o wakacyjnej wyprawie autostopowej i opiszę mój ostatni wyjazd w rumuńskie góry, który odbył się w dniach 16-22. września. Będąc dokładnym wyjazd odbył się w celu zdobycia najwyższego szczytu Rumunii, który miałem odwiedzić podczas [wakacyjnej wyprawy](/2013/08/12/dzienniki-z-wakacji-autostop-2013/). Chodzi oczywiście o szczyt Moldoveanu (2544 m n.p.m.) leżący w Górach Fogaraskich.

1) Dojazd z Warszawy w Góry.
----------------------------

Ze względów finansowych wyjazd miał kosztować jak najmniej. Zakupiliśmy bilet na polskiegobusa jakiś czas wcześniej, aby bardzo rano stawić się w Rzeszowie. Biorąc pod uwagę cenę biletu oraz poczęstunek na pokładzie koszta wyszły minimalne. Ponadto dosyć mocno ograniczał nas czas, więc musieliśmy część drogi odbyć nocą.

Z Rzeszowa udaliśmy się szynobusem do miejscowości Babica, który z kolei kosztował 2zł za osobę, a dostaliśmy się w bardzo dobre miejsce do łapania stopa. Stamtąd kurs do Miejsca Piastowego, z którego łapiemy coś do Barwinka, czyli do miejscowości granicznej. Kierowca podwozi nas na parking przy granicy.

Na miejscu niestety żadna ciężarówka na parkingu nie jedzie do Rumunii, ale po pół minuty stania z tabliczką na Rumunię zatrzymuje się polska ciężarówka, która podwozi nas na granicę Węgiersko-Rumuńską. Stamtąd znów z rodakiem trafiamy na tzw Express, czyli polski parking w Rumunii (jest nawet polska flaga!). Nocujemy w ciepłym pomieszczeniu ochrony i rano ruszamy do Sibiu.

Kierowca z Expressu do Sibiu bardzo nie lubi Rumunii. Dowiadujemy się, że na miejscu są sami Cyganie (i to bardzo źle!), każdy będzie chciał od nas paszport, aby wziąć łapówkę w celu jego oddania. Każdy autochton to oczywiście złodziej. Dodatkowo mamy obowiązkowo mieć ze sobą kije, a najlepiej broń, aby chronić się przed dzikimi psami i niedźwiedziami, które podobno są wszędzie. Prawdę mówiąc był to mój pierwszy tak negatywnie nastawiony kierowca (i pierwszy, który chciał, abyśmy za każdym razem opuścili kabinę jak on wychodził).

Kończy się trasa tranzytowa i przesiadamy się na autostop lokalny. Mamy sporą konkurencję w postaci autochtonów, ale po chwili łapiemy coś w naszą stronę, to znaczy do miejscowości Ucea de Jos. Tam łapiemy już na Victorię. Kierowca częstuje nas winogronami, chce z nami śpiewać lokalne pieśni i podwozi do centrum miasta. Zakupy i w drogę.

2) Wędrówka na szczyt.
----------------------

Z Victorii ruszamy szlakiem czerwonym trójkątnym. Po drodze spotykamy elektrownię słoneczną.

Uwaga! Z powodu pośpiechu w drodze w górę na podziwianiu okolicy skupiliśmy się schodząc, więc, chcąc zachować chronologię zdarzeń, zdjęcia z trasy są po opisie "szczytu" :)

Niestety dosyć późno zajechaliśmy do Victorii i nie zdążamy dotrzeć do pierwszego schroniska. Zaczyna padać. Warunki są koszmarne, ale udaje się zrobić szybko zupkę chińską na palniku gazowym. Czekamy. Niestety nie przestaje padać, a już chwilę temu zapadł zmrok więc pada decyzja o rozłożeniu namiotu. Warunki nie były dobre na namiot, co widać poniżej.

Komfort snu też nie był zbyt dobry. Z jednej strony skała, z drugiej przepaść, a lekko pochylony teren powoli zsuwa nas w stronę przepaści. Do tego zegarek ręczny wysiadł, więc zamiast o 7 ruszamy po 10. Moja towarzyszka na pytanie o to dlaczego o 4 według jej zegarka jest jasno odpowiada, że... w środku lasu są lampy. Zaspany wyobrażam sobie lampy przyczepione do drzew i idę dalej spać.

W końcu jak wstajemy ruszamy w kierunku szczytu. Za jakieś 40min dochodzimy do schroniska [Cabana Turnuri](http://www.turnuri.ro/), obok którego na kuchence robimy coś do jedzenia i ruszamy dalej. Wysoko robi się dosyć gęsta mgła i widoczne przed chwilą szczyty znikają w mleku.

Pod wieczór docieramy do schroniska [Cabana Podragu](http://www.podragu.ro/), w którym, z uwagi na niską temperaturę na zewnątrz (około 1C), płacimy za nocleg. W środu jest dosyć ciepło, to znaczy jakieś 10C.

Wszyscy straszyli, że obok schroniska jest ogromna kupa śmieci, ale jej nie znajdujemy. Zamiast tego odkrywamy znane wszystkim jeziorko. Zbliża się zmrok, więc chwilę wspinamy się po skałkach w okolicy schroniska i na noc wracamy do środka. Późny obiad i spać. Niestety moja komórka nie wytrzymała warunków i padła. Ładowanie nic nie pomaga, stan baterii zerowy.

3) Nieudane zdobycie szczytu.
-----------------------------

Jaka jest pogoda na Moldoveanu każdy wie. Zazwyczaj jest dosyć słaba i nie ma opcji wejścia na szczyt. Pani ze schroniska mówiła, że może następnego dnia będzie lepiej, ale o poranku zweryfikowała swoje plany i zaprosiła nas za rok. No trudno, można było się tego spodziewać.

4) Powrót do Victorii i Polski.
-------------------------------

W związku z warunkami pogodowymi wracamy tym samym szlakiem do Victorii. Po drodze zauważmy pomnik wspinacza, któremu chyba nie udało się przeżyć tego podejścia.

Szlak ogólnie wygląda jakby inaczej niż w drugą stronę. Często są kamieniste lub gliniaste podejścia, na których podczas deszczu można ładnie polatać. Oznaczenia szlaków ogólnie są dobre. Podczas trasy są tylko 2 bardzo dobre miejsca na namiot - między Victorią a pierwszym schroniskiem oraz przy schronisku Podragu.

Na drodze znajduje się także tajemnicza jaskinia, na której ścianie widać nawet oznaczenie naszego szlaku. Wchodzimy kawałek do środka, ale jaskinia ciągnie się dosyć daleko i rezygnujemy z wchodzenia za dalsze zakręty. W środku jest dużo nietoperzy.

Po drodze znajduje się także ogromna ilość malowniczych mostków. Data powstania niestety jest nieznana.

Z Victorii łapiemy stopa na drogę krajową. Tam udaje się złapać tureckiego tira, który upewnia się czy jesteśmy małżeństwem, daje nam jabłko i zawozi do ronda, z którego łapiemy dalej.

Na rondzie trafiamy na polaka, który podwozi nas na kolejny słynny parking, to znaczy Okrąglaka. Na nim na cb-radiu znajdujemy kolejnego kierowcę, który właśnie wyjechał. Aktualny kierowca mimo końca czasu pracy podwozi nas kawałek do kolejnego szofera, przesiadamy się i jedziemy prosto do Polski! Po drodze mamy małe problemy (kończy się benzyna, a nie ma gdzie zatankować i zapłacić w euro), ale cudem udaje się uzupełnić bak i jechać dalej. Tym transportem docieramy już do Barwinka.

Z Barwinka łapiemy transport do Miejsca Piastowego, a następnie do Rzeszowa, z którego stopem dojeżdżamy do Krakowa.

5) Kraków!
----------

Kraków upłynął pod znakiem odwiedzania znajomych. Zostawiliśmy rzeczy w przechowalni bagażu i cali brudni bez prysznica od 5 dni ruszyliśmy na zwiedzanie miasta. Niestety nie raz w Krakowie już byłem, więc zwiedzanie ograniczamy do szlajania się po mieście bez żadnych planów.

Na koniec dnia ruszamy do Agi, którą poznałem w Gruzji na autostopowej wyprawie. Gadka szmatka, oglądanie fotek z wyjazdów, czas na normalny prysznic! Następnego dnia rano jedziemy do Zakrzówka, odstawiamy moją towarzyszkę do autobusu, który zawiezie ją na stację kolejową. Ja zostaję jeszcze w Krakowie.

Po krótkim spacerku zmieniam miejsce zamieszkania i odwiedzam Przemka, któremu dosyć długo obiecywałem odwiedziny. Wieczorem jeszcze udaję się z Agą na ściankę wspinaczkową (polecam!) i następnego dnia rano chcę jechać stopem do Warszawy, ale cudem znajduję kasę akurat na bilet studencki i jadę interregio. Miałem (ja oraz moje stopy) dość łażenia i ucieszyłem się w sumie z pociągowej trasy.

6) Wskazówki.
-------------

Zawsze czytając relacje z gór szukam ciekawych wskazówek. Oto i one:

* Bardzo polecam podejście właśnie z Victorii. Idąc drogą biegnącą obok torów prosto trafiamy na tabliczkę prowadzącą do szlaku.
* Należy uważać jeśli chodzi o czasówki.
* Jeśli chcemy nocować między Victorią a Podragu to jest do tego dostosowany las na początku (po prostu trzeba odbić), potem jest jedna polanka, a za nią nocleg w namiocie możliwy jest dopiero przy podragu. Możemy także nocować w pierwszym schronisku i schronie (za pierwszym schroniskiem!).
* Pamiętajcie o ciepłym ubraniu. Na dole wydaje się ciepło, ale przy Podragu normą jest 0-5 stopni Celcjusza.
* Szlaki wbrew pozorom są w miarę dobrze oznakowane (przynajmniej ten, na którym byliśmy).

7) Podsumowanie.
----------------

Wyjazd ogólnie uważam za udany. Nie udało się wejść na szczyt, ale tego można było się spodziewać. Dużo ludzi było na miejscu, więc nie tylko my liczyliśmy na dobre warunki. Udało się jednak zdobyć coś powyżej 2000 m n.p.m., więc mój cel jest zrealizowany. Za rok czas na 3000 m n.p.m.! :)

foto: [flickr](http://www.flickr.com/photos/peterulrich/9438097698/in/photolist-fo1HCo-fo1Na5-fnLcSi-fnLb8g-fo1uF1-fnLiMv-fo1QSL-fo1ARY-fo1HSE-fo1DZ9-fnLoiF-fo1DMf-fo1C6N-fo1tdh-fo1wv3-fo1MvN-fnLAXV-fo1Hp9-fo1QAW-fnLsBX-fnLzkH-fo1SoU-fnLhx4-fo1QqU-fo1sAC-fnLuj6-fnLBcK-fnLxkX-fo1sod-fnLfvV-fo1Ra9-fo1vgj-fnLe86-fo1M4C-fnLnWz-fnLocD-fnLi4k-fo1LkJ-fnLvx6-fo1CPb-fnLwoR-fo1zVw-fnLoSB-fnLdC6-fo1v7q-fo1zDE-fo1wiN-fo1AxJ-fo1FrU-fo1yBA-fnLrgF/) (header), własne (reszta)


text:
from kinko.nodes import Tuple, Symbol, List, String
from kinko.sugar import InterpolateString, TranslateDots, TransformError
from kinko.errors import Errors

from .base import NODE_EQ_PATCHER
from .test_parser import parse, parse_raw

def interpolate(node):
    return InterpolateString().visit(node)

def translate(node, errors):
    return TranslateDots(errors).visit(node)

def check_eq(first, second):
    with NODE_EQ_PATCHER:
        assert first == second

def check_location(src, node, fragment):
    a, b = node.location.start.offset, node.location.end.offset
    assert src[a:b] == fragment

def check_error(src, msg, fragment):
    errors = Errors()
    try:
        translate(parse_raw(src), errors),
    except TransformError:
        error, = errors.list
        assert error.message.startswith(msg)
        start = error.location.start.offset
        end = error.location.end.offset
        assert src[start:end] == fragment
    else:
        raise AssertionError('Error not raised')

def test_interpolate():
    src = 'foo "before {a} {b.c} after"'
    node = interpolate(parse_raw(src))
    check_eq(
        node,
        List([Tuple([
            Symbol('foo'),
            Tuple([Symbol('join'), List([
                String('before '),
                Symbol('a'),
                String(' '),
                Symbol('b.c'),
                String(' after'),
            ])]),
        ])]),
    )
    items = node.values[0].values[1].values[1].values
    check_location(src, items[0], '"before ')
    check_location(src, items[1], 'a')
    check_location(src, items[2], ' ')
    check_location(src, items[3], 'b.c')
    check_location(src, items[4], ' after"')

def test_interpolate_first():
    src = 'foo "{a} after"'
    node = interpolate(parse_raw(src))
    check_eq(
        node,
        List([Tuple([
            Symbol('foo'),
            Tuple([Symbol('join'), List([
                Symbol('a'),
                String(' after'),
            ])]),
        ])]),
    )
    items = node.values[0].values[1].values[1].values
    check_location(src, items[0], 'a')
    check_location(src, items[1], ' after"')

def test_interpolate_last():
    src = 'foo "before {a}"'
    node = interpolate(parse_raw(src))
    check_eq(
        node,
        List([Tuple([
            Symbol('foo'),
            Tuple([Symbol('join'), List([
                String('before '),
                Symbol('a'),
            ])]),
        ])]),
    )
    items = node.values[0].values[1].values[1].values
    check_location(src, items[0], '"before ')
    check_location(src, items[1], 'a')

def test_interpolate_var_only():
    src = 'foo "{a}"'
    node = interpolate(parse_raw(src))
    check_eq(
        node,
        List([Tuple([
            Symbol('foo'),
            Symbol('a'),
        ])]),
    )
    check_location(src, node.values[0].values[1], 'a')

def test_interpolate_string_only():
    src = 'foo "text"'
    node = interpolate(parse_raw(src))
    check_eq(
        node,
        List([Tuple([
            Symbol('foo'),
            String('text'),
        ])]),
    )
    check_location(src, node.values[0].values[1], '"text"')

def test_interpolate_empty_string():
    src = 'foo ""'
    node = interpolate(parse_raw(src))
    check_eq(
        node,
        List([Tuple([
            Symbol('foo'),
            String(''),
        ])]),
    )
    check_location(src, node.values[0].values[1], '""')

def test_interpolate_invalid():
    check_eq(
        interpolate(parse_raw('foo "before {.a} {b.} {a..b} {.} '
                              '{..} after"')),
        List([Tuple([
            Symbol('foo'),
            String('before {.a} {b.} {a..b} {.} {..} after'),
        ])]),
    )
    check_eq(
        interpolate(parse_raw('foo "before {.a} {b.} {c} {a..b} '
                              '{.} {..} after"')),
        List([Tuple([
            Symbol('foo'),
            Tuple([Symbol('join'), List([
                String('before {.a} {b.} '),
                Symbol('c'),
                String(' {a..b} {.} {..} after'),
            ])]),
        ])]),
    )

def test_parser_interpolate():
    node = parse("""
    foo
      "bar {value} baz"
    """)
    check_eq(
        node,
        List([
            Tuple([
                Symbol('foo'),
                Tuple([Symbol('join'), List([
                    String('bar '),
                    Symbol('value'),
                    String(' baz'),
                ])]),
            ]),
        ]),
    )

def test_translate_dots_invalid():
    check_error('foo\n  bar.baz', 'Symbol in this position',
                'bar.baz')


text:
module Helpers
  def create_routes
    destination = File.join(destination_root, 'config')

    FileUtils.mkdir_p(destination)
    FileUtils.touch File.join(destination, 'routes.rb')
  end

  def create_app(options = {})
    Rails.application = nil

    Class.new(Rails::Application).tap do |app|
      config = app.config.assets
      assets = app.assets
      config.paths = []

      assets.cache = ActiveSupport::Cache.lookup_store(:null_store)
      config.compress = options[:compress]
      config.debug    = options[:debug]
      config.paths << fixture_root
      config.paths << File.expand_path('javascripts')
      yield(app) if block_given?

      app.config.eager_load = false
      app.config.active_support.deprecation = :log
      app.initialize!
    end
  end

  def fixture_root
    File.expand_path('../../stylesheets', __FILE__)
  end

  def images_root
    File.expand_path('../../images', __FILE__)
  end

  def output_root
    File.expand_path('../../cases', __FILE__)
  end

  def fixture(name)
    source = fixture_path(name)
    output = css_path(name)
    [source, output].map do |path|
      File.read(path) if File.file?(path)
    end
  end

  def css_path(name)
    File.join(output_root, "#{name}.css")
  end

  def fixture_path(name)
    File.join(fixture_root, "#{name}.styl")
  end

  def dependencies_on(asset)
    context = env.context_class.new(env, asset.logical_path, asset.pathname)
    context.evaluate(asset.pathname)
    context._dependency_paths
  end
end


text:
using UnityEngine;
using System.Collections;

namespace VGDC.GameManagement {

	/// <summary>
	/// All playable game modes.
	/// </summary>
	public enum GameModeType {
		ProtectTheQueen
	}

}


text:
import {
  moduleFor,
  test
} from 'ember-qunit';

moduleFor('controller:anime/quotes', 'AnimeQuotesController', {
  // Specify the other units that are required for this test.
  needs: ['controller:current-user']
});

// Replace this with your real tests.
test('it exists', function() {
  var controller = this.subject();
  ok(controller);
});


text:
<?php

 // This file is not an action, but a common file loaded by every action of this module

define('LABEL_SIZE', 2);
define('INPUT_SIZE', 8);