text:
class Performance < ActiveRecord::Base
  # Attributes that are accessible to everyone (needed for signup)
  attr_accessible :contest_category_id, :pieces_attributes, :appearances_attributes

  amoeba do
    enable # Allow deep duplication
  end

  belongs_to  :contest_category
  belongs_to  :predecessor,   class_name: "Performance", inverse_of: :successor,
                              include: { contest_category: { contest: :host } }
  belongs_to  :stage_venue,   class_name: "Venue"
  has_one     :successor,     class_name: "Performance", foreign_key: "predecessor_id",
                              inverse_of: :predecessor, dependent: :nullify
  has_many    :appearances,   inverse_of: :performance, dependent: :destroy
  has_many    :participants,  through: :appearances
  has_many    :pieces,        inverse_of: :performance, dependent: :destroy

  delegate :contest, to: :contest_category
  delegate :category, to: :contest_category

  accepts_nested_attributes_for :pieces,      allow_destroy: true
  accepts_nested_attributes_for :appearances, allow_destroy: true

  validates :contest_category_id, presence: true

  validate :contest_and_venue_hosts_match

  validate :require_one_appearance
  validate :require_one_piece

  validate :check_role_combinations

  validate :stage_time_in_contest_days
  validate :stage_field_values_complete

  before_create :add_unique_tracing_code
  before_save :update_age_group

  # Returns stage time in contest time zone
  def stage_time_in_tz
    if self.stage_time.nil?
      nil
    else
      self.stage_time.in_time_zone(self.contest.host.time_zone)
    end
  end

  # Returns all performances in current round and year
  def self.current
    self.in_contest(Contest.current)
  end

  # Returns all performances in contests that are currently open (for signup/edits)
  def self.in_open_contest
    self.in_contest(Contest.open)
  end

  # Returns all performances in given contest
  def self.in_contest(contest_id)
    joins(:contest_category)
    .select("performances.*, contest_categories.contest_id")
    .where(contest_categories: { contest_id: contest_id })
  end

  # Returns all performances that advanced from given contest(s)
  def self.advanced_from_contest(contest_ids)
    joins("INNER JOIN performances AS predecessors ON predecessors.id = performances.predecessor_id")
    .joins("INNER JOIN contest_categories AS predecessor_ccs ON predecessor_ccs.id = predecessors.contest_category_id")
    .where("predecessor_ccs.contest_id IN (?)", contest_ids)
  end

  # Returns all performances in given category
  def self.in_category(category_id)
    joins(:contest_category)
    .where(contest_categories: { category_id: category_id })
  end

  # Returns all performances in given contest category
  def self.in_contest_category(contest_category_id)
    where(contest_category_id: contest_category_id)
  end

  # Returns all performances in given age group
  def self.in_age_group(age_group)
    where(age_group: age_group)
  end

  # Returns all performances in given genre
  def self.in_genre(genre)
    joins(contest_category: :category)
    .where(categories: { genre: genre })
  end

  # Returns all classical performances
  def self.classical
    self.in_genre('classical')
  end

  # Returns all Kimu performances
  def self.kimu
    self.in_genre('kimu')
  end

  # Returns all popular performances
  def self.popular
    self.in_genre('popular')
  end

  # Returns all performances on a given date, or unschedule if not date given
  def self.on_date(date)
    if date.nil?
      where(stage_time: nil)
    else
      if date.class == String
        # Convert to Date object first
        date = Date.new(*date.split('-').map(&:to_i))
      end
      where(stage_time: date...(date + 1.day))
    end
  end

  # Returns all performances whose stage venue is the given venue
  def self.at_stage_venue(venue_id)
    where(stage_venue_id: venue_id)
  end

  # Returns all performances whose stage venue is empty or the given venue
  def self.venueless_or_at_stage_venue(venue_id)
    where("performances.stage_venue_id IS NULL OR performances.stage_venue_id = ?", venue_id)
  end

  # Orders performances chronologically by stage date
  def self.stage_order
    order("performances.stage_time").browsing_order
  end

  # Orders performances by category, then age group (smallest first)
  def self.browsing_order
    includes(contest_category: :category)
    .order('categories.genre, categories.solo DESC, categories.name, performances.age_group')
  end

  # Return the host the performance is associated with
  def associated_host
    case self.contest.round
    when 1
      self.contest.host
    when 2
      if self.predecessor
        self.predecessor.contest.host
      end
    end
  end

  # Return the country the performance is associated with
  def associated_country_code
    self.associated_host.try(:country_code)
  end

  # Return participant of performance that has a soloist role
  def soloist
    self.appearances.select { |a| a.solo? }.first
  end

  # Return all participants of performance that have an accompanist role
  def accompanists
    self.appearances.with_role('accompanist').map(&:participant)
  end

  # Return all ensemble appearances of performance
  def ensemble_appearances
    self.appearances.with_role('ensemblist')
  end

  def duration
    if self.pieces.empty?
      0 # Pretty short show
    else
      # Sum durations (in seconds) of all pieces together
      self.pieces.map(&:duration).inject { |sum, d| sum + d }
    end
  end

  def rounded_duration
    # Round up in five-minute steps (5, 10, 15, ...)
    (self.duration.to_f / 300).ceil * 300
  end

  def rounded_end_time
    # Time the performance is scheduled to end (using rounded duration)
    self.stage_time + self.rounded_duration.seconds
  end

  # Return whether the performance as a whole can migrate to next round
  def advances_to_next_round?
    # Don't advance if category's maximum round is reached
    if self.contest.round >= self.category.max_round
      return false
    end

    # Prevent from advancing if the age group is not officially allowed in this category
    age_group_index = JUMU_AGE_GROUPS.index(self.age_group)
    return false if age_group_index < JUMU_AGE_GROUPS.index(self.category.official_min_age_group)
    return false if age_group_index > JUMU_AGE_GROUPS.index(self.category.official_max_age_group)

    if self.soloist
      # Soloist determines
      self.soloist.may_advance_to_next_round?
    else
      # Use some ensemblist
      self.ensemble_appearances.any? { |a| a.may_advance_to_next_round? }
    end
  end

  private

    def add_unique_tracing_code
      begin
        # Generate a random 5-digit code, avoiding leading zero
        code = rand(10000..99999).to_s
      end while Performance.where(tracing_code: code).exists?

      self.tracing_code = code
    end

    def update_age_group
      self.appearances.each do |appearance|
        if appearance.solo? || appearance.ensemble?
          # Use age group of soloist or first ensemblist
          self.age_group = appearance.age_group
          return
        end
      end
      # Else empty the age group
      self.age_group = nil
    end

    def contest_and_venue_hosts_match
      if !stage_venue.nil? and contest.host != stage_venue.host
        errors.add(:base, :contest_and_venue_hosts_must_match)
      end
    end

    def require_one_appearance
      errors.add(:base, :needs_one_appearance) if appearances_empty?
    end

    def require_one_piece
      errors.add(:base, :needs_one_piece) if pieces_empty?
    end

    def check_role_combinations
      if !appearances_empty? # Do nil check and ignore appearances marked for destruction
        # Check if there are many soloists
        if appearances.select { |a| a.solo? }.size > 1
          errors.add(:base, :cannot_have_many_soloists)
        end

        # Check if all participants are accompanists
        if appearances.all? {|a| a.accompaniment? }
          errors.add(:base, :cannot_have_mere_accompanists)
        end

        # Check if there is a lonely ensemblist
        if appearances.size == 1 && appearances.all? {|a| a.ensemble? }
          errors.add(:base, :cannot_have_single_ensemblist)
        end

        # Check if there are both soloists and ensemblists
        has_soloists = appearances.select {|a| a.solo? }.size > 0
        has_ensemblists = appearances.select {|a| a.ensemble? }.size > 0
        if has_soloists && has_ensemblists
          errors.add(:base, :cannot_have_soloists_and_ensemblists)
        end
      end
    end

    def stage_time_in_contest_days
      # TODO: Take time zone into account for contest.begins and contest.ends
      if stage_time && (stage_time < contest.begins || stage_time > contest.ends + 1.day)
        errors.add(:base, :cannot_have_stage_time_outside_contest_days)
      end
    end

    def stage_field_values_complete
      if stage_time && !stage_venue_id || !stage_time && stage_venue_id
        errors.add(:base, :cannot_have_incomplete_stage_field_values)
      end
    end

    def appearances_empty?
      appearances.empty? || appearances.all? { |appearance| appearance.marked_for_destruction? }
    end

    def pieces_empty?
      pieces.empty? || pieces.all? { |piece| piece.marked_for_destruction? }
    end
end


text:
Magneto
=======
Magneto is a system using which people with physical disabilities will be able to control a computer with arm movements and voice commands. This sort of gives the power of Magneto (from Xmen), hence the name!

