text:
[![license](https://img.shields.io/github/license/mashape/apistatus.svg)](https://opensource.org/licenses/MIT)
[![Build Status](https://travis-ci.org/PRX/fixer.prx.org.svg?branch=master)](https://travis-ci.org/PRX/fixer.prx.org)
[![Code Climate](https://codeclimate.com/github/PRX/fixer.prx.org/badges/gpa.svg)](https://codeclimate.com/github/PRX/fixer.prx.org)
[![Coverage Status](https://coveralls.io/repos/PRX/fixer.prx.org/badge.svg?branch=master)](https://coveralls.io/r/PRX/fixer.prx.org?branch=master)
[![Dependency Status](https://gemnasium.com/PRX/fixer.prx.org.svg)](https://gemnasium.com/PRX/fixer.prx.org)

Application providing asynchronous media file processing.

Jobs are submitted via a REST API to the master application that delegates processing to any number of worker processes using messages on prioritized queues.  Workers process files and save the results to number of destinations, updating the master, and sending webhook notifications.

## Installation

### Install basics
* Ruby (tested on 2.1)
* Postgres (9.3.4, needs to support uuid type extension)
* gems: bundler, rake

### Install media tools
Fixer uses the [audio_monster](https://github.com/PRX/audio_monster) gem which relies on many command line tools to process media. Below is the list of tools to install:
```
brew install lame
brew install flac
brew install sox
brew install twolame --frontend
brew install madplay
brew install mp3val
brew install ffmpeg
```

For images you also need the ImageMagick or GraphicsMagick command-line tool.
```
brew install imagemagick
```

### Configuration
The `dotenv` gem is used for development, and a sample `env-example` file is included with the list of keys.
```
cp env-example .env
vi .env
```

### Service credentials
Fixer requires credentials to the following, provided as environment variables.

* Internet Archive (S3-like API)
* Open Calais
* Yahoo Content Analysis
* AWS S3 (via credentials or EC2 IAM role)

### Application code
```
git clone git@github.com:PRX/fixer.prx.org.git
cd fixer.prx.org
bundle install
rake db:create
rake db:migrate
```

## Description

Fixer was designed as an application to process media files.
A user creates an application with a set of oAuth credentials (id and secret).
Using these credentials, jobs can be created for fixer to work on.

Each job has:
* A `original` url for the media file to be worked on.
* A `job_type` to indicate what type of media file this is (e.g. text, audio, etc.)
* One or more tasks to perform work on that media file.

Each task has:
* A `task_type`, indicating what work should be done (transcode, cut, concatenate with other files)
* A `destination` url that indicates where the product of that work should be saved.
* A callback url to send back notifications (e.g. a webhook or email) of status and completion

By default, tasks within a job are run in parallel, but they can also run serially by creating a Sequence.
Each Sequence is a kind of Task, and has:
* One or more tasks to perform work on that media file in that order by a worker
* A callback url to send back notifications (e.g. a webhook or email) of status and completion
* The input source for a task will be the output of the prior task

## Structure

Fixer is made up of a `master` web application and `workers` that asynchronously process jobs.

The `master` is a Rails web application providing an oAuth2 REST API for managing jobs, and asynchronous processes that handle task updates from workers.  When jobs are created or retried, the `master` initiates processing by creating a prioritized message for each task in a job.
The `master` stores information about Jobs, Tasks, TaskLogs (updates), and WebHooks in a relational DB (postgres by default).  It also uses the db to store info for users, and oAuth applications, authorizations, and tokens.
To handle scheduled retries, the `master` also has a scheduler (i.e. the `say_when` gem) that allows it set when the retry will run, and runs a process to handle these scheduled actions at the prescribed date and time.

The `worker` is a multi-threaded Ruby process (using `shoryken` or `sidekiq`) that listens on the prioritized task queues, and processes the messages it receives.
As it processes a task, the `worker` sends update messages about the processing to a task update queue.

The only communication between master and the workers are via messages. A task message to a worker contains the complete information about the task necessary for processing the task - it does not connect to any data stores to get information about the task, or to explicitly update the task.

### File Sources and Destinations

Each Job has a source URL, and each of its Tasks can have a destination URL.

The destination URL is where the file to be created or written to as a result of the task.
The scheme for the URL indicates the file should be written to an FTP server ('ftp://user:password@host/path/to/file.mp3), s3 ('s3://bucket/path/to/file.wav), or the Internet Archive ('ia://archive-item/file.ogg').

A source URL can also be to get a file via an http(s) get request, i.e. 'http://' or 'https://'.

For testing purposes (i.e. disabled in production), the 'file://' scheme is supported for using local files as sources and destinations.

### Processing Updates: Callbacks and Retries

When the master receives an update, it always updates its record of the status of the task and overall job.
can schedule a retries on failure, and initiates callbacks via webhooks or  emails.  Callbacks can be specified for each task, a sequence, or a job. For example, if there is a callback on the job, callbacks will only occur when the entire job is complete.  If the callback is on a task, then only changes and completion of that task will cause a callback.

### Worker Library

Fixer uses `ActiveJob` to abstract which worker/queuing library is used. It has been tested with `shoryuken` and `sidekiq`. It includes initializers and config files for those two options, but could be extended for other options.

By setting the `WORKER_LIB` you can choose to use either 'shoryken' or 'sidekiq' for messaging and async task processing.

`ActiveJob` has a default 'inline' value, for development and testing, where tasks are called synchronously - no messaging or worker process is used at all. This is obviously not recommended for production use, but works fine for development and testing.

Also under config is a `worker.rb` file to be used for worker only processes.  Using this file, all of Rails is not loaded, and no DB connection is configured or used.

#### Start Shoryuken

Before using shoryuken, you need the SQS queues created.
You can use a rake task for this:
```
bundle exec rake sqs:create
```

To start one process for all messages:
```
bundle exec shoryuken -R -C ./config/shoryuken/all.yml
```

To start two processes for master and worker messages:
```
bundle exec shoryuken -R -C ./config/shoryuken/master.yml
bundle exec shoryuken -r ./config/worker.rb -C ./config/shoryuken/worker.yml
```

#### Start Sidekiq

To start one process for all messages:
```
bundle exec sidekiq -C ./config/sidekiq/all.yml
```

To start two processes for master and worker messages:
```
bundle exec sidekiq -C ./config/sidekiq/master.yml
bundle exec sidekiq -r ./config/worker.rb -C ./config/sidekiq/worker.yml
```

## Containers

### Pre-existing

We are publishing 3 docker images for the different processes that make up fixer:
- https://registry.hub.docker.com/u/publicradioexchange/fixer_master/
- https://registry.hub.docker.com/u/publicradioexchange/fixer_masterprocessor/
- https://registry.hub.docker.com/u/publicradioexchange/fixer_worker/

You should then be able to run and use these by providing a database and the proper environment variables.
We are working on the following to help as well:
- A sample compose yml file for running them locally
- Instructions and supporting files to deploy on Amazon's Elastic Beanstalk

### Building

In the `container` folder are scripts and files to build docker images for fixer.

`container/build.sh` can be called from the project dir to build the images.

There are three images defined under `container/images/`
- `master` is the main web application, using phusion/passenger ruby images as base, and running nginx
- `master_processor` is the image to run proecss to listen for messages to update the master
- `worker` is an image defining a worker processs listening to task messages to work on
- `docker-compose.yml` defines how these images relate to a postgres db

Within each image folder are supporting configuration files and templates.

Image builds are done by copying the correct files into the `build` folder.
This way only the specific required files are built for a particular image.

### Using compose

There is a `container/docker-compose.yml` file that specifies a postgres db, and the app images.
This is used for building, but can also be used for running instances.

Add a '.env.production' file to the app root to be used when running images.
No `.env*` file will be copied to the `build` dir, and so will not be included in images.

### Building

- `container/build.sh` builds all the images
- `container/build.sh up` will build and run
- `container/build.sh clean` will delete the `build` dir

### Using

The containers rely on ENV values.

For example, a new user will be created based on the following ENV vars during `master` image start:
```
bundle exec rake user:create FIXER_USER_EMAIL=user@domain.com FIXER_USER_PASSWORD=user-password
```

## Copyright
© Copyright PRX, Public Radio Exchange https://www.prx.org

## License
Fixer is offered under the [MIT license](https://opensource.org/licenses/MIT)


text:
<manifest
    package="com.geronimostudios.bottommenuview">

    <application />
</manifest>

redpajama_set_name: RedPajamaGithub


text:
package bartil.map;

import java.util.List;
import java.util.function.Function;

import io.baratine.core.Result;

public interface MapManager<K,V>
{
  void exists(K key, Result<Boolean> result);
  void find(Function<K,Boolean> matcher, Result<List<K>> result);

  void deleteSequentially(Result<Integer> result, K ... keys);
  void deleteFork(Result<Integer> result, K ... keys);
}


text:
package org.onetwo.cloud.zuul.limiter;

import org.onetwo.boot.limiter.InvokeContext;
import org.onetwo.boot.limiter.InvokeContext.InvokeType;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

/**
 * @author wayshall
 * <br/>
 */
public class PreLimiterZuulFilter extends AbstractLimiterZuulFilter {

	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	@Override
	protected InvokeContext createInvokeContext() {
		return createInvokeContext(InvokeType.BEFORE);
	}

	@Override
	public int filterOrder() {
		return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER;
	}

}


text:
require 'loggr/adapter'

# This is basically a factory facade to create new Logger instances
# which behave all like standard Ruby Stdlib Loggers.
#
class LoggerFactory
  # Ensure we get all those factory methods directly here
  extend Loggr::Adapter
end


text:
import { ReactionHandler } from '../model/bot';
import { State } from '../model/state';

import * as utils from '../utils';

import * as config from '../../config.json';

interface LeaderboardState {
    page: number;
}

export const leaderboardReactionHandler: ReactionHandler<LeaderboardState> = {
    type: 'leaderboard',
    emojis: ['⏮', '◀', '▶', '⏭'],
    init: () => {
        return { page: 0 };
    },
    update: (state, emoji) => {
        const leaderboard = State.getState().data.leaderboard;
        const pageSize = config.bot.leaderboardSize;
        const lastPage = Math.floor(leaderboard.length / pageSize);
        let newPage: number = 0;

        switch (emoji.name) {
            case '⏮':
                newPage = 0; break;
            case '◀':
                newPage = Math.max(0, state.page - 1); break;
            case '▶':
                newPage = Math.min(lastPage, state.page + 1); break;
            case '⏭':
                newPage = lastPage; break;
        }

        const willUpdate = newPage !== state.page;
        state.page = newPage;
        return willUpdate;
    },
    getContents: state => {
        const leaderboard = State.getState().data.leaderboard;
        const pageSize = config.bot.leaderboardSize;
        const first = state.page * pageSize;
        return utils.formatPlayerList(leaderboard.slice(first, first + pageSize));
    },
};


text:
@interface XHSegmentControl()
<
    UIScrollViewDelegate
>

@property(nonatomic)            CGRect              lastSelectRect;
@property(nonatomic, strong)    NSArray             *items;
@property(nonatomic, strong)    UIScrollView        *scrollView;
@property(nonatomic, strong)    CALayer             *lineLayer;
@property(nonatomic)            CGFloat             beginOffsetX;

- (void)segmentItemClicked:(XHSegmentItem *)item;

@end

@implementation XHSegmentControl

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

-(void)awakeFromNib
{
    [self initialize];
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, self.borderColor.CGColor);
    CGContextSetLineWidth(context, self.borderWidth);
    CGContextMoveToPoint(context, 0, CGRectGetMaxY(rect) - self.borderWidth);
    CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMaxY(rect) - self.borderWidth);
    CGContextStrokePath(context);
}

- (void)layoutSubviews
{
    CGSize size = self.frame.size;
    self.scrollView.frame = CGRectMake(0, 0, size.width, size.height);

    //  contentSize
    XHSegmentItem *item = [self.items lastObject];
    self.scrollView.contentSize = CGSizeMake(CGRectGetMaxX(item.frame), CGRectGetHeight(self.scrollView.frame));

}

#pragma mark - Initialize Method

- (void)initialize
{
    // 初始化数据
    self.highlightColor = Default_Highlight_Color;
    self.titleColor = Default_Color;
    self.titleFont = Default_Title_font;
    self.lineWidth = Default_Line_Width;
    self.backgroundColor = [UIColor whiteColor];

    self.items = [[NSMutableArray alloc] init];

    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))];
    self.scrollView.autoresizesSubviews = NO;
    self.scrollView.alwaysBounceHorizontal = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.scrollsToTop = NO;
    [self addSubview:self.scrollView];

    //  初始化高亮线
    self.lineLayer = [[CALayer alloc] init];
    self.lineLayer.backgroundColor = self.highlightColor.CGColor;
    [self.scrollView.layer addSublayer:self.lineLayer];
}

- (void)createItems
{
    if (!self.titles || self.titles.count == 0) {
        return;
    }

    NSMutableArray *arrayItem = [[NSMutableArray alloc] initWithCapacity:self.titles.count];

    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat itemWidth = 0.;
    CGFloat itemHeight = CGRectGetHeight(self.frame);
    CGRect  itemRect = CGRectZero;
    for (int i = 0; i < self.titles.count; i++) {

        NSString *title = self.titles[i];

        if (self.segmentType == XHSegmentTypeFilled) {

            itemWidth = screenWidth/self.titles.count;
            itemRect = CGRectMake(i * itemWidth, 0, itemWidth, itemHeight);
        }
        else if (self.segmentType == XHSegmentTypeFit) {

            itemWidth = [XHSegmentItem caculateWidthWithtitle:title titleFont:self.titleFont];
            XHSegmentItem *lastItem = [arrayItem lastObject];
            itemRect = CGRectMake(CGRectGetMaxX(lastItem.frame), 0, itemWidth, itemHeight);
        }
        else {

        }

        XHSegmentItem *item = [self createItem:itemRect title:title];
        [arrayItem addObject:item];
    }

    self.items = [arrayItem mutableCopy];
}

- (XHSegmentItem *)createItem:(CGRect)rect title:title
{
    XHSegmentItem *item = [[XHSegmentItem alloc] initWithFrame:rect];
    item.title = title;
    item.titleColor = self.titleColor;
    item.titleFont = self.titleFont;
    item.highlightColor = self.highlightColor;
    [item addTarget:self action:@selector(segmentItemClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:item];
    return item;
}

#pragma mark - Public Method

- (void)load
{
    // 初始化scrollview
    if (self.backgroundImage) {
        self.backgroundColor = [UIColor colorWithPatternImage:self.backgroundImage];
    }

    //  load 高亮线
    self.lineLayer.backgroundColor = self.highlightColor.CGColor;
     self.lineLayer.frame = CGRectMake(CGRectGetMinX(self.lineLayer.frame), CGRectGetHeight(self.frame) - self.lineWidth, CGRectGetWidth(self.lineLayer.frame), self.lineWidth);

    // 初始化scrollview
    if (self.backgroundImage) {
        self.backgroundColor = [UIColor colorWithPatternImage:self.backgroundImage];
    }

    for (UIView *view in self.scrollView.subviews) {
        [view removeFromSuperview];
    }
    [self createItems];

    //  根据type初始化items
    self.selectIndex = 0;
    [self layoutSubviews];
}

- (void)scrollToRate:(CGFloat)rate
{
    if (!self.items || self.items.count == 0) {
        return;
    }
    XHSegmentItem *currentItem = self.items[self.selectIndex];
    XHSegmentItem *previousItem = self.selectIndex > 0 ? self.items[self.selectIndex - 1]: nil;
    XHSegmentItem *nextItem = (self.selectIndex < self.items.count - 1)? self.items[self.selectIndex + 1]: nil;
    if (fabs(rate) > 0.5) {

        if (rate > 0) {

            if (nextItem) {
                [self segmentItemSelected:nextItem];
            }
        }
        else if (rate < 0) {

            if (previousItem) {
                [self segmentItemSelected:previousItem];
            }
        }
    }
    else
    {
        if (currentItem) {
            [self segmentItemSelected:currentItem];
        }
    }

    CGFloat dx = 0.;
    CGFloat dw = 0.;
    if (rate > 0) {

        if (nextItem) {

            dx = CGRectGetMinX(nextItem.frame) - CGRectGetMinX(currentItem.frame);
            dw = CGRectGetWidth(nextItem.frame) - CGRectGetWidth(currentItem.frame);
        }
        else {

            dx = CGRectGetWidth(currentItem.frame);
        }
    }
    else if (rate < 0) {

        if (previousItem) {

            dx = CGRectGetMinX(currentItem.frame) - CGRectGetMinX(previousItem.frame);
            dw = CGRectGetWidth(currentItem.frame) - CGRectGetWidth(previousItem.frame);
        }
        else {

            dx = CGRectGetWidth(currentItem.frame);
        }
    }

    CGFloat x = CGRectGetMinX(self.lastSelectRect) + rate * dx;
    CGFloat w = CGRectGetWidth(self.lastSelectRect) + rate * dw;
    self.lineLayer.frame = CGRectMake(x, CGRectGetMinY(self.lastSelectRect), w, CGRectGetHeight(self.lastSelectRect));
}

#pragma mark - Private Method

- (void)segmentItemClicked:(XHSegmentItem *)item
{
    [self setSelectIndex:[self.items indexOfObject:item] animation:NO];
}

- (void)segmentItemSelected:(XHSegmentItem *)item
{
    for (XHSegmentItem *i in self.items) {

        i.selected = NO;
        [item refresh];
    }
    item.selected = YES;
}

#pragma mark - Setters

- (void)setSelectIndex:(NSInteger)selectIndex animation:(BOOL)animation
{
    _selectIndex = selectIndex;
    if (selectIndex < self.items.count) {

        XHSegmentItem *item = self.items[selectIndex];
        [self segmentItemSelected:item];

        self.lineLayer.frame = CGRectMake(CGRectGetMinX(item.frame), CGRectGetHeight(item.frame) - self.lineWidth, CGRectGetWidth(item.frame), self.lineWidth);
        self.lastSelectRect = self.lineLayer.frame;

        [self.scrollView scrollRectToVisible:item.frame animated:YES];
        [self.delegate xhSegmentSelectAtIndex:selectIndex animation:animation];
    }
}

- (void)setSelectIndex:(NSInteger)selectIndex
{
    _selectIndex = selectIndex;
    [self setSelectIndex:selectIndex animation:YES];
}

- (void)setHighlightColor:(UIColor *)highlightColor
{
    _highlightColor = highlightColor;
    self.lineLayer.backgroundColor = highlightColor.CGColor;
}

@end


text:
set -ex

# avoid slow finalization after the script has exited.
source $(dirname $0)/../../../tools/internal_ci/helper_scripts/move_src_tree_and_respawn_itself_rc

# change to grpc repo root
cd $(dirname $0)/../../..

source tools/internal_ci/helper_scripts/prepare_build_linux_rc

# prerequisites for ruby artifact build on linux
source tools/internal_ci/helper_scripts/prepare_build_linux_ruby_artifact_rc

# configure ccache
source tools/internal_ci/helper_scripts/prepare_ccache_rc

# Build all ruby linux artifacts (this step actually builds all the native and source gems)
tools/run_tests/task_runner.py -f artifact linux ruby ${TASK_RUNNER_EXTRA_FILTERS} -j 6 --inner_jobs 6 -x build_artifacts/sponge_log.xml || FAILED="true"

# Ruby "build_package" step is basically just a passthough for the "grpc" gems, so it's enough to just
# copy the native gems directly to the "distribtests" step and skip the "build_package" phase entirely.
# Note that by skipping the "build_package" step, we are also skipping the build of "grpc-tools" gem
# but that's fine since the distribtests only test the "grpc" native gems.

# The next step expects to find the artifacts from the previous step in the "input_artifacts" folder.
# in addition to that, preserve the contents of "artifacts" directory since we want kokoro
# to upload its contents as job output artifacts.
rm -rf input_artifacts
mkdir -p input_artifacts
cp -r artifacts/ruby_native_gem_*/* input_artifacts/ || true

# Run all ruby linux distribtests
# We run the distribtests even if some of the artifacts have failed to build, since that gives
# a better signal about which distribtest are affected by the currently broken artifact builds.
tools/run_tests/task_runner.py -f distribtest linux ruby ${TASK_RUNNER_EXTRA_FILTERS} -j 12 -x distribtests/sponge_log.xml || FAILED="true"

tools/internal_ci/helper_scripts/store_artifacts_from_moved_src_tree.sh

if [ "$FAILED" != "" ]
then
  exit 1
fi


text:
"""
Django settings for seamless project.

For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'zixc1k$i$z17y&))$q7ta+(tb*8nt@e^vn5^dzrj*0-=l8oytj'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
	'oauth',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'seamless.urls'

WSGI_APPLICATION = 'seamless.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# my constants
CONSTANTS = {
	'CLIENT_ID': 'my app client id from azure ad',
	'CLIENT_KEY': 'my app client key from azure ad',
	'STEP_1_TEMPLATE_NAME': 'oauth/step1.html',
	'STEP_2_TEMPLATE_NAME': 'oauth/step2.html',
	'REDIRECT_URI': 'http://localhost:8000/oauth/step2/',
	'AUTHORIZATION_BASE_URL': 'https://login.windows.net/%s/oauth2/authorize',
	'BASE_TOKEN_URL': 'https://login.windows.net/%s/oauth2/token',
	'RESOURCE_URI': 'https://management.core.windows.net/',
	'GET_SUBSCRIPTIONS_URL': 'https://management.core.windows.net/subscriptions',
	'MS_API_VERSION_HEADER': 'x-ms-version',
	'MS_API_VERSION_HEADER_VALUE': '2013-08-01'
}

# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/

STATIC_URL = '/static/'


text:
class Intervention < StudyRelationship
  has_many :intervention_arm_group_labels
  has_many :intervention_other_names

  def self.top_level_label
    '//intervention'
  end

  def attribs
    {
     :intervention_type=>get('intervention_type'),
     :name => get('intervention_name'),
     :description => get('description'),
     :intervention_arm_group_labels => InterventionArmGroupLabel.create_all_from(opts),
     :intervention_other_names => InterventionOtherName.create_all_from(opts)
    }
  end

	def other_names
		intervention_other_names
	end

	def type
		intervention_type
	end

end


text:
<?php

namespace UserFrosting;

/**
 * PageSchema class
 *
 * A PageSchema object manages the CSS and JS assets used by your website.
 * This allows you to organize your pages into groups, and assign different sets of CSS and JS resources to include for each group,
 * as well as a set of common resources to include in all pages.  It also provides an interface for automatically minifying and combining
 * these resources for production builds, using the YUI Compressor.  Minification requires that your web server have write access to the `js/min`
 * and `css/min` directories.
 * The minification tool should be re-run any time a CSS/JS include is added or removed, including those from plugin installation.
 * @todo Replace this whole thing with Bower/Grunt.
 * @package UserFrosting
 * @author Alex Weissman
 */
class PageSchema {

    /**
     * @var string the root URI of the css directory
     */
    protected $_css_uri;
    /**
     * @var string the root filesystem path of the css directory
     */
    protected $_css_path;
    /**
     * @var string the root URI of the js directory
     */
    protected $_js_uri;
    /**
     * @var string the root filesystem path of the js directory
     */
    protected $_js_path;
    /**
     * @var array a multidimensional array of css includes, keyed by page group name, each which contains a list of CSS files
     */
    protected $_css_includes = [];
    /**
     * @var array a multidimensional array of js includes, keyed by page group name, each which contains a list of JS files
     */
    protected $_js_includes_top = [];
    /**
     * @var array a multidimensional array of js includes, keyed by page group name, each which contains a list of JS files
     */
    protected $_js_includes_bottom = [];

    /**
     * Create a new PageSchema instance.
     *
     * @param string $css_uri the root URI of the css directory
     * @param string $css_path the root filesystem path of the css directory
     * @param string $js_uri the root URI of the css directory
     * @param string $js_path the root URI of the css directory
     */
    public function __construct($css_uri, $css_path, $js_uri, $js_path){
        $this->_css_uri =  $css_uri;
        $this->_css_path = $css_path;
        $this->_js_uri =  $js_uri;
        $this->_js_path = $js_path;
    }

    /**
     * Register a CSS include for a specified page group.
     *
     * The path should be the relative path of the file with respect to the `public/css/` directory of your website.
     * You should use a group name of "common" if you wish to register the CSS resource for all page groups.
     * @param string $group_name the name of the page group to register this resource with.  Use "common" to register with all groups.
     * @param string $path the path, relative to the `public/css/` directory of your website, where the file is located.
     * @return void
     */
    public function registerCSS($group_name, $path){
        if (!isset($this->_css_includes[$group_name]))
            $this->_css_includes[$group_name] = [];

        if (!in_array($path, $this->_css_includes))
            $this->_css_includes[$group_name][] = $path;
    }

    /**
     * Register a JS include for a specified page group.
     *
     * The path should be the relative path of the file with respect to the `public/js/` directory of your website.
     * You should use a group name of "common" if you wish to register the JS resource for all page groups.
     * @param string $group_name the name of the page group to register this resource with.  Use "common" to register with all groups.
     * @param string $path the path, relative to the `public/js/` directory of your website, where the file is located.
     * @param string $position whether to include this JS asset in the head ("top"), or footer ("bottom"), of your website.
     * @throws Exception position must be specified as either "top" or "bottom".
     * @return void
     */
    public function registerJS($group_name, $path, $position = "bottom"){
        if ($position == "bottom"){
            if (!isset($this->_js_includes_bottom[$group_name]))
                $this->_js_includes_bottom[$group_name] = [];

            if (!in_array($path, $this->_js_includes_bottom[$group_name]))
                $this->_js_includes_bottom[$group_name][] = $path;
        } else if ($position == "top"){
            if (!isset($this->_js_includes_top[$group_name]))
                $this->_js_includes_top[$group_name] = [];

            if (!in_array($path, $this->_js_includes_top[$group_name]))
                $this->_js_includes_top[$group_name][] = $path;
        } else {
            throw new \Exception("'position' must be either 'top' or 'bottom'.");
        }
    }

    /**
     * Get an array containing the full paths to all CSS includes to be used for a specified page group.
     *
     * @param string $group_name the name of the page group to retrieve the includes for.  Will automatically include any files that were assigned as "common".  Defaults to "common".
     * @param bool $minify specify whether or not to minify and combine the includes.  If set to `true`, the returned array will have the minified combined asset file instead of the unminified files.
     * @return array an array containing the full paths of the CSS files to be included.
     */
    public function getCSSIncludes($group_name = "common", $minify = false) {
        // Check if the specified group actually exists, otherwise use the common minified file.
        if (isset($this->_css_includes[$group_name]))
            $minfile = "min/$group_name.min.css";
        else
            $minfile = "min/common.min.css";
        return $this->mergeIncludes($this->_css_uri, $this->_css_includes, $group_name, $minfile , $minify);
    }

    /**
     * Get an array containing the full paths to all JS includes to be included in the header for a specified page group.
     *
     * @param string $group_name the name of the page group to retrieve the includes for.  Will automatically include any files that were assigned as "common".  Defaults to "common".
     * @param bool $minify specify whether or not to minify and combine the includes.  If set to `true`, the returned array will have the minified combined asset file instead of the unminified files.
     * @return array an array containing the full paths of the JS files to be included.
     */
    public function getJSTopIncludes($group_name = "common", $minify = false) {
        // Check if the specified group actually exists, otherwise use nothing.
        if (isset($this->_js_includes_top[$group_name]))
            $minfile = "min/$group_name-top.min.js";
        else {
            $minfile = "";
            $minify = false;
        }
        return $this->mergeIncludes($this->_js_uri, $this->_js_includes_top, $group_name, $minfile, $minify);
    }

    /**
     * Get an array containing the full paths to all JS includes to be included in the footer for a specified page group.
     *
     * @param string $group_name the name of the page group to retrieve the includes for.  Will automatically include any files that were assigned as "common".  Defaults to "common".
     * @param bool $minify specify whether or not to minify and combine the includes.  If set to `true`, the returned array will have the minified combined asset file instead of the unminified files.
     * @return array an array containing the full paths of the JS files to be included.
     */
    public function getJSBottomIncludes($group_name = "common", $minify = false) {
        // Check if the specified group actually exists, otherwise use the common minified file.
        if (isset($this->_js_includes_bottom[$group_name]))
            $minfile = "min/$group_name-bottom.min.js";
        else
            $minfile = "min/common-bottom.min.js";
        return $this->mergeIncludes($this->_js_uri, $this->_js_includes_bottom, $group_name, $minfile, $minify);
    }

    /**
     * Generate the full list of paths for a particular group of includes, including common includes.
     *
     * This function merges any group-specific includes with the common includes.
     * It also prepends the root URL for the type of resource (JS or CSS) to those includes.
     * @param string $root the root URL for this type of resource (usually the JS or CSS URL).
     * @param array $raw the raw array containing all includes, from which to extract the appropriate includes.
     * @param string $group_name the name of the page group to generate the list of includes for.
     * @param string $minfile the name of the minfile to create, with path relative to the root folder for this type of asset.
     * @param bool $minify specify whether or not to minify and combine the includes.  If set to `true`, the returned array will have the minified combined asset file instead of the unminified files.
     * @param bool $include_externals specify whether or not to include non-local assets as well (e.g., CDN)
     * @return array an array containing the full paths of the files to be included for the specified asset type.
     */
    private function mergeIncludes($root, $raw, $group_name, $minfile, $minify = false, $include_externals = true){
        // Combine the common and group-specific includes
        if (isset($raw["common"]))
            $includes = $raw["common"];
        else
            $includes = [];
        if ($group_name != "common" && isset($raw[$group_name]))
            $includes = array_merge($includes, $raw[$group_name]);

        // For minified, replace with minified file but we still need to include any external includes
        if ($minify){
            $includes_parsed = [$root . "/" . $minfile];
            // Include external files
            if ($include_externals) {
                foreach ($includes as $path){
                    if (strpos($path, 'http') === 0)
                        $includes_parsed[] = $path;
                }
            }
        } else {
            $includes_parsed = [];
            foreach ($includes as $path){
                if (strpos($path, 'http') === 0) {
                    if ($include_externals)
                        $includes_parsed[] = $path;
                } else
                    $includes_parsed[] = $root . "/" . $path;
            }
        }
        return $includes_parsed;
    }

    /**
     * Builds the minified CSS and JS files for the site.
     *
     * This function uses the Yahoo User Interface (YUI) interface (http://yui.github.io/yuicompressor/) to compress and minify the files as specified in this PageSchema object.  The user account under which the web server runs must have write access to the `min` subdirectories.
     * @param bool $debug If set to true, write information about the minification process to the error log.
     * @return void
     */
    public function build($debug = false){
        // Determine path to YUI jar file
        $yui = __DIR__ . "/yuicompressor-2.4.8.jar";

        /*
         * In XAMPP and Mac OSX, by default Apache is run under the user 'daemon'.  To grant proper write permissions, run the following shell command:
         * `sudo chown -R daemon:daemon <write_path>`
         * This will grant ownership of the path to the web server.
         */
        $web_user = trim(`whoami`);

        if ($debug) {
            error_log("Running as user: $web_user");
            error_log("YUI compressor is in $yui");
        }

        // For each manifest group, build the corresponding minified, bundled (concatenated) JS and CSS files

        // Build CSS
        foreach ($this->_css_includes as $group_name => $group){
            if ($debug) {
                error_log("Building CSS for page group '$group_name'...");
            }
            $this->buildGroup($yui, $this->_css_path, $this->_css_includes, $group_name, "$group_name.min.css", $debug);
        }

        // Build head JS
        foreach ($this->_js_includes_top as $group_name => $group){
            if ($debug) {
                error_log("Building top JS for page group '$group_name'...");
            }
            $this->buildGroup($yui, $this->_js_path, $this->_js_includes_top, $group_name, "$group_name-top.min.js", $debug);
        }

        // Build footer JS
        foreach ($this->_js_includes_bottom as $group_name => $group){
            if ($debug) {
                error_log("Building bottom JS for page group '$group_name'...");
            }
            $this->buildGroup($yui, $this->_js_path, $this->_js_includes_bottom, $group_name, "$group_name-bottom.min.js", $debug);
        }
    }

    /**
     * Build the minified file for a specified page group and asset type.
     *
     * Uses the YUI compressor (http://yui.github.io/yuicompressor/) to minify JS and CSS asset files, writing to a specified file.
     * @param string $yui the path to the YUI compressor JAR.
     * @param string $path_root the root file path for this type of resource (usually the JS or CSS path).
     * @param array $raw the raw array containing all includes, from which to extract the appropriate includes.
     * @param string $group_name the name of the page group to generate the minified file for.
     * @param string $minfile the name of the minfile to create, with path relative to the root folder for this type of asset.
     * @param bool $debug if set to true, write information about the minification process to the error log.
     * @return void
     */
    private function buildGroup($yui, $path_root, $includes, $group_name, $minfile, $debug = false){
        $paths = $this->mergeIncludes($path_root, $includes, $group_name, "", false, false);

        // Test permissions on writing to min file:
        $output_dir = $path_root . "/min/";
        $output_file = $output_dir . $minfile;
        $this->writeMinifiedFile($output_dir, $output_file, []);

        // Each file will be minified, and the result appended to the output array
        $group_arr = [];
        foreach($paths as $path){
            if ($debug) {
                error_log("----Minifying file '$path'");
            }

            // This will let us run the compressor and detect any errors
            $descriptorspec = array(
                0 => array("pipe", "r"),  // stdin
                1 => array("pipe", "w"),  // stdout
                2 => array("pipe", "w"),  // stderr
            );

            $process = proc_open("export DYLD_LIBRARY_PATH=''; java -jar $yui $path", $descriptorspec, $pipes);

            $stdout = stream_get_contents($pipes[1]);
            fclose($pipes[1]);

            $stderr = stream_get_contents($pipes[2]);
            fclose($pipes[2]);

            // Throw exception if there was an error
            if ($stderr){
                throw new \Exception("Unable to minify '$path'.  YUI error message:\n" . $stderr);
            }

            // If successful, append this minified content to the group file
            $group_arr[] = $stdout;
        }

        // Write minified CSS to the output file
        if ($debug) {
            error_log("--Attempting to write to file '$output_file'...");
        }
        return $this->writeMinifiedFile($output_dir, $output_file, $group_arr);
    }

    /**
     * Write minified content to a specified file.
     *
     * @param string $output_dir the directory that will contain the minified file.
     * @param string $output_file the full path and filename of the minified file to write.
     * @param array $content an array of strings that makes up the content to be written.
     * @throws Exception Insufficient permissions to write to the specified directory.
     * @return void
     */
    private function writeMinifiedFile($output_dir, $output_file, $content){
        try {
            file_put_contents($output_file, implode("\n", $content));
            return true;
        } catch (\Exception $e){
            $web_user = trim(`whoami`);
            throw new \Exception("Access denied to write to '$output_file'.  Be sure that the directory exists, and that the user '$web_user' has permission to write to this directory.  To grant write access in OSX/Linux/etc, try running the chown command: 'sudo chown -R $web_user:$web_user $output_dir'.");
        }
    }

}


text:
package com.github.mdr.ascii.layout.coordAssign

import com.github.mdr.ascii.common.Translatable
import com.github.mdr.ascii.layout.layering.RealVertex
import com.github.mdr.ascii.layout.layering.Vertex
import com.github.mdr.ascii.util.Utils
import com.github.mdr.ascii.util.Utils._

/**
 * VertexInfo's for all the vertices in a single layer.
 */
case class LayerInfo(vertexInfos: Map[Vertex, VertexInfo]) extends Translatable[LayerInfo] {

  def vertexInfo(v: Vertex): Option[VertexInfo] = vertexInfos.get(v)

  def isEmpty = vertexInfos.isEmpty

  def maxRow = vertexInfos.values.map(_.greaterRegion.bottomRow).fold(0)(_ max _)

  def maxColumn = vertexInfos.values.map(_.greaterRegion.rightColumn).fold(0)(_ max _)

  private def getSelfEdgeBuffer(vertexInfo: VertexInfo) =
    if (vertexInfo.selfInPorts.size > 0) (vertexInfo.selfInPorts.size + 1) else 0
  def topSelfEdgeBuffer: Int = vertexInfos.values.map(getSelfEdgeBuffer).fold(0)(_ max _)

  def translate(down: Int = 0, right: Int = 0) =
    copy(vertexInfos = transformValues(vertexInfos)(_.translate(down, right)))

  def realVertexInfos: List[(RealVertex, VertexInfo)] = vertexInfos.toList.collect {
    case (vertex: RealVertex, info) ⇒ (vertex, info)
  }

}


text:
package temple.core.utils.font;

/**
 * Created by stephan on 16-1-2015.
 */
public enum FontFaceType {
    FUTURA_BOOK("fonts/Poppins-Regular.ttf"),
    FUTURA_MEDIUM("fonts/Poppins-Medium.ttf");

    private final String _assetName;

    FontFaceType(String assetName) {
        _assetName = assetName;
    }

    public String getAssetName() {
        return _assetName;
    }
}


text:
// Include file for R3 view frustum class
#ifndef __R3__FRUSTUM__H__
#define __R3__FRUSTUM__H__

/* Begin namespace */
namespace gaps {

////////////////////////////////////////////////////////////////////////
// Class definition
////////////////////////////////////////////////////////////////////////

struct R3Frustum : public R3Solid {
public:
  // Constructor
  R3Frustum(void);
  R3Frustum(const R3Point& viewpoint,
    const R3Vector& towards, const R3Vector& up,
    RNAngle xfov, RNAngle yfov,
    RNLength neardist, RNLength fardist);

  // Property functions
  const R3Halfspace& Halfspace(int dir, int dim) const;
  const R3CoordSystem& CoordSystem(void) const;
  const R3Point Corner(RNOctant octant) const;
  const R3Point Corner(int xdir, int ydir, int zdir) const;
  const RNAngle XFov(void) const;
  const RNAngle YFov(void) const;
  const RNLength Near(void) const;
  const RNLength Far(void) const;
  const RNBoolean IsEmpty(void) const;

  // Shape propetry functions/operators
  virtual const RNBoolean IsPoint(void) const;
  virtual const RNBoolean IsLinear(void) const ;
  virtual const RNBoolean IsPlanar(void) const ;
  virtual const RNBoolean IsConvex(void) const ;
  virtual const RNInterval NFacets(void) const;
  virtual const RNArea Area(void) const;
  virtual const RNVolume Volume(void) const;
  virtual const R3Point Centroid(void) const;
  virtual const R3Point ClosestPoint(const R3Point& point) const;
  virtual const R3Point FurthestPoint(const R3Point& point) const;
  virtual const R3Shape& BShape(void) const;
  virtual const R3Box BBox(void) const;
  virtual const R3Sphere BSphere(void) const;

  // Manipulation functions
  virtual void Empty(void);
  virtual void Transform(const R3Transformation& transformation);
  virtual void SetHalfspace(int dir, int dim, const R3Halfspace& halfspace);

  // Draw function
  virtual void Draw(const R3DrawFlags draw_flags = R3_DEFAULT_DRAW_FLAGS) const;
  virtual void Outline(const R3DrawFlags draw_flags = R3_DEFAULT_DRAW_FLAGS) const;

  // Standard shape definitions
  RN_CLASS_TYPE_DECLARATIONS(R3Frustum);
  R3_SHAPE_RELATIONSHIP_DECLARATIONS(R3Frustum);

public:
  R3CoordSystem cs;
  R3Halfspace halfspaces[2][3];
  RNAngle xfov, yfov;
  RNLength neardist, fardist;
};

// Inline functions

inline const R3CoordSystem& R3Frustum::
CoordSystem(void) const
{
  // Return coordinate system for frustum
  // (apex at origin, -z points towards, +x points right, +y points up)
  return cs;
}

inline const RNAngle R3Frustum::
XFov(void) const
{
  // Return half angle between planes
  return xfov;
}

inline const RNAngle R3Frustum::
YFov(void) const
{
  // Return half angle between planes
  return yfov;
}

inline const RNLength R3Frustum::
Near(void) const
{
  // Return near distance
  return neardist;
}

inline const RNLength R3Frustum::
Far(void) const
{
  // Return near distance
  return fardist;
}

inline const RNBoolean R3Frustum::
IsEmpty(void) const
{
  // Return whether frustum is empty
  return (neardist >= fardist) ? TRUE : FALSE;
}

inline const R3Halfspace& R3Frustum::
Halfspace(int dir, int dim) const
{
  // Return halfspace
  return halfspaces[dir][dim];
}

inline void R3Frustum::
SetHalfspace(int dir, int dim, const R3Halfspace& halfspace)
{
  // Set halfspace
  this->halfspaces[dir][dim] = halfspace;
}

// End namespace
}

// End include guard
#endif


text:
javascripts
===========

Lucas Java Scripts


text:
package com.softserve.app;

import java.util.List;

import javax.json.*;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import com.softserve.app.model.Owner;
import com.softserve.app.model.Pet;
import com.softserve.app.repository.PetRepository;
import com.softserve.app.repository.PetRepositoryStub;

@Path("pets") //http:localhost:8080/rest1/webapi/pets
public class PetResouce {

	private PetRepository petRepository = new PetRepositoryStub();

	@POST
	@Path("pet")//http:localhost:8080/rest1/webapi/pets/pet
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	public Pet createPet(Pet pet) {

		System.out.println("Creating pet: "+pet.getType() + ", " + pet.getSize() + ", Owned by: " + pet.getOwner().getName());

		petRepository.create(pet);

		return pet;
	}

	@POST
	@Path("pet") //http:localhost:8080/rest1/webapi/pets/pet
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	public Pet createPetParams(MultivaluedMap<String, String> formParams) {

		System.out.println(formParams.getFirst("type"));
		System.out.println(formParams.getFirst("size"));
		System.out.println(formParams.getFirst("ownerName"));

		Pet pet = new Pet();
		pet.setId(formParams.getFirst("id"));
		pet.setType(formParams.getFirst("type"));
		pet.setSize(Integer.parseInt(formParams.getFirst("size")));

		Owner owner = new Owner();
		owner.setName(formParams.getFirst("ownerName"));
		owner.setId(formParams.getFirst("ownerID"));
		owner.setAdress(formParams.getFirst("ownerAdress"));
		pet.setOwner(owner);

		System.out.println(pet.getOwner().getName()+ "pet to add");

		petRepository.create(pet);

		return pet;
	}

	@GET //http:localhost:8080/rest1/webapi/pets
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	public List<Pet> getAllPets() {
		return petRepository.findAllPets();
	}

	@GET
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	@Path("{petId}") //http:localhost:8080/rest1/webapi/pets/101
	public Pet getPet(@PathParam ("petId") String petId) {
		return petRepository.findPet(petId);
	}

	@GET
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	@Path("{petId}/owner") //http:localhost:8080/rest1/webapi/pets/101/owner
	public Owner getPetOwner(@PathParam ("petId") String petId) {

		Pet pet = petRepository.findPet(petId);
		Owner owner = pet.getOwner();
		return owner;

	}

	@PUT
	@Path("pet") //http:localhost:8080/rest1/webapi/pets/pet
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	public Pet update(MultivaluedMap<String, String> formParams) {

		System.out.println("ping");
		System.out.println(formParams.getFirst("petId"));
		System.out.println(formParams.getFirst("petType"));

		String petId = formParams.getFirst("petId");
		String petType = formParams.getFirst("petType");

		Pet pet = petRepository.update(petId, petType);

		return pet;

	}

	@DELETE
	@Path("{petId}") //http:localhost:8080/rest1/webapi/pets/101
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	public String delete (@PathParam ("petId") String petId) {

		System.out.println("ping");
		System.out.println(petId);

		int k = petRepository.delete(petId);

		if (k==1) {
			return  "Pet deleted";
		}
		return  "Pet not found";
	}

}


text:
/* NOTE: This file is autogenerated, do not edit this file directly.*/

#ifndef Charts_NumberTickCalculator_cpp
#define Charts_NumberTickCalculator_cpp

#include <TRCharts/NumberTickCalculator.hpp>

Charts::NumberTickCalculator::~NumberTickCalculator(void)
{
}

#endif


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

<title>Uses of Class java.awt.Event (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev

Next

Frames

No Frames

All Classes

Uses of Class
java.awt.Event

Packages that use Event

Package
Description

java.awt

Contains all of the classes for creating user
interfaces and for painting graphics and images.

Uses of Event in java.awt

Fields in java.awt declared as Event

Modifier and Type
Field and Description

Event
Event.evt

The next event.

Methods in java.awt with parameters of type Event

Modifier and Type
Method and Description

boolean
Component.action(Event evt,
      Object what)

Deprecated.

As of JDK version 1.1,
 should register this component as ActionListener on component
 which fires action events.

void
Container.deliverEvent(Event e)

Deprecated.

As of JDK version 1.1,
 replaced by dispatchEvent(AWTEvent e)

void
Component.deliverEvent(Event e)

Deprecated.

As of JDK version 1.1,
 replaced by dispatchEvent(AWTEvent e).

boolean
Component.gotFocus(Event evt,
        Object what)

Deprecated.

As of JDK version 1.1,
 replaced by processFocusEvent(FocusEvent).

boolean
Component.handleEvent(Event evt)

Deprecated.

As of JDK version 1.1
 replaced by processEvent(AWTEvent).

boolean
Component.keyDown(Event evt,
       int key)

Deprecated.

As of JDK version 1.1,
 replaced by processKeyEvent(KeyEvent).

boolean
Component.keyUp(Event evt,
     int key)

Deprecated.

As of JDK version 1.1,
 replaced by processKeyEvent(KeyEvent).

boolean
Component.lostFocus(Event evt,
         Object what)

Deprecated.

As of JDK version 1.1,
 replaced by processFocusEvent(FocusEvent).

boolean
Component.mouseDown(Event evt,
         int x,
         int y)

Deprecated.

As of JDK version 1.1,
 replaced by processMouseEvent(MouseEvent).

boolean
Component.mouseDrag(Event evt,
         int x,
         int y)

Deprecated.

As of JDK version 1.1,
 replaced by processMouseMotionEvent(MouseEvent).

boolean
Component.mouseEnter(Event evt,
          int x,
          int y)

Deprecated.

As of JDK version 1.1,
 replaced by processMouseEvent(MouseEvent).

boolean
Component.mouseExit(Event evt,
         int x,
         int y)

Deprecated.

As of JDK version 1.1,
 replaced by processMouseEvent(MouseEvent).

boolean
Component.mouseMove(Event evt,
         int x,
         int y)

Deprecated.

As of JDK version 1.1,
 replaced by processMouseMotionEvent(MouseEvent).

boolean
Component.mouseUp(Event evt,
       int x,
       int y)

Deprecated.

As of JDK version 1.1,
 replaced by processMouseEvent(MouseEvent).

boolean
MenuContainer.postEvent(Event evt)

Deprecated.

As of JDK version 1.1
 replaced by dispatchEvent(AWTEvent).

boolean
Window.postEvent(Event e)

Deprecated.

As of JDK version 1.1
 replaced by dispatchEvent(AWTEvent).

boolean
MenuComponent.postEvent(Event evt)

Deprecated.

As of JDK version 1.1, replaced by dispatchEvent.

boolean
Component.postEvent(Event e)

Deprecated.

As of JDK version 1.1,
 replaced by dispatchEvent(AWTEvent).

Constructors in java.awt with parameters of type Event

Constructor and Description

AWTEvent(Event event)

Constructs an AWTEvent object from the parameters of a 1.0-style event.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev

Next

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
-include $(APPDIR)/Make.defs

# Hello, World! for hn70ap built-in application info

CONFIG_HN70AP_NETMON_PRIORITY ?= SCHED_PRIORITY_DEFAULT
CONFIG_HN70AP_NETMON_STACKSIZE ?= 2048

APPNAME = netmon
PRIORITY = $(CONFIG_HN70AP_NETMON_PRIORITY)
STACKSIZE = $(CONFIG_HN70AP_NETMON_STACKSIZE)

# Hello, World! Example

ASRCS =
CSRCS =
MAINSRC = netmon_main.c

CONFIG_HN70AP_NETMON_PROGNAME ?= netmon$(EXEEXT)
PROGNAME = $(CONFIG_HN70AP_NETMON_PROGNAME)

include $(APPDIR)/Application.mk


text:
#import "NSTimeZone.h"

@interface NSTimeZone (NSTimeZone)
- (Class)classForCoder;
- (id)initWithCoder:(id)arg1;
- (void)encodeWithCoder:(id)arg1;
@end


text:
from collections import defaultdict
import json
import os

import requests

import time
from dateutil.parser import parse
# import pdb

# URL strings needed to interact with Facebook's Graph API
baseurl = "https://graph.facebook.com/v2.5/"
access_token = os.environ['GRAPH_TOKEN']

# Get the necessary data from the user's posts
post_fields = ['message', 'created_time', 'likes.limit(0).summary(total_count)', 'comments.limit(0).summary(total_count)', 'shares', 'type', 'source', 'attachments']

########################
### Helper Functions ###
########################

def api_request(graph_id, fields, limit):
    """
        Web request to Graph API retrieving JSON data, turns  said JSON data into a Python dict
    """
    fields = ','.join(fields)
    params = 'posts{%s}' % fields
    base_query = baseurl + graph_id
    params = {"fields": params, "limit": limit, "access_token": access_token}

    response = requests.get(base_query, params=params)
    content = response.content.decode('utf-8')
    # print(response.from_cache)
    return json.loads(content)

##########################
### Facebook API Query ###
##########################

def facebook_json(user_id):

    # Retrieve the user's ten recent posts
    posts = api_request(user_id, fields=post_fields, limit=10)

    posts = posts['posts']["data"]

    json_list = []

    for post in posts:
        post = defaultdict(lambda: "none", post)
        cleaned_data = defaultdict(lambda: "none")
        cleaned_data['id'] = post['id']
        cleaned_data['message'] = post['message']

        if 'shares' in post.keys():
            cleaned_data['shares'] = post['shares']['count']
        else:
            cleaned_data['shares'] = "none"

        # convert date string to datetime object
        date = parse(post['created_time'], fuzzy=True, yearfirst=True)
        # turn date into unix timestamp
        cleaned_data['date_posted'] = time.mktime(date.timetuple())

        cleaned_data['comments'] = post['comments']['summary']['total_count']
        cleaned_data['likes'] = post['likes']['summary']['total_count']
        cleaned_data['photo'] = post['attachments']

        if post['type'] == 'video':
            cleaned_data['video'] = post['source']
        else:
            cleaned_data['video'] = "none"

        json_list.append(cleaned_data)

    return json_list


text:
using Contabile::Validator
module Contabile

  class Entry

    include Constants
    include Mongoid::Document
    include Mongoid::Timestamps

    field :type, type: String
    field :amount, type: Float
    field :tag, type: String, default: Constants::Tags[:general]
    field :date,  type: DateTime, default: Time.now
    field :note, type: String, default: ''

    validates_inclusion_of :type, in: Constants::Types.keys.map{ |k| k.to_s }, message: "type error"
    validates_numericality_of :amount, greater_than: 0
    validates_inclusion_of :tag, in: Constants::Tags.values.map{ |t| t.to_s }, message: "tag error"

#    validate :entry_validator

    store_in collection: Constants::CollectionName, database: Constants::DatabaseName

    def month
      date.month
    end

    def entry_validator
      type.validate_type
      tag.validate_tag_value
      amount.to_s.validate_amount
    end

  end # Entry

end # Contabile


text:
module ProtesteAuthorize
  class PermissionStore
    delegate :current_user, :session, to: :@view

    def initialize(view, app_id)
      @view   = view
      @app_id = app_id
    end

    def valid?
      current_user? && app_id?
    end

    def invalid?
      !valid?
    end

    def permissions!
      return permissions if has_permissions?
      cache!
      @permissions = Rails.cache.fetch("proteste_permissions_#{current_user.id}", expires_in: 2.hours) do
        get_permissions
      end
    end

    def permissions
      @permissions
    end

    def self.load_user_permissions(view, app_id)
      permission = ProtesteAuthorize::PermissionStore.new(view, app_id)
      return nil if permission.invalid?

      permission.permissions!
    end

    protected

    def get_permissions
      ProtesteAuthorize::Consumers.permissions(app_id, user_login)
    end

    def has_permissions?
      in_cache? && !permissions.nil?
    end

    def user_login
      current_user.login
    end

    def app_id
      @app_id
    end

    def current_user?
      !current_user.nil?
    end

    def app_id?
      !@app_id.nil?
    end

    def in_cache?
      if session[:permissions_on_cache].nil?
        Rails.cache.delete("proteste_permissions_#{current_user.id}")
        false
      else
        true
      end
    end

    def cache!
      session[:permissions_on_cache] ||= true
    end

  end
end


text:
package com.louddoor.hbase_streaming;

import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.OutputStream;

import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.Text;

public class ByteSerializer extends Serializer {
	DataOutput dout;
	protected byte[] tab = Bytes.toBytes("\t");

	public ByteSerializer(OutputStream out) {
		super(out);
		dout = new DataOutputStream(out);
	}

	@Override
	public void writeMap(ImmutableBytesWritable rowKey, Result in) throws Exception {
		rowKey.write(dout); //writes bytes.length + bytes
		/*
		 * totalLengthOfResult(int)
		 * foreach keyvalue = lengthOfKV + KV.bytes
		 *
		 * KV.bytes:
		 * keyLength(int) + valueLength(int) + rowLength(short) + rowKey(bytes) + familyLength(byte) + family(bytes) + qualifier(bytes) + timestamp(long) + type(byte) + value(bytes)
		 *
		 */
		in.write(this.dout);
		dout.write(newLine);
	}

	@Override
	public void writeReduce(Text rowKey, Iterable<Text> values) throws Exception {
		rowKey.write(dout); //writes bytes.length + bytes

		for (Text val : values)
		{
			val.write(dout); //writes bytes.length + bytes
		}

		dout.write(newLine);
	}

}


text:
// flow-typed signature: d3cb6f93a9e75807ccab51cf60a55c5b
// flow-typed version: <<STUB>>/babel-plugin-transform-react-remove-prop-types_v^0.4.4/flow_v0.45.0

/**
 * This is an autogenerated libdef stub for:
 *
 *   'babel-plugin-transform-react-remove-prop-types'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module 'babel-plugin-transform-react-remove-prop-types' {
  declare module.exports: any;
}

/**
 * We include stubs for each file inside this npm package in case you need to
 * require those files directly. Feel free to delete any files that aren't
 * needed.
 */
declare module 'babel-plugin-transform-react-remove-prop-types/lib/index' {
  declare module.exports: any;
}

declare module 'babel-plugin-transform-react-remove-prop-types/lib/isAnnotatedForRemoval' {
  declare module.exports: any;
}

declare module 'babel-plugin-transform-react-remove-prop-types/lib/isStatelessComponent' {
  declare module.exports: any;
}

declare module 'babel-plugin-transform-react-remove-prop-types/lib/remove' {
  declare module.exports: any;
}

declare module 'babel-plugin-transform-react-remove-prop-types/src/index' {
  declare module.exports: any;
}

declare module 'babel-plugin-transform-react-remove-prop-types/src/isAnnotatedForRemoval' {
  declare module.exports: any;
}

declare module 'babel-plugin-transform-react-remove-prop-types/src/isStatelessComponent' {
  declare module.exports: any;
}

declare module 'babel-plugin-transform-react-remove-prop-types/src/remove' {
  declare module.exports: any;
}

// Filename aliases
declare module 'babel-plugin-transform-react-remove-prop-types/lib/index.js' {
  declare module.exports: $Exports<'babel-plugin-transform-react-remove-prop-types/lib/index'>;
}
declare module 'babel-plugin-transform-react-remove-prop-types/lib/isAnnotatedForRemoval.js' {
  declare module.exports: $Exports<'babel-plugin-transform-react-remove-prop-types/lib/isAnnotatedForRemoval'>;
}
declare module 'babel-plugin-transform-react-remove-prop-types/lib/isStatelessComponent.js' {
  declare module.exports: $Exports<'babel-plugin-transform-react-remove-prop-types/lib/isStatelessComponent'>;
}
declare module 'babel-plugin-transform-react-remove-prop-types/lib/remove.js' {
  declare module.exports: $Exports<'babel-plugin-transform-react-remove-prop-types/lib/remove'>;
}
declare module 'babel-plugin-transform-react-remove-prop-types/src/index.js' {
  declare module.exports: $Exports<'babel-plugin-transform-react-remove-prop-types/src/index'>;
}
declare module 'babel-plugin-transform-react-remove-prop-types/src/isAnnotatedForRemoval.js' {
  declare module.exports: $Exports<'babel-plugin-transform-react-remove-prop-types/src/isAnnotatedForRemoval'>;
}
declare module 'babel-plugin-transform-react-remove-prop-types/src/isStatelessComponent.js' {
  declare module.exports: $Exports<'babel-plugin-transform-react-remove-prop-types/src/isStatelessComponent'>;
}
declare module 'babel-plugin-transform-react-remove-prop-types/src/remove.js' {
  declare module.exports: $Exports<'babel-plugin-transform-react-remove-prop-types/src/remove'>;
}


text:
body {
  background-color: var(--color-background);
  font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
  margin: 0;
  padding: 0;
  line-height: 1.5;
}

body {
  color: var(--color-on-background);
}

a {
  color: inherit;
  text-decoration: none;
  border-bottom: 1px solid transparent;
  transition: var(--transition-color);
}

a:hover {
  border-color: currentColor;
}

img {
  max-width: 100%;
  border-radius: var(--radius);
}


text:
package sa.com.is;

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

public interface Body {
    /**
     * Returns the raw data of the body, without transfer encoding etc applied.
     * TODO perhaps it would be better to have an intermediate "simple part" class where this method could reside
     *    because it makes no sense for multiparts
     */
    public InputStream getInputStream() throws MessagingException;

    /**
     * Sets the content transfer encoding (7bit, 8bit, quoted-printable or base64).
     */
    public void setEncoding(String encoding) throws MessagingException;

    public String getEncoding();

    /**
     * Writes the body's data to the given {@link OutputStream}.
     * The written data is transfer encoded (e.g. transformed to Base64 when needed).
     */
    public void writeTo(OutputStream out) throws IOException, MessagingException;
}


text:
.ui-carousel {
	display: flex;
	flex-direction: column;
	width: 100%;
}

.ui-carousel-content {
	display: flex;
	flex-direction: column;
	flex-wrap: nowrap;
	overflow: auto;
	padding: 0 .5em;
}

.ui-carousel-prev,
.ui-carousel-next {
	align-self: center;
	text-align: center;
	flex-grow: 0;
	flex-shrink: 0;
	width: 2.5em;
	height: 2.5em;
	position: relative;
}

.ui-carousel-prev span,
.ui-carousel-next span {
	width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.ui-carousel-container {
	display: flex;
    flex-direction: row;
    padding: 0 .1em;
}

.ui-carousel-header,
.ui-carousel-footer {
	padding: .5em;
	z-index: 1;
}

.ui-carousel-items-content {
    overflow: hidden;
    width: 100%;
}

.ui-carousel-items-container {
    display: flex;
    flex-wrap: nowrap;
    flex-direction: row;
}

.ui-carousel-items-container .ui-carousel-item {
    width: 100%;
    box-sizing: border-box;
    overflow: auto;
}

.ui-carousel-dots-container {
    display: flex;
    flex-direction: row;
    justify-content: center;
    flex-wrap: wrap;
    margin: .5em;
}

/* Vertical */
.ui-carousel-vertical .ui-carousel-container {
    flex-direction: column;
    width: 100%;
}

.ui-carousel-vertical .ui-carousel-items-container {
    flex-direction: column;
    height: 100%;
}

.ui-carousel-vertical .ui-carousel-dots-container {
    margin: .75em 0;
}


text:
<?php
namespace app\models;

use Yii;
use yii\db\ActiveRecord;

class Author extends ActiveRecord
{
    public static function tableName()
    {
        return '{{%author}}';
    }

}


text:
package com.example.project.tabhost;

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

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.example.ch05project.R;

public class RatingListViewActivity extends ListActivity {
	private static String[] applicationNames = new String[] { "多功能日历",
			"eoeMarket客户端", "耐玩的重力消砖块", "白社会", "程序终结者" };
	private static String[] authors = new String[] { "李宁", "eoemobile", "wawa",
			"ApkHome", "lucyfa" };
	private static int[] resIds = new int[] { R.drawable.calendar,
			R.drawable.eoemarket, R.drawable.brick, R.drawable.whitesociety,
			R.drawable.terminater };
	private static float[] applicationRating = new float[] { (float) 5.0,
			(float) 5.0, (float) 3.5, (float) 5.0, (float) 4.0 };
	String inflater = Context.LAYOUT_INFLATER_SERVICE;
	LayoutInflater layoutInflater;
	private RatingAdapter raAdapter;

	private class RatingAdapter extends BaseAdapter {
		private Context context;

		public RatingAdapter(Context context) {
			this.context = context;
			layoutInflater = (LayoutInflater) context
					.getSystemService(inflater);
		}

		@Override
		public int getCount() {
			return applicationNames.length;
		}

		@Override
		public Object getItem(int position) {
			return applicationNames[position];
		}

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

		public void setRating(int position, float rating) {
			applicationRating[position] = rating;
			notifyDataSetChanged();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LinearLayout linearLayout = (LinearLayout) layoutInflater.inflate(
					R.layout.tabhost_rating_main, null);
			ImageView ivLogo = (ImageView) linearLayout
					.findViewById(R.id.tabhost_ratingmain_ivLogo);
			TextView tvApplicationName = ((TextView) linearLayout
					.findViewById(R.id.tvApplicationName));
			TextView tvAuthor = (TextView) linearLayout
					.findViewById(R.id.tvAuthor);
			TextView tvRating = (TextView) linearLayout
					.findViewById(R.id.tvRating);
			RatingBar ratingBar = (RatingBar) linearLayout
					.findViewById(R.id.ratingbar);
			ivLogo.setImageResource(resIds[position]);
			tvApplicationName.setText(applicationNames[position]);
			tvAuthor.setText(authors[position]);
			tvRating.setText(String.valueOf(applicationRating[ position]));
			ratingBar.setRating(applicationRating[position]);
			return linearLayout;
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, final int position, long id) {
		super.onListItemClick(l, v, position, id);
		View myView = getLayoutInflater().inflate(R.layout.tabhost_rating, null);
		final RatingBar ratingBar = (RatingBar) myView
				.findViewById(R.id.tabhost_rating_ratingbar);
		ratingBar.setRating(applicationRating[position]);
		new AlertDialog.Builder(this).setTitle(applicationNames[position])
		.setMessage("给应用程序打分").setIcon(resIds[position])
		.setView(myView).setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				raAdapter.setRating(position, ratingBar.getRating());

			}
		}).setNegativeButton("取消", null).show();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		List<View> viewList = new ArrayList<View>();
		viewList.add(getLayoutInflater().inflate(R.layout.tabhost_rating_main,
				null));
		raAdapter = new RatingAdapter(this);
		setListAdapter(raAdapter);
	}

}


text:
using namespace mscapi;

Scoped<CryptoKey> CryptoKey::Create(PCERT_PUBLIC_KEY_INFO spki)
{
    LOGGER_FUNCTION_BEGIN;

    try {
        if (!spki) {
            THROW_PARAM_REQUIRED_EXCEPTION("spki");
        }

#pragma region Import SPKI to BKey
        ALG_ID dwAlgId = CertOIDToAlgId(spki->Algorithm.pszObjId);
        DWORD dwProvType = PROV_RSA_FULL;
        switch (dwAlgId) {
        case CALG_ECDH:
        case CALG_ECDSA:
            dwProvType = PROV_EC_ECDSA_FULL;
        }

        Scoped<bcrypt::Key> bKey(new bcrypt::Key);
        bKey->ImportPublicKeyInfo(X509_ASN_ENCODING, spki);
#pragma endregion

#pragma region Translate BKey to NKey
        NTSTATUS status = 0;

        Scoped<std::wstring> algName = bKey->GetAlgorithmName();

        LPWSTR blobType = BCRYPT_RSAPUBLIC_BLOB;

        if (algName->compare(BCRYPT_RSA_ALGORITHM) == 0 ||
            algName->compare(BCRYPT_RSA_SIGN_ALGORITHM) == 0) {
            blobType = BCRYPT_RSAPUBLIC_BLOB;
        }
        else if (algName->compare(BCRYPT_ECDH_ALGORITHM) == 0 ||
            algName->compare(BCRYPT_ECDSA_P256_ALGORITHM) == 0 ||
            algName->compare(BCRYPT_ECDSA_P384_ALGORITHM) == 0 ||
            algName->compare(BCRYPT_ECDSA_P521_ALGORITHM) == 0 ||
            algName->compare(BCRYPT_ECDH_P256_ALGORITHM) == 0 ||
            algName->compare(BCRYPT_ECDH_P384_ALGORITHM) == 0 ||
            algName->compare(BCRYPT_ECDH_P521_ALGORITHM) == 0 ||
            algName->compare(BCRYPT_ECDSA_ALGORITHM) == 0) {
            blobType = BCRYPT_ECCPUBLIC_BLOB;
        }
        else {
            std::string algNameA(algName->begin(), algName->end()); // convert to string
            THROW_EXCEPTION("Unsupported algorithm '%s'", algNameA.c_str());
        }

        Scoped<Buffer> blobBuffer = bKey->Export(blobType);

        Scoped<ncrypt::Key> nKey(new ncrypt::Key);
        nKey->Import(blobType, blobBuffer);
#pragma endregion

        Scoped<CryptoKey> cryptoKey(new CryptoKey);
        cryptoKey->key = nKey;

        return cryptoKey;

    }
    CATCH_EXCEPTION
}

CryptoKey::CryptoKey() :
    key(NULL),
    info(NULL)
{
}

CryptoKey::CryptoKey(Scoped<Handle<HCRYPTPROV_OR_NCRYPT_KEY_HANDLE>> key):
    CryptoKey()
{
    this->key = key;
}

CryptoKey::CryptoKey(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE handle, DWORD dwKeySpec) :
    CryptoKey()
{
    if (NCryptIsKeyHandle(handle)) {
        // CNG
        key = Scoped<ncrypt::Key>(new ncrypt::Key(handle));
    }
    else {
        key = Scoped<crypt::Key>(new crypt::Key(handle));

#pragma region try to convert CAPI to CNG
        NTSTATUS status = 0;
        NCRYPT_KEY_HANDLE hNKey = NULL;
        status = NCryptTranslateHandle(NULL, &hNKey, handle, NULL, dwKeySpec, 0);
        if (!status) {
            key = Scoped<ncrypt::Key>(new ncrypt::Key(hNKey));
        }
#pragma endregion
    }
}

CryptoKey::CryptoKey(Scoped<crypt::ProviderInfo> info) :
    CryptoKey()
{
    this->info = info;
}

BOOL CryptoKey::IsCNG()
{
    return NCryptIsKeyHandle(Get());
}

HCRYPTPROV_OR_NCRYPT_KEY_HANDLE CryptoKey::Get()
{
    LOGGER_FUNCTION_BEGIN;

    try {
        NTSTATUS status = 0;

        if (!key.get()) {
            HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hKey = NULL;
            PCRYPT_KEY_PROV_INFO provInfo = info->Get();

            if (provInfo->dwProvType) {
                // CAPI
                Scoped<crypt::Key> ckey(new crypt::Key);
                ckey->Open(provInfo);
                hKey = ckey->Get();

#pragma region try to convert CAPI to CNG
                NCRYPT_KEY_HANDLE hNKey = NULL;
                status = NCryptTranslateHandle(NULL, &hNKey, hKey, NULL, provInfo->dwKeySpec, 0);
                if (!status) {
                    key = Scoped<ncrypt::Key>(new ncrypt::Key(hNKey));
                }
                else {
                    key = ckey;
                }
#pragma endregion
            }
            else {
                // CNG
                Scoped<ncrypt::Key> nkey(new ncrypt::Key);
                nkey->Open(provInfo);

                key = nkey;
            }
        }

        return key->Get();
    }
    CATCH_EXCEPTION
}

DWORD CryptoKey::GetKeySpec()
{
    LOGGER_FUNCTION_BEGIN;

    try {
        if (info.get()) {
            // ProvInfo
            return info->Get()->dwKeySpec;
        }
        else if (IsCNG()) {
            return AT_KEYEXCHANGE;
        }
        else {
            // CAPI
            return GetCKey()->GetNumber(PP_KEYSPEC);
        }
    }
    CATCH_EXCEPTION
}

Scoped<Buffer> CryptoKey::GetID()
{
    LOGGER_FUNCTION_BEGIN;

    try {
        Scoped<Buffer> spki(new Buffer(0));
        DWORD dwSpkiLen = 0;

        auto pubKeyInfo = ExportPublicKeyInfo(Get());

        return DIGEST_SHA1(pubKeyInfo->PublicKey.pbData, pubKeyInfo->PublicKey.cbData);
    }
    CATCH_EXCEPTION
}

crypt::Key * CryptoKey::GetCKey()
{
    LOGGER_FUNCTION_BEGIN;

    try {
        Get();

        crypt::Key* res = dynamic_cast<crypt::Key*>(key.get());
        if (!res) {
            THROW_EXCEPTION("Key is not CAPI");
        }

        return res;
    }
    CATCH_EXCEPTION
}

ncrypt::Key * CryptoKey::GetNKey()
{
    LOGGER_FUNCTION_BEGIN;

    try {
        Get();

        ncrypt::Key* res = dynamic_cast<ncrypt::Key*>(key.get());
        if (!res) {
            THROW_EXCEPTION("Key is not CNG");
        }

        return res;
    }
    CATCH_EXCEPTION
}


text:
package com.sebastian.sokolowski.auctionhunter.main.views;

import android.content.Context;
import android.graphics.Canvas;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.ItemTouchHelper;
import android.util.AttributeSet;

import com.sebastian.sokolowski.auctionhunter.main.adapter.MainAdapter;

/**
 * Created by Sebastian Sokołowski on 02.03.17.
 */

public class SliderRecyclerView extends RecyclerView {
    private static final String TAG = SliderRecyclerView.class.getSimpleName();

    public SliderRecyclerView(Context context) {
        super(context);
        initSwipe();
    }

    public SliderRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initSwipe();
    }

    public SliderRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initSwipe();
    }

    private void initSwipe() {
        ItemTouchHelper.Callback simpleCallback = new ItemTouchHelper.Callback() {

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

            @Override
            public int getMovementFlags(RecyclerView recyclerView, ViewHolder viewHolder) {
                int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
                return makeMovementFlags(dragFlags, swipeFlags);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, ViewHolder viewHolder, ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(ViewHolder viewHolder, int direction) {
                if (getAdapter() != null) {
                    MainAdapter mainAdapter = (MainAdapter) getAdapter();
                    mainAdapter.onItemDismiss(viewHolder.getAdapterPosition());
                }
            }

            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView,
                                    RecyclerView.ViewHolder viewHolder, float dX, float dY,
                                    int actionState, boolean isCurrentlyActive) {

                if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
                    ((MainAdapter.TargetViewHolder) viewHolder).container.setTranslationX(dX);

                } else {
                    super.onChildDraw(c, recyclerView, viewHolder, dX, dY,
                            actionState, isCurrentlyActive);
                }
            }
        };

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
        itemTouchHelper.attachToRecyclerView(this);
    }
}


text:
<?php

namespace TestsAlwaysIncluded\SymfonyConsoleBootstrapInstaller;

use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;

class PackageInstallerPlugin implements PluginInterface
{
    /**
     * Adds the package installer
     *
     * @param Composer $composer
     * @param IOInterface $inputOutput
     */
    public function activate(Composer $composer, IOInterface $inputOutput)
    {
        $packageInstaller = new PackageInstaller($inputOutput, $composer);
        $composer->getInstallationManager()->addInstaller($packageInstaller);
    }
}


text:
namespace blink {

bool IsKnownSearchEngine(const String& url) {
  GURL gurl(url.Utf8());
  if (!gurl.is_valid()) {
    return false;
  }

  return SearchEngineUtils::GetEngineType(gurl) > 0;
}

}  // namespace blink


text:
<img src="../../docs/images/header.png" width="500" >

### Header with default components

For quick setup we provide default components, which are React Native Elements Icon for left/right buttons and React Native Text for title. You can customize them with configuration objects passed in as props.

```js
<Header
  leftComponent={{ icon: 'menu', style: { color: '#fff'} }}
  centerComponent={{ text: 'MY TITLE', style: { color: '#fff' } }}
  rightComponent={{ icon: 'home', style: { color: '#fff'} }}
/>
```

### Header with custom components passed in through props

You can pass in your custom components like this too.

```js
<Header
  leftComponent={<MyCustomLeftComponent />}
  centerComponent={<MyCustomCenterComponent />}
  rightComponent={<MyCustomRightComponent />}
/>
```

### Header with mixed components

You can also mix the content, for example you can have default components defined by configuration combined with custom components. Passing a render function that returns a React Element is valid too.

```js
<Header
  leftComponent={<MyCustomLeftComponent />}
  centerComponent={this.renderCenterComponent()}
  rightComponent={{ icon: 'home', style: { color: '#fff'} }}
/>
```

### Header with custom components passed in as children

```js
<Header>
  <MyCustomLeftComponent />
  <MyCustomCenterComponent />
  <MyCustomRightComponent />
</Header>
```

### Component precedence

Components defined through props take precedence over components passed in as children, so in this case only the left component with icon set to home will be rendered.

```js
<Header
  leftComponent={{ icon: 'menu' }}
>
  <MyCustomLeftComponent />
  <MyCustomCenterComponent />
  <MyCustomRightComponent />
</Header>
```

### Header customisability

We wanted the Header to be as customisable as possible, so you are free to try different combinations of props.

```js
<Header
  statusBarProps={{ barStyle: 'light-content' }}
  leftComponent={<MyCustomLeftComponent />}
  centerComponent={{ text: 'MY TITLE', style: { color: '#fff'} }}
  outerContainerStyles={{ backgroundColor: '#3D6DCC' }}
/>
```

### Header Props

| prop | default | type | description |
| ---- | ---- | ----| ---- |
| statusBarProps | none | object (props) | accepts all props for StatusBar |
| leftComponent | none | configuration object for default component (icon: string, ...props for React Native Elements Icon) or a valid React Element | define your left component here |
| centerComponent | none | configuration object for default component (text: string, ...props for React Native Text component) valid React Element | define your center component here |
| rightComponent | none | configuration object for default component (icon: string, ...props for React Native Elements Icon component) or a valid React Element | define your right component here |
| backgroundColor | none | string | sets backgroundColor of the parent component |
| outerContainerStyles | none | object (style) | styling for outer container |
| innerContainerStyles | none | object (style) | styling for inner container |


text:
<?php

/**
 * @see https://developers.podio.com/doc/hooks
 */
class PodioHook extends PodioObject
{
    public function __construct($podio, $attributes = array())
    {
        parent::__construct($podio);
        $this->property('hook_id', 'integer', array('id' => true));
        $this->property('status', 'string');
        $this->property('type', 'string');
        $this->property('url', 'string');
        $this->property('created_on', 'datetime');

        $this->has_one('created_by', 'ByLine');
        $this->has_one('created_via', 'Via');

        $this->init($attributes);
    }

    /**
     * @see https://developers.podio.com/doc/hooks/get-hooks-215285
     */
    public function get_for($ref_type, $ref_id)
    {
        return $this->listing($this->podio->get("/hook/{$ref_type}/{$ref_id}/"));
    }

    /**
     * @see https://developers.podio.com/doc/hooks/create-hook-215056
     */
    public function create($ref_type, $ref_id, $attributes = array())
    {
        $body = $this->podio->post("/hook/{$ref_type}/{$ref_id}/", $attributes)->json_body();
        return $body['hook_id'];
    }

    /**
     * @see https://developers.podio.com/doc/hooks/request-hook-verification-215232
     */
    public function verify($hook_id)
    {
        return $this->podio->post("/hook/{$hook_id}/verify/request")->json_body();
    }

    /**
     * @see https://developers.podio.com/doc/hooks/validate-hook-verification-215241
     */
    public function validate($hook_id, $attributes = array())
    {
        return $this->podio->post("/hook/{$hook_id}/verify/validate", $attributes)->json_body();
    }

    /**
     * @see https://developers.podio.com/doc/hooks/delete-hook-215291
     */
    public function delete($hook_id)
    {
        return $this->podio->delete("/hook/{$hook_id}");
    }

}


text:
/**
 * USAGE:
 *
 * jStorage requires Prototype, MooTools or jQuery! If jQuery is used, then
 * jQuery-JSON (http://code.google.com/p/jquery-json/) is also needed.
 * (jQuery-JSON needs to be loaded BEFORE jStorage!)
 *
 * Methods:
 *
 * -set(key, value)
 * $.jStorage.set(key, value) -> saves a value
 *
 * -get(key[, default])
 * value = $.jStorage.get(key [, default]) ->
 *    retrieves value if key exists, or default if it doesn't
 *
 * -deleteKey(key)
 * $.jStorage.deleteKey(key) -> removes a key from the storage
 *
 * -flush()
 * $.jStorage.flush() -> clears the cache
 *
 * <value> can be any JSON-able value, including objects and arrays.
 *
 */

(function($){
	if(!$ || !($.toJSON || Object.toJSON || window.JSON)){
		throw new Error("jQuery, MooTools or Prototype needs to be loaded before jStorage!");
	}

	var
		/* This is the object, that holds the cached values */
		_storage = {},

		/* Actual browser storage (localStorage or globalStorage['domain']) */
		_storage_service = {jStorage:"{}"},

		/* DOM element for older IE versions, holds userData behavior */
		_storage_elm = null,

		/* function to encode objects to JSON strings */
		json_encode = $.toJSON || Object.toJSON || (window.JSON && (JSON.encode || JSON.stringify)),

		/* function to decode objects from JSON strings */
		json_decode = $.evalJSON || (window.JSON && (JSON.decode || JSON.parse)) || function(str){
			return String(str).evalJSON();
		};

	////////////////////////// PRIVATE METHODS ////////////////////////

	/**
	 * Initialization function. Detects if the browser supports DOM Storage
	 * or userData behavior and behaves accordingly.
	 * @returns undefined
	 */
	function _init(){
		/* Check if browser supports localStorage */
		if(window.localStorage){
			try {
				_storage_service = window.localStorage;
			} catch(E0) {/* Firefox fails when touching localStorage and cookies are disabled */}
		}
		/* Check if browser supports globalStorage */
		else if(window.globalStorage){
			try {
				_storage_service = window.globalStorage[window.location.hostname];
			} catch(E1) {/* Firefox fails when touching localStorage and cookies are disabled */}
		}
		/* Check if browser supports userData behavior */
		else {
			_storage_elm = document.createElement('link');
			if(_storage_elm.addBehavior){

				/* Use a DOM element to act as userData storage */
				_storage_elm.style.behavior = 'url(#default#userData)';

				/* userData element needs to be inserted into the DOM! */
				document.getElementsByTagName('head')[0].appendChild(_storage_elm);

				_storage_elm.load("jStorage");
				var data = "{}";
				try{
					data = _storage_elm.getAttribute("jStorage");
				}catch(E2){}
				_storage_service.jStorage = data;
			}else{
				_storage_elm = null;
				return;
			}
		}

		/* if jStorage string is retrieved, then decode it */
		if(_storage_service.jStorage){
			try{
				_storage = json_decode(_storage_service.jStorage);
			}catch(E3){_storage_service.jStorage = "{}";}
		}else{
			_storage_service.jStorage = "{}";
		}
	}

	/**
	 * This functions provides the "save" mechanism to store the jStorage object
	 * @returns undefined
	 */
	function _save(){
		try{
			_storage_service.jStorage = json_encode(_storage);
			// If userData is used as the storage engine, additional
			if(_storage_elm) {
				_storage_elm.setAttribute("jStorage",_storage_service.jStorage);
				_storage_elm.save("jStorage");
			}
		}catch(E4){/* probably cache is full, nothing is saved this way*/}
	}

	/**
	 * Function checks if a key is set and is string or numberic
	 */
	function _checkKey(key){
		if(!key || (typeof key != "string" && typeof key != "number")){
			throw new TypeError('Key name must be string or numeric');
		}
		return true;
	}

	////////////////////////// PUBLIC INTERFACE /////////////////////////

	$.jStorage = {
		/* Version number */
		version: "0.1.3",

		/**
		 * Sets a key's value.
		 *
		 * @param {String} key - Key to set. If this value is not set or not
		 *				a string an exception is raised.
		 * @param value - Value to set. This can be any value that is JSON
		 *				compatible (Numbers, Strings, Objects etc.).
		 * @returns the used value
		 */
		set: function(key, value){
			_checkKey(key);
			_storage[key] = value;
			_save();
			return value;
		},

		/**
		 * Looks up a key in cache
		 *
		 * @param {String} key - Key to look up.
		 * @param {mixed} def - Default value to return, if key didn't exist.
		 * @returns the key value, default value or <null>
		 */
		get: function(key, def){
			_checkKey(key);
			if(key in _storage){
				return _storage[key];
			}
			return typeof(def) == 'undefined' ? null : def;
		},

		/**
		 * Deletes a key from cache.
		 *
		 * @param {String} key - Key to delete.
		 * @returns true if key existed or false if it didn't
		 */
		deleteKey: function(key){
			_checkKey(key);
			if(key in _storage){
				delete _storage[key];
				_save();
				return true;
			}
			return false;
		},

		/**
		 * Deletes everything in cache.
		 *
		 * @returns true
		 */
		flush: function(){
			_storage = {};
			_save();
			/*
			 * Just to be sure - andris9/jStorage#3
			 */
			if (window.localStorage){
				try{
					localStorage.clear();
				}catch(E5){}
			}
			return true;
		},

		/**
		 * Returns a read-only copy of _storage
		 *
		 * @returns Object
		*/
		storageObj: function(){
			function F() {}
			F.prototype = _storage;
			return new F();
		}
	};

	// Initialize jStorage
	_init();

})(window.jQuery || window.$);


text:
SHELL=/bin/bash
export PATH := ./node_modules/.bin/:$(PATH):./bin/

PACKAGE = asyncjs
REQUIRE_NAME = async
UGLIFY = uglifyjs
XYZ = support/xyz.sh --repo git@github.com:caolan/async.git
COPY_ES = sed -E "s/(import.+)lodash/\1lodash-es/g"

BUILDDIR = build
BUILD_ES = build-es
DIST = dist
JS_INDEX = lib/index.js
SCRIPTS = ./support
JS_SRC = $(shell find lib/ -type f -name '*.js') lib/index.js
INDEX_SRC = $(shell find lib/ -type f -name '*.js' | grep -v 'index') $(SCRIPTS)/index-template.js $(SCRIPTS)/aliases.json ${SCRIPTS}/generate-index.js
LINT_FILES = lib/ mocha_test/ $(shell find perf/ -maxdepth 2 -type f) $(shell find support/ -maxdepth 2 -type f -name "*.js") karma.conf.js

UMD_BUNDLE = $(BUILDDIR)/dist/async.js
UMD_BUNDLE_MIN = $(BUILDDIR)/dist/async.min.js
UMD_BUNDLE_MAP = $(BUILDDIR)/dist/async.min.map
ALIAS_ES = $(shell node $(SCRIPTS)/list-aliases.js build-es/)
ES_MODULES = $(patsubst lib/%.js, build-es/%.js,  $(JS_SRC)) $(ALIAS_ES)
ALIAS_CJS = $(shell node $(SCRIPTS)/list-aliases.js build/)
CJS_MODULES = $(patsubst lib/%.js, build/%.js,  $(JS_SRC)) $(ALIAS_CJS)

all: clean lint build test

test:
	npm test

clean:
	rm -rf $(BUILDDIR)
	rm -rf $(BUILD_ES)
	rm -rf $(DIST)
	rm -rf $(JS_INDEX)
	rm -rf tmp/ docs/ .nyc_output/ coverage/
	rm -rf perf/versions/

lint:
	eslint $(LINT_FILES)

# Compile the ES6 modules to singular bundles, and individual bundles
build-bundle: build-modules $(UMD_BUNDLE)

build-modules: $(CJS_MODULES)

$(JS_INDEX): $(INDEX_SRC)
	node $(SCRIPTS)/generate-index.js > $@

$(BUILDDIR)/%.js: lib/%.js
	mkdir -p "$(@D)"
	node $(SCRIPTS)/build/compile-module.js --file $< --output $@

define COMPILE_ALIAS
$A: $(shell node $(SCRIPTS)/get-alias.js $A)
	mkdir -p "$$(@D)"
	node $(SCRIPTS)/build/compile-module.js --file $$< --output $$@
endef
$(foreach A,$(ALIAS_CJS),$(eval $(COMPILE_ALIAS)))

$(UMD_BUNDLE): $(ES_MODULES) package.json
	mkdir -p "$(@D)"
	node $(SCRIPTS)/build/aggregate-bundle.js

# Create the minified UMD versions and copy them to dist/ for bower
build-dist: $(DIST) $(DIST)/async.js $(DIST)/async.min.js $(DIST)/async.min.map

$(DIST):
	mkdir -p $@

$(UMD_BUNDLE_MIN): $(UMD_BUNDLE)
	mkdir -p "$(@D)"
	$(UGLIFY) $< --mangle --compress \
		--source-map $(UMD_BUNDLE_MAP) \
		--source-map-url async.min.map \
		-o $@

$(DIST)/async.js: $(UMD_BUNDLE)
	cp $< $@

$(DIST)/async.min.js: $(UMD_BUNDLE_MIN)
	cp $< $@

$(DIST)/async.min.map: $(UMD_BUNDLE_MIN)
	cp $(UMD_BUNDLE_MAP) $@

build-es: $(ES_MODULES)

$(BUILD_ES)/%.js: lib/%.js
	mkdir -p "$(@D)"
	$(COPY_ES) $< > $@

define COPY_ES_ALIAS
$A: $(shell node $(SCRIPTS)/get-alias.js $A)
	mkdir -p "$$(@D)"
	$(COPY_ES) $$< > $$@
endef
$(foreach A,$(ALIAS_ES),$(eval $(COPY_ES_ALIAS)))

test-build: $(UMD_BUNDLE) $(UMD_BUNDLE_MIN)
	mocha support/build.test.js

build-config: $(BUILDDIR)/package.json $(BUILDDIR)/bower.json $(BUILDDIR)/README.md $(BUILDDIR)/LICENSE $(BUILDDIR)/CHANGELOG.md

build-es-config: $(BUILD_ES)/package.json $(BUILD_ES)/README.md $(BUILD_ES)/LICENSE $(BUILD_ES)/CHANGELOG.md

$(BUILDDIR)/package.json: package.json
	mkdir -p "$(@D)"
	support/sync-cjs-package.js > $@

$(BUILDDIR)/%: %
	mkdir -p "$(@D)"
	cp $< $@

$(BUILD_ES)/package.json: package.json
	mkdir -p "$(@D)"
	support/sync-es-package.js > $@

$(BUILD_ES)/README.md: README.es.md
	mkdir -p "$(@D)"
	cp $< $@

$(BUILD_ES)/%: %
	mkdir -p "$(@D)"
	cp $< $@

.PHONY: build-modules build-bundle build-dist build-es build-config build-es-config test-build

build: build-bundle build-dist build-es build-config build-es-config test-build

.PHONY: test lint build all clean

.PHONY: release-major release-minor release-patch release-prerelease
release-major release-minor release-patch release-prerelease: all
	npm i # ensure dependencies are up to date (#1158)
	git add --force $(DIST)
	git commit -am "Update built files"; true
	$(XYZ) --increment $(@:release-%=%)
	# build again to propagate the version
	$(MAKE) build-config
	$(MAKE) build-es-config
	cd build/ && npm publish
	cd build-es/ && npm publish
	$(MAKE) publish-doc

.PHONY: doc publish-doc
doc:
	jsdoc -c ./support/jsdoc/jsdoc.json
	node support/jsdoc/jsdoc-fix-html.js

publish-doc: doc
	git diff-files --quiet # fail if unstanged changes
	git diff-index --quiet HEAD # fail if uncommited changes
	npm run-script jsdoc
	gh-pages-deploy