text:
@interface YXJSlideBarItem ()

@property (copy, nonatomic) NSString *title;
@property (assign, nonatomic) CGFloat fontSize;
@property (assign, nonatomic) CGFloat selectedFontSize;
@property (strong, nonatomic) UIColor *color;
@property (strong, nonatomic) UIColor *selectedColor;

@end

@implementation YXJSlideBarItem

#pragma mark - Lifecircle

- (instancetype) init {
    if (self = [super init]) {
        _fontSize = DEFAULT_TITLE_FONTSIZE;
        _selectedFontSize = DEFAULT_TITLE_SELECTED_FONTSIZE;
        _color = DEFAULT_TITLE_COLOR;
        _selectedColor = DEFAULT_TITLE_SELECTED_COLOR;

        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    CGFloat titleX = (CGRectGetWidth(self.frame) - [self titleSize].width) * 0.5;
    CGFloat titleY = (CGRectGetHeight(self.frame) - [self titleSize].height) * 0.5;

    CGRect titleRect = CGRectMake(titleX, titleY, [self titleSize].width, [self titleSize].height);
    NSDictionary *attributes = @{NSFontAttributeName : [self titleFont], NSForegroundColorAttributeName : [self titleColor]};
    [_title drawInRect:titleRect withAttributes:attributes];
}

#pragma mark - Custom Accessors

- (void)setSelected:(BOOL)selected {
    _selected = selected;
    [self setNeedsDisplay];
}

#pragma mark - Public

- (void)setItemTitle:(NSString *)title {
    _title = title;
    [self setNeedsDisplay];
}

- (void)setItemTitleFont:(CGFloat)fontSize {
    _fontSize = fontSize;
    [self setNeedsDisplay];
}

- (void)setItemSelectedTileFont:(CGFloat)fontSize {
    _selectedFontSize = fontSize;
    [self setNeedsDisplay];
}

- (void)setItemTitleColor:(UIColor *)color {
    _color = color;
    [self setNeedsDisplay];
}

- (void)setItemSelectedTitleColor:(UIColor *)color {
    _selectedColor = color;
    [self setNeedsDisplay];
}

#pragma mark - Private

- (CGSize)titleSize {
    NSDictionary *attributes = @{NSFontAttributeName : [self titleFont]};
    CGSize size = [_title boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    size.width = ceil(size.width);
    size.height = ceil(size.height);

    return size;
}

- (UIFont *)titleFont {
    UIFont *font;
    if (_selected) {
        font = [UIFont boldSystemFontOfSize:_selectedFontSize];
    } else {
        font = [UIFont systemFontOfSize:_fontSize];
    }
    return font;
}

- (UIColor *)titleColor {
    UIColor *color;
    if (_selected) {
        color = _selectedColor;
    } else {
        color = _color;
    }
    return color;
}

#pragma mark - Public Class Method

+ (CGFloat)widthForTitle:(NSString *)title {
    NSDictionary *attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:DEFAULT_TITLE_FONTSIZE]};
    CGSize size = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    size.width = ceil(size.width) + HORIZONTAL_MARGIN * 2;

    return size.width;
}

#pragma mark - Responder

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self.selected = YES;
    if (self.delegate && [self.delegate respondsToSelector:@selector(slideBarItemSelected:)]) {
        [self.delegate slideBarItemSelected:self];
    }
}

@end


text:
<?php

namespace Nve\Constants;

abstract class Url
{
    const BASEURL            = "http://api01.nve.no/hydrology/forecast/avalanche/v1.0.0/api/";
    const REGION_URL         = "AvalancheWarningByRegion/%s/%s/%s";// {details}/{region}/{language}
    const COORD_URL          = "AvalancheWarningByCoordinates/%s/%s/%s/%s"; // {details}/{latitude}/{longitude}/{language}
    const START_END_DATE_URL = "/%s/%s"; // {startdate}/{enddate}
    const START_DATE_URL     = "/%s";
    const SUMMARY_URL        = "RegionSummary/%s"; // {details}

}

redpajama_set_name: RedPajamaGithub


text:
"""
Implementation for `pmg potcar` CLI.
"""

import os

from pymatgen.io.vasp import Potcar

def proc_dir(dirname, procfilefunction):
    """
    Process a directory.

    Args:
        dirname (str): Directory name.
        procfilefunction (callable): Callable to execute on directory.
    """
    for f in os.listdir(dirname):
        if os.path.isdir(os.path.join(dirname, f)):
            proc_dir(os.path.join(dirname, f), procfilefunction)
        else:
            procfilefunction(dirname, f)

def gen_potcar(dirname, filename):
    """
    Generate POTCAR from POTCAR.spec in directories.

    Args:
        dirname (str): Directory name.
        filename (str): Filename in directory.
    """
    if filename == "POTCAR.spec":
        fullpath = os.path.join(dirname, filename)
        with open(fullpath, "r") as f:
            elements = f.readlines()
        symbols = [el.strip() for el in elements if el.strip() != ""]
        potcar = Potcar(symbols)
        potcar.write_file(os.path.join(dirname, "POTCAR"))

def generate_potcar(args):
    """
    Generate POTCAR.

    Args:
        args (dict): Args from argparse.
    """
    if args.recursive:
        proc_dir(args.recursive, gen_potcar)
    elif args.symbols:
        try:
            p = Potcar(args.symbols, functional=args.functional)
            p.write_file("POTCAR")
        except Exception as ex:
            print("An error has occurred: {}".format(str(ex)))

    else:
        print("No valid options selected.")

if __name__ == "__main__":
    proc_dir(os.getcwd(), gen_potcar)


text:
<?php

namespace PragmaRX\Health\Support;

use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use JsonSerializable;
use PragmaRX\Health\Commands;
use PragmaRX\Health\Events\RaiseHealthIssue;
use PragmaRX\Health\Support\Traits\ImportProperties;
use PragmaRX\Health\Support\Traits\ToArray;
use Ramsey\Uuid\Uuid;

class Resource implements JsonSerializable
{
    use ToArray, ImportProperties;

    /**
     * @var string
     */
    public $id;

    /**
     * @var string
     */
    public $name;

    /**
     * @var string
     */
    public $slug;

    /**
     * @var string
     */
    public $abbreviation;

    /**
     * @var bool
     */
    public $isGlobal;

    /**
     * @var string
     */
    public $errorMessage;

    /**
     * @var array
     */
    public $style;

    /**
     * @var bool
     */
    public $notify;

    /**
     * @var Collection
     */
    public $targets;

    /**
     * @var ResourceChecker
     */
    public $checker;

    /**
     * @var Collection
     */
    public $resources;

    /**
     * @var bool
     */
    protected $notified;

    /**
     * @var string
     */
    protected $currentAction;

    /**
     * @var string
     */
    protected $currentCaller;

    /**
     * @var bool|null
     */
    protected $graphEnabled = null;

    /**
     * @var string
     */
    public $executable;

    /**
     * @var string
     */
    public $internal_error;

    /**
     * Resource factory.
     *
     * @param  Collection  $data
     * @return resource
     *
     * @throws \Exception
     */
    public static function factory(Collection $data)
    {
        $instance = new static();

        $instance->id = (string) Uuid::uuid4();

        $instance->name = $data['name'];

        $instance->slug = Str::slug($data['name']);

        try {
            $instance->graphEnabled = isset($data['graph_enabled'])
                ? $data['graph_enabled']
                : null;

            $instance->abbreviation = $data['abbreviation'];

            $instance->targets = $instance->instantiateTargets(
                $data['targets'] ?? collect()
            );

            $instance->notify =
                $data['notify'] ?? config('health.notifications.enabled');

            $instance->style = $instance->keysToCamel(config('health.style'));

            $instance->style['columnSize'] =
                $data['column_size'] ?? $instance->style['columnSize'];

            $instance->errorMessage =
                $data['error_message'] ?? config('health.errors.message');

            $instance->isGlobal = $data['is_global'] ?? false;

            $instance->checker = $instance->instantiateChecker($data['checker']);

            $instance->executable = isset($data['executable']) ? $data['executable'] : null;

            $instance->importProperties($data);
        } catch (\Throwable $exception) {
            $instance->internal_error = 'Error instantiating resource: '.$exception->getMessage().'. Please check the resource configuration file.';
        }

        return $instance;
    }

    /**
     * Instantiate all checkers for a resource.
     *
     * @param  Collection  $targets
     * @return Collection|\IlluminateAgnostic\Arr\Support\Collection|\IlluminateAgnostic\Collection\Support\Collection|\IlluminateAgnostic\Str\Support\Collection|mixed|\Tightenco\Collect\Support\Collection|\Vanilla\Support\Collection
     */
    public function instantiateTargets(Collection $targets)
    {
        if ($targets->isEmpty()) {
            return collect([Target::factory($this, $targets)]);
        }

        $current = collect();

        $targets = $targets
            ->map(function (Collection $targetList) {
                return $targetList->map(function ($target, $name) {
                    return Target::factory($this, $target, $name);
                });
            })
            ->reduce(function ($current, $targetList) {
                foreach ($targetList as $target) {
                    $current[] = $target;
                }

                return $current;
            }, $current);

        return $targets;
    }

    /**
     * Instantiate one checker.
     *
     * @param  string  $checker
     * @return object
     */
    public function instantiateChecker(string $checker)
    {
        return instantiate($checker);
    }

    /**
     * Check all targets for a resource.
     *
     * @param  string  $action
     * @param  string  $caller
     * @return resource
     */
    public function check($action = 'resource', $caller = 'console')
    {
        $this->setCurrentAction($action)
             ->setCurrentCaller($caller)
            ->targets->each(function (
            Target $target
        ) {
                $target->check($target);
            });

        $this->notify();

        return $this;
    }

    /**
     * Check global resources.
     *
     * @param $resources
     * @return resource
     */
    public function checkGlobal($resources)
    {
        return $this->setResources($resources)->check();
    }

    /**
     * Check if is healthy.
     *
     * @return mixed
     */
    public function isHealthy()
    {
        return $this->targets->reduce(function ($carry, $target) {
            return $carry && $target->result->healthy;
        }, true);
    }

    /**
     * Check status of the resource (overall).
     *
     * @return mixed
     */
    public function getStatus()
    {
        $exitCode = Commands::EXIT_CODES[result::OK];
        $this->targets->each(function ($target) use (&$exitCode) {
            // Handles exit codes based on the result's status.
            $thisStatus = $target->result->getStatus();
            $thisExitCode = Commands::EXIT_CODES[$thisStatus];
            // An exit code with a greater value should be preferred as the output.
            if ($thisExitCode > $exitCode) {
                $exitCode = $thisExitCode;
            }
        });

        return array_flip(Commands::EXIT_CODES)[$exitCode];
    }

    protected function keysToCamel($array)
    {
        return collect($array)->mapWithKeys(function ($item, $key) {
            return [Str::camel($key) => $item];
        });
    }

    /**
     * Notify about health problems.
     */
    protected function notify()
    {
        if ($this->canNotify()) {
            $this->sendNotifications();
        }
    }

    /**
     * Send notifications.
     *
     * @return static
     */
    protected function sendNotifications()
    {
        return collect(config('health.notifications.channels'))->each(function (
            $channel
        ) {
            try {
                event(new RaiseHealthIssue($this, $channel));
            } catch (\Exception $exception) {
                report($exception);
            }
        });
    }

    /**
     * Can we notify about errors on this resource?
     *
     * @return bool
     */
    protected function canNotify()
    {
        return
            ! $this->notified &&
            $this->notificationsAreEnabled() &&
            ! $this->isHealthy();
    }