See [this](http://lifepluslinux.blogspot.in/2015/02/gyroscope-accelerometer-geomagnetometer.html) for more details.

[![Magneto Mouse control](http://img.youtube.com/vi/KwDT-jdFseQ/0.jpg)](http://www.youtube.com/watch?v=KwDT-jdFseQ)
[![Magneto Voice control](http://img.youtube.com/vi/bbGgnCgv9rE/0.jpg)](http://www.youtube.com/watch?v=bbGgnCgv9rE)

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.imagepipeline.nativecode;

import static com.facebook.soloader.nativeloader.NativeLoaderDelegate.SKIP_MERGED_JNI_ONLOAD;

import android.os.Build;
import com.facebook.infer.annotation.Nullsafe;
import com.facebook.soloader.nativeloader.NativeLoader;

/** Single place responsible for ensuring that native-imagetranscoder.so is loaded */
@Nullsafe(Nullsafe.Mode.STRICT)
public class NativeJpegTranscoderSoLoader {
  private static boolean sInitialized;

  public static synchronized void ensure() {
    if (!sInitialized) {
      // On Android 4.1.2 the loading of the native-imagetranscoder native library can fail because
      // of the dependency with fb_jpegturbo. In this case we have to explicitely load that
      // library
      if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
        try {
          NativeLoader.loadLibrary("fb_jpegturbo", SKIP_MERGED_JNI_ONLOAD);
        } catch (UnsatisfiedLinkError error) {
          // Head in the sand
        }
      }
      NativeLoader.loadLibrary("native-imagetranscoder");
      sInitialized = true;
    }
  }
}


text:
#ifndef __FACTORYSET_H
#define __FACTORYSET_H

#define MAX_STRING_LENGTH	32

struct factorysetcontainer {
	uchar mac[6];
	int usb_vendor_id;
	int usb_product_id;
	int pxm50;
#if defined(CONFIG_VIDEO)
	unsigned char disp_name[MAX_STRING_LENGTH];
#endif
	unsigned char serial[MAX_STRING_LENGTH];
	int version;
};

int factoryset_read_eeprom(int i2c_addr);
int factoryset_setenv(void);
extern struct factorysetcontainer factory_dat;

#endif /* __FACTORYSET_H */


text:
package com.k_beta.android.app.internal.di.modules;

import com.k_beta.android.app.data.net.RestApi;
import com.k_beta.android.app.internal.di.scope.ApiScope;
import dagger.Module;
import dagger.Provides;
import retrofit2.Retrofit;

import javax.inject.Singleton;

/**
 * Created by Denis Kholevinsky
 */

@Module
public class ApiModule {

    @Provides
    @Singleton
    RestApi provideCommonApiService(Retrofit retrofit) {
        return retrofit.create(RestApi.class);
    }

}


text:
<!doctype html>

  <meta charset="UTF-8">
  <title>Example - example-example.csp-production</title>

    <button ng-click="ctrl.inc()" id="inc">Increment</button>

      {{ctrl.counter}}

    <button ng-click="ctrl.evil()" id="evil">Evil</button>

      {{ctrl.evilError}}


text:
class TagsController < ApplicationController
  load_and_authorize_resource :course
  load_and_authorize_resource :tag, through: :course

  before_filter :load_general_course_data, only: [:new, :edit, :create, :show, :index]

  def new
  end

  def create
    expire_fragment("course/#{@course.id}/tags")
    respond_to do |format|
      if @tag.save
        format.html { redirect_to course_tags_path(@course),
                      notice: "The tag '#{@tag.name}' has been created." }
      else
        format.html { render action: "new" }
      end
    end
  end

  def edit
    @tag_groups = @course.tag_groups
  end

  def update
    expire_fragment("course/#{@course.id}/tags")
    respond_to do |format|
      if @tag.update_attributes(params[:tag])
        format.html { redirect_to course_tags_path(@course),
                      notice: "The tag '#{@tag.name}' has been updated." }
      else
        format.html { render action: "edit" }
      end
    end
  end

  def show
    @questions =  @course.questions.tagged_with(@tag, any: true)
    @missions = @questions.assessments.accessible_by(current_ability).mission
    @trainings = @questions.assessments.accessible_by(current_ability).training
  end

  def index
    @tag_groups = @course.tag_groups.includes(:tags)
    #always put uncategorized last
    uc = @course.tag_groups.uncategorized
    @tag_groups -= [uc]
    @tag_groups << uc

    respond_to do |format|
      format.json { render json: @tags.map {|t| {id: t.id, name: t.name }}}
      format.html
    end
  end

  def destroy
    expire_fragment("course/#{@course.id}/tags")
    @tag.destroy
    respond_to do |format|
      format.html { redirect_to course_tags_url(@course),
                    notice: "The tag '#{@tag.name}' has been removed." }
    end
  end
end


text:
/*
 * This file was automatically generated by sel-utils and
 * released under the MIT License.
 *
 * License: https://github.com/sel-project/sel-utils/blob/master/LICENSE
 * Repository: https://github.com/sel-project/sel-utils
 * Generated from https://github.com/sel-project/sel-utils/blob/master/xml/protocol/bedrock141.xml
 */
package sul.protocol.bedrock141.play;

import sul.utils.*;

public class GuiDataPickItem extends Packet {

	public static final int ID = (int)54;

	public static final boolean CLIENTBOUND = false;
	public static final boolean SERVERBOUND = true;

	@Override
	public int getId() {
		return ID;
	}

	public int slot;

	public GuiDataPickItem() {}

	public GuiDataPickItem(int slot) {
		this.slot = slot;
	}

	@Override
	public int length() {
		return 5;
	}

	@Override
	public byte[] encode() {
		this._buffer = new byte[this.length()];
		this.writeVaruint(ID);
		this.writeLittleEndianInt(slot);
		return this.getBuffer();
	}

	@Override
	public void decode(byte[] buffer) {
		this._buffer = buffer;
		this.readVaruint();
		slot=readLittleEndianInt();
	}

	public static GuiDataPickItem fromBuffer(byte[] buffer) {
		GuiDataPickItem ret = new GuiDataPickItem();
		ret.decode(buffer);
		return ret;
	}

	@Override
	public String toString() {
		return "GuiDataPickItem(slot: " + this.slot + ")";
	}

}


text:
package com.all.client.view.format;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

import com.all.i18n.DefaultMessages;
import com.all.i18n.Internationalizable;
import com.all.i18n.Messages;

public class TimeFeedFormatter implements Internationalizable {

	private static final String EMPTY_STRING = "";
	private static final int UNIT_CONVERSION_TIME = 60;
	private static final int DAY_UNIT_CONVERSION_TIME = 60 * 60 * 24;
	private static final int WEEK_UNIT_CONVERSION_TIME = 60 * 60 * 24 * 7;
	private static NumberFormat timeFormatter = NumberFormat.getInstance();
	private static String SEC_LABEL;
	private static String ABOUT_A_MINUTE_LABEL;
	private static String MINUTES_LABEL;
	private static String HOURS_LABEL;
	private static String FEW_HOURS_LABEL;
	private static String DAY_OF_THIS_WEEK_LABEL;
	private static String YESTERDAY_LABEL;
	private Messages messages;
	private Calendar calendar;
	private static final TimeZone TIME_ZONE = TimeZone.getTimeZone("UTC");

	static {
		timeFormatter.setMaximumFractionDigits(1);
	}

	public String getTimeFormatString(Date feedDate, Date serverDate) {
		Date local;
		if (serverDate == null) {
			local = GregorianCalendar.getInstance(TIME_ZONE).getTime();
		} else {
			local = serverDate;
		}
		long diff = (local.getTime() - feedDate.getTime()) / 1000;
		if (diff < DAY_UNIT_CONVERSION_TIME) {
			return getFormat(diff);
		}
		if (diff < getYesterdayTime(feedDate, local)) {
			return YESTERDAY_LABEL;
		} else if (diff < WEEK_UNIT_CONVERSION_TIME) {
			return getDaysWithinAWeek(feedDate);
		} else {
			return getDateAfterAWeek(feedDate);
		}
	}

	private String getDateAfterAWeek(Date feedDate) {
		SimpleDateFormat simpleDateFormat = null;
		calendar = Calendar.getInstance();
		calendar.setTime(feedDate);
		int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
		switch (dayOfMonth) {
		case 1:
			simpleDateFormat = messages.getFormatter("format.date.feed.1");
			break;
		case 2:
			simpleDateFormat = messages.getFormatter("format.date.feed.2");
			break;
		case 3:
			simpleDateFormat = messages.getFormatter("format.date.feed.3");
			break;
		default:
			simpleDateFormat = messages.getFormatter("format.date.feed");
			break;
		}
		return simpleDateFormat.format(feedDate);
	}

	public String getFormat(long sec) {
		if (sec < UNIT_CONVERSION_TIME) {
			return timeFormatter.format(sec) + SEC_LABEL;
		}
		if (sec < UNIT_CONVERSION_TIME * 2) {
			return ABOUT_A_MINUTE_LABEL;
		}
		long minutes = sec / 60;
		if (minutes < UNIT_CONVERSION_TIME) {
			return timeFormatter.format(minutes) + MINUTES_LABEL;
		}
		long hours = minutes / 60;
		if (hours < 2) {
			return HOURS_LABEL;
		} else if (hours < 24) {
			return timeFormatter.format(hours) + FEW_HOURS_LABEL;
		}
		return EMPTY_STRING;
	}

	private String getDaysWithinAWeek(Date feedDate) {
		SimpleDateFormat simpleDateFormat = messages.getFormatter("format.date.weekDay");
		if (((DefaultMessages) messages).getLocale().equals(Locale.US)) {
			return DAY_OF_THIS_WEEK_LABEL + " " + simpleDateFormat.format(feedDate);
		}
		return simpleDateFormat.format(feedDate) + " " + DAY_OF_THIS_WEEK_LABEL;
	}

	@Override
	public void internationalize(Messages messages) {
		this.messages = messages;
		SEC_LABEL = " " + messages.getMessage("feed.timer.secs");
		ABOUT_A_MINUTE_LABEL = " " + messages.getMessage("feed.timer.aboutMinute");
		MINUTES_LABEL = " " + messages.getMessage("feed.timer.minutes");
		HOURS_LABEL = " " + messages.getMessage("feed.timer.hours");
		FEW_HOURS_LABEL = " " + messages.getMessage("feed.timer.fewHours");
		YESTERDAY_LABEL = " " + messages.getMessage("feed.timer.yesterday");
		DAY_OF_THIS_WEEK_LABEL = " " + messages.getMessage("feed.timer.thisWeek");
	}

	@Override
	public void removeMessages(Messages messages) {
		messages.remove(this);
	}

	@Override
	public void setMessages(Messages messages) {
		messages.add(this);
	}

	private long getYesterdayTime(Date feedDate, Date local) {
		int hours = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
		int minutes = Calendar.getInstance().get(Calendar.MINUTE);
		int seconds = Calendar.getInstance().get(Calendar.SECOND);
		Date yesterdayDate = new Date();
		long newTime = (yesterdayDate.getTime()) - (DAY_UNIT_CONVERSION_TIME * 1000) - (hours * 60 * 60 * 1000)
				- (minutes * 60 * 1000) - (seconds * 1000);
		yesterdayDate.setTime(newTime);
		return (local.getTime() - yesterdayDate.getTime()) / 1000;
	}
}


text:
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
module Main
  ( main
  ) where

import Dhall

data E2
  = E2
    { u :: Vector Natural
    , t :: Vector Text
    } deriving (Generic, Show)

data Example
  = Example
    { one :: Natural
    , str :: Text
    , nest :: E2
    } deriving (Generic, Show)

instance Interpret E2
instance Interpret Example

main :: IO ()
main = do
  x <- input auto "./confspec.dhall"
  print (x :: Example)


text:
package de.omnikryptec.old.d2;

import java.util.ArrayList;

public class Quadtree {

    private int MAX_OBJECTS = 10;

    private int level;
    private ArrayList<Rectangle> objects;
    private Rectangle bounds;
    private Quadtree[] nodes;
    private Quadtree parent;

    /*
     * Constructor
     */
    public Quadtree(int pLevel, Rectangle pBounds, Quadtree... pnodes) {
	level = pLevel;
	objects = new ArrayList<>();
	bounds = pBounds;
	nodes = pnodes;
    }

    public int getlevel() {
	return level;
    }

    @Override
    public String toString() {
	return "QT: " + bounds.toString();
    }

    public Quadtree(int plevel, Rectangle bo) {
	this(plevel, bo, new Quadtree[4]);
    }

    /*
     * Clears the quadtree
     */
    public void clear() {
	objects.clear();
	if (parent != null) {
	    Quadtree tmp = parent;
	    parent = null;
	    tmp.clear();
	}
	for (int i = 0; i < nodes.length; i++) {
	    if (nodes[i] != null) {
		nodes[i].clear();
		nodes[i] = null;
	    }
	}
    }

    /*
     * Splits the node into 4 subnodes
     */
    private void split() {
	float subWidth = (bounds.getWidth() / 2);
	float subHeight = (bounds.getHeight() / 2);
	float x = bounds.minX;
	float y = bounds.minY;
	if (nodes[0] == null) {
	    nodes[0] = new Quadtree(level + 1, new Rectangle(x + subWidth, y, subWidth, subHeight)).setParent(this);
	}
	if (nodes[1] == null) {
	    nodes[1] = new Quadtree(level + 1, new Rectangle(x, y, subWidth, subHeight)).setParent(this);
	}
	if (nodes[2] == null) {
	    nodes[2] = new Quadtree(level + 1, new Rectangle(x, y + subHeight, subWidth, subHeight)).setParent(this);
	}
	if (nodes[3] == null) {
	    nodes[3] = new Quadtree(level + 1, new Rectangle(x + subWidth, y + subHeight, subWidth, subHeight))
		    .setParent(this);
	}
    }

    private void parentize(int newindex) {
	float width = bounds.getWidth() * 2;
	float height = bounds.getHeight() * 2;
	Quadtree[] array = new Quadtree[4];
	array[newindex] = this;
	Rectangle parentbounds = new Rectangle(0, 0, width, height);
	switch (newindex) {
	case 0:
	    parentbounds.minX = bounds.minX - bounds.getWidth();
	    parentbounds.minY = bounds.minY - bounds.getHeight();
	    break;
	case 1:
	    parentbounds.minX = bounds.minX;
	    parentbounds.minY = bounds.minY - bounds.getHeight();
	    break;
	case 2:
	    parentbounds.minX = bounds.minX;
	    parentbounds.minY = bounds.minY;
	    break;
	case 3:
	    parentbounds.minX = bounds.minX - bounds.getWidth();
	    parentbounds.minY = bounds.minY;
	    break;
	}
	parentbounds.setWidth(width).setHeight(height);
	setParent(new Quadtree(level - 1, parentbounds, array));
    }

    private Quadtree setParent(Quadtree tree) {
	this.parent = tree;
	return this;
    }

    /*
     * Determine which node the object belongs to. -1 means object cannot completely
     * fit within a child node and is part of the parent node
     */
    private int getIndex(Rectangle pRect) {
	int index = -1;
	double verticalMidpoint = bounds.minX + (bounds.getWidth() / 2);
	double horizontalMidpoint = bounds.minY + (bounds.getHeight() / 2);

	// Object can completely fit within the top quadrants
	boolean topQuadrant = (pRect.minY < horizontalMidpoint && pRect.minY + pRect.getHeight() < horizontalMidpoint);
	// Object can completely fit within the bottom quadrants
	boolean bottomQuadrant = (pRect.minY > horizontalMidpoint);

	// Object can completely fit within the left quadrants
	if (pRect.minX < verticalMidpoint && pRect.minX + pRect.getWidth() < verticalMidpoint) {
	    if (topQuadrant) {
		index = 1;
	    } else if (bottomQuadrant) {
		index = 2;
	    }
	}
	// Object can completely fit within the right quadrants
	else if (pRect.minX > verticalMidpoint) {
	    if (topQuadrant) {
		index = 0;
	    } else if (bottomQuadrant) {
		index = 3;
	    }
	}

	return index;
    }

    private boolean outOfBounds(Rectangle rect) {
	return rect.maxX > bounds.maxX || rect.maxY > bounds.maxY || rect.minX < bounds.minX || rect.minY < bounds.minY;
    }

    private int getIn(Rectangle r) {
	boolean bottomInd = r.maxY > bounds.maxY;
	boolean rightInd = r.minX < bounds.minX;
	int index = 0;
	if (bottomInd) {
	    if (rightInd) {
		index = 3;
	    } else {
		index = 2;
	    }
	} else {
	    if (rightInd) {
		index = 0;
	    } else {
		index = 1;
	    }
	}
	return index;
    }

    /*
     * Insert the object into the quadtree. If the node exceeds the capacity, it
     * will split and add all objects to their corresponding nodes.
     */
    public void insert(Rectangle pRect) {
	if (outOfBounds(pRect)) {
	    if (parent == null) {
		parentize(getIn(pRect));
	    } else {
		parent.insert(pRect);
	    }
	    return;
	}
	if (nodes[0] != null) {
	    int index = getIndex(pRect);

	    if (index >= 0 && nodes[index] != null) {
		nodes[index].insert(pRect);

		return;
	    }
	}

	objects.add(pRect);

	if (objects.size() > MAX_OBJECTS) {
	    split();
	    int i = 0;
	    while (i < objects.size()) {
		int index = getIndex(objects.get(i));
		if (index >= 0) {
		    nodes[index].insert(objects.remove(i));
		} else {
		    i++;
		}
	    }
	}
    }

    /*
     * Return all objects that could collide with the given object
     */
    public ArrayList<Rectangle> retrieve(ArrayList<Rectangle> returnObjects, Rectangle pRect) {
	int index = getIndex(pRect);
	if (index >= 0 && nodes[index] != null) {
	    nodes[index].retrieve(returnObjects, pRect);
	}
	returnObjects.addAll(objects);
	return returnObjects;
    }
}


text:
import * as eta from "eta-lib";

import * as express from "express";

export class Model implements eta.Model {
    public render(req: express.Request, res: express.Response, callback: (env: { [key: string]: any }) => void): void {
        if (!eta.params.test(req.body, ["userid"])) {
            callback({ errcode: eta.http.InvalidParameters });
            return;
        }
        let sql: string = `
            SELECT
                CONCAT(AuthorPerson.firstName, ' ', AuthorPerson.lastName) AS author,
                Log.timestamp,
                Log.message,
                Log.type
            FROM
                Log
                    LEFT JOIN Person AuthorPerson ON
                        Log.author = AuthorPerson.id
            WHERE
                Log.about = ?
            ORDER BY Log.timestamp`;
        eta.db.query(sql, [req.body.userid], (err: eta.DBError, rows: any[]) => {
            if (err) {
                eta.logger.dbError(err);
                callback({ errcode: eta.http.InternalError });
                return;
            }
            callback({
                "raw": JSON.stringify(rows)
            });
        });
    }
}


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

<link rel="icon" type="image/x-icon" href="favicon.ico" />
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>chigraph: Class Index</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

chigraph
    master

Systems programming language written for beginners in LLVM

Class Index

c | d | f | g | h | l | m | n | r | s

  c

  f

  h

  n

  s

ChiModule (chi)   	Flags (chi)   	hash< boost::filesystem::path > (std)   	NamedDataType (chi)   	Result::ScopedContext (chi)

Context (chi)   	FunctionCompiler (chi)   	hash< boost::uuids::uuid > (std)   	NodeCompiler (chi)   	Subprocess (chi)

  d

  g

  l

	NodeInstance (chi)

NodeType (chi)

DataType (chi)   	GraphFunction (chi)   	LangModule (chi)

  r

Debugger (chi)   	GraphModule (chi)

  m

DefaultModuleCache (chi)   	GraphStruct (chi)   	Result (chi)

		ModuleCache (chi)

c | d | f | g | h | l | m | n | r | s

Generated on Sat Sep 16 2017 17:41:35 for chigraph by

     1.8.13


text:
#include "mmtt.h"
#include "mmtt_depth.h"
#include "mmtt_kinect.h"

DepthCamera* DepthCamera::makeDepthCamera(MmttServer* s, std::string camtype) {
	return new KinectDepthCamera(s);
}


text:
import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'star-rating',
  templateUrl: './star-rating.component.html',
  styleUrls: ['./star-rating.component.css']
})
export class StarRatingComponent implements OnInit {
  @Input() rating: number;
  ratingAux: number;
  @Output() ratingChanged: EventEmitter<number> = new EventEmitter<number>();

  constructor() { }

  setRating() {
    this.ratingChanged.emit(this.ratingAux);
  }

  ngOnInit() {
    this.ratingAux = this.rating;
  }

}


text:
<?php

namespace yii\db\cubrid;

use yii\db\ColumnSchemaBuilder as AbstractColumnSchemaBuilder;

/**
 * ColumnSchemaBuilder is the schema builder for Cubrid databases.
 *
 * @author Chris Harris <chris@buckshotsoftware.com>
 * @since 2.0.8
 */
class ColumnSchemaBuilder extends AbstractColumnSchemaBuilder
{
    /**
     * @inheritdoc
     */
    protected function buildUnsignedString()
    {
        return $this->isUnsigned ? ' UNSIGNED' : '';
    }

    /**
     * @inheritdoc
     */
    protected function buildAfterString()
    {
        return $this->after !== null ?
            ' AFTER ' . $this->db->quoteColumnName($this->after) :
            '';
    }

    /**
     * @inheritdoc
     */
    protected function buildFirstString()
    {
        return $this->isFirst ? ' FIRST' : '';
    }

    /**
     * @inheritdoc
     */
    protected function buildCommentString()
    {
        return $this->comment !== null ? ' COMMENT ' . $this->db->quoteValue($this->comment) : '';
    }

    /**
     * @inheritdoc
     */
    public function __toString()
    {
        switch ($this->getTypeCategory()) {
            case self::CATEGORY_PK:
                $format = '{type}{check}{comment}{append}{pos}';
                break;
            case self::CATEGORY_NUMERIC:
                $format = '{type}{length}{unsigned}{notnull}{unique}{default}{check}{comment}{append}{pos}';
                break;
            default:
                $format = '{type}{length}{notnull}{unique}{default}{check}{comment}{append}{pos}';
        }
        return $this->buildCompleteString($format);
    }
}


text:
require 'sax-machine'
require 'ce-greenbutton/elements/gb_interval_block'
require 'ce-greenbutton/elements/gb_usage_point'
require 'ce-greenbutton/elements/gb_local_time_parameters'
require 'ce-greenbutton/elements/gb_reading_type'

module GreenButton
  module Parser
    # a sax-machine mapping for the Content structure
    #
    # For example:
    #   content = GbContent.parse(open(content.xml))
    #
    #
    # Author: ahmed.seddiq
    # Version: 1.0
    class GbContent
      include SAXMachine

      # Elements with "espi" namespace
      element :'espi:UsagePoint', class: GbUsagePoint, as: :usage_point
      element :'espi:IntervalBlock', class: GbIntervalBlock, as: :interval_block
      element :'espi:LocalTimeParameters', class: GbLocalTimeParameters, as: :local_time_parameters
      element :'espi:ReadingType', class: GbReadingType, as: :reading_type

      # Elements without namespace
      element :UsagePoint, class: GbUsagePoint, as: :usage_point
      element :IntervalBlock, class: GbIntervalBlock, as: :interval_block
      element :LocalTimeParameters, class: GbLocalTimeParameters, as: :local_time_parameters
      element :ReadingType, class: GbReadingType, as: :reading_type

    end
  end
end


text:
describe("chorus.views.DatasetShowContentHeader", function() {
    beforeEach(function() {
        this.model = backboneFixtures.dataset({
            tags: [
                {name: "alpha"}
            ],
            associatedWorkspaces: [backboneFixtures.workspaceJson(), backboneFixtures.workspaceJson(), backboneFixtures.workspaceJson()],
            tableauWorkbooks: [backboneFixtures.tableauWorkbook().attributes, backboneFixtures.tableauWorkbook().attributes, backboneFixtures.tableauWorkbook().attributes]
        });
        this.model.loaded = false;
        delete this.model.statusCode;
        this.model.fetch();
        this.view = new chorus.views.DatasetShowContentHeader({
            model: this.model,
            workspaceId: 123
        });
        this.qtipSpy = stubQtip();

        this.view.render();
    });

    describe('when the dataset is not loaded', function() {
        it('does not render', function() {
            expect(this.view.$('img.icon')).not.toExist();
        });
    });

    describe('when the dataset fetch completes', function() {
        beforeEach(function(){
            this.server.completeFetchFor(this.model);
        });

        it('renders the header', function() {
            expect(this.view.$('img.icon')).toExist();
        });

        it("renders the list of tags", function() {
            expect(this.view.$('.text-tags')).toContainText("alpha");
        });

        it("has a workspace id for the tagbox", function() {
            expect(this.view.tagBox.options.workspaceIdForTagLink).toBe(123);
        });

        describe("tableau publishing details", function() {
            it("is in the custom header", function() {
                expect(this.view.$('.published_to')).toExist();
            });

            it("qtip-ifies the other_menu", function() {
                this.view.$('.published_to .open_other_menu').click();
                expect(this.qtipSpy).toHaveVisibleQtip();
                expect(this.qtipSpy.find('li').length).toBe(2);
            });

            context("when the dataset has not been published to tableau", function() {
                beforeEach(function() {
                    delete this.view.model._tableauWorkbooks;
                    this.view.model.unset("tableauWorkbooks");
                });

                it("renders successfully, without the tableau workbook section", function() {
                    this.view.render();
                    expect(this.view.$('.published_to')).not.toExist();
                });
            });
        });

        describe("workspace usage", function() {
            it("is in the custom header", function() {
                expect(this.view.$('.found_in')).toExist();
            });

            it("qtip-ifies the other_menu", function() {
                this.view.$('.found_in .open_other_menu').click();
                expect(this.qtipSpy).toHaveVisibleQtip();
                expect(this.qtipSpy.find('li').length).toBe(2);
            });

            context("when the tabular data is not used in any workspace", function() {
                beforeEach(function() {
                    delete this.view.model._workspaceAssociated;
                    this.view.model.unset("associatedWorkspaces");
                });

                it("renders successfully, without the workspace usage section", function() {
                    this.view.render();
                    expect(this.view.$('.found_in')).not.toExist();
                });
            });
        });
    });
});


text:
/**
 * @file Functions related to performances ratios computation.
 * @author Roman Rubsamen <roman.rubsamen@gmail.com>
 */

/**
* @function gainToPainRatio
*
* @summary Compute the gain to pain ratio of a portfolio.
*
* @description This function returns the gain to pain ratio of a portfolio, provided as an
* equity curve.
*
* The the gain to pain ratio is defined as the sum of all returns divided by the absolute value of the sum of all losses, c.f. the reference.
*
* From the reference, a gain to pain ratio above 1.0 is very good, and a gain to pain ratio above 1.5 is excellent.
*
* @see Hedge Fund Market Wizards: How Winning Traders Win, Jack D. Schwager, Wiley, 2012
*
* @param {Array.<number>} portfolioEquityCurve the portfolio equity curve, an array of real numbers.
* @return {number} the gain to pain ratio of the portfolio.
*
* @example
* gainToPainRatio([1, 2, 1]);
* // 1.0
*
* @example
* gainToPainRatio([1, 1.1, 1.4]);
* // NaN
*/
self.gainToPainRatio = function(portfolioEquityCurve) {
	// Compute the arithmetic returns of the portfolio
	var returns = self.arithmeticReturns(portfolioEquityCurve).slice(1); // First value is NaN

	// If there is no usable returns, exit
	if (returns.length == 0) {
		return NaN;
	}

	// Else, compute the gain to pain ratio as the the sum of the returns divided by
	// the sum of the absolute values of the negative returns, c.f. the reference.
	var numerator = mean_(returns);
	var denominator = lpm_(returns, 1, 0.0);

	// Return the gain to pain ratio
	if (denominator == 0.0) {
		return NaN; // The gain to pain ratio is undefined in case there is no negative returns
	}
	else {
		return numerator/denominator;
	}
}


text:
package org.bowlerframework.model

/**
 * Marker interface for beans to tell RequestMappers a bean that is allowable for creation on GET and DELETE
 * even when it is not found in a Transformer lookup
 */

trait Transient


text:
            <button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" class="navbar-toggle collapsed" type="button">
                Toggle navigation

            </button>
            Memento

Articles

                    Administration

Gestion des tags

Connexion

Déconnexion


text:
package org.apache.hadoop.hdfs.server.blockmanagement;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;

import java.util.Set;

/**
 * An implementation of @see BlockPlacementStatus for
 * @see BlockPlacementPolicyWithUpgradeDomain
 */
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class BlockPlacementStatusWithUpgradeDomain implements
    BlockPlacementStatus {

  private final BlockPlacementStatus parentBlockPlacementStatus;
  private final Set<String> upgradeDomains;
  private final int numberOfReplicas;
  private final int upgradeDomainFactor;

  /**
   * @param parentBlockPlacementStatus the parent class' status
   * @param upgradeDomains the set of upgrade domains of the replicas
   * @param numberOfReplicas the number of replicas of the block
   * @param upgradeDomainFactor the configured upgrade domain factor
   */
  public BlockPlacementStatusWithUpgradeDomain(
      BlockPlacementStatus parentBlockPlacementStatus,
      Set<String> upgradeDomains, int numberOfReplicas,
      int upgradeDomainFactor){
    this.parentBlockPlacementStatus = parentBlockPlacementStatus;
    this.upgradeDomains = upgradeDomains;
    this.numberOfReplicas = numberOfReplicas;
    this.upgradeDomainFactor = upgradeDomainFactor;
  }

  @Override
  public boolean isPlacementPolicySatisfied() {
    return parentBlockPlacementStatus.isPlacementPolicySatisfied() &&
        isUpgradeDomainPolicySatisfied();
  }

  private boolean isUpgradeDomainPolicySatisfied() {
    if (numberOfReplicas <= upgradeDomainFactor) {
      return (numberOfReplicas <= upgradeDomains.size());
    } else {
      return upgradeDomains.size() >= upgradeDomainFactor;
    }
  }

  @Override
  public String getErrorDescription() {
    if (isPlacementPolicySatisfied()) {
      return null;
    }
    StringBuilder errorDescription = new StringBuilder();
    if (!parentBlockPlacementStatus.isPlacementPolicySatisfied()) {
      errorDescription.append(parentBlockPlacementStatus.getErrorDescription());
    }
    if (!isUpgradeDomainPolicySatisfied()) {
      if (errorDescription.length() != 0) {
        errorDescription.append(" ");
      }
      errorDescription.append("The block has " + numberOfReplicas +
          " replicas. But it only has " + upgradeDomains.size() +
              " upgrade domains " + upgradeDomains +".");
    }
    return errorDescription.toString();
  }

  @Override
  public int getAdditionalReplicasRequired() {
    if (isPlacementPolicySatisfied()) {
      return 0;
    } else {
      // It is possible for a block to have the correct number of upgrade
      // domains, but only a single rack, or be on multiple racks, but only in
      // one upgrade domain.
      int parent = parentBlockPlacementStatus.getAdditionalReplicasRequired();
      int child;

      if (numberOfReplicas <= upgradeDomainFactor) {
        child = numberOfReplicas - upgradeDomains.size();
      } else {
        child = upgradeDomainFactor - upgradeDomains.size();
      }
      return Math.max(parent, child);
    }
  }
}


text:
namespace tensorflow {

REGISTER_OP("PointsToOctree")
    .Input("in_points: string")
    .Attr("depth: int=6")
    .Attr("full_depth: int=2")
    .Attr("node_dis: bool=False")
    .Attr("node_feature: bool=False")
    .Attr("split_label: bool=False")
    .Attr("adaptive: bool=False")
    .Attr("adp_depth: int=4")
    .Attr("th_normal: float=0.1")
    .Attr("th_distance: float=2.0")
    .Attr("extrapolate: bool=False")
    .Attr("save_pts: bool=False")
    .Attr("key2xyz: bool=False")
    .Output("out_octree: string")
    .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {
      c->set_output(0, c->input(0));
      return Status::OK();
    })
    .Doc(R"doc(Points To Octree operator.)doc");

class PointsToOctreeOp : public OpKernel {
 public:
  explicit PointsToOctreeOp(OpKernelConstruction* context) :
    OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr("depth", &depth_));
    OP_REQUIRES_OK(context, context->GetAttr("full_depth", &full_depth_));
    OP_REQUIRES_OK(context, context->GetAttr("node_dis", &node_dis_));
    OP_REQUIRES_OK(context, context->GetAttr("node_feature", &node_feature_));
    OP_REQUIRES_OK(context, context->GetAttr("split_label", &split_label_));
    OP_REQUIRES_OK(context, context->GetAttr("adaptive", &adaptive_));
    OP_REQUIRES_OK(context, context->GetAttr("adp_depth", &adp_depth_));
    OP_REQUIRES_OK(context, context->GetAttr("th_distance", &th_distance_));
    OP_REQUIRES_OK(context, context->GetAttr("th_normal", &th_normal_));
    OP_REQUIRES_OK(context, context->GetAttr("extrapolate", &extrapolate_));
    OP_REQUIRES_OK(context, context->GetAttr("save_pts", &save_pts_));
    OP_REQUIRES_OK(context, context->GetAttr("key2xyz", &key2xyz_));
  }

  void Compute(OpKernelContext* context) override {
    const Tensor& data_in = context->input(0);
    CHECK_EQ(data_in.NumElements(), 1);

    // init the points
    Points point_cloud_;
    point_cloud_.set(data_in.flat<string>()(0).data());

    // check the points
    string msg;
    bool succ = point_cloud_.info().check_format(msg);
    CHECK(succ) << msg;

    // init the octree info
    OctreeInfo octree_info_;
    octree_info_.initialize(depth_, full_depth_, node_dis_,
      node_feature_, split_label_, adaptive_, adp_depth_,
      th_distance_, th_normal_, key2xyz_, extrapolate_,
      save_pts_, point_cloud_);

    // build the octree
    Octree octree_;
    octree_.build(octree_info_, point_cloud_);
    const vector<char>& octree_buf = octree_.buffer();

    // output
    Tensor* out_data = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(0, data_in.shape(), &out_data));
    string& out_str = out_data->flat<string>()(0);
    out_str.assign(octree_buf.begin(), octree_buf.end());
  }

 private:
  int depth_;
  int full_depth_;
  bool node_dis_;
  bool node_feature_;
  bool split_label_;
  bool adaptive_;
  int adp_depth_;
  float th_distance_;
  float th_normal_;
  bool extrapolate_;
  bool save_pts_;
  bool key2xyz_;
};

REGISTER_KERNEL_BUILDER(Name("PointsToOctree").Device(DEVICE_CPU), PointsToOctreeOp);
}  // namespace tensorflow


text:
module Hive.WebSocketServer.Message where

import Mitchell.Prelude

import Hive.Action
import Hive.Game

import Data.Aeson

data InMessage
  = InMessageAction Action
  | InMessageUnknown ByteString

instance FromJSON InMessage where
  parseJSON = withObject "object" (\o ->
    o .: "type" >>=
      withText "text" (\case
        "action" -> map InMessageAction (o .: "action")))

data OutMessage
  = OutMessageGameState GameState

instance ToJSON OutMessage where
  toJSON = \case
    OutMessageGameState state ->
      object
        [ "type"       .= String "game_state"
        , "game_state" .= toJSON state
        ]


text:
CREATE TABLE "user_balances" (
 "id" UUID PRIMARY KEY NOT NULL,
 "user_id" UUID NOT NULL,
 "user_api_key_id" UUID NOT NULL,
 "exchange_name" text NOT NULL,
 "currency" text NOT NULL,
 "currency_long" text NOT NULL,
 "blockchain_address" text,
 "available" decimal NOT NULL default 0,
 "exchange_total" decimal NOT NULL default 0,
 "exchange_available" decimal NOT NULL default 0,
 "pending_deposit" decimal,
 "created_on" TIMESTAMP DEFAULT now(),
 "updated_on" TIMESTAMP default current_timestamp
);