    /**
     * Is notification enabled for this resource?
     *
     * @return bool
     */
    protected function notificationsAreEnabled()
    {
        return
            $this->notify &&
            config('health.notifications.enabled') &&
            config('health.notifications.notify_on.'.$this->currentAction) &&
            config('health.notifications.notify_from.'.$this->currentCaller, true);
    }

    /**
     * Set current action.
     *
     * @param  string  $currentAction
     * @return resource
     */
    public function setCurrentAction(string $currentAction)
    {
        $this->currentAction = $currentAction;

        return $this;
    }

    /**
     * Set current caller.
     *
     * @param  string  $currentCaller
     * @return resource
     */
    public function setCurrentCaller(string $currentCaller)
    {
        $this->currentCaller = $currentCaller;

        return $this;
    }

    /**
     * Resources setter.
     *
     * @param $resources
     * @return resource
     */
    protected function setResources($resources)
    {
        $this->resources = $resources;

        return $this;
    }

    /**
     * Object to json.
     *
     * @return false|string
     */
    public function __toString()
    {
        return json_encode($this->__toArray($this, 6));
    }

    /**
     * Prepare the resource for JSON serialization.
     *
     * @return string
     */
    public function jsonSerialize()
    {
        return json_decode($this->__toString(), true);
    }
}


text:
package com.rng.site.web.controllers;

import com.rng.entities.Results;
import com.rng.site.service.ResultService;
import com.rng.site.service.SampleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * Created by MoldovanM2 on 7/7/2017.
 */
@Controller
public class ResultController extends SiteBaseController{

    @Autowired
    private ResultService resultService;
    @Autowired
    private SampleService sampleService;

    @Override
    protected String getHeaderTitle()
    {
        return "Results";
    }

    @RequestMapping(value="/results", method= RequestMethod.GET)
    protected String result(Model model)
    {
        List<Results> results=resultService.getAllResults();
        model.addAttribute("results", results);
        return "result";
    }

    @RequestMapping(value="/result/{sample_id}", method= RequestMethod.GET)
    protected String result_sample(@PathVariable Integer sample_id,Model model)
    {
        List<Results> results=resultService.getAllResultsBySample(sample_id);
        model.addAttribute("results", results);
        return "result";
    }

    @RequestMapping(value="/result", method= RequestMethod.GET)
    protected String result_category(@RequestParam(name="category_id", defaultValue="") Integer category_id,@RequestParam(name="sample_id", defaultValue="") Integer sample_id, Model model)
    {
        List<Results> results=resultService.getAllResultsBySampleAndCategory(category_id,sample_id);
        model.addAttribute("results", results);
        return "result";
    }

}


text:
@interface WechatShortVideoController () <SCRecorderDelegate, SCAssetExportSessionDelegate, MBProgressHUDDelegate>
@property (weak, nonatomic) IBOutlet UIView *scanPreviewView;
@property (weak, nonatomic) IBOutlet UIView *operatorView;
@property (weak, nonatomic) IBOutlet UIButton *captureTipBtn;
@property (weak, nonatomic) IBOutlet UIView *middleTipView;
@property (weak, nonatomic) IBOutlet UILabel *middleOperatorTip;
@property (weak, nonatomic) IBOutlet UIButton *captureRealBtn;
@property (strong, nonatomic) SCRecorderToolsView *focusView;
@property (weak, nonatomic) IBOutlet UIView *middleProgressView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *middleProgressViewWidthConstraint;
@property (strong, nonatomic) NSTimer *exportProgressBarTimer;
@property (strong, nonatomic) MBProgressHUD *progressHUD;

@end

@implementation WechatShortVideoController {
    BOOL captureValidFlag;
    SCRecorder *_recorder;
    SCRecordSession *_recordSession;
    NSTimer *longPressTimer;

    //Preview
    SCPlayer *_player;

    //Video filepath
    NSURL *VIDEO_OUTPUTFILE;
}

@synthesize delegate;

#pragma mark - Do Next Func
- (void)doNextWhenVideoSavedSuccess {
    //file path is VIDEO_OUTPUTFILE

}

- (IBAction)closeAction:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    VIDEO_OUTPUTFILE = [NSURL fileURLWithPath:[PATH_OF_DOCUMENT stringByAppendingPathComponent:VIDEO_DEFAULTNAME]];

    captureValidFlag = NO;

    [self configRecorder];
    [self configControlStyle];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self prepareSession];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [_recorder previewViewFrameChanged];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [_recorder startRunning];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_recorder stopRunning];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    _recorder.previewView = nil;
    [_player pause];
    _player = nil;
}

#pragma mark - View Config
- (void)configRecorder {
    _recorder = [SCRecorder recorder];
    _recorder.captureSessionPreset = [SCRecorderTools bestCaptureSessionPresetCompatibleWithAllDevices];
    _recorder.maxRecordDuration = CMTimeMake(30 * VIDEO_MAX_TIME, 30);
    _recorder.delegate = self;
    _recorder.autoSetVideoOrientation = YES;

    UIView *previewView = self.scanPreviewView;
    _recorder.previewView = previewView;

    self.focusView = [[SCRecorderToolsView alloc] initWithFrame:previewView.bounds];
    self.focusView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
    self.focusView.recorder = _recorder;
    [previewView addSubview:self.focusView];

    self.focusView.outsideFocusTargetImage = [UIImage imageNamed:@"WechatShortVideo_scan_focus"];
    _recorder.initializeSessionLazily = NO;

    NSError *error;
    if (![_recorder prepare:&error]) {
        NSLog(@"Prepare error: %@", error.localizedDescription);
    }
}

- (void)configControlStyle {
    self.middleProgressView.backgroundColor = NORMAL_TIPCOLOR;
    [self.captureTipBtn setTitleColor:NORMAL_TIPCOLOR forState:UIControlStateNormal];
    self.captureTipBtn.layer.borderColor = [NORMAL_TIPCOLOR CGColor];
    [self.captureTipBtn setTitle:RECORD_BTN_TITLE forState:UIControlStateNormal];
}

- (void)prepareSession {
    if (_recorder.session == nil) {

        SCRecordSession *session = [SCRecordSession recordSession];
        session.fileType = AVFileTypeQuickTimeMovie;

        _recorder.session = session;
    }
}

- (void)initialProgressView {
    self.middleProgressViewWidthConstraint.constant = self.middleTipView.frame.size.width;
}

- (void)refreshProgressViewLengthByTime:(CMTime)duration {
    CGFloat durationTime = CMTimeGetSeconds(duration);
    CGFloat progressWidthConstant = (VIDEO_MAX_TIME - durationTime) / VIDEO_MAX_TIME * self.middleTipView.frame.size.width;
    self.middleProgressViewWidthConstraint.constant = progressWidthConstant >= 0 ? progressWidthConstant : 0;
}

- (void)showMiddleTipView {
    [self setNormalOperatorTipStyle];
    [self initialProgressView];
    [UIView animateWithDuration:0.2 animations:^{
        self.middleTipView.alpha = 1;
    } completion:^(BOOL finished) {

    }];
}

- (void)hideMiddleTipView {
    [UIView animateWithDuration:0.2 animations:^{
        self.middleTipView.alpha = 0;
    } completion:^(BOOL finished) {

    }];
}

- (void)showCaptureBtn {
    //cancel capture and restore the capture button
    [UIView animateWithDuration:0.2 delay:0.2 options:UIViewAnimationOptionCurveEaseInOut  animations:^{
        self.captureTipBtn.transform = CGAffineTransformIdentity;
        self.captureTipBtn.alpha = 1;
    } completion:^(BOOL finished) {

    }];
}

- (void)hideCaptureBtn {
    //scale and hidden
    [UIView animateWithDuration:0.2 animations:^{
        self.captureTipBtn.transform = CGAffineTransformMakeScale(1.5, 1.5);
        self.captureTipBtn.alpha = 0;
    } completion:^(BOOL finished) {

    }];
}

- (void)setNormalOperatorTipStyle {
    self.middleOperatorTip.textColor = NORMAL_TIPCOLOR;
    self.middleOperatorTip.text = OPERATE_RECORD_TIP;
    self.middleOperatorTip.backgroundColor = [UIColor clearColor];
    self.middleProgressView.backgroundColor = NORMAL_TIPCOLOR;
}

- (void)setReleaseOperatorTipStyle {
    self.middleOperatorTip.textColor = [UIColor whiteColor];
    self.middleOperatorTip.backgroundColor = WARNING_TIPCOLOR;
    self.middleOperatorTip.text = OPERATE_CANCEL_TIP;
    self.middleProgressView.backgroundColor = WARNING_TIPCOLOR;
}

- (void)captureSuccess {
    captureValidFlag = YES;
}

- (void)cancelCaptureWithSaveFlag:(BOOL)saveFlag {
    [_recorder pause:^{
        if (saveFlag) {
            //Preview and save
            [self configPreviewMode];
        } else {
            //retake prepare
            SCRecordSession *recordSession = _recorder.session;
            if (recordSession != nil) {
                _recorder.session = nil;
                if ([[SCRecordSessionManager sharedInstance] isSaved:recordSession]) {
                    [recordSession endSegmentWithInfo:nil completionHandler:nil];
                } else {
                    [recordSession cancelSession:nil];
                }
            }
            [self prepareSession];
        }
    }];
}