ALTER TABLE "user_balances" ADD CONSTRAINT "user_balance_fk"
  FOREIGN KEY("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "user_balances" ADD CONSTRAINT "user_balance_api_key_fk"
  FOREIGN KEY("user_api_key_id") REFERENCES "user_api_keys"("id") ON DELETE CASCADE ON UPDATE CASCADE;


text:
namespace swift {

/// A single requirement placed on the type parameters (or associated
/// types thereof) of a
class Requirement
    : public RequirementBase<Type,
                             llvm::PointerIntPair<Type, 3, RequirementKind>,
                             LayoutConstraint> {
public:
  /// Create a conformance or same-type requirement.
  Requirement(RequirementKind kind, Type first, Type second)
      : RequirementBase(kind, first, second) {}

  /// Create a layout constraint requirement.
  Requirement(RequirementKind kind, Type first, LayoutConstraint second)
    : RequirementBase(kind, first, second) {}

  /// Whether this requirement's types contain ErrorTypes.
  bool hasError() const;

  /// Whether this requirement is written with canonical types.
  bool isCanonical() const;

  /// Canonicalize the types in this requirement.
  Requirement getCanonical() const;

  /// Subst the types involved in this requirement.
  ///
  /// The \c args arguments are passed through to Type::subst.
  template <typename ...Args>
  Requirement subst(Args &&...args) const {
    auto newFirst = getFirstType().subst(std::forward<Args>(args)...);
    switch (getKind()) {
    case RequirementKind::SameShape:
    case RequirementKind::Conformance:
    case RequirementKind::Superclass:
    case RequirementKind::SameType: {
      auto newSecond = getSecondType().subst(std::forward<Args>(args)...);
      return Requirement(getKind(), newFirst, newSecond);
    }
    case RequirementKind::Layout:
      return Requirement(getKind(), newFirst, getLayoutConstraint());
    }

    llvm_unreachable("Unhandled RequirementKind in switch.");
  }

  ProtocolDecl *getProtocolDecl() const;

  /// Determines if this substituted requirement is satisfied.
  ///
  /// \param conditionalRequirements An out parameter initialized to an
  /// array of requirements that the caller must check to ensure this
  /// requirement is completely satisfied.
  bool isSatisfied(ArrayRef<Requirement> &conditionalRequirements,
                   bool allowMissing = false) const;

  /// Determines if this substituted requirement can ever be satisfied,
  /// possibly with additional substitutions.
  ///
  /// For example, if 'T' is unconstrained, then a superclass requirement
  /// 'T : C' can be satisfied; however, if 'T' already has an unrelated
  /// superclass requirement, 'T : C' cannot be satisfied.
  bool canBeSatisfied() const;

  /// Linear order on requirements in a generic signature.
  int compare(const Requirement &other) const;

  SWIFT_DEBUG_DUMP;
  void dump(raw_ostream &out) const;
  void print(raw_ostream &os, const PrintOptions &opts) const;
  void print(ASTPrinter &printer, const PrintOptions &opts) const;
};

inline void simple_display(llvm::raw_ostream &out, const Requirement &req) {
  req.print(out, PrintOptions());
}

/// A requirement as written in source, together with a source location. See
/// ProtocolDecl::getStructuralRequirements().
struct StructuralRequirement {
  /// The actual requirement, where the types were resolved with the
  /// 'Structural' type resolution stage.
  Requirement req;

  /// The source location where the requirement is written, used for redundancy
  /// and conflict diagnostics.
  SourceLoc loc;

  /// A flag indicating whether the requirement was inferred from the
  /// application of a type constructor. Also used for diagnostics, because
  /// an inferred requirement made redundant by an explicit requirement is not
  /// diagnosed as redundant, since we want to give users the option of
  /// spelling out these requirements explicitly.
  bool inferred = false;
};

} // end namespace swift

#endif


text:
import { Utility } from './utility';

// import { freemem } from 'os';

/**
 * Create socket.io server listening on provided port on localhost.
 * The server will separate the extension to one and preview clients to another room
 * and will distribute all commands comming from one room to another.
 * @param {Number} port
*/
function startSocketServer(projectDirectory, port) {
    // create express app
    var app = require('express')();
    // pass app to node.js server
    var http = require('http').Server(app);
    // pass server to socket.io
    var io = require('socket.io')(http);
    // must enable cors
    var cors = require('cors');
    // TODO: allow access only from localhost
    // var corsOptions = {
    //     origin: 'http://localhost:*'
    // };
    // io.set('origins', 'http://localhost:* localhost:*');
    // app.use(cors(corsOptions));
    app.use(cors());

    var debugMode = false;

    console.log("starting socket server...");
    io.on('connection', function(socket){
        console.log("connection...");
        // console.log(socket);

        // distribute sockets to rooms
        socket.on('ext-room', function(debug) {
            socket.join('extension');
            debugMode = debug;
            console.log("extension room join: debug = " + debug);
            if(debugMode) {
                app.get('/', function(req, res){
                    projectDirectory = projectDirectory.replace('\\', '/');
                    res.sendFile(projectDirectory + '/vxproj/js/socket-debugger.html');
                });
                io.to('logroom').emit('chat message', 'extension room joined');
            }
        });
        socket.on('preview-room', function(room) {
            socket.join('preview');
            if(debugMode) {
                io.to('logroom').emit('chat message', 'preview room joined');
            }
        });

        socket.on('ext-send-command', function(command) {
            io.to('preview').emit('preview-receive-command', command);
            if(debugMode) {
                io.to('logroom').emit('chat message', 'extension sending command ' + command + ' to preview');
            }
        });

        socket.on('preview-send-command', function(command) {
            io.to('extension').emit('ext-receive-command', command);
            if(debugMode) {
                io.to('logroom').emit('chat message', 'preview sending command ' + command + ' to extension');
            }
        });

        if(debugMode) {
            socket.on('logroom', function(msg) {
                socket.join('logroom');
                io.emit('chat message', 'logroom created!');
            })
        }
    });

    var promise = Utility.getAvailablePortPromiseAsync(port);
    promise.then(function(availablePort) {
        http.listen(availablePort);
        console.log("socket listening on: " + availablePort);
    }).catch(function(error) {
        console.log("socket-server catch promise: " + error);
    });
    return promise;
}
// export the method to enable code completion when imported in .ts
exports.startSocketServer = startSocketServer;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta name="generator" content="AWStats 6.7 (build 1.892) from config file awstats.2818332.conf (http://awstats.sourceforge.net)">
<meta name="robots" content="noindex,nofollow">
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<meta http-equiv="description" content="Awstats - Advanced Web Statistics for 0340a95.netsolhost.com (2014-05)">
<title>Statistics for 0340a95.netsolhost.com (2014-05)</title>

<form name="FormDateFilter" action="/cgi-bin/awstats.pl?config=2818332.1405&configdir=/data/22/2/81/47/2570699/meta/2818332/config&output=keyphrases" style="padding: 0px 0px 0px 0px; margin-top: 0">

Statistics for: 	0340a95.netsolhost.com

Last Update: 	01 Jun 2014 - 01:46

Reported period:	Month May 2014

</form>

Close window

Keyphrases used on search engines

54 different keyphrases	Search	Percent

connor-davidson resilience scale	10	10.9 %

cd-risc	10	10.9 %

connor davidson resilience scale	5	5.4 %

resilience scale for adults	4	4.3 %

cd risc	3	3.2 %

connor and davidson resilience scale	3	3.2 %

installerex official website	3	3.2 %

connor davidson resilience scale pdf	3	3.2 %

the connor-davidson resilience scale	3	3.2 %

connor davidson resilience scale free download	2	2.1 %

betac	2	2.1 %

www.resiliencescale.com	1	1 %

native american resilience scale	1	1 %

connor davidson resilience scale items	1	1 %

connor davidson grit	1	1 %

conor davidson resiliency scale	1	1 %

cd-risc 10	1	1 %

the connor-davidson resilience scale cdrisc	1	1 %

connor davidson resilience scale full assessment	1	1 %

connor-davidson resilience scale validity	1	1 %

connor-davidson resilience scale the resilience scale for adults and the brief resilience scale	1	1 %

connor davidson resilience scale cd risc	1	1 %

connor/davidson resilience scale	1	1 %

tab_hty.top	1	1 %

what is the connor 10 item scale american children	1	1 %

connordavidson-resiliencescale.com	1	1 %

subscase scale items resilience connor and davidson	1	1 %

connor davidson resilience scale download	1	1 %

resilience connor davidson scale 2003 pdf	1	1 %

the connor davidson resilience scale	1	1 %

download 25 items resilience scale	1	1 %

cd-risc hindi version	1	1 %

the connor‐davidson resilience scale cd‐risc	1	1 %

scales of resilience	1	1 %

http //www.cd-risc.com	1	1 %

www.conordavidson-resiliencescale.com	1	1 %

connor-davidson resilience scale cd-risc 25	1	1 %

resilience scale	1	1 %

connor davidson	1	1 %

koner davidson s resilience	1	1 %

installerex facebook	1	1 %

cd risc 10	1	1 %

cd risc 10 orang cacat	1	1 %

factors items resilience connor and davidson	1	1 %

connor and davidson	1	1 %

the connor-davidson resilience scale cd-risk	1	1 %

cd-risc- connor-davidson resilience scale manual	1	1 %

connor km connor davidson resilience scale depression and anxiety 18	1	1 %

cd-risc 25 scale of conner davidso n	1	1 %

cd risc 10 portugal	1	1 %

connor davidson resilience scale 10 item	1	1 %

cd-risc-10	1	1 %

scoring reslilency scale	1	1 %

development of a new resilience scale the connor-davidson resilience scale cd-risc	1	1 %

Advanced Web Statistics 6.7 (build 1.892) - Created by awstats


text:
<?php

/**
 * Customer region attribute source
 *
 * @category    Mage
 * @package     Mage_Customer
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Customer_Model_Entity_Address_Attribute_Source_Region
    extends Mage_Customer_Model_Resource_Address_Attribute_Source_Region
{
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _instanceMethods = require('./instance-methods');

var instanceMethods = _interopRequireWildcard(_instanceMethods);

var _nonNativeExtensions = require('./non-native-extensions');

var nonNativeExtensions = _interopRequireWildcard(_nonNativeExtensions);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var MemoryFileSystem = function MemoryFileSystem(rootNode) {
  _classCallCheck(this, MemoryFileSystem);

  this.rootNode = rootNode;
};

// mixin methods

exports.default = MemoryFileSystem;
Object.keys(instanceMethods).map(function (key) {
  return MemoryFileSystem.prototype[key] = instanceMethods[key];
});
Object.keys(nonNativeExtensions).map(function (key) {
  return MemoryFileSystem.prototype[key] = nonNativeExtensions[key];
});


text:
module MyTimeline
  class ControlPanelController < MyTimeline::ApplicationController

    def index
      @enabled_plugins = MyTimeline.enabled_plugins
    end

    def timezone
      if rails4?
        @user.time_zone = user_params[:time_zone]
      else
        @user.time_zone = params[user_param][:time_zone]
      end

      @user.save!
      redirect_to :back, notice: "Time zone setting saved."
    end

  private

    if rails4?
      define_method :user_params do
        params.required(user_param).permit :time_zone
      end
    end

    def user_param
      MyTimeline.user_class.model_name.param_key.to_sym
    end
  end
end


text:
This command line tool will analyze the invoice from a cloud provider and create a report with the total usage and cost, including the equivalent products and cost on GCP. We take the invoice CSV as input, and generate an ascii table or a CSV file with the information extracted.

This tool requires [nodejs](https://nodejs.org/en/).

**DISCLAIMER**: This is not an officially supported Google product.

## Processing the invoice

Only the AWS invoice is supported at this time. Invoice Insights can process the following services from the invoice:

- **AWS Regions** and **VM types**.
- **Premium OS**: Windows, Red Hat and Suse
- **Block Storage**: `sc1`, `st1`, `gp2` and `io1`
- **RDS Instance Hours**
- **Elasticache Instance Hours**

## Translating into Google Cloud

Invoice Insights can translate to the following services on Google Cloud:

- **VM types**: standard VMs (incl. high memory and high CPU), memory-optimized, custom (incl. extended memory), shared core (`f1-micro` and `g1-small`).
- **Usage type**: on demand, preemptible, commit 1 year, commit 3 year
- **Premium OS**: Windows, Red Hat and Suse
- **Block storage**: Standard and SSD
- **Cloud SQL instances**
- **Memorystore instances**

## Feature Roadmap

The following is a list of to-do features in the roadmap:

- **Local SSDs** and **GPUs** are included in the report, but not automatically mapped to GCP yet.
- **RDS Storage**, **Aurora Storage** and **RDS Snapshots**. You can extract those from the Summary.
- **Network egress** report. You can extract that from the Summary.
- **S3 storage report** (operations and Gb/month). You can extract that from the Summary.
- **SAP Premium OS** (Red Hat and Suse)
- **SQL Server instances**
- **Elasticache snapshots**

## Getting started

```sh
# Get high-level summary from an AWS invoice
npx @google-cloud/invoice-insights summary invoice.csv

# Get VM stats and GCP equivalent
npx @google-cloud/invoice-insights instances invoice.csv --format csv

# Print mappings with debug information, rounding to months, overriding a region mapping
npx @google-cloud/invoice-insights instances invoice.csv --debug --roundMonths --mapRegion eu-central-1=europe-west1
```

## Mapping to instances on GCP

We search for a VM with the same number of CPUs and a difference in memory below the predefined memory window (10% by default). If there is no match, a custom VM will be used instead.

Shared core (`t2` instances on AWS) will be mapped to `f1-micro` and `g1-small` on GCP when possible, or to a standard VM otherwise. Instance mappings can be overriden with `--mapInstance`, and region mapping with `--mapRegion`. These arguments can receive multiple values.

```bash
npx @google-cloud/invoice-insights invoice.csv --mapInstance t2.nano=n1-standard1 --mapInstance t2.micro=n1-standard2 --mapRegion eu-central-1=europe-west1
```

When calculating SUDs, we assume that VMs are running 730 hours per month (100% of the time) where possible. This is used to estimate the number of concurrent instances.

## Exporting your invoice from AWS

If pricing details are considered sensitive information, filter out these columns when creating the invoice export from AWS:

- `BlendedRate`
- `CurrencyCode`
- `CostBeforeTax`
- `Credits`
- `TaxAmount`
- `TaxType`
- `TotalCost`

## Contributing

Pull Requests are welcome! If you are planning to work on this code, this is what you need to get started.

First, install the [Google Cloud SDK](https://cloud.google.com/sdk/) and [jq](https://stedolan.github.io/jq/) (`sudo apt install jq`). Once done, you may want to update the local information about pricing and VM types.

```bash
# Download the latest SKUs and VM sizes
bin/get-aws-skus
bin/get-gcp-skus
bin/get-gcp-vm-types

# Test that the downloaded files are well-formed JSON
npx jsonlint third_party/ec2instances.info/aws-skus.json
npx jsonlint assets/gcp-skus.json
npx jsonlint assets/gcp-vm-types.json

# Run the tests: (add --watch to keep watching)
npx mocha -r esm
```

To explore the SKUs manually:

```bash
# Find all SKUs for RAM and memory on Google Cloud
grep 'Ram running in' assets/gcp-skus.json | sort | uniq -u
grep 'Core running in' assets/gcp-skus.json | sort | uniq -u

# Find all SKUs for commitment 1yr
cat assets/gcp-skus.json | jq '.[] | select(.category.usageType=="Commit1Yr") | .description' | sort | uniq -u

# Find all Cloud SQL SKUs
cat assets/gcp-skus.json | jq '.[] | select(.category.serviceDisplayName=="Cloud SQL" and (.description | contains("Network") | not ) ) | .description' | sort | uniq -u

# Find all SKUs with more than one pricing tier (for example f1-micro is free the first 730 hours)
cat assets/gcp-skus.json | jq '.[] | select(.pricingInfo[].pricingExpression.tieredRates | length > 1) | .description'|sort |uniq -u
```


text:
package com.jaumo.cropimage.gallery;

import android.net.Uri;

import java.util.HashMap;

//
// ImageList and Image classes have one-to-one correspondence.
// The class hierarchy (* = abstract class):
//
//    IImageList
//    - BaseImageList (*)
//      - VideoList
//      - ImageList
//        - DrmImageList
//    - SingleImageList (contains UriImage)
//    - ImageListUber
//
//    IImage
//    - BaseImage (*)
//      - VideoObject
//      - Image
//        - DrmImage
//    - UriImage
//

/**
 * The interface of all image collections used in gallery.
 */
public interface IImageList {
    HashMap<String, String> getBucketIds();

    /**
     * Returns the count of image objects.
     *
     * @return the number of images
     */
    int getCount();

    /**
     * @return true if the count of image objects is zero.
     */
    boolean isEmpty();

    /**
     * Returns the image at the ith position.
     *
     * @param i the position
     * @return the image at the ith position
     */
    IImage getImageAt(int i);

    /**
     * Returns the image with a particular Uri.
     *
     * @param uri
     * @return the image with a particular Uri. null if not found.
     */
    IImage getImageForUri(Uri uri);

    /**
     * @param image
     * @return true if the image was removed.
     */
    boolean removeImage(IImage image);

    /**
     * Removes the image at the ith position.
     *
     * @param i the position
     */
    boolean removeImageAt(int i);

    int getImageIndex(IImage image);

    /**
     * Closes this list to release resources, no further operation is allowed.
     */
    void close();
}


text:
package stored_requests

import (
	"context"
	"encoding/json"
	"errors"
	"testing"

	"github.com/prebid/prebid-server/metrics"
	"github.com/prebid/prebid-server/stored_requests/caches/nil_cache"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

func setupFetcherWithCacheDeps() (*mockCache, *mockCache, *mockCache, *mockFetcher, AllFetcher, *metrics.MetricsEngineMock) {
	reqCache := &mockCache{}
	impCache := &mockCache{}
	respCache := &mockCache{}
	metricsEngine := &metrics.MetricsEngineMock{}
	fetcher := &mockFetcher{}
	afetcherWithCache := WithCache(fetcher, Cache{reqCache, impCache, respCache, &nil_cache.NilCache{}}, metricsEngine)

	return reqCache, impCache, respCache, fetcher, afetcherWithCache, metricsEngine
}

func TestPerfectCache(t *testing.T) {
	reqCache, impCache, respCache, fetcher, aFetcherWithCache, metricsEngine := setupFetcherWithCacheDeps()
	impIDs := []string{"known"}
	reqIDs := []string{"req-id"}
	respIDs := []string{"resp-id"}
	ctx := context.Background()

	reqCache.On("Get", ctx, reqIDs).Return(
		map[string]json.RawMessage{
			"req-id": json.RawMessage(`{"req":true}`),
		})
	impCache.On("Get", ctx, impIDs).Return(
		map[string]json.RawMessage{
			"known": json.RawMessage(`{}`),
		})
	respCache.On("Get", ctx, respIDs).Return(
		map[string]json.RawMessage{
			"resp-id": json.RawMessage(`{"req":true}`),
		})
	metricsEngine.On("RecordStoredReqCacheResult", metrics.CacheHit, 1)
	metricsEngine.On("RecordStoredReqCacheResult", metrics.CacheMiss, 0)
	metricsEngine.On("RecordStoredImpCacheResult", metrics.CacheHit, 1)
	metricsEngine.On("RecordStoredImpCacheResult", metrics.CacheMiss, 0)

	reqData, impData, errs := aFetcherWithCache.FetchRequests(ctx, reqIDs, impIDs)
	respData, fetchRespErrs := aFetcherWithCache.FetchResponses(ctx, respIDs)

	reqCache.AssertExpectations(t)
	impCache.AssertExpectations(t)
	respCache.AssertExpectations(t)
	fetcher.AssertExpectations(t)
	metricsEngine.AssertExpectations(t)
	assert.JSONEq(t, `{"req":true}`, string(reqData["req-id"]), "Fetch requests should fetch the right request data")
	assert.JSONEq(t, `{"req":true}`, string(respData["resp-id"]), "Fetch responses should fetch the right response data")
	assert.JSONEq(t, `{}`, string(impData["known"]), "FetchRequests should fetch the right imp data")
	assert.Len(t, errs, 0, "FetchRequest shouldn't return any errors")
	assert.Len(t, fetchRespErrs, 0, "FetchResponses shouldn't return any errors")
}

func TestImperfectCache(t *testing.T) {
	reqCache, impCache, respCache, fetcher, aFetcherWithCache, metricsEngine := setupFetcherWithCacheDeps()
	impIDs := []string{"cached", "uncached"}
	respIDs := []string{"cached", "uncached"}
	ctx := context.Background()

	impCache.On("Get", ctx, impIDs).Return(
		map[string]json.RawMessage{
			"cached": json.RawMessage(`true`),
		})
	reqCache.On("Get", ctx, []string(nil)).Return(
		map[string]json.RawMessage{})
	respCache.On("Get", ctx, respIDs).Return(
		map[string]json.RawMessage{
			"cached": json.RawMessage(`true`),
		})

	fetcher.On("FetchRequests", ctx, []string{}, []string{"uncached"}).Return(
		map[string]json.RawMessage{},
		map[string]json.RawMessage{
			"uncached": json.RawMessage(`false`),
		},
		[]error{},
	)
	impCache.On("Save", ctx,
		map[string]json.RawMessage{
			"uncached": json.RawMessage(`false`),
		})

	fetcher.On("FetchResponses", ctx, []string{"uncached"}).Return(
		map[string]json.RawMessage{
			"uncached": json.RawMessage(`false`),
		},
		[]error{},
	)
	respCache.On("Save", ctx,
		map[string]json.RawMessage{
			"uncached": json.RawMessage(`false`),
		})

	reqCache.On("Save", ctx, map[string]json.RawMessage{})

	metricsEngine.On("RecordStoredReqCacheResult", metrics.CacheHit, 0)
	metricsEngine.On("RecordStoredReqCacheResult", metrics.CacheMiss, 0)
	metricsEngine.On("RecordStoredImpCacheResult", metrics.CacheHit, 1)
	metricsEngine.On("RecordStoredImpCacheResult", metrics.CacheMiss, 1)

	reqData, impData, errs := aFetcherWithCache.FetchRequests(ctx, nil, impIDs)
	respData, fetchRespErrs := aFetcherWithCache.FetchResponses(ctx, respIDs)

	impCache.AssertExpectations(t)
	respCache.AssertExpectations(t)
	fetcher.AssertExpectations(t)
	metricsEngine.AssertExpectations(t)
	assert.Len(t, reqData, 0, "Fetch requests should return nil if no request IDs were passed")
	assert.JSONEq(t, `true`, string(impData["cached"]), "FetchRequests should fetch the right imp data")
	assert.JSONEq(t, `false`, string(impData["uncached"]), "FetchRequests should fetch the right imp data")
	assert.JSONEq(t, `true`, string(respData["cached"]), "FetchResponses should fetch the right resp data")
	assert.JSONEq(t, `false`, string(respData["uncached"]), "FetchResponses should fetch the right resp data")
	assert.Len(t, errs, 0, "FetchRequest shouldn't return any errors")
	assert.Len(t, fetchRespErrs, 0, "FetchResponses shouldn't return any errors")
}

func TestMissingData(t *testing.T) {
	reqCache, impCache, respCache, fetcher, aFetcherWithCache, metricsEngine := setupFetcherWithCacheDeps()
	impIDs := []string{"unknown"}
	respIDs := []string{"unknown"}
	ctx := context.Background()

	impCache.On("Get", ctx, impIDs).Return(
		map[string]json.RawMessage{},
	)
	reqCache.On("Get", ctx, []string(nil)).Return(
		map[string]json.RawMessage{})

	respCache.On("Get", ctx, []string(respIDs)).Return(
		map[string]json.RawMessage{})

	fetcher.On("FetchRequests", ctx, []string{}, impIDs).Return(
		map[string]json.RawMessage{},
		map[string]json.RawMessage{},
		[]error{
			errors.New("Data not found"),
		},
	)

	fetcher.On("FetchResponses", ctx, respIDs).Return(
		map[string]json.RawMessage{},
		[]error{
			errors.New("Data not found"),
		},
	)

	impCache.On("Save", ctx,
		map[string]json.RawMessage{},
	)
	reqCache.On("Save", ctx,
		map[string]json.RawMessage{},
	)

	respCache.On("Save", ctx,
		map[string]json.RawMessage{},
	)
	metricsEngine.On("RecordStoredReqCacheResult", metrics.CacheHit, 0)
	metricsEngine.On("RecordStoredReqCacheResult", metrics.CacheMiss, 0)
	metricsEngine.On("RecordStoredImpCacheResult", metrics.CacheHit, 0)
	metricsEngine.On("RecordStoredImpCacheResult", metrics.CacheMiss, 1)

	reqData, impData, errs := aFetcherWithCache.FetchRequests(ctx, nil, impIDs)
	respData, fetchRespErrs := aFetcherWithCache.FetchResponses(ctx, respIDs)

	reqCache.AssertExpectations(t)
	impCache.AssertExpectations(t)
	respCache.AssertExpectations(t)
	fetcher.AssertExpectations(t)
	metricsEngine.AssertExpectations(t)
	assert.Len(t, errs, 1, "FetchRequests for missing data should return an error")
	assert.Len(t, fetchRespErrs, 1, "FetchResponses for missing data should return an error")
	assert.Len(t, reqData, 0, "FetchRequests for missing data shouldn't return anything")
	assert.Len(t, impData, 0, "FetchRequests for missing data shouldn't return anything")
	assert.Len(t, respData, 0, "FetchRequests for missing data shouldn't return anything")
}

// Prevents #311
func TestCacheSaves(t *testing.T) {
	reqCache, impCache, respCache, fetcher, aFetcherWithCache, metricsEngine := setupFetcherWithCacheDeps()
	impIDs := []string{"abc", "abc"}
	respIDs := []string{"abc", "abc"}
	ctx := context.Background()

	impCache.On("Get", ctx, impIDs).Return(
		map[string]json.RawMessage{
			"abc": json.RawMessage(`{}`),
		})
	respCache.On("Get", ctx, respIDs).Return(
		map[string]json.RawMessage{
			"abc": json.RawMessage(`{}`),
		})
	reqCache.On("Get", ctx, []string(nil)).Return(
		map[string]json.RawMessage{})
	metricsEngine.On("RecordStoredReqCacheResult", metrics.CacheHit, 0)
	metricsEngine.On("RecordStoredReqCacheResult", metrics.CacheMiss, 0)
	metricsEngine.On("RecordStoredImpCacheResult", metrics.CacheHit, 2)
	metricsEngine.On("RecordStoredImpCacheResult", metrics.CacheMiss, 0)

	_, impData, errs := aFetcherWithCache.FetchRequests(ctx, nil, []string{"abc", "abc"})
	respData, fetchRespErrs := aFetcherWithCache.FetchResponses(ctx, respIDs)

	impCache.AssertExpectations(t)
	respCache.AssertExpectations(t)
	fetcher.AssertExpectations(t)
	metricsEngine.AssertExpectations(t)
	assert.Len(t, impData, 1, "FetchRequests should return data only once for duplicate requests")
	assert.JSONEq(t, `{}`, string(impData["abc"]), "FetchRequests should fetch the right imp data")
	assert.JSONEq(t, `{}`, string(respData["abc"]), "FetchResponses should fetch the right resp data")
	assert.Len(t, errs, 0, "FetchRequests with duplicate IDs shouldn't return an error")
	assert.Len(t, fetchRespErrs, 0, "FetchResponses with duplicate IDs shouldn't return an error")
}

func setupAccountFetcherWithCacheDeps() (*mockCache, *mockFetcher, AllFetcher, *metrics.MetricsEngineMock) {
	accCache := &mockCache{}
	metricsEngine := &metrics.MetricsEngineMock{}
	fetcher := &mockFetcher{}
	afetcherWithCache := WithCache(fetcher, Cache{&nil_cache.NilCache{}, &nil_cache.NilCache{}, &nil_cache.NilCache{}, accCache}, metricsEngine)

	return accCache, fetcher, afetcherWithCache, metricsEngine
}

func TestAccountCacheHit(t *testing.T) {
	accCache, fetcher, aFetcherWithCache, metricsEngine := setupAccountFetcherWithCacheDeps()
	cachedAccounts := []string{"known"}
	ctx := context.Background()

	// Test read from cache
	accCache.On("Get", ctx, cachedAccounts).Return(
		map[string]json.RawMessage{
			"known": json.RawMessage(`true`),
		})

	metricsEngine.On("RecordAccountCacheResult", metrics.CacheHit, 1)
	account, errs := aFetcherWithCache.FetchAccount(ctx, "known")

	accCache.AssertExpectations(t)
	fetcher.AssertExpectations(t)
	metricsEngine.AssertExpectations(t)
	assert.JSONEq(t, `true`, string(account), "FetchAccount should fetch the right account data")
	assert.Len(t, errs, 0, "FetchAccount shouldn't return any errors")
}

func TestAccountCacheMiss(t *testing.T) {
	accCache, fetcher, aFetcherWithCache, metricsEngine := setupAccountFetcherWithCacheDeps()
	uncachedAccounts := []string{"uncached"}
	uncachedAccountsData := map[string]json.RawMessage{
		"uncached": json.RawMessage(`true`),
	}
	ctx := context.Background()

	// Test read from cache
	accCache.On("Get", ctx, uncachedAccounts).Return(map[string]json.RawMessage{})
	accCache.On("Save", ctx, uncachedAccountsData)
	fetcher.On("FetchAccount", ctx, "uncached").Return(uncachedAccountsData["uncached"], []error{})
	metricsEngine.On("RecordAccountCacheResult", metrics.CacheMiss, 1)

	account, errs := aFetcherWithCache.FetchAccount(ctx, "uncached")

	accCache.AssertExpectations(t)
	fetcher.AssertExpectations(t)
	metricsEngine.AssertExpectations(t)
	assert.JSONEq(t, `true`, string(account), "FetchAccount should fetch the right account data")
	assert.Len(t, errs, 0, "FetchAccount shouldn't return any errors")
}

func TestComposedCache(t *testing.T) {
	c1 := &mockCache{}
	c2 := &mockCache{}
	c3 := &mockCache{}
	c4 := &mockCache{}
	impCache := &mockCache{}
	cache := Cache{
		Requests:  ComposedCache{c1, c2, c3, c4},
		Imps:      impCache,
		Responses: ComposedCache{c1, c2, c3, c4},
	}
	metricsEngine := &metrics.MetricsEngineMock{}
	fetcher := &mockFetcher{}
	aFetcherWithCache := WithCache(fetcher, cache, metricsEngine)
	reqIDs := []string{"1", "2", "3"}
	impIDs := []string{}
	ctx := context.Background()

	c1.On("Get", ctx, reqIDs).Return(
		map[string]json.RawMessage{
			"1": json.RawMessage(`{"id": "1"}`),
		})
	c2.On("Get", ctx, []string{"2", "3"}).Return(
		map[string]json.RawMessage{
			"2": json.RawMessage(`{"id": "2"}`),
		})
	c3.On("Get", ctx, []string{"3"}).Return(
		map[string]json.RawMessage{
			"3": json.RawMessage(`{"id": "3"}`),
		})
	impCache.On("Get", ctx, []string{}).Return(map[string]json.RawMessage{})

	metricsEngine.On("RecordStoredReqCacheResult", metrics.CacheHit, 3)
	metricsEngine.On("RecordStoredReqCacheResult", metrics.CacheMiss, 0)
	metricsEngine.On("RecordStoredImpCacheResult", metrics.CacheHit, 0)
	metricsEngine.On("RecordStoredImpCacheResult", metrics.CacheMiss, 0)

	reqData, impData, errs := aFetcherWithCache.FetchRequests(ctx, reqIDs, impIDs)
	respData, fetchRespErrs := aFetcherWithCache.FetchResponses(ctx, reqIDs)

	c1.AssertExpectations(t)
	c2.AssertExpectations(t)
	c3.AssertExpectations(t)
	impCache.AssertExpectations(t)
	fetcher.AssertExpectations(t)
	metricsEngine.AssertExpectations(t)
	assert.Len(t, reqData, len(reqIDs), "FetchRequests should be able to return all request data from a composed cache")
	assert.Len(t, respData, len(reqIDs), "FetchResponses should be able to return all response data from a composed cache")
	assert.Len(t, impData, len(impIDs), "FetchRequests should be able to return all imp data from a composed cache")
	assert.Len(t, errs, 0, "FetchRequests shouldn't return an error when trying to use a composed cache")
	assert.Len(t, fetchRespErrs, 0, "FetchResponses shouldn't return an error when trying to use a composed cache")
	assert.JSONEq(t, `{"id": "1"}`, string(reqData["1"]), "FetchRequests should fetch the right req data")
	assert.JSONEq(t, `{"id": "2"}`, string(reqData["2"]), "FetchRequests should fetch the right req data")
	assert.JSONEq(t, `{"id": "3"}`, string(reqData["3"]), "FetchRequests should fetch the right req data")
	assert.JSONEq(t, `{"id": "1"}`, string(respData["1"]), "FetchResponses should fetch the right resp data")
	assert.JSONEq(t, `{"id": "2"}`, string(respData["2"]), "FetchResponses should fetch the right resp data")
	assert.JSONEq(t, `{"id": "3"}`, string(respData["3"]), "FetchResponses should fetch the right resp data")
}

type mockFetcher struct {
	mock.Mock
}

func (f *mockFetcher) FetchRequests(ctx context.Context, requestIDs []string, impIDs []string) (map[string]json.RawMessage, map[string]json.RawMessage, []error) {
	args := f.Called(ctx, requestIDs, impIDs)
	return args.Get(0).(map[string]json.RawMessage), args.Get(1).(map[string]json.RawMessage), args.Get(2).([]error)
}

func (f *mockFetcher) FetchResponses(ctx context.Context, ids []string) (data map[string]json.RawMessage, errs []error) {
	args := f.Called(ctx, ids)
	return args.Get(0).(map[string]json.RawMessage), args.Get(1).([]error)
}

func (a *mockFetcher) FetchAccount(ctx context.Context, accountID string) (json.RawMessage, []error) {
	args := a.Called(ctx, accountID)
	return args.Get(0).(json.RawMessage), args.Get(1).([]error)
}

func (f *mockFetcher) FetchCategories(ctx context.Context, primaryAdServer, publisherId, iabCategory string) (string, error) {
	return "", nil
}

type mockCache struct {
	mock.Mock
}

func (c *mockCache) Get(ctx context.Context, ids []string) map[string]json.RawMessage {
	args := c.Called(ctx, ids)
	return args.Get(0).(map[string]json.RawMessage)
}

func (c *mockCache) Save(ctx context.Context, data map[string]json.RawMessage) {
	c.Called(ctx, data)
}

func (c *mockCache) Invalidate(ctx context.Context, ids []string) {
	c.Called(ctx, ids)
}


text:
package org.apache.shardingsphere.dbtest.engine;

import com.google.common.base.Joiner;
import lombok.AccessLevel;
import lombok.Getter;
import org.apache.shardingsphere.dbtest.env.DatabaseTypeEnvironment;
import org.apache.shardingsphere.dbtest.env.EnvironmentPath;
import org.apache.shardingsphere.dbtest.env.IntegrateTestEnvironment;
import org.apache.shardingsphere.dbtest.env.datasource.DataSourceUtil;
import org.apache.shardingsphere.dbtest.env.schema.SchemaEnvironmentManager;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlMasterSlaveDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlShadowDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlShardingDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import org.apache.shardingsphere.underlying.common.database.type.DatabaseType;
import org.junit.After;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import javax.sql.DataSource;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

@RunWith(Parameterized.class)
@Getter(AccessLevel.PROTECTED)
public abstract class BaseIT {

    public static final String NOT_VERIFY_FLAG = "NOT_VERIFY";

    private final String ruleType;

    private final DatabaseTypeEnvironment databaseTypeEnvironment;

    private final Map<String, DataSource> dataSourceMap;

    private final DataSource dataSource;

    static {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    }

    public BaseIT(final String ruleType, final DatabaseTypeEnvironment databaseTypeEnvironment) throws IOException, JAXBException, SQLException {
        this.ruleType = ruleType;
        this.databaseTypeEnvironment = databaseTypeEnvironment;
        if (databaseTypeEnvironment.isEnabled()) {
            dataSourceMap = createDataSourceMap();
            dataSource = createDataSource();
        } else {
            dataSourceMap = null;
            dataSource = null;
        }
    }

    private Map<String, DataSource> createDataSourceMap() throws IOException, JAXBException {
        Collection<String> dataSourceNames = SchemaEnvironmentManager.getDataSourceNames(ruleType);
        Map<String, DataSource> result = new HashMap<>(dataSourceNames.size(), 1);
        for (String each : dataSourceNames) {
            result.put(each, DataSourceUtil.createDataSource(databaseTypeEnvironment.getDatabaseType(), each));
        }
        return result;
    }

    private DataSource createDataSource() throws SQLException, IOException {
        switch (ruleType) {
            case "masterslave":
                return YamlMasterSlaveDataSourceFactory.createDataSource(dataSourceMap, new File(EnvironmentPath.getRuleResourceFile(ruleType)));
            case "shadow":
                return YamlShadowDataSourceFactory.createDataSource(dataSourceMap, new File(EnvironmentPath.getRuleResourceFile(ruleType)));
            default:
                return YamlShardingDataSourceFactory.createDataSource(dataSourceMap, new File(EnvironmentPath.getRuleResourceFile(ruleType)));
        }
    }

    protected final String getExpectedDataFile(final String path, final String ruleType, final DatabaseType databaseType, final String expectedDataFile) {
        if (null == expectedDataFile) {
            return null;
        }
        String prefix = path.substring(0, path.lastIndexOf(File.separator));
        String result = Joiner.on("/").join(prefix, "dataset", ruleType, databaseType.getName().toLowerCase(), expectedDataFile);
        if (new File(result).exists()) {
            return result;
        }
        result = Joiner.on("/").join(prefix, "dataset", ruleType, expectedDataFile);
        if (new File(result).exists()) {
            return result;
        }
        return Joiner.on("/").join(prefix, "dataset", expectedDataFile);
    }

    protected static void createDatabasesAndTables() {
        createDatabases();
        dropTables();
        createTables();
    }

    protected static void createDatabases() {
        try {
            for (String each : IntegrateTestEnvironment.getInstance().getRuleTypes()) {
                SchemaEnvironmentManager.dropDatabase(each);
            }
            for (String each : IntegrateTestEnvironment.getInstance().getRuleTypes()) {
                SchemaEnvironmentManager.createDatabase(each);
            }
        } catch (final JAXBException | IOException | SQLException ex) {
            ex.printStackTrace();
        }
    }

    protected static void createTables() {
        try {
            for (String each : IntegrateTestEnvironment.getInstance().getRuleTypes()) {
                SchemaEnvironmentManager.createTable(each);
            }
        } catch (final JAXBException | IOException | SQLException ex) {
            ex.printStackTrace();
        }
    }

    protected static void dropDatabases() {
        try {
            for (String each : IntegrateTestEnvironment.getInstance().getRuleTypes()) {
                SchemaEnvironmentManager.dropDatabase(each);
            }
        } catch (final JAXBException | IOException ex) {
            ex.printStackTrace();
        }
    }

    protected static void dropTables() {
        try {
            for (String each : IntegrateTestEnvironment.getInstance().getRuleTypes()) {
                SchemaEnvironmentManager.dropTable(each);
            }
        } catch (final JAXBException | IOException ex) {
            ex.printStackTrace();
        }
    }

    @After
    public void tearDown() {
        if (dataSource instanceof ShardingDataSource) {
            ((ShardingDataSource) dataSource).getRuntimeContext().getExecutorKernel().close();
        }
    }
}


text:
extern crate rustbox;
extern crate vex;
extern crate getopts;

use getopts::Options;
use std::env;
use std::path::Path;

use self::rustbox::{RustBox};

use vex::editor::{State};

fn main() {
	let args: Vec<String> = env::args().collect();
    let program = args[0].clone();

    let mut opts = Options::new();
    opts.optflag("h", "help", "print this help menu");
    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m }
        Err(f) => { panic!(f.to_string()) }
    };
    if matches.opt_present("h") {
        print_usage(&program, opts);
        return;
    }

    let rustbox = match RustBox::init(Default::default()) {
        Result::Ok(v) => v,
        Result::Err(e) => panic!("{}", e),
    };

	let mut state = State::new(rustbox.width(), rustbox.height());
	for name in matches.free {
		state.open(Path::new(&name));
	}
	state.edit(&rustbox);
}

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Usage: {} FILE [options]", program);
    print!("{}", opts.usage(&brief));
}


text:
using namespace boost::python;
using namespace IECorePython;
using namespace Gaffer;
using namespace GafferScene;
using namespace GafferSceneUI;
using namespace GafferBindings;

namespace
{

void setScene( SceneGadget &g, ScenePlug &scene )
{
	ScopedGILRelease gilRelease;
	g.setScene( &scene );
}

GafferScene::ScenePlugPtr getScene( SceneGadget &g )
{
	return const_cast<GafferScene::ScenePlug *>( g.getScene() );
}

void setContext( SceneGadget &g, Context &context )
{
	ScopedGILRelease gilRelease;
	g.setContext( &context );
}

void setExpandedPaths( SceneGadget &g, const IECore::PathMatcher &expandedPaths )
{
	ScopedGILRelease gilRelease;
	g.setExpandedPaths( expandedPaths );
}

void setMinimumExpansionDepth( SceneGadget &g, size_t depth )
{
	ScopedGILRelease gilRelease;
	g.setMinimumExpansionDepth( depth );
}

void setPaused( SceneGadget &g, bool paused )
{
	ScopedGILRelease gilRelease;
	g.setPaused( paused );
}

void waitForCompletion( SceneGadget &g )
{
	ScopedGILRelease gilRelease;
	g.waitForCompletion();
}

struct SceneGadgetSlotCaller
{
	boost::signals::detail::unusable operator()( boost::python::object slot, SceneGadgetPtr g )
	{
		try
		{
			slot( g );
		}
		catch( const error_already_set &e )
		{
			ExceptionAlgo::translatePythonException();
		}
		return boost::signals::detail::unusable();
	}
};

IECore::CompoundObjectPtr getOpenGLOptions( const SceneGadget &g )
{
	return g.getOpenGLOptions()->copy();
}

IECore::StringVectorDataPtr getSelectionMask( const SceneGadget &g )
{
	const IECore::StringVectorData *d = g.getSelectionMask();
	return d ? d->copy() : nullptr;
}

IECore::InternedStringVectorDataPtr objectAt( SceneGadget &g, IECore::LineSegment3f &l )
{
	IECore::InternedStringVectorDataPtr result = new IECore::InternedStringVectorData;
	if( g.objectAt( l, result->writable() ) )
	{
		return result;
	}
	return nullptr;
}

tuple objectAndIntersectionAt( SceneGadget &g, IECore::LineSegment3f &l )
{
	IECore::InternedStringVectorDataPtr result = new IECore::InternedStringVectorData;
	Imath::V3f hitPos( 0.0f );
	if( g.objectAt( l, result->writable(), hitPos ) )
	{
		return boost::python::make_tuple( result, hitPos );
	}
	return boost::python::make_tuple( object(), hitPos );
}

} // namespace