#pragma mark - Record finish Preview and save
- (void)configPreviewMode {
    if ([self.scanPreviewView viewWithTag:400]) {
        return;
    }

    [self hideCaptureBtn];
    self.captureRealBtn.enabled = NO;

    _player = [SCPlayer player];
    SCVideoPlayerView *playerView = [[SCVideoPlayerView alloc] initWithPlayer:_player];
    playerView.tag = 400;
    playerView.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    playerView.frame = self.scanPreviewView.bounds;
    playerView.autoresizingMask = self.scanPreviewView.autoresizingMask;
    [self.scanPreviewView addSubview:playerView];
    _player.loopEnabled = YES;

    [_player setItemByAsset:_recorder.session.assetRepresentingSegments];
    [_player play];

    UIView *videoOperateView = [[UIView alloc] init];
    videoOperateView.alpha = 0;
    videoOperateView.tag = 400;
    videoOperateView.frame = CGRectMake(self.operatorView.frame.size.width / 2.0 - 100, self.operatorView.frame.size.height/ 2.0 - 65, 200, 130);
    videoOperateView.backgroundColor = [UIColor clearColor];

    UIButton *videoConfirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    videoConfirmBtn.frame = CGRectMake(0, 0, videoOperateView.frame.size.width, 50);
    videoConfirmBtn.layer.cornerRadius = 25;
    videoConfirmBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [videoConfirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [videoConfirmBtn setTitle:SAVE_BTN_TITLE forState:UIControlStateNormal];
    videoConfirmBtn.layer.backgroundColor = [NORMAL_TIPCOLOR CGColor];
    [videoConfirmBtn addTarget:self action:@selector(saveCapture) forControlEvents:UIControlEventTouchUpInside];

    [videoOperateView addSubview:videoConfirmBtn];

    UIButton *videoRetakeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    videoRetakeBtn.frame = CGRectMake(0, videoOperateView.frame.size.height - 50, videoOperateView.frame.size.width, 50);
    videoRetakeBtn.layer.cornerRadius = 25;
    videoRetakeBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [videoRetakeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [videoRetakeBtn setTitle:RETAKE_BTN_TITLE forState:UIControlStateNormal];
    videoRetakeBtn.layer.backgroundColor = [WARNING_TIPCOLOR CGColor];
    [videoRetakeBtn addTarget:self action:@selector(removePreviewMode) forControlEvents:UIControlEventTouchUpInside];
    [videoOperateView addSubview:videoRetakeBtn];

    [self.operatorView addSubview:videoOperateView];

    [UIView animateWithDuration:1 animations:^{
        videoOperateView.alpha = 1;
    } completion:^(BOOL finished) {
    }];
}

- (void)removePreviewMode {
    self.captureRealBtn.enabled = YES;
    [_player pause];
    _player = nil;
    for (UIView *subview in self.scanPreviewView.subviews) {
        if (subview.tag == 400) {
            [subview removeFromSuperview];
        }
    }
    for (UIView *subview in self.operatorView.subviews) {
        if (subview.tag == 400) {
            [subview removeFromSuperview];
        }
    }

    [self cancelCaptureWithSaveFlag:NO];
    [self showCaptureBtn];
}

- (void)saveCapture {
    [_player pause];

    void(^completionHandler)(NSURL *url, NSError *error) = ^(NSURL *url, NSError *error) {
        if (error == nil) {
            [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
            UISaveVideoAtPathToSavedPhotosAlbum(url.path, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
            NSString *fileName = url.lastPathComponent;
            NSString *cachePath = GJCFAppCachePath(fileName);
            NSURL *fileUrl = [NSURL fileURLWithPath:cachePath];
            [GJCFFileManager copyItemAtURL:url toURL:fileUrl error:nil];
        } else {
            self.progressHUD.labelText = [NSString stringWithFormat:@"Failed to save\n%@", error.localizedDescription];
            self.progressHUD.mode = MBProgressHUDModeCustomView;
            [self.progressHUD hide:YES afterDelay:3];
        }
    };

    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];

    SCAssetExportSession *exportSession = [[SCAssetExportSession alloc] initWithAsset:_recorder.session.assetRepresentingSegments];
    exportSession.videoConfiguration.preset = SCPresetHighestQuality;
    exportSession.audioConfiguration.preset = SCPresetHighestQuality;
    exportSession.videoConfiguration.maxFrameRate = 35;
    exportSession.outputUrl = VIDEO_OUTPUTFILE;
    exportSession.outputFileType = AVFileTypeMPEG4;
    exportSession.delegate = self;

    self.progressHUD = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    self.progressHUD.delegate = self;
    self.progressHUD.mode = MBProgressHUDModeDeterminate;

    CFTimeInterval time = CACurrentMediaTime();
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        [_player play];

        NSLog(@"Completed compression in %fs", CACurrentMediaTime() - time);

        [[UIApplication sharedApplication] endIgnoringInteractionEvents];

        completionHandler(exportSession.outputUrl, exportSession.error);
    }];
}

#pragma mark - MBProgressHUDDelegate

- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [hud removeFromSuperview];
    hud = nil;
}

#pragma mark - SCRecorderDelegate
- (void)recorder:(SCRecorder *)recorder didAppendVideoSampleBufferInSession:(SCRecordSession *)recordSession {
    //update progressBar
    [self refreshProgressViewLengthByTime:recordSession.duration];
}

- (void)recorder:(SCRecorder *__nonnull)recorder didCompleteSession:(SCRecordSession *__nonnull)session {
    //confirm capture
    [self hideMiddleTipView];
    if (captureValidFlag) {
        //preview and save video
        [self cancelCaptureWithSaveFlag:YES];
    } else {
        [self cancelCaptureWithSaveFlag:NO];
        [self showCaptureBtn];
    }
}

- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo: (void *) contextInfo {
    [[UIApplication sharedApplication] endIgnoringInteractionEvents];

    if (error == nil) {
        self.progressHUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"WechatShortVideo_37x-Checkmark.png"]];
        self.progressHUD.mode = MBProgressHUDModeCustomView;
        [self.progressHUD hide:YES afterDelay:1];

        //return the filepath
        [self removePreviewMode];
        [self doNextWhenVideoSavedSuccess];

        if ([delegate respondsToSelector:@selector(finishWechatShortVideoCapture:)]) {
            [delegate finishWechatShortVideoCapture:VIDEO_OUTPUTFILE];
        }
    } else {
        self.progressHUD.labelText = [NSString stringWithFormat:@"Failed to save\n%@", error.localizedDescription];
        self.progressHUD.mode = MBProgressHUDModeCustomView;
        [self.progressHUD hide:YES afterDelay:3];
    }
}

#pragma mark - SCAssetExportSessionDelegate
- (void)assetExportSessionDidProgress:(SCAssetExportSession *)assetExportSession {
    dispatch_async(dispatch_get_main_queue(), ^{
        float progress = assetExportSession.progress;
        self.progressHUD.progress = progress;
    });
}

#pragma mark - Center Record Btn ActionEvent
- (IBAction)captureStartDragExit:(UIButton *)captureBtn {
    [UIView transitionWithView:self.middleOperatorTip duration:0.2 options:UIViewAnimationOptionTransitionFlipFromTop animations:^{
        [self setReleaseOperatorTipStyle];
    } completion:^(BOOL finished) {

    }];
}

- (IBAction)captureStartDrayEnter:(UIButton *)captureBtn {
    [UIView transitionWithView:self.middleOperatorTip duration:0.2 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
        [self setNormalOperatorTipStyle];
    } completion:^(BOOL finished) {

    }];
}

- (IBAction)captureStartTouchUpInside:(UIButton *)captureBtn {
    //confirm capture
    [self hideMiddleTipView];
    if (captureValidFlag) {
        //preview and save video
        [self cancelCaptureWithSaveFlag:YES];
    } else {
        [self cancelCaptureWithSaveFlag:NO];
        [self showCaptureBtn];
    }
}

- (IBAction)captureStartTouchUpOutside:(UIButton *)captureBtn {
    if (self.captureRealBtn.enabled) {
        [self showCaptureBtn];
    }
    [self hideMiddleTipView];
    [self cancelCaptureWithSaveFlag:NO];
}

- (IBAction)captureStartTouchDownAction:(UIButton *)captureBtn {
    captureValidFlag = NO;
    if (longPressTimer) {
        [longPressTimer invalidate];
        longPressTimer = nil;
    }
    longPressTimer = [NSTimer scheduledTimerWithTimeInterval:VIDEO_VALID_MINTIME target:self selector:@selector(captureSuccess) userInfo:nil repeats:NO];

    [_recorder record];
    [self hideCaptureBtn];
    [self showMiddleTipView];
}

@end


text:
"""
Usage:
  models_regression.py [--num_cores=<num>]

  -h, --help             Show help text.
  -v, --version          Show version.
  --num_cores=<num>      Number of cores to be used by simulator
"""

from re import T
from docopt import docopt
import pandas as pd
import numpy as np
import os
from jinja2 import Template
import concurrent.futures
import shutil
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

def call_simulator(file_name):
    """Call simulation commands to perform simulation.
    Args:
        file_name (str): Netlist file name.
    """
    os.system(f"Xyce -hspice-ext all {file_name} -l {file_name}.log")

def ext_measured(device,vn,d_in, Id_sim, corner):

    # Get dimensions used for each device
    dirpath = f"{device}_{Id_sim}_{corner}"
    dimensions = pd.read_csv(f"{dirpath}/{device}.csv",usecols=["W (um)" , "L (um)"])
    loops = dimensions["L (um)"].count()

    # Extracting measured values for each W & L
    for i in range (0,loops):
        width  = dimensions["W (um)"].iloc[i]
        length = dimensions["L (um)"].iloc[i]

        # Special case for 1st measured values
        if i == 0 :
            # measured Id
            col_list = [f"{vn}",f"{d_in}_{corner}"]
            df_measured = pd.read_csv(f"{dirpath}/{device}.csv",usecols=col_list)
            df_measured.columns = [f"{vn}",f"{d_in}_{corner}"]
            df_measured.to_csv(f"{dirpath}/measured_{Id_sim}/{i}_measured_A{width}_P{length}.csv", index = False)
        else:
            # measured Id
            col_list = [f"{vn}",f"{d_in}_{corner}.{i}"]
            df_measured = pd.read_csv(f"{dirpath}/{device}.csv",usecols=col_list)
            df_measured.columns = [f"{vn}",f"{d_in}_{corner}"]
            df_measured.to_csv(f"{dirpath}/measured_{Id_sim}/{i}_measured_A{width}_P{length}.csv", index = False)

def ext_simulated(device,vn,d_in,vn_sweeps,Id_sim, corner):

    # Get dimensions used for each device
    dirpath = f"{device}_{Id_sim}_{corner}"
    dimensions = pd.read_csv(f"{dirpath}/{device}.csv",usecols=["W (um)" , "L (um)"])
    loops = dimensions["L (um)"].count()
    netlist_tmp = f"./device_netlists/{Id_sim}.spice"
    for i in range (0,loops):
        width  = dimensions["W (um)"].iloc[int(i)]
        length = dimensions["L (um)"].iloc[int(i)]

        if i % 4 == 0: temp = -40
        elif i % 4 == 1: temp = 25
        elif i % 4 == 2: temp = 125
        else:
            temp = 175
        with open(netlist_tmp) as f:
            tmpl = Template(f.read())
            os.makedirs(f"{dirpath}/{device}_netlists_{Id_sim}",exist_ok=True)
            with open(f"{dirpath}/{device}_netlists_{Id_sim}/{i}_{device}_netlist_A{width}_P{length}.spice", "w") as netlist:
                netlist.write(tmpl.render(device = device, area = width, pj = length, i = i , temp = temp, Id_sim = Id_sim , corner = corner ))
            netlist_path  = f"{dirpath}/{device}_netlists_{Id_sim}/{i}_{device}_netlist_A{width}_P{length}.spice"
            # Running ngspice for each netlist
            with concurrent.futures.ProcessPoolExecutor(max_workers=workers_count) as executor:
                executor.submit(call_simulator, netlist_path)

            # Writing simulated data
            df_simulated = pd.read_csv(f"{dirpath}/simulated_{Id_sim}/{i}_simulated_A{width}_P{length}.csv",header=0)
            #df_simulated.to_csv(f"{dirpath}/simulated_{Id_sim}/{i}_simulated_A{width}_P{length}.csv",index= False)

            # zero array to append in it shaped (vn_sweeps, number of trials + 1)
            new_array = np.zeros((vn_sweeps, 2))
            new_array[:len(df_simulated.index), 0] = df_simulated.iloc[:, 0]

            new_array[:len(df_simulated.index), 1] = df_simulated.iloc[:, 0]

            # Writing final simulated data
            df_simulated = pd.DataFrame(new_array)
            df_simulated.to_csv(f"{dirpath}/simulated_{Id_sim}/{i}_simulated_A{width}_P{length}.csv",index= False)
            df_simulated.columns = [f"{vn}",f"{d_in}_{corner}"]
            df_simulated.to_csv(f"{dirpath}/simulated_{Id_sim}/{i}_simulated_A{width}_P{length}.csv",index= False)