void GafferSceneUIModule::bindSceneGadget()
{

	scope s = GafferUIBindings::GadgetClass<SceneGadget>()
		.def( init<>() )
		.def( "setScene", &setScene )
		.def( "getScene", &getScene )
		.def( "setContext", &setContext )
		.def( "getContext", (Gaffer::Context *(SceneGadget::*)())&SceneGadget::getContext, return_value_policy<CastToIntrusivePtr>() )
		.def( "setExpandedPaths", &setExpandedPaths )
		.def( "getExpandedPaths", &SceneGadget::getExpandedPaths, return_value_policy<copy_const_reference>() )
		.def( "setMinimumExpansionDepth", &setMinimumExpansionDepth )
		.def( "getMinimumExpansionDepth", &SceneGadget::getMinimumExpansionDepth )
		.def( "getPaused", &SceneGadget::getPaused )
		.def( "setPaused", &setPaused )
		.def( "state", &SceneGadget::state )
		.def( "stateChangedSignal", &SceneGadget::stateChangedSignal, return_internal_reference<1>() )
		.def( "waitForCompletion", &waitForCompletion )
		.def( "setOpenGLOptions", &SceneGadget::setOpenGLOptions )
		.def( "getOpenGLOptions", &getOpenGLOptions )
		.def( "setSelectionMask", &SceneGadget::setSelectionMask )
		.def( "getSelectionMask", &getSelectionMask )
		.def( "objectAt", &objectAt )
		.def( "objectAndIntersectionAt", &objectAndIntersectionAt )
		.def( "objectsAt", &SceneGadget::objectsAt )
		.def( "setSelection", &SceneGadget::setSelection )
		.def( "getSelection", &SceneGadget::getSelection, return_value_policy<copy_const_reference>() )
		.def( "selectionBound", &SceneGadget::selectionBound )
	;

	enum_<SceneGadget::State>( "State" )
		.value( "Paused", SceneGadget::Paused )
		.value( "Running", SceneGadget::Running )
		.value( "Complete", SceneGadget::Complete )
	;

	SignalClass<SceneGadget::SceneGadgetSignal, DefaultSignalCaller<SceneGadget::SceneGadgetSignal>, SceneGadgetSlotCaller>( "ImageGadgetSignal" );

}


text:
var parser = new window.DOMParser();
var serializer = new window.XMLSerializer();

module.exports = {
    serializeToString: function (obj) {
        return serializer.serializeToString(obj);
    },
    parseFromString: function (str, mimetype) {
        return parser.parseFromString(str, mimetype);
    },
    createElementNS: function (ns, name) {
        return document.createElementNS(ns, name);
    }
};


text:
管理 Node.js的 web 程序

pm2 将一些功能设计为模块
```
pm2 install <module_name> // 安装模块
```

- pm2-logrotate auto rotate logs of PM2 and applications managed
- pm2-webshell expose a fully capable terminal in browsers
- pm2-autopull auto pull all applications managed by PM2

用 pm2 将 http-server 守护执行
```
pm2 start /home/tqcenglish/.nvm/versions/node/v6.0.0/bin/http-server --name pdf-online -- -p 9001
```

##  文档
- [pm2使用说明](https://wohugb.gitbooks.io/pm2/content/)


text:
<component name="libraryTable">
  <library name="Maven: com.github.fommil.netlib:netlib-native_system-linux-armhf:natives:1.1">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/com/github/fommil/netlib/netlib-native_system-linux-armhf/1.1/netlib-native_system-linux-armhf-1.1-natives.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/com/github/fommil/netlib/netlib-native_system-linux-armhf/1.1/netlib-native_system-linux-armhf-1.1-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/com/github/fommil/netlib/netlib-native_system-linux-armhf/1.1/netlib-native_system-linux-armhf-1.1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
package edu.harvard.econcs.turkserver.server;

import java.net.InetAddress;
import java.util.Map;

import edu.harvard.econcs.turkserver.api.ClientController;
import edu.harvard.econcs.turkserver.api.HITWorker;
import edu.harvard.econcs.turkserver.client.ClientAnnotationManager;
import edu.harvard.econcs.turkserver.client.QuizResults;
import edu.harvard.econcs.turkserver.server.MessageException;

/**
 * A testing class that wires together server and client side communication without cometD
 *
 * @author mao
 *
 */
public final class FakeHITWorker implements HITWorker, ClientController {

	protected String hitId;
	protected String assignmentId;
	protected String workerId;
	protected String username;

	ClientAnnotationManager<?> clientWrapper;

	// This is set AFTER instantiation
	String expId;
	EventAnnotationManager expEvent;

	public static <C> FakeHITWorker getNew(String hitId, String assignmentId, String workerId, String username,
			Class<C> clientClass) throws Exception {
		FakeHITWorker fakeWorker = new FakeHITWorker();
		fakeWorker.hitId = hitId;
		fakeWorker.assignmentId = assignmentId;
		fakeWorker.workerId = workerId;
		fakeWorker.username = username;

		fakeWorker.clientWrapper = new ClientAnnotationManager<C>(fakeWorker, clientClass);
		return fakeWorker;
	}

	public void initialize(String expId, EventAnnotationManager events) {
		this.expId = expId;
		expEvent = events;
	}

	public Object getClientBean() {
		return clientWrapper.getClientBean();
	}

	@Override
	public String getHitId() {
		return hitId;
	}

	@Override
	public String getAssignmentId() {
		return assignmentId;
	}

	@Override
	public String getWorkerId() {
		return workerId;
	}

	@Override
	public String getUsername() {
		return username;
	}

	@Override
	public InetAddress getIPAddress() {
		// TODO Auto-generated method stub
		return null;
	}

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

	@Override
	public long getLastDisconnectedTime() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public long getTotalDisconnectedTime() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int getNumDisconnects() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public long getLastInactiveTime() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public long getTotalInactiveTime() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public double getInactivePercent() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getInactiveInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	void deliverExperimentBroadcast(Map<String, Object> msg) {
		clientWrapper.deliverBroadcast(msg);
	}

	@Override
	public void deliverExperimentService(Map<String, Object> msg) throws MessageException {
		clientWrapper.deliverService(msg);
	}

	@Override
	public String toString() {
		return "Fake HITWorker with " + hitId;
	}

	/* ****************************************
	 * Client-side methods
	 ******************************************/

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

	}

	@Override
	public void sendQuizResults(QuizResults qr) {
		// TODO Auto-generated method stub
		System.out.println("Sending quiz results not implemented yet");
	}

	@Override
	public void sendExperimentBroadcast(Map<String, Object> data) {
		expEvent.deliverBroadcastMsg(expId, this, data);
	}

	@Override
	public void sendExperimentService(Map<String, Object> data) {
		expEvent.deliverServiceMsg(expId, this, data);
	}

	@Override
	public void recordInactivity(long timeInactive) {
		// TODO Auto-generated method stub
		System.out.println("Recording inactivity not implemented yet");
	}
}