def error_cal(device,vn,d_in,Id_sim, corner):

    # Get dimensions used for each device
    dirpath = f"{device}_{Id_sim}_{corner}"
    dimensions = pd.read_csv(f"{dirpath}/{device}.csv",usecols=["W (um)" , "L (um)"])
    loops = dimensions["L (um)"].count()
    df_final = pd.DataFrame()
    for i in range (0,loops):
        width  = dimensions["W (um)"].iloc[int(i)]
        length = dimensions["L (um)"].iloc[int(i)]
        if i % 4 == 0: temp = -40
        elif i % 4 == 1: temp = 25
        elif i % 4 == 2: temp = 125
        else:
            temp = 175

        measured  = pd.read_csv(f"{dirpath}/measured_{Id_sim}/{i}_measured_A{width}_P{length}.csv")
        simulated = pd.read_csv(f"{dirpath}/simulated_{Id_sim}/{i}_simulated_A{width}_P{length}.csv")

        error_1 = round (100 * abs((abs(measured.iloc[:, 1]) - abs(simulated.iloc[:, 1]))/abs(measured.iloc[:, 1])),6)

        df_error = pd.DataFrame(data=[measured.iloc[:, 0],error_1]).transpose()
        df_error.to_csv(f"{dirpath}/error_{Id_sim}/{i}_{device}_error_A{width}_P{length}.csv",index= False)

        # Mean error
        mean_error = (df_error[f"{d_in}_{corner}"].mean())/6
        # Max error
        max_error = df_error[f"{d_in}_{corner}"].max()
        # Max error location
        max_index = max((df_error == max_error).idxmax())
        max_location_vgs = (df_error == max_error).idxmax(axis=1)[max_index]
        max_location_vds = df_error[f"{vn}"][max_index]

        df_final_ = {'Run no.': f'{i}', 'Temp': f'{temp}', 'Device name': f'{dirpath}', 'Area': f'{width}', 'Perimeter': f'{length}', 'Simulated_Val':f'{Id_sim}','Mean error%':f'{"{:.2f}".format(mean_error)}', 'Max error%':f'{"{:.2f}".format(max_error)} @ {max_location_vgs} & vn (V) = {max_location_vds}'}
        df_final = df_final.append(df_final_, ignore_index = True)
    # Max mean error
    print (df_final)
    df_final.to_csv (f"{dirpath}/Final_report_{Id_sim}.csv", index = False)
    out_report = pd.read_csv (f"{dirpath}/Final_report_{Id_sim}.csv")
    print ("\n",f"Max. mean error = {out_report['Mean error%'].max()}%")
    print ("=====================================================================================================================================================")

def main():

    devices = ["np_3p3","dnwpw","dnwps","np_6p0", "nwp_3p3","nwp_6p0","pn_3p3","pn_6p0","sc_diode"]
    corners = ["typical","ff","ss"]
    measures = [["iv","Vn1 (V)", " |In1(A)| diode", 103]]#,
                # ["cv","Vj", "diode", 17]]

    for device in devices:
        for measure in measures:
            for corner in corners:
                # Folder structure of measured values
                Id_sim, diode_vn, diode_in, no_of_vn_sweeps = measure[0], measure[1], measure[2], measure[3]
                dirpath = f"{device}_{Id_sim}_{corner}"
                if os.path.exists(dirpath) and os.path.isdir(dirpath):
                    shutil.rmtree(dirpath)
                os.makedirs(f"{dirpath}/measured_{Id_sim}",exist_ok=False)

                # From xlsx to csv
                read_file = pd.read_excel (f"../../180MCU_SPICE_DATA/Diode/{device}_{Id_sim}.nl_out.xlsx")
                read_file.to_csv (f"{dirpath}/{device}.csv", index = False, header=True)

                # Folder structure of simulated values
                os.makedirs(f"{dirpath}/simulated_{Id_sim}",exist_ok=False)
                os.makedirs(f"{dirpath}/error_{Id_sim}",exist_ok=False)

                ext_measured (device,diode_vn,diode_in, Id_sim, corner)

                ext_simulated(device,diode_vn,diode_in,no_of_vn_sweeps,Id_sim, corner)

    for device in devices:
        for measure in measures:
            for corner in corners:
                # Folder structure of measured values
                Id_sim, diode_vn, diode_in, no_of_vn_sweeps = measure[0], measure[1], measure[2], measure[3]
                error_cal    (device,diode_vn,diode_in,Id_sim, corner)

# ================================================================
# -------------------------- MAIN --------------------------------
# ================================================================

if __name__ == "__main__":

    # Args
    arguments     = docopt(__doc__, version='comparator: 0.1')
    workers_count = os.cpu_count()*2 if arguments["--num_cores"] == None else int(arguments["--num_cores"])

    # Calling main function
    main()


text:
import React, {Component} from 'react';

export default class Route extends Component {
    render() {
        console.log(this.props);
        const {routeComponent, title, routerActions} = this.props;
        if(!routeComponent) return null;

        return (
            <this.props.routeComponent title={title} routerActions={routerActions}/>
        )
    }
}


text:
package it.angelic.soulissclient.model;

import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.database.Cursor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import androidx.annotation.NonNull;
import it.angelic.soulissclient.Constants;
import it.angelic.soulissclient.R;
import it.angelic.soulissclient.model.db.SoulissDBOpenHelper;
import it.angelic.soulissclient.util.FontAwesomeEnum;
import it.angelic.soulissclient.util.FontAwesomeUtil;

/**
 * Souliss Unit, the node
 * <p/>
 * It has a List of @SoulissTypical , and represents an actual arduino-like board
 *
 * @author shine
 */
public class SoulissNode implements Serializable, ISoulissNode {

    private static final long serialVersionUID = 8673027563853737718L;
    private transient Context context;
    private short health;
    /* Icon resource ID > se null torna chipset */
    private Integer iconId;
    private short id;
    private String name;
    private Calendar refreshedAt;

    private List<SoulissTypical> soulissTypicals;

    public SoulissNode(Context c, short id) {
        super();
        this.id = id;
        context = c;
        soulissTypicals = new ArrayList<>();
    }

    /**
     * Data transfer method
     *
     * @param cursor risultato della select
     * @return
     */
    public static SoulissNode cursorToNode(Context c, Cursor cursor) {
        SoulissNode comment = new SoulissNode(c, cursor.getShort(1));

        comment.setHealth(cursor.getShort(cursor.getColumnIndex(SoulissDBOpenHelper.COLUMN_NODE_HEALTH)));
        if (!cursor.isNull(cursor.getColumnIndex(SoulissDBOpenHelper.COLUMN_NODE_ICON)))
            comment.setIconResourceId(cursor.getInt(cursor.getColumnIndex(SoulissDBOpenHelper.COLUMN_NODE_ICON)));
        comment.setName(cursor.getString(cursor.getColumnIndex(SoulissDBOpenHelper.COLUMN_NODE_NAME)));

        Calendar now = Calendar.getInstance();
        now.setTime(new Date(cursor.getLong(cursor.getColumnIndex(SoulissDBOpenHelper.COLUMN_NODE_LASTMOD))));
        comment.setRefreshedAt(now);
        return comment;
    }

    public void addTypical(SoulissTypical rest) {
        soulissTypicals.add(rest);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        SoulissNode that = (SoulissNode) o;

        return id == that.id;

    }

    public List<SoulissTypical> getActiveTypicals() {
        ArrayList<SoulissTypical> copy = new ArrayList<>();

        for (SoulissTypical soulissTypical : soulissTypicals) {
            if (!soulissTypical.isRelated() && !soulissTypical.isEmpty())
                copy.add(soulissTypical);
        }

        return copy;
    }

    public short getHealth() {
        return health;
    }

    public void setHealth(short health) {
        this.health = health;
    }

    public String getHealthPercent() {
        return getHealth() * 100 / 255 + "%";
    }

    public int getIconResourceId() {
        return iconId == null ? FontAwesomeUtil.getCodeIndexByFontName(context, FontAwesomeEnum.fa_microchip.getFontName()) : iconId;
    }

    public void setIconResourceId(int itemResId) {
        iconId = itemResId;
    }

    public String getName() {
        return name;
    }

    public void setName(String namer) {
        name = namer;
    }

    public
    @NonNull
    String getNiceName() {
        if (name != null && "".compareToIgnoreCase(name) != 0)
            return name; //+ " ("+SoulissClient.getAppContext().getString(R.string.node)+" "+ getNodeId() + ")";
        else if (id > Constants.MASSIVE_NODE_ID)
            return context.getString(R.string.node) + " " + Constants.int2roman(getNodeId());
        else
            return context.getString(R.string.allnodes);
    }

    public short getNodeId() {
        return id;
    }

    public Calendar getRefreshedAt() {
        return refreshedAt;
    }

    public void setRefreshedAt(Calendar refreshedAt) {
        this.refreshedAt = refreshedAt;
    }

    public SoulissTypical getTypical(short slot) throws NotFoundException {
        for (SoulissTypical soulissTypical : soulissTypicals) {
            if (soulissTypical.getSlot() == slot)
                return soulissTypical;
        }
        throw new NotFoundException("Slot " + slot + " not found on node " + getNodeId());

    }

    public List<SoulissTypical> getTypicals() {
        return soulissTypicals;
    }

    public void setTypicals(List<SoulissTypical> soulissTypicals) {
        this.soulissTypicals = soulissTypicals;
    }

    @Override
    public int hashCode() {
        return (int) id;
    }

    public void setId(short id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return getNiceName();
    }
}


text:
layout: ncrc_post
title: NCRC 2015 Awards
---

Congratulations to our 2015 National Collegiate Research Conference award winners!

#### Grand Prize

Mahima Sukumar — Hippocampal neurogenesis contributes to the antidepressant effect of electroconvulsive stimulation in a mouse model of stress-induced depression

#### Awards of Excellence

Kathleen DiNapoli in Biology— Tomato mutants and introgression lines provide evidence for a role of flavonoids in lateral root and root hair development.

Nneoma Adaku in Chemistry  — A Novel Species of Fungal Endophyte Produces an Inhibitor of DNA Double-Strand Break Repair

Nicholas Rivera in the Physical Sciences— Construction of Bound States in the Continuum in Separable Systems

Isobel Green in the Social and Behavioral Sciences— A Study of Resting and Reading: Investigating the Neural Signature of Developmental Dyslexia through Resting-State fMRI Analysis

James Golden in Government, Policy, and Economics— Bacterial Contamination in Reusable Bottles Used for Drinking Water in Ecuador

Jacqueline Masehi-Lano in Engineering, Math, and Computer Science — Measuring the Release Rate of Growth Factors from a Heparin-Based Hydrogel for Corneal Wound-Healing

#### Honorable Mention

Francis Masuda in Biology — Characterization of a Novel Family of Odorant Receptors associated with Innate Behavior

Theresa Oei in Chemistry— Identifying Targets of Herpesvirus Saimiri MicroRNAs

Daniel Kolbman in the Physical Sciences — Role of Differential Physical Properties in Emergent Behavior of 3D Cell Co-cultures

Tara Streng in the Social and Behavioral Sciences — Sexual Assault Prevention and Reporting on College Campuses: A Review of Policies and Recommendations

Emily Mediate in Government, Policy, and Economics — Disabling Donor Demands: the Coercion of the International HIV/AIDS Agenda

David Glass in Engineering, Math, and Computer Science — Engineering a bispecific antibody with hybrid IgG/IgA effector function

#### Innovation Challenge

Final Five: Jacob Massa, Theresa Oei, Soham Rege, Yeon Joo Lee, Natalia Romano Spica

No Survivors: Derek Frank, Joseliya Embuscado, Jess Li, Annabel Imbrie-Moore, Bryan Kudisch, Rebecca Casazza, Nneoma Adaku, Aleksandar Makelov

GISE: Jingting Kang, Nikki Mehran, Kiana Murphy, Madhushree Zope, Serry Park, Akane Fujimoto, Nathen Huang, Sarafina Nance

Gold Team Alpha Squadron: Allison Chan, Caitlyn Mullins, Dandi Meng, Franklin Lee, Gina Sun, Max Mauerman, Ryan Cannon, Shelby Newsad, Zachary Anderson


text:
package de.gurkenlabs.litiengine.attributes;

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

/**
 * An attribute is a numerical representation of a property that can be adjusted using {@link AttributeModifier}s.
 *

 * It typically doesn't adjust the raw base value (unless explicitly requested) and instead adjusts the value by
 * registered modifications. This is e.g. useful when a property might only be changed for a certain period of time or
 * we need to know the original value of a property.
 *

 *
 *

 *  An example use-case are player stats that might be affected throughout the game (e.g. via certain skills,
 * upgrades or level-ups).
 *

 *
 * @param <T>
 *          The type of the attribute value.
 */
public class Attribute<T extends Number> {

  private final List<AttributeModifier<T>> modifiers;

  private T baseValue;

  /**
   * Initializes a new instance of the {@code Attribute} class.
   *
   * @param initialValue
   *          The initial value
   */
  public Attribute(final T initialValue) {
    this.modifiers = new ArrayList<>();
    this.baseValue = initialValue;
  }

  /**
   * Adds the specified modifier to this attribute.
   *
   * @param modifier
   *          The modifier to be added to this instance.
   */
  public void addModifier(final AttributeModifier<T> modifier) {
    if (this.getModifiers().contains(modifier)) {
      return;
    }

    this.getModifiers().add(modifier);
    Collections.sort(this.getModifiers());
  }

  /**
   * Removes the specified modifier from this attribute.
   *
   * @param modifier
   *          The modifier to be removed from this instance.
   */
  public void removeModifier(final AttributeModifier<T> modifier) {
    this.getModifiers().remove(modifier);
    Collections.sort(this.getModifiers());
  }

  /**
   * Gets the current value of this attribute, respecting all the registered {@code AttributeModifier}s.
   *
   * @return The current value of this attribute.
   */
  public T get() {
    return this.applyModifiers(this.getBase());
  }

  /**
   * Gets the raw base value of this attribute without applying any modifications.
   *
   * @return The raw base value of this attribute.
   */
  public T getBase() {
    return this.baseValue;
  }

  /**
   * Gets all modifiers added to this instance.
   *
   * @return All modifiers added to this instance.
   */
  public List<AttributeModifier<T>> getModifiers() {
    return this.modifiers;
  }

  /**
   * Determines whether the specified modifier instance is added to this attribute instance.
   *
   * @param modifier
   *          The modifier to check for.
   * @return True if the modifier was added to this attribute instance; otherwise false.
   */
  public boolean isModifierApplied(final AttributeModifier<T> modifier) {
    return this.getModifiers().contains(modifier);
  }

  /**
   * Adjusts the base value of this attribute once with the specified modifier.
   *
   * @param modifier
   *          The modifier used to adjust this attribute's base value.
   *
   * @see #getBase()
   * @see #setBaseValue(Number)
   */
  public void modifyBaseValue(final AttributeModifier<T> modifier) {
    this.baseValue = modifier.modify(this.getBase());
  }

  /**
   * Adjusts the base value of this attribute once with the specified modifier.
   *
   * @param modification
   *          The modification type.
   * @param value
   *          The modification value to be applied.
   */
  public void modifyBaseValue(final Modification modification, double value) {
    this.baseValue = new AttributeModifier<T>(modification, value).modify(this.getBase());
  }

  /**
   * Sets the base value of this attribute.
   *
   * @param baseValue
   *          The base value to be set.
   */
  public void setBaseValue(final T baseValue) {
    this.baseValue = baseValue;
  }

  /**
   * Apply modifiers.
   *
   * @param baseValue
   *          the base value
   * @return the t
   */
  protected T applyModifiers(final T baseValue) {
    T currentValue = baseValue;
    for (final AttributeModifier<T> modifier : this.getModifiers()) {
      currentValue = modifier.modify(currentValue);
    }

    return currentValue;
  }

  @Override
  public String toString() {
    return this.get() == null ? null : this.get().toString();
  }
}


text:
+++
Title = "Location"
Type = "event"
Description = "Location for Devopsdays New York City 2021"
+++

Watch this space for information about the venue including address, map/direction, parking/transit, and any hotel details.

<!-- Uncomment this only if you have set the coordinates for your location in the config yaml. Get Latitude and Longitude of a Point: http://itouchmap.com/latlong.html -->
<!-- {{< event_map >}} -->

<!-- Edit and uncomment to let people know what accessibility features you have available -->
<!--
    Example from Minneapolis 2020

    We offer wheelchair-designated spaces, chairs, and standing options (with tall tables) in the mainstage session room; a quiet room; bathrooms labeled according to the facilities they contain; professional live captioning of mainstage sessions; ingredient labeling (based on data provided when registering); and private space (upon request) for those nursing. We'd also be happy to accommodate any other accessibility needs upon request: {{< email_organizers >}}
-->


text:
<title>dlib C++ Library - server_kernel.cpp</title>

// Copyright (C) 2003  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_SERVER_KERNEL_CPp_
#define DLIB_SERVER_KERNEL_CPp_

#include "server_kernel.h"
#include "../string.h"

namespace dlib
{

// ----------------------------------------------------------------------------------------

    server::
    server (
    ) :
        listening_port(0),
        running(false),
        shutting_down(false),
        running_signaler(running_mutex),
        thread_count(0),
        thread_count_signaler(thread_count_mutex),
        max_connections(1000),
        thread_count_zero(thread_count_mutex),
        graceful_close_timeout(500)
    {
    }

// ----------------------------------------------------------------------------------------

    server::
    ~server (
    )
    {
        clear();
    }

// ----------------------------------------------------------------------------------------

    unsigned long server::
    get_graceful_close_timeout (
    ) const
    {
        auto_mutex lock(max_connections_mutex);
        return graceful_close_timeout;
    }

// ----------------------------------------------------------------------------------------

    void server::
    set_graceful_close_timeout (
        unsigned long timeout
    )
    {
        auto_mutex lock(max_connections_mutex);
        graceful_close_timeout = timeout;
    }

// ----------------------------------------------------------------------------------------

    int server::
    get_max_connections (
    ) const
    {
        max_connections_mutex.lock();
        int temp = max_connections;
        max_connections_mutex.unlock();
        return temp;
    }

// ----------------------------------------------------------------------------------------

    void server::
    set_max_connections (
        int max
    )
    {
        // make sure requires clause is not broken
        DLIB_CASSERT(
            max >= 0 ,
            "\tvoid server::set_max_connections"
            << "\n\tmax == " << max
            << "\n\tthis: " << this
            );

        max_connections_mutex.lock();
        max_connections = max;
        max_connections_mutex.unlock();
    }

// ----------------------------------------------------------------------------------------

    void server::
    clear (
    )
    {
        // signal that we are shutting down
        shutting_down_mutex.lock();
        shutting_down = true;
        shutting_down_mutex.unlock();

        max_connections_mutex.lock();
        listening_port_mutex.lock();
        listening_ip_mutex.lock();
        listening_ip = "";
        listening_port = 0;
        max_connections = 1000;
        graceful_close_timeout = 500;
        listening_port_mutex.unlock();
        listening_ip_mutex.unlock();
        max_connections_mutex.unlock();

        // tell all the connections to shut down
        cons_mutex.lock();
        connection* temp;
        while (cons.size() > 0)
        {
            cons.remove_any(temp);
            temp->shutdown();
        }
        cons_mutex.unlock();

        // wait for all the connections to shut down
        thread_count_mutex.lock();
        while (thread_count > 0)
        {
            thread_count_zero.wait();
        }
        thread_count_mutex.unlock();

        // wait for the listener to close
        running_mutex.lock();
        while (running == true)
        {
            running_signaler.wait();
        }
        running_mutex.unlock();

        // signal that the shutdown is complete
        shutting_down_mutex.lock();
        shutting_down = false;
        shutting_down_mutex.unlock();
    }

// ----------------------------------------------------------------------------------------

    void server::
    start_async_helper (
    )
    {
        try
        {
            start_accepting_connections();
        }
        catch (std::exception& e)
        {
            sdlog << LERROR << e.what();
        }
    }

// ----------------------------------------------------------------------------------------

    void server::
    start_async (
    )
    {
        auto_mutex lock(running_mutex);
        if (running)
            return;

        // Any exceptions likely to be thrown by the server are going to be
        // thrown when trying to bind the port.  So calling this here rather
        // than in the thread we are about to make will cause start_async()
        // to report errors back to the user in a very straight forward way.
        open_listening_socket();

        async_start_thread.reset(new thread_function(make_mfp(*this,&server::start_async_helper)));
    }

// ----------------------------------------------------------------------------------------

    void server::
    open_listening_socket (
    )
    {
        if (!sock)
        {
            int status = create_listener(sock,listening_port,listening_ip);
            const int port_used = listening_port;

            // if there was an error then clear this object
            if (status < 0)
            {
                max_connections_mutex.lock();
                listening_port_mutex.lock();
                listening_ip_mutex.lock();
                listening_ip = "";
                listening_port = 0;
                max_connections = 1000;
                graceful_close_timeout = 500;
                listening_port_mutex.unlock();
                listening_ip_mutex.unlock();
                max_connections_mutex.unlock();
            }

            // throw an exception for the error
            if (status == PORTINUSE)
            {
                throw dlib::socket_error(
                    EPORT_IN_USE,
                    "error occurred in server::start()\nport " + cast_to_string(port_used) + " already in use"
                );
            }
            else if (status == OTHER_ERROR)
            {
                throw dlib::socket_error(
                    "error occurred in server::start()\nunable to create listener"
                );
            }
        }

        running_mutex.lock();
        running = true;
        running_mutex.unlock();
    }

// ----------------------------------------------------------------------------------------

    void server::
    start (
    )
    {
        // make sure requires clause is not broken
        DLIB_CASSERT(
              this->is_running() == false,
            "\tvoid server::start"
            << "\n\tis_running() == " << this->is_running()
            << "\n\tthis: " << this
            );

        start_accepting_connections();

    }

// ----------------------------------------------------------------------------------------

    void server::
    start_accepting_connections (
    )
    {
        open_listening_socket();

        // determine the listening port
        bool port_assigned = false;
        listening_port_mutex.lock();
        if (listening_port == 0)
        {
            port_assigned = true;
            listening_port = sock->get_listening_port();
        }
        listening_port_mutex.unlock();
        if (port_assigned)
            on_listening_port_assigned();

        int status = 0;

        connection* client;
        bool exit = false;
        while ( true )
        {

            // accept the next connection
            status = sock->accept(client,1000);

            // if there was an error then quit the loop
            if (status == OTHER_ERROR)
            {
                break;
            }

            shutting_down_mutex.lock();
            // if we are shutting down then signal that we should quit the loop
            exit = shutting_down;
            shutting_down_mutex.unlock();

            // if we should be shutting down
            if (exit)
            {
                // if a connection was opened then close it
                if (status == 0)
                    delete client;
                break;
            }

            // if the accept timed out
            if (status == TIMEOUT)
            {
                continue;
            }

            // add this new connection to cons
            cons_mutex.lock();
            connection* client_temp = client;
            try{cons.add(client_temp);}
            catch(...)
            {
                sock.reset();
                delete client;
                cons_mutex.unlock();

                // signal that we are not running start() anymore
                running_mutex.lock();
                running = false;
                running_signaler.broadcast();
                running_mutex.unlock();

                clear();
                throw;
            }
            cons_mutex.unlock();

            // make a param structure
            param* temp = 0;
            try{
            temp = new param (
                            *this,
                            *client,
                            get_graceful_close_timeout()
                            );
            } catch (...)
            {
                sock.reset();
                delete client;
                running_mutex.lock();
                running = false;
                running_signaler.broadcast();
                running_mutex.unlock();
                clear();
                throw;
            }

            // if create_new_thread failed
            if (!create_new_thread(service_connection,temp))
            {
                delete temp;
                // close the listening socket
                sock.reset();

                // close the new connection and remove it from cons
                cons_mutex.lock();
                connection* ctemp;
                if (cons.is_member(client))
                {
                    cons.remove(client,ctemp);
                }
                delete client;
                cons_mutex.unlock();

                // signal that the listener has closed
                running_mutex.lock();
                running = false;
                running_signaler.broadcast();
                running_mutex.unlock();

                // make sure the object is cleared
                clear();

                // throw the exception
                throw dlib::thread_error(
                    ECREATE_THREAD,
                    "error occurred in server::start()\nunable to start thread"
                    );
            }
            // if we made the new thread then update thread_count
            else
            {
                // increment the thread count
                thread_count_mutex.lock();
                ++thread_count;
                if (thread_count == 0)
                    thread_count_zero.broadcast();
                thread_count_mutex.unlock();
            }

            // check if we have hit the maximum allowed number of connections
            max_connections_mutex.lock();
            // if max_connections is zero or the loop is ending then skip this
            if (max_connections != 0)
            {
                // wait for thread_count to be less than max_connections
                thread_count_mutex.lock();
                while (thread_count >= max_connections)
                {
                    max_connections_mutex.unlock();
                    thread_count_signaler.wait();
                    max_connections_mutex.lock();

                    // if we are shutting down the quit the loop
                    shutting_down_mutex.lock();
                    exit = shutting_down;
                    shutting_down_mutex.unlock();
                    if (exit)
                        break;
                }
                thread_count_mutex.unlock();
            }
            max_connections_mutex.unlock();

            if (exit)
            {
                break;
            }
        } //while ( true )

        // close the socket
        sock.reset();

        // signal that the listener has closed
        running_mutex.lock();
        running = false;
        running_signaler.broadcast();
        running_mutex.unlock();

        // if there was an error with accept then throw an exception
        if (status == OTHER_ERROR)
        {
            // make sure the object is cleared
            clear();

            // throw the exception
            throw dlib::socket_error(
             "error occurred in server::start()\nlistening socket returned error"
                );
        }
    }

// ----------------------------------------------------------------------------------------

    bool server::
    is_running (
    ) const
    {
        running_mutex.lock();
        bool temp = running;
        running_mutex.unlock();
        return temp;
    }

// ----------------------------------------------------------------------------------------

    const std::string server::
    get_listening_ip (
    ) const
    {
        listening_ip_mutex.lock();
        std::string ip(listening_ip);
        listening_ip_mutex.unlock();
        return ip;
    }

// ----------------------------------------------------------------------------------------

    int server::
    get_listening_port (
    ) const
    {
        listening_port_mutex.lock();
        int port = listening_port;
        listening_port_mutex.unlock();
        return port;
    }

// ----------------------------------------------------------------------------------------

    void server::
    set_listening_port (
        int port
    )
    {
        // make sure requires clause is not broken
        DLIB_CASSERT(
            ( port >= 0 &&
              this->is_running() == false ),
            "\tvoid server::set_listening_port"
            << "\n\tport         == " << port
            << "\n\tis_running() == " << this->is_running()
            << "\n\tthis: " << this
            );

        listening_port_mutex.lock();
        listening_port = port;
        listening_port_mutex.unlock();
    }

// ----------------------------------------------------------------------------------------

    void server::
    set_listening_ip (
        const std::string& ip
    )
    {
        // make sure requires clause is not broken
        DLIB_CASSERT(
            ( ( is_ip_address(ip) || ip == "" ) &&
              this->is_running() == false ),
            "\tvoid server::set_listening_ip"
            << "\n\tip           == " << ip
            << "\n\tis_running() == " << this->is_running()
            << "\n\tthis: " << this
            );

        listening_ip_mutex.lock();
        listening_ip = ip;
        listening_ip_mutex.unlock();
    }

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
    // static member function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    const logger server::sdlog("dlib.server");

    void server::
    service_connection(
        void* item
    )
    {
        param& p = *static_cast<param*>(item);

        p.the_server.on_connect(p.new_connection);

        // remove this connection from cons and close it
        p.the_server.cons_mutex.lock();
        connection* temp;
        if (p.the_server.cons.is_member(&p.new_connection))
            p.the_server.cons.remove(&p.new_connection,temp);
        p.the_server.cons_mutex.unlock();

        try{ close_gracefully(&p.new_connection, p.graceful_close_timeout); }
        catch (...) { sdlog << LERROR << "close_gracefully() threw"; }

        // decrement the thread count and signal if it is now zero
        p.the_server.thread_count_mutex.lock();
        --p.the_server.thread_count;
        p.the_server.thread_count_signaler.broadcast();
        if (p.the_server.thread_count == 0)
            p.the_server.thread_count_zero.broadcast();
        p.the_server.thread_count_mutex.unlock();

        delete &p;

    }

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_SERVER_KERNEL_CPp_


text:
<?xml version="1.0"?>
<project name="skillstr" default="jar" basedir="..">

	<property name="wowza.lib.dir" value="/Library/WowzaMediaServer/lib"/>
	<property name="jar.filename" value="skillstr.jar"/>
	<property name="core.build.dir" value="bin"/>

	<target name="jar">
		<jar jarfile="${wowza.lib.dir}/${jar.filename}">
			<fileset dir="${core.build.dir}"/>
		</jar>
	</target>

</project>


text:
package ru.beykerykt.bullsandcows;

import java.awt.Color;

public class Resources {

	public static class Localization {
		public static String TITLE_NAME = "Быки и коровы";
		public static String STAGE_VERSION = "Develop-0.0.1";

		public static String PLAYER_NAME = "Имя игрока:";
		public static String BOT_NAME = "Имя бота:";
		public static String PLAYER_DEFAULT_NAME = "DevelopedOne";
		public static String BOT_DEFAULT_NAME = "Bob";

		public static String YOUR_CODE = "Код для разгадывания:";
		public static String YOUR_CODE_DESCRPTION = "Ваш код должен содержать только 4 цифры от 0 до 6.";

		public static class Algoritms {
			public static String ALGORITHM_FOR_SEARCH = "Алгоритм для поиска:";
			public static String RANDOM_ALGORITHM = "Рандом";
			public static String BOB_ALGORITHM = "Алгоритм Боба Кули";
			public static String MAGIC_ALGORITHM = "Магический";
		}

		public static String START_SEARCHING = "Начать поиск";
		public static String STOP_SEARCHING = "Остановить поиск";
		public static String UNAVAILABLE = "Недоступно";

		public static String I_THINK = "Я думаю это...";
		public static String ATTEMPT = "Попытка номер ";
		public static String RANDOM_BUTTON = "Рандомное число";
	}

	public static class ResourcePaths {
		// Icons
		public static String ICON_PATH = "/res/icons/icon.png";

		// Fonts
		public static String REGULAR_FONT_PATH = "/res/fonts/Lato-Regular.ttf";
		public static String ITALIC_FONT_PATH = "/res/fonts/Lato-Italic.ttf";
	}

	public static class Colors {
		public static Color WHITE = Color.WHITE; // background ?
		public static Color CYAN = new Color(0, 177, 229); // cyanogen
	}
}


text:
/**
 */
package org.osate.xtext.aadl2.agcl.agcl.impl;

import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.ecore.EClass;

import org.eclipse.emf.ecore.impl.ENotificationImpl;

import org.osate.xtext.aadl2.agcl.agcl.AgclPackage;
import org.osate.xtext.aadl2.agcl.agcl.BooleanConstant;

/**
 *
 * An implementation of the model object 'Boolean Constant'.
 *
 *

 * The following features are implemented:
 *

 *
{@link org.osate.xtext.aadl2.agcl.agcl.impl.BooleanConstantImpl#getVal Val}

 *

 *

 *
 * @generated
 */
public class BooleanConstantImpl extends PSLExpressionImpl implements BooleanConstant
{
  /**
   * The default value of the '{@link #getVal() Val}' attribute.
   *
   *
   * @see #getVal()
   * @generated
   * @ordered
   */
  protected static final String VAL_EDEFAULT = null;

  /**
   * The cached value of the '{@link #getVal() Val}' attribute.
   *
   *
   * @see #getVal()
   * @generated
   * @ordered
   */
  protected String val = VAL_EDEFAULT;

  /**
   *
   *
   * @generated
   */
  protected BooleanConstantImpl()
  {
    super();
  }

  /**
   *
   *
   * @generated
   */
  @Override
  protected EClass eStaticClass()
  {
    return AgclPackage.Literals.BOOLEAN_CONSTANT;
  }

  /**
   *
   *
   * @generated
   */
  public String getVal()
  {
    return val;
  }

  /**
   *
   *
   * @generated
   */
  public void setVal(String newVal)
  {
    String oldVal = val;
    val = newVal;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, AgclPackage.BOOLEAN_CONSTANT__VAL, oldVal, val));
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public Object eGet(int featureID, boolean resolve, boolean coreType)
  {
    switch (featureID)
    {
      case AgclPackage.BOOLEAN_CONSTANT__VAL:
        return getVal();
    }
    return super.eGet(featureID, resolve, coreType);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eSet(int featureID, Object newValue)
  {
    switch (featureID)
    {
      case AgclPackage.BOOLEAN_CONSTANT__VAL:
        setVal((String)newValue);
        return;
    }
    super.eSet(featureID, newValue);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eUnset(int featureID)
  {
    switch (featureID)
    {
      case AgclPackage.BOOLEAN_CONSTANT__VAL:
        setVal(VAL_EDEFAULT);
        return;
    }
    super.eUnset(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public boolean eIsSet(int featureID)
  {
    switch (featureID)
    {
      case AgclPackage.BOOLEAN_CONSTANT__VAL:
        return VAL_EDEFAULT == null ? val != null : !VAL_EDEFAULT.equals(val);
    }
    return super.eIsSet(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public String toString()
  {
    if (eIsProxy()) return super.toString();

    StringBuffer result = new StringBuffer(super.toString());
    result.append(" (val: ");
    result.append(val);
    result.append(')');
    return result.toString();
  }

} //BooleanConstantImpl


text:
<?php

declare(strict_types=1);

namespace Jnjxp\Vk\Aware;

use Jnjxp\Vk\AuthHelperInterface;
use Jnjxp\Vk\Exception;
use Psr\Http\Message\ServerRequestInterface as Request;

trait AuthAwareTrait
{
    protected $authAttribute = AuthHelperInterface::class;

    public function setAuthAttribute(string $attr) : void
    {
        $this->authAttribute = $attr;
    }

    protected function getAuthHelper(Request $request) : AuthHelperInterface
    {
        $auth = $request->getAttribute($this->authAttribute, false);

        if (! $auth instanceof AuthHelperInterface) {
            throw Exception\MissingAttributeException::missing(
                AuthHelperInterface::class,
                $this->authAttribute,
                $this
            );
        }

        return $auth;
    }
}


text:
import logging

from django.views.generic import ListView

logger = logging.getLogger(__name__)

class CampaignStatsView(ListView):
    """Shows stats on campaigns"""
    template_name = 'campaign/stats.html'
    queryset = []  # TODO: replace fake queryset with an existing model


text:
using System;
namespace Braintree
{
    [Serializable]
    public class UpdateDiscountRequest : UpdateModificationRequest
    {
    }
}


text:
DROP TABLE libros_autores;
DROP TABLE libros_traductores;
DROP TABLE libros;
DROP TABLE ubicaciones;
DROP TABLE tipos;
DROP TABLE traductores;
DROP TABLE autores;
DROP TABLE colecciones;
DROP TABLE editoriales;


text:
package org.ferrit.core.crawler

import akka.actor.{Actor, ActorSystem, ActorRef, Props, Terminated}
import akka.testkit.{TestKit, ImplicitSender, TestProbe}
import akka.routing.Listen
import org.scalatest.{FlatSpec, BeforeAndAfterAll}
import org.scalatest.matchers.ShouldMatchers
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.util.Random
import org.ferrit.core.crawler.FetchMessages._
import org.ferrit.core.crawler.CrawlWorker._
import org.ferrit.core.filter.FirstMatchUriFilter
import org.ferrit.core.filter.FirstMatchUriFilter._
import org.ferrit.core.http.{HttpClient, Request, Response}
import org.ferrit.core.model.CrawlJob
import org.ferrit.core.parser.MultiParser
import org.ferrit.core.robot.{RobotRulesCache, RobotRulesCacheActor}
import org.ferrit.core.uri.{CrawlUri, UriReader, InMemoryFrontier}
import org.ferrit.core.uri.{UriCache, InMemoryUriCache}
import org.ferrit.core.util.{Counters, MediaCounters, Media, UniqueId}
import org.ferrit.core.test.FakeHttpClient._
import org.ferrit.core.test.{ParrotHttpClient, LinkedListHttpClient}
import org.ferrit.core.test.{MockRobotRulesCache, PartResponse}
import org.ferrit.core.test.{ProxyActor}

class TestCrawlWorker extends FlatSpec with ShouldMatchers with BeforeAndAfterAll {

  implicit val system = ActorSystem("test")

  implicit val execContext = system.dispatcher

  override def afterAll():Unit = system.shutdown()

  class CrawlTest extends TestKit(system) with ImplicitSender {

    /**
     * The CrawlWorker is intended to be a child of CrawlerManager
     * with all communication to it mediated through the CrawlerManager.
     * Therefore we create a proxy parent for the CrawlWorker and talk
     * to the crawler through the proxy.
     *
     * Another reason for using this proxy:
     * It is possible to create a CrawlWorker using system.actorOf(...),
     * but messages sent by the CrawlWorker to it's
     * parent (which it thinks is the CrawlerManager) are not handled
     * by the guardian actor and end up logged as dead letters.
     */
    def makeCrawlerProxy(crawlerProps: Props):ActorRef = {
      val realParent = testActor // i.e. this TestKit
      system.actorOf(
        Props(classOf[ProxyActor], realParent, crawlerProps, mkCrawlerName)
      )
    }

  }

  /**
   * To help debug test failures, a debug logger can be registered with
   * the Crawler that will then log the internal activitiy.
   * For example, just add this line before running crawler:
   *
   *   proxy !Listen(logger)
   *
   */
  def logger = system.actorOf(Props[CrawlLog])

  def mockRobotRulesCache = makeRobotRulesCache(new MockRobotRulesCache)

  def makeRobotRulesCache(cache: RobotRulesCache) =
    system.actorOf(Props(classOf[RobotRulesCacheActor], cache))

  val html = """
        |<!doctype html>
        |
        |<title>Page Title</title>
        |
        |  %s
        |
        |
        |
        |  %s
        |
        |
        """.stripMargin
    val css =
        """#item { background: url('%s') }"""

  /**
   * Each crawler Actor requires a different name else Akka complains.
   * Underlying reason is that test actors may still exist for some time after a
   * test has completed and names collide with the Actor in the next test.
   */
  def mkCrawlerName = "crawler-" + System.currentTimeMillis + "-" + Random.nextInt(100)

  def seedsFor(uri: String) = Seq(CrawlUri(uri))
  def uriFilterFor(uri: String) = new FirstMatchUriFilter(Seq(Accept(uri.r)))

  /**
   * Generic config used by all tests, customisable by making a copy
   */
  def makeConfig(uri: String) = CrawlConfig(
      id = UniqueId.next,
      userAgent = Some("Test Agent"),
      crawlerName = "Test Crawler " + scala.util.Random.nextInt(10000),
      seeds = seedsFor(uri),
      uriFilter = uriFilterFor(uri),
      tests = Some(Seq(s"accept: $uri")),
      crawlDelayMillis = 0,
      crawlTimeoutMillis = 10000,
      maxDepth = Int.MaxValue,
      maxFetches = 10000,
      maxQueueSize = 10000,
      maxRequestFails = 0.5
    )

  def makeJob(config: CrawlConfig) = CrawlJob.create(config, "localhost")

  behavior of "CrawlWorker"

  it should "start and then stop by itself normally" in new CrawlTest {

    val config = makeConfig("http://site.net")

    val proxy = makeCrawlerProxy(Props(
      classOf[CrawlWorker],
      makeJob(config),
      config,
      new InMemoryFrontier,
      new InMemoryUriCache,
      new ParrotHttpClient(Map.empty),
      mockRobotRulesCache,
      MultiParser.default,
      new DefaultStopRule
    ))

    proxy ! Listen(self)
    proxy ! Run
    fishForMessage(1.second) {
      case Stopped(CompletedOkay, job) => true
      case _ => false
    }

  }

  it should "respond to Stop request" in new CrawlTest {

    val site = "http://site.net"
    val config = makeConfig(site)

    val proxy = makeCrawlerProxy(Props(
      classOf[CrawlWorker],
      makeJob(config),
      config,
      new InMemoryFrontier,
      new InMemoryUriCache,
      new LinkedListHttpClient(site, 2),
      mockRobotRulesCache,
      MultiParser.default,
      new DefaultStopRule
    ))

    proxy ! Listen(self)
    proxy ! Run
    fishForMessage(1.second) {
      case StartOkay(_, _) => true
      case _ => false
    }
    proxy ! StopCrawl
    fishForMessage(1.second) {
      case Stopped(StopRequested, job) => true
      case _ => false
    }

  }

  it should "crawl and find links in pages" in new CrawlTest {

    val site = "http://site.net"
    val responses = Map(
      s"$site" ->
          HtmlResponse(html.format("",
            """link
               link
               link
               link""")),
      s"$site/page1.html" ->
          HtmlResponse(html.format("",
            """link""")),
      s"$site/page2.html" ->
          HtmlResponse(html.format(
            """<link rel="stylsheet" type="text/css" href="styles.css" />""",
            """link""")),
      s"$site/plain.txt" ->
          TextResponse("some plain text"),
      s"$site/styles.css" ->
          CssResponse(css.format("spacecats.png")))

    val uriFilter = new FirstMatchUriFilter(Seq(
      Reject((site + """/.+\.txt""").r),
      Accept(site.r)
    ))

    val config = makeConfig(site).copy(uriFilter = uriFilter)

    val proxy = makeCrawlerProxy(Props(
      classOf[CrawlWorker],
      makeJob(config),
      config,
      new InMemoryFrontier,
      new InMemoryUriCache,
      new ParrotHttpClient(responses),
      mockRobotRulesCache,
      MultiParser.default,
      new DefaultStopRule
    ))

    proxy ! Listen(self)
    proxy ! Run

    fishForMessage(1.second) {
      case Stopped(CompletedOkay, job) =>
        List(job.fetchCounters, job.responseCounters, job.mediaCounters) should equal (List(
          Map(
            FetchAttempts -> 6, // 1 index, 3 html, 1 css, 1 png, but no .txt
            FetchSucceeds -> 4, // 3 html, 1 css
            FetchFails -> 2 // 1 page3.html, 1 png
          ),
          Map(
            "200" -> 4,
            "404" -> 2 // page3.html + png
          ),
          Map(
            "text/html; charset=UTF-8" -> Media(3, 783),
            "text/css; charset=UTF-8" -> Media(1, 42)
          )
        ))
        true
      case _ => false
    }

  }

  it should "ignore links containing unsupported schemes" in new CrawlTest {

    val site = "http://site.net"
    val responses = Map(
      s"$site" ->
          HtmlResponse(html.format("",
            """link
               email
               ftp location"""))
      )

    val uriFilter = new FirstMatchUriFilter(Seq(Accept(site.r)))
    val config = makeConfig(site).copy(uriFilter = uriFilter)

    val crawler = makeCrawlerProxy(Props(
      classOf[CrawlWorker],
      makeJob(config),
      config,
      new InMemoryFrontier,
      new InMemoryUriCache,
      new ParrotHttpClient(responses),
      mockRobotRulesCache,
      MultiParser.default,
      new DefaultStopRule
    ))

    crawler ! Listen(self)
    crawler ! Run

    fishForMessage(1.second) {
      case Stopped(CompletedOkay, job) =>
        job.fetchCounters should equal (Map(FetchAttempts -> 1, FetchSucceeds -> 1))
        job.responseCounters should equal (Map("200" -> 1))
        true
      case _ => false
    }

  }

  it should "handle a larger number of pages" in new CrawlTest {

    val site = "http://site.net"
    val totalPages = 1000
    val config = makeConfig(site)

    val proxy = makeCrawlerProxy(Props(
      classOf[CrawlWorker],
      makeJob(config),
      config,
      new InMemoryFrontier,
      new InMemoryUriCache,
      new LinkedListHttpClient(site, totalPages),
      mockRobotRulesCache,
      MultiParser.default,
      new DefaultStopRule
    ))

    proxy ! Listen(self)
    proxy ! Run

    fishForMessage(3.second) {
      case Stopped(CompletedOkay, job) =>
        List(job.fetchCounters, job.responseCounters, job.mediaCounters) should equal (List(
          Map(
            FetchAttempts -> totalPages,
            FetchSucceeds -> totalPages
          ),
          Map(
            "200" -> totalPages
          ),
          Map(
            "text/html; charset=UTF-8" -> Media(totalPages, 224730)
          )
        ))
        true
      case _ => false
    }

  }

  it should "not fetch resources blocked by robots.txt" in new CrawlTest {

    val site = "http://site.net"
    val page = HtmlResponse(html.format("",
            """link
               link"""))
    val responses = Map(
              s"$site" -> page,
              s"$site/page2.html" -> page,
              s"$site/page1.html" -> page)

    val robotsCache = new MockRobotRulesCache() {
      override def allow(ua: String, reader: UriReader) = {
        Future.successful(reader.crawlUri.crawlableUri != s"$site/page2.html")
      }
    }
    val config = makeConfig(site)

    val proxy = makeCrawlerProxy(Props(
      classOf[CrawlWorker],
      makeJob(config),
      config,
      new InMemoryFrontier,
      new InMemoryUriCache,
      new ParrotHttpClient(responses),
      makeRobotRulesCache(robotsCache),
      MultiParser.default,
      new DefaultStopRule
    ))

    proxy ! Listen(self)
    proxy ! Run

    fishForMessage(1.second) {
      case Stopped(CompletedOkay, job) =>
        job.fetchCounters should equal (Map(
          FetchAttempts -> 2, // 3 - 1 blocked
          FetchSucceeds -> 2
        ))
        true
      case _ => false
    }

  }

  it should "apply the right crawl delay for the site and config" in new CrawlTest {

    val site1 = "http://site1.net"
    val site2 = "http://site2.net"
    val site3 = "http://site3.net"

    // For simplicity ignore second to millisecond conversion
    // TestDefaultRobotRulesCache already tests for this

    val site1delay = None // site 1 has no robots.txt crawl-delay directive
    val site2delay = 10   // site 2 has a delay < config default
    val confDelay =  20   // the crawl config default (in between site 2 and 3)
    val site3delay = 30   // site 3 has a delay > config default

    val responses = Map(
      site1 -> HtmlResponse(html.format("",
              """link
                 link""")),
      site2 -> HtmlResponse(html),
      site3 -> HtmlResponse(html)
    )

    val uriFilter = new FirstMatchUriFilter(Seq(Accept("http://site.*".r)))

    val robotsCache = new MockRobotRulesCache() {
      override def getDelayFor(ua: String, reader: UriReader):Future[Option[Int]] = {
        val delay:Option[Int] = reader.crawlUri.crawlableUri match {
          case "http://site2.net" => Some(site2delay)
          case "http://site3.net" => Some(site3delay)
          case _ => None
        }
        Future.successful(delay)
      }
    }

    val config = makeConfig(site1).copy(
        uriFilter = uriFilter,
        crawlDelayMillis = confDelay
    )

    val proxy = makeCrawlerProxy(Props(
      classOf[CrawlWorker],
      makeJob(config),
      config,
      new InMemoryFrontier,
      new InMemoryUriCache,
      new ParrotHttpClient(responses),
      makeRobotRulesCache(robotsCache),
      MultiParser.default,
      new DefaultStopRule
    ))

    proxy ! Listen(self)
    proxy ! Run

    var results = Map[String, Long]()

    def expectFetchScheduled = {
      fishForMessage(1.second) {
        case FetchScheduled(f, delay) =>
          results = results + (f.uri.crawlableUri -> delay)
          true
        case _ => false
      }
    }
    expectFetchScheduled
    expectFetchScheduled
    expectFetchScheduled

    fishForMessage(1.second) {
      case Stopped(CompletedOkay, job) => true
      case _ => false
    }

    results.get(site1) should equal (Some(confDelay))
    results.get(site2) should equal (Some(confDelay))
    results.get(site3) should equal (Some(site3delay))

  }

  it should "observe the maximum crawl depth setting" in new CrawlTest {

    val site = "http://site.net"

    // Depth: 0     1      2     3
    // -------------------------------
    //        index
    //            \_page1
    //                  \_page2
    //                         \_page3

    val depth = 3
    val found = 4 // if including depth 0
    val totalPages = 10 // provide more pages than should be crawled
    val config = makeConfig(site).copy(maxDepth = depth)

    val proxy = makeCrawlerProxy(Props(
      classOf[CrawlWorker],
      makeJob(config),
      config,
      new InMemoryFrontier,
      new InMemoryUriCache,
      new LinkedListHttpClient(site, totalPages),
      mockRobotRulesCache,
      MultiParser.default,
      new DefaultStopRule
    ))

    proxy !Listen(self)
    proxy !Run

    fishForMessage(1.second) {
      case Stopped(CompletedOkay, job) =>
        List(job.fetchCounters, job.responseCounters, job.mediaCounters) should equal (List(
          Map(
            FetchAttempts -> found,
            FetchSucceeds -> found
          ),
          Map(
            "200" -> found
          ),
          Map(
            "text/html; charset=UTF-8" -> Media(found, 884)
          )
        ))
        true
      case _ => false
    }

  }

  it should "observe the maximum crawl depth even with multiple seeds" in new CrawlTest {

    //  Example: assuming a crawl depth limit of 1
    //
    //    a - allowed because is depth 1
    //    b - allowed because is depth 1
    //    c - not allowed because is depth 2
    //    d - allowed because even though d is depth 2 from seed 1
    //        it is depth 1 from seed 2, so permitted
    //
    //     Seed 1      Seed 2
    //      /   \        |
    //     a     b       |
    //    / \            |
    //   /   \           |
    //  c     d ---------/
    //

    val seed1 = "http://site1.net"
    val seed2 = "http://site2.net"
    val pageA = "http://site1.net/pageA"
    val pageB = "http://site1.net/pageB"
    val pageC = "http://site1.net/pageC"
    val pageD = "http://site1.net/pageD"

    val maxDepth = 1
    val found = 5 // seed1, seed2, pageA, pageB, pageD

    val responses = Map(
      seed1 -> HtmlResponse(html.format("", """linklink""")),
      seed2 -> HtmlResponse(html.format("", """link""")),
      pageA -> HtmlResponse(html.format("", """linklink""")),
      pageB -> HtmlResponse(html),
      pageC -> HtmlResponse(html),
      pageD -> HtmlResponse(html)
    )

    val config = makeConfig("http://site.*").copy(
      seeds = Seq(
        CrawlUri(seed1),
        CrawlUri(seed2)
      ),
      maxDepth = maxDepth
    )

    val proxy = makeCrawlerProxy(Props(
      classOf[CrawlWorker],
      makeJob(config),
      config,
      new InMemoryFrontier,
      new InMemoryUriCache,
      new ParrotHttpClient(responses),
      mockRobotRulesCache,
      MultiParser.default,
      new DefaultStopRule
    ))

    proxy !Listen(self)
    proxy !Run

    fishForMessage(1.second) {
      case Stopped(CompletedOkay, job) =>
        List(job.fetchCounters, job.responseCounters, job.mediaCounters) should equal (List(
            Map(
              FetchAttempts -> found,
              FetchSucceeds -> found
            ),
            Map(
              "200" -> found
            ),
            Map(
              "text/html; charset=UTF-8" -> Media(found, 980)
            )
        ))
        true
      case _ => false
    }

  }

  it should "abort after the maximum fetch limit is exceeded" in new CrawlTest {

    val site = "http://site.net"
    val maxFetch = 5
    val config = makeConfig(site).copy(maxFetches = maxFetch)

    val proxy = makeCrawlerProxy(Props(
      classOf[CrawlWorker],
      makeJob(config),
      config,
      new InMemoryFrontier,
      new InMemoryUriCache,
      new LinkedListHttpClient(site, 10),
      mockRobotRulesCache,
      MultiParser.default,
      new DefaultStopRule
    ))

    proxy !Listen(self)
    proxy !Run

    fishForMessage(1.second) {
      case Stopped(TooManyFetches, job) =>
        job.fetchCounters should equal (Map(
          FetchAttempts -> maxFetch,
          FetchSucceeds -> maxFetch
        ))
        true
      case _ => false
    }

  }

  it should "abort when too many fetches have failed" in new CrawlTest {

    // The order of queued URIs within the same depth level is non-deterministic.
    // This can lead to test failures if there are mixed 200/404 responses for
    // a batch of pages at the same level.
    // This layout of pages prevents test failure by having all the 200
    // successes happen first, and then have the 404s occur at depth 2.
    // That way the percentage of success to fail is not skewed in favour
    // of failure too early on.
    //
    // index
    //     \_page1
    //     |_page2
    //           \_page3 (404)
    //           |_page4 (404)
    //           |_page5 (404)
    //           ...
    //           |_page10 (404)
    //

    val index = "http://site.net"
    val page1 = "http://site.net/page1"
    val page2 = "http://site.net/page2"

    val responses = Map(
      index -> HtmlResponse(html.format("",
                """link
                   link""")),
      page1 -> HtmlResponse(html),
      page2 -> HtmlResponse(html.format("",
                """link
                   link
                   link
                   link
                   link
                   link
                   link
                   link""")))

    val config = makeConfig(index)

    val proxy = makeCrawlerProxy(Props(
      classOf[CrawlWorker],
      makeJob(config),
      config,
      new InMemoryFrontier,
      new InMemoryUriCache,
      new ParrotHttpClient(responses),
      mockRobotRulesCache,
      MultiParser.default,
      new DefaultStopRule
    ))

    proxy !Listen(self)
    proxy !Run

    fishForMessage(1.second) {
      case Stopped(TooManyFetchesFailed, job) =>
        job.fetchCounters should equal (Map(
          FetchAttempts -> 10,
          FetchSucceeds -> 3,
          FetchFails -> 7
        ))
        true
      case _ => false
    }

  }

  it should "abort after the crawl timeout is exceeded" in new CrawlTest {

    val site = "http://site.net"
    val page = HtmlResponse(html.format("",
            """link
               link
               link"""))

    val responses = Map(
        s"$site" -> page,
        s"$site/page3.html" -> page,
        s"$site/page2.html" -> page,
        s"$site/page1.html" -> page
      )

    // Simulate a slow server.
    // 4 pages to crawl, each taking 100ms is a 400ms crawl.
    // The crawl timeout must therefore less than 400ms.

    val reqDelay = 100.milliseconds
    val crawlTimeout = 300
    val config = makeConfig(site).copy(crawlTimeoutMillis = crawlTimeout)

    val proxy = makeCrawlerProxy(Props(
      classOf[CrawlWorker],
      makeJob(config),
      config,
      new InMemoryFrontier,
      new InMemoryUriCache,
      new ParrotHttpClient(responses) {
        override def responseDelay = reqDelay
      },
      mockRobotRulesCache,
      MultiParser.default,
      new DefaultStopRule
    ))

    proxy !Listen(self)
    proxy !Run

    fishForMessage(1.second) {
      case Stopped(CrawlTimeout, job) => true
      case _ => false
    }

  }

  class FailedCrawl extends CrawlTest {

    def testFailingCrawler(config: CrawlConfig, expectedMsg: String) = {

      val proxy = makeCrawlerProxy(Props(
        classOf[CrawlWorker],
        makeJob(config),
        config,
        new InMemoryFrontier,
        new InMemoryUriCache,
        new ParrotHttpClient(Map.empty),
        mockRobotRulesCache,
        MultiParser.default,
        new DefaultStopRule
      ))

      proxy ! Listen(self)
      proxy ! Run

      fishForMessage(1.second) {
        case StartFailed(CrawlRejectException(msg), _) if (expectedMsg == msg) => true
        case _ => false
      }
    }
  }

  it should "abort when a bad CrawlConfig is discovered" in new FailedCrawl {
    // see TestCrawlConfig for fuller testing
    testFailingCrawler(
        makeConfig("http://site.net").copy(userAgent = None),
        CrawlConfig.UserAgentMissing
    )
  }

  /**
   * Requests can fail for various reasons. These are a completely separate
   * issue to possible 500 errors that may occur on the target server side.
   *
   * - ConnectTimeout
   * - SocketTimeout
   * - MaxContentLengthExceeded - e.g. cut off for very large files
   * - InternalException - thrown for any reason
   *
   */
  // it should "handle a request internal error" in {

  // }

  // it should "handle a request timeout and continue" in {

  // }

  // it should "redirect after a 3XX response up to X times" in {

  // }

}


text:
<?php
//Models and Controllers must named with mixed case, ie. uppercase first letter

class Trails_model extends CI_Model{

	function __construct(){

		parent::__construct();

	}// \__construct

	function get_trails(){

		$query = $this->db->get('robson_valley_trails');
		return $query->result();

	}//\get_letters

/*	function get_trails(){

		$query = $this->db->get('robson_valley_trails');
		return $query->result();

	}//\get_letters*/

	function get_trail_detail($id){
		$this->db->select('*');
		$this->db->from('robson_valley_trails');
		$this->db->where( 'robson_valley_trails.trail_id', $id); //name of column, what we are matching to the column
		$query = $this->db->get();
		return $query->result();
	}// \get_letter_detail

	function get_report_detail($id){

		$this->db->select('*');
		$this->db->from('trail_reports');
		$this->db->join('tank_users', 'tank_users.id = trail_reports.author_id');
		$this->db->where( 'report_id', $id); //name of column, what we are matching to the column
		$query = $this->db->get();
		return $query->result();

	}// \get_report_detail

/*	function get_trail_name($id){

		$this->db->where( 'id', $id); //name of column, what we are matching to the column
		$query = $this->db->get('robson_valley_trails');
		/*$results = $query['trail_name'];*/
		//get trail name from db table
		//return $query->$results();

	//}// \get_letter_detail*/

/*	function get_reports($trail_name){
		$this->db->where('trail_name', $trail_name);
		$query = $this->db->get('trail_reports');
		return $query->results();
	}*/

	function insert_trail($data){
		//print_r($data);
		$this->db->insert('robson_valley_trails', $data);
	}

	function edit_trail($data, $id){
		//print_r($data);
		//where clause...
		$this->db->where( 'trail_id', $id);
		//insert...
		$this->db->update('robson_valley_trails', $data);
	}//\edit_letter

	function delete_trail($id){
		//print_r($id);
		//where clause...
		$this->db->where( 'trail_id', $id);
		//delete...
		$this->db->delete('robson_valley_trails');
	}//\edit_letter

}// \Trail_model