text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors
{
    using System.Collections.Generic;

    using DotNetNuke.Services.Installer.Packages;
    using Newtonsoft.Json;

    [JsonObject]
    public class JsLibraryPackageDetailDto : PackageInfoDto
    {
        public JsLibraryPackageDetailDto()
        {
        }

        public JsLibraryPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package)
        {
        }

        [JsonProperty("objectName")]
        public string ObjectName { get; set; }

        [JsonProperty("defaultCdn")]
        public string DefaultCdn { get; set; }

        [JsonProperty("fileName")]
        public string FileName { get; set; }

        [JsonProperty("location")]
        public string Location { get; set; }

        [JsonProperty("customCdn")]
        public string CustomCdn { get; set; }

        [JsonProperty("dependencies")]
        public IEnumerable<UsedByPackage> Dependencies { get; set; }

        [JsonProperty("usedBy")]
        public IEnumerable<UsedByPackage> UsedBy { get; set; }
    }
}


text:
'''
Plays back recorded joint positions of one of the two Baxter arms.  The
recorded joint positions are from a python-style file in an array called data.
'''

# System includes
import os
import sys

# Local includes
from baxter_projectyouth import util

def print_usage():
    'Prints usage information to the console'
    print 'Usage:'
    print '    {0} <which arm>'.format(__file__)
    print '    {0} --help'
    print
    print 'Description:'
    print '    This script will playback joints saved in the file from the'
    print '    easy_recorder.py script, which is'
    print '        left_save_joints.py (for saving from the left arm)'
    print '        right_save_joints.py (for saving from the rightarm)'
    print
    print '    It will play this in a loop until CTRL-C is pressed by the user.'
    print
    print 'Arguments:'
    print '    <which arm> - This is either "left" or "right" indicating'
    print '                  which arm to control.'
    print
    print '    --help - This option prints this information and exits.'
    print

def main(arguments):
    'Main entry point.  Plays recorded joint angles in a loop until CTRL-C.'

    # Argument parsing
    if '-h' in arguments or '--help' in arguments:
        print_usage()
        return 0

    which_arm = arguments[0]

    # Connect to Baxter
    util.connect_to_baxter('easy_playback_' + which_arm)

    sys.path.append(os.path.realpath(os.curdir))
    if which_arm == 'left':
        import left_saved_joints as saved_joints
    elif which_arm == 'right':
        import right_saved_joints as saved_joints
    else:
        sys.stderr.write('Error: Not a valid first argument: ' + which_arm \
                + '\n')
        print_usage()
        return 1

    # Output some instructions
    print
    print 'This script plays recorded joint positions recorded from the'
    print 'easy_recorder.py script.  These joint positions are of the baxter'
    print 'arms and store in a python file.  The playback will continue in a'
    print 'loop until you press CTRL-C.'
    print
    print 'You have chosen to playback the ' + \
            '{0} arm from {0}_saved_joints.py.'.format(which_arm)
    print
    print 'When you are finished, press <CTRL>-C to quit'
    print

    while util.is_baxter_running():
        for positions in saved_joints.path:
            if which_arm == 'left':
                util.move_left_arm_to_positions(positions)
            elif which_arm == 'right':
                util.move_right_arm_to_positions(positions)

    return 0

# This calls the main() function if this script is called instead of imported
if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

redpajama_set_name: RedPajamaGithub


text:
package bigtable.fraud.beam;

import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions;
import org.apache.beam.sdk.options.Description;

/*
 * This interface contains all the necessary command line arguments when
 * writing to CBT.
 */
public interface LoadDatasetOptions extends DataflowPipelineOptions {

  /**
   * @return Cloud project id.
   */
  @Description("The CBT project id.")
  String getProjectID();

  /**
   * @param projectID the Cloud project id.
   */
  void setProjectID(String projectID);

  /**
   * @return Cloud Bigtable instance id.
   */
  @Description("The CBT instance id.")
  String getCBTInstanceId();

  /**
   * @param instanceID the Cloud Bigtable instance id.
   */
  void setCBTInstanceId(String instanceID);

  /**
   * @return Cloud Bigtable table id.
   */
  @Description("The destination CBT table id.")
  String getCBTTableId();

  /**
   * @param tableID Cloud Bigtable table id.
   */
  void setCBTTableId(String tableID);

  /**
   * @return customer profile input file.
   */
  @Description("The Cloud Storage path to the profile CSV file.")
  String getCustomerProfileInputFile();

  /**
   * @param location customer profile file location.
   */
  void setCustomerProfileInputFile(String location);

  /**
   * @return transactions history input file.
   */
  @Description("The Cloud Storage path to the history CSV file.")
  String getHistoryInputFile();

  /**
   * @param location transaction history file location.
   */
  void setHistoryInputFile(String location);

  /**
   * @return Random UUID.
   */
  @Description("A random UUID to make the job name unique.")
  String getRandomUUID();

  /**
   * @param randomUUID a random string to make the job name unique.
   */
  void setRandomUUID(String randomUUID);
}


text:
@implementation GLBarChart

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];

    if (self) {
        [self.container addSubview:self.chartView];
    }

    return self;
}

#pragma mark - private methods

- (void)parseData {
    [super parseData];

    self.chartData.min = 0.0f;

    [self getYValueRange];
}

- (void)checkData {
    [super checkData];

    NSArray *xValues = self.chartData.xValues;
    NSArray *yValues = self.chartData.yValues;

    [self getYValueGrade];

    if (xValues.count && yValues.count) {
        self.chartData.noData = NO;
    } else {
        self.chartData.noData = YES;
    }
}

- (void)initChart {
    [super initChart];

    CGFloat  w = self.frame.size.width;
    CGFloat  h = self.frame.size.height;

    NSArray *values = self.chartData.xValues;

    CGFloat  margin    = self.chartData.margin;
    CGFloat  barWidth  = self.chartData.barWidth;
    CGFloat  barMargin = self.chartData.barMargin;

    CGFloat contentWidth  = (barWidth + barMargin * 2) * values.count;
    CGFloat contentHeight = h - margin * 2;

    if (contentWidth < w - margin * 2) {
        contentWidth = w - margin * 2;
    }

    CGRect frame = {{0.0f, 0.0f}, {contentWidth, contentHeight}};

    self.chartView.frame       = frame;
    self.container.contentSize = frame.size;

    if (self.chartData.chartInitDirection == GLChartInitDirectionLeft) {
        self.container.contentOffset = CGPointMake(0.0f, 0.0f);
    } else {
        self.container.contentOffset = CGPointMake(contentWidth - (w - margin * 2), 0.0f);
    }

    for (GLBar *bar in self.chartView.subviews) {
        [bar removeFromSuperview];
    }
}

- (void)drawChart {
    [super drawChart];

    CGFloat   h = self.container.contentSize.height;

    NSArray  *values = self.chartData.yValues;

    CGFloat   barWidth  = self.chartData.barWidth;
    CGFloat   barMargin = self.chartData.barMargin;

    for (int i = 0; i < values.count; i++) {
        GLBar *bar = [[GLBar alloc] init];

        CGRect frame = {{(barWidth + barMargin * 2) * i + barMargin, 0.0f}, {barWidth, h}};

        bar.frame = frame;
        bar.data  = values[i];

        [self.chartView addSubview:bar];
    }
}

- (void)getYValueRange {
    for (NSArray *list in self.chartData.yValues) {
        CGFloat value = 0.0f;

        for (NSDictionary *item in list) {
            value += [item[@"value"] floatValue];
        }

        if (self.chartData.count == 0) {
            self.chartData.count = list.count;
        }

        if (self.chartData.max < value) {
            self.chartData.max = value;
        }
    }
}

- (void)getYValueGrade {
    NSMutableArray *yValues = [self.chartData.yValues mutableCopy];

    for (int i = 0; i < yValues.count; i++) {
        NSMutableArray *list = [yValues[i] mutableCopy];

        for (int j = 0; j < list.count; j++) {
            NSMutableDictionary *item = [list[j] mutableCopy];

            CGFloat value = [item[@"value"] floatValue];

            if (self.chartData.max == 0 || value == 0) {
                item[@"grade"] = @0.0f;
            } else {
                item[@"grade"] = @(value / self.chartData.max);
            }

            [list replaceObjectAtIndex:j withObject:item];
        }

        [yValues replaceObjectAtIndex:i withObject:list];
    }

    self.chartData.yValues = yValues;
}

- (void)createXAxisLabels {
    CGFloat   h = self.container.contentSize.height;

    NSArray  *values = self.chartData.xValues;

    CGFloat   barWidth  = self.chartData.barWidth;
    CGFloat   barMargin = self.chartData.barMargin;

    CGFloat   labelFontSize  = self.chartData.labelFontSize;
    NSString *labelTextColor = self.chartData.labelTextColor;

    for (int i = 0; i < values.count; i++) {
        UILabel *label = [[UILabel alloc] init];

        [self.xAxisLabels addObject:label];

        NSString *labelText = [[NSString alloc] initWithFormat:@"%@", values[i]];
        CGSize    labelSize = [labelText sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:labelFontSize]}];
        CGRect    labelRect = {{(barWidth + barMargin * 2) * i, h}, {barWidth + barMargin * 2, labelSize.height}};

        label.frame         = labelRect;
        label.text          = labelText;
        label.font          = [UIFont systemFontOfSize   :labelFontSize];
        label.textColor     = [UIColor colorWithHexString:labelTextColor];
        label.textAlignment = NSTextAlignmentCenter;

        [self.container addSubview:label];
    }
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
    Copyright 2011 Google Inc.
    Copyright 2011 Peter Kuterna

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

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

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

<view
    class="net.peterkuterna.android.apps.devoxxfrsched.ui.widget.ObservableScrollView"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:devoxxfrsched="http://schemas.android.com/apk/res/net.peterkuterna.android.apps.devoxxfrsched"
    android:id="@+id/schedule_items_scroll"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fadingEdge="vertical">
    <view
        class="net.peterkuterna.android.apps.devoxxfrsched.ui.widget.ScheduleItemsLayout"
        android:id="@+id/schedule_items"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layerType="software">
        <view
            class="net.peterkuterna.android.apps.devoxxfrsched.ui.widget.TimeRulerView"
            android:id="@id/schedule_items_ruler"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            devoxxfrsched:headerWidth="@dimen/schedule_label_header_width"
            devoxxfrsched:hourHeight="@dimen/schedule_hour_height"
            devoxxfrsched:horizDivider="true"
            devoxxfrsched:labelTextSize="@dimen/text_size_small"
            devoxxfrsched:labelPaddingLeft="@dimen/schedule_label_padding"
            devoxxfrsched:labelColor="#000000"
            devoxxfrsched:dividerColor="#22000000"
            devoxxfrsched:startHour="7"
            devoxxfrsched:endHour="23" />
        <View
            android:id="@id/schedule_items_now"
            android:background="@drawable/now_bar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </view>
</view>


text:
class CreateUserAddedData < ActiveRecord::Migration
  def change
    create_table :user_added_data do |t|
      t.integer :user_id, :null => false
      t.string :subject, :null => false
      t.string :predicate, :null => false
      t.string :object, :null => false
      t.timestamps
      t.datetime :deleted_at
    end
    add_index :user_added_data, :user_id, :name => 'user_id'
    add_index :user_added_data, :subject, :name => 'subject'

    create_table :user_added_data_metadata do |t|
      t.integer :user_added_data_id, :null => false
      t.string :predicate, :null => false
      t.string :object, :null => false
      t.timestamps
    end
    add_index :user_added_data_metadata, :user_added_data_id, :name => 'user_added_data_id'

    create_table :curated_structured_data do |t|
      t.integer :user_id, :null => false
      t.string :subject, :null => false
      t.string :predicate, :null => false
      t.string :object, :null => false
      t.integer :vetted_id, :null => false
      t.integer :visibility_id, :null => false
      t.integer :comment_id, :null => false
      t.timestamps
    end
    add_index :curated_structured_data, :user_id, :name => 'user_id'
    add_index :curated_structured_data, :subject, :name => 'subject'
  end
end


text:
using System.Collections.Generic;

public class Team
{
	public int TeamNo = -1;

	public int Resources = 8000;
	public List<Unit> Units = new List<Unit>();
	public List<Building> Buildings = new List<Building>();

	private const int INCOME_PER_BUILDING = 3000;

	public void GainIncome()
	{
		Resources += INCOME_PER_BUILDING * Buildings.Count;
	}

	public void ResetUnits()
	{
		for (int i = 0; i < Units.Count; i++)
		{
			Units[i].Reset();
		}
		for (int i = 0; i < Buildings.Count; i++)
		{
			Buildings[i].Reset();
		}
	}

	public void HealUnitsInCities()
	{
		for (int i = 0; i < Units.Count; i++)
		{
			if (Units[i].GetHitPoints() != 10 && Units[i].BuildingOn != null && Units[i].BuildingOn.Team == Units[i].Team)
			{
				if (Units[i].BuildingOn.Type == Building.CITY)
					Units[i].Heal(1);
				else if (Units[i].BuildingOn.Type == Building.BASE)
					Units[i].Heal(2);
			}
		}
	}
	public void HealUncontestedBuildings()
	{
		for (int i = 0; i < Buildings.Count; i++)
		{
			if (Buildings[i].GetHitPoints() < Buildings[i].GetHitPointsMax() && (Buildings[i].UnitOnTop == null || Buildings[i].UnitOnTop.Team == TeamNo))
				Buildings[i].Heal(2);
		}
	}
}


text:
import React from 'react';
import "./styles.css";

import Section from '../Section';

const SectionDark = (props) => <Section {...props} className="SectionDark">{props.children}</Section>;

export default SectionDark


text:
package org.linkedin.glu.provisioner.plan.api;

/**
 * @author ypujante@linkedin.com
 */
public class StepFilters
{
  public static IStepFilter ACCEPT_ALL = new IStepFilter()
  {
    @Override
    public boolean accept(IStep iStep)
    {
      return true;
    }
  };

  @SuppressWarnings("unchecked")
  public static <T> IStepFilter<T> acceptAll()
  {
    return ACCEPT_ALL;
  }

  /**
   * Constructor
   */
  public StepFilters()
  {
  }
}


text:
$:.unshift File.expand_path(File.join(File.dirname(__FILE__), 'builder'))

require 'assets_handler'
require 'html_helper'
require 'test_builder'
require 'template'
require 'fixtures'
require 'builder_options'
require 'suite_builder'
require 'missing_template_error'

module UnittestJS
  module Builder
    def self.empty_dir!(dir)
      dir = DirPathname.new(dir)
      dir.exists? ? dir.empty! : dir.mk_and_stamp!
    end
  end
end


text:
class AddSignedToUsers < ActiveRecord::Migration
  def change
    add_column :users, :signed, :boolean, :default => false
  end
end


text:
<?php

namespace RedisClient\Command\Traits\Version3x0;

/**
 * Cluster Commands
 * @link http://redis.io/commands#cluster
 * @link http://redis.io/topics/cluster-tutorial
 */
trait ClusterCommandsTrait {

    /**
     * CLUSTER ADDSLOTS slot [slot ...]
     * Available since 3.0.0.
     * Time complexity: O(N) where N is the total number of hash slot arguments
     * @link http://redis.io/commands/cluster-addslots
     *
     * @param int|int[] $slots
     * @return bool True if the command was successful. Otherwise an error is returned.
     */
    public function clusterAddslots($slots) {
        return $this->returnCommand(['CLUSTER', 'ADDSLOTS'], null, (array)$slots);
    }

    /**
     * CLUSTER COUNT-FAILURE-REPORTS node-id
     * Available since 3.0.0.
     * Time complexity: O(N) where N is the number of failure reports
     * @link http://redis.io/commands/cluster-count-failure-reports
     *
     * @param int $nodeId
     * @return int The number of active failure reports for the node.
     */
    public function clusterCountFailureReports($nodeId) {
        return $this->returnCommand(['CLUSTER', 'COUNT-FAILURE-REPORTS'], null, [$nodeId]);
    }

    /**
     * CLUSTER COUNTKEYSINSLOT slot
     * Available since 3.0.0.
     * Time complexity: O(1)
     * @link http://redis.io/commands/cluster-countkeysinslot
     *
     * @param int $slot
     * @return int
     */
    public function clusterCountkeysinslot($slot) {
        return $this->returnCommand(['CLUSTER', 'COUNTKEYSINSLOT'], null, [$slot]);
    }

    /**
     * CLUSTER DELSLOTS slot [slot ...]
     * Available since 3.0.0.
     * Time complexity: O(N) where N is the total number of hash slot arguments
     * @link http://redis.io/commands/cluster-delslots
     *
     * @param int|int[] $slots
     * @return bool True if the command was successful. Otherwise an error is returned.
     */
    public function clusterDelslots($slots) {
        return $this->returnCommand(['CLUSTER', 'DELSLOTS'], null, (array)$slots);
    }

    /**
     * CLUSTER FAILOVER [FORCE|TAKEOVER]
     * Available since 3.0.0.
     * Time complexity: O(1)
     * @link http://redis.io/commands/cluster-failover
     *
     * @param string|null $option FORCE|TAKEOVER
     * @return
     */
    public function clusterFailover($option = null) {
        return $this->returnCommand(['CLUSTER', 'FAILOVER'], null, $option ? [$option] : null);
    }

    /**
     * CLUSTER FORGET node-id
     * Available since 3.0.0.
     * Time complexity: O(1)
     * @link http://redis.io/commands/cluster-forget
     *
     * @param int $nodeId
     * @return bool True if the command was executed successfully, otherwise an error is returned.
     */
    public function clusterForget($nodeId) {
        return $this->returnCommand(['CLUSTER', 'FORGET'], null, [$nodeId]);
    }

    /**
     * CLUSTER GETKEYSINSLOT slot count
     * Available since 3.0.0.
     * Time complexity: O(log(N)) where N is the number of requested keys
     * @link http://redis.io/commands/cluster-getkeysinslot
     *
     * @param int $slot
     * @param int $count
     * @return array From 0 to count key names in a Redis array reply.
     */
    public function clusterGetkeysinslot($slot, $count) {
        return $this->returnCommand(['CLUSTER', 'GETKEYSINSLOT'], null, [$slot, $count]);
    }

    /**
     * CLUSTER INFO
     * Available since 3.0.0.
     * Time complexity: O(1)
     * @link http://redis.io/commands/cluster-info
     *
     * @return string A map between named fields and values in the form of <field>:<value>
     * lines separated by newlines composed by the two bytes CRLF.
     */
    public function clusterInfo() {
        return $this->returnCommand(['CLUSTER', 'INFO']);
    }

    /**
     * CLUSTER KEYSLOT key
     * Available since 3.0.0.
     * Time complexity: O(N) where N is the number of bytes in the key
     * @link http://redis.io/commands/cluster-keyslot
     *
     * @param string $key
     * @return int The hash slot number.
     */
    public function clusterKeyslot($key) {
        return $this->returnCommand(['CLUSTER', 'KEYSLOT'], $key, [$key]);
    }

    /**
     * CLUSTER MEET ip port
     * Available since 3.0.0.
     * Time complexity: O(1)
     * @link http://redis.io/commands/cluster-meet
     *
     * @param string $ip
     * @param int $port
     * @return bool True if the command was successful.
     * If the address or port specified are invalid an error is returned.
     */
    public function clusterMeet($ip, $port) {
        return $this->returnCommand(['CLUSTER', 'MEET'], null, [$ip, $port]);
    }

    /**
     * CLUSTER NODES
     * Available since 3.0.0.
     * Time complexity: O(N) where N is the total number of Cluster nodes
     * @link http://redis.io/commands/cluster-nodes
     *
     * @return string The serialized cluster configuration.
     */
    public function clusterNodes() {
        return $this->returnCommand(['CLUSTER', 'NODES']);
    }

    /**
     * CLUSTER REPLICATE node-id
     * Available since 3.0.0.
     * Time complexity: O(1)
     * @link http://redis.io/commands/cluster-replicate
     *
     * @param int $nodeId
     * @return bool True if the command was executed successfully, otherwise an error is returned.
     */
    public function clusterReplicate($nodeId) {
        return $this->returnCommand(['CLUSTER', 'REPLICATE'], null, [$nodeId]);
    }

    /**
     * CLUSTER RESET [HARD|SOFT]
     * Available since 3.0.0.
     * Time complexity: O(N) where N is the number of known nodes.
     * The command may execute a FLUSHALL as a side effect.
     * @link http://redis.io/commands/cluster-reset
     *
     * @param string $option HARD|SOFT
     * @return bool True if the command was successful. Otherwise an error is returned.
     */
    public function clusterReset($option = null) {
        return $this->returnCommand(['CLUSTER', 'RESET'], null, $option ? [$option] : null);
    }

    /**
     * CLUSTER SAVECONFIG
     * Available since 3.0.0.
     * Time complexity: O(1)
     * @link http://redis.io/commands/cluster-saveconfig
     *
     * @return bool
     */
    public function clusterSaveconfig() {
        return $this->returnCommand(['CLUSTER', 'SAVECONFIG']);
    }

    /**
     * CLUSTER SET-CONFIG-EPOCH config-epoch
     * Available since 3.0.0.
     * Time complexity: O(1)
     * @link http://redis.io/commands/cluster-set-config-epoch
     *
     * @param string $config
     * @return bool True if the command was executed successfully, otherwise an error is returned.
     */
    public function clusterSetConfigEpoch($config) {
        return $this->returnCommand(['CLUSTER', 'SET-CONFIG-EPOCH'], null, [$config]);
    }

    /**
     * CLUSTER SETSLOT slot IMPORTING|MIGRATING|STABLE|NODE [node-id]
     * Available since 3.0.0.
     * Time complexity: O(1)
     * @link http://redis.io/commands/cluster-setslot
     *
     * @param string $slot
     * @param string $subcommand IMPORTING|MIGRATING|STABLE|NODE
     * @param int|null $nodeId
     * @return bool All the subcommands return OK if the command was successful. Otherwise an error is returned.
     */
    public function clusterSetslot($slot, $subcommand, $nodeId = null) {
        $params = [$slot, $subcommand];
        if (isset($nodeId)) {
            $params[] = $nodeId;
        }
        return $this->returnCommand(['CLUSTER', 'SETSLOT'], null, $params);
    }

    /**
     * CLUSTER SLAVES node-id
     * Available since 3.0.0.
     * Time complexity: O(1)
     * @link http://redis.io/commands/cluster-slaves
     *
     * @param int $nodeId
     * @return string The serialized cluster configuration.
     */
    public function clusterSlaves($nodeId) {
        return $this->returnCommand(['CLUSTER', 'SLAVES'], null, [$nodeId]);
    }

    /**
     * CLUSTER SLOTS
     * Available since 3.0.0.
     * Time complexity: O(N) where N is the total number of Cluster nodes
     * @link http://redis.io/commands/cluster-slots
     *
     * @return array Nested list of slot ranges with IP/Port mappings.
     */
    public function clusterSlots() {
        return $this->returnCommand(['CLUSTER', 'SLOTS']);
    }

    /**
     * READONLY
     * Available since 3.0.0.
     * Time complexity: O(1)
     * @link http://redis.io/commands/readonly
     *
     * @return bool
     */
    public function readonly() {
        return $this->returnCommand(['READONLY']);
    }

    /**
     * READWRITE
     * Available since 3.0.0.
     * Time complexity: O(1)
     * @link http://redis.io/commands/readwrite
     *
     * @return bool
     */
    public function readwrite() {
        return $this->returnCommand(['READWRITE']);
    }

}


text:
/*!
  \file
  \brief  Envelope extraction prototypes
*/

#ifndef __ENVELOPE_EXTRACTION_H
#define __ENVELOPE_EXTRACTION_H

#include "sbrdecoder.h"

#include "FDK_bitstream.h"
#include "lpp_tran.h"

#include "psdec.h"

#define ENV_EXP_FRACT 0
/*!< Shift raw envelope data to support fractional numbers.
  Can be set to 8 instead of 0 to enhance accuracy during concealment.
  This is not required for conformance and #requantizeEnvelopeData() will
  become more expensive.
*/

#define EXP_BITS 6
/*!< Size of exponent-part of a pseudo float envelope value (should be at least 6).
  The remaining bits in each word are used for the mantissa (should be at least 10).
  This format is used in the arrays iEnvelope[] and sbrNoiseFloorLevel[]
  in the FRAME_DATA struct which must fit in a certain part of the output buffer
  (See buffer management in sbr_dec.cpp).
  Exponents and mantissas could also be stored in separate arrays.
  Accessing the exponent or the mantissa would be simplified and the masks #MASK_E
  resp. #MASK_M would   no longer be required.
*/

#define MASK_M (((1 << (FRACT_BITS - EXP_BITS)) - 1) << EXP_BITS)  /*!< Mask for extracting the mantissa of a pseudo float envelope value */
#define MASK_E ((1 << EXP_BITS) - 1)           /*!< Mask for extracting the exponent of a pseudo float envelope value */

#define SIGN_EXT ( ((SCHAR)-1) ^ MASK_E)        /*!< a CHAR-constant with all bits above our sign-bit set */
#define ROUNDING ( (FIXP_SGL)(1<<(EXP_BITS-1)) ) /*!< 0.5-offset for rounding the mantissa of a pseudo-float envelope value */
#define NRG_EXP_OFFSET  16                     /*!< Will be added to the reference energy's exponent to prevent negative numbers */
#define NOISE_EXP_OFFSET  38                   /*!< Will be added to the noise level exponent to prevent negative numbers */

typedef enum
{
  HEADER_NOT_PRESENT,
  HEADER_OK,
  HEADER_RESET
}
SBR_HEADER_STATUS;

typedef enum
{
  SBR_NOT_INITIALIZED,
  UPSAMPLING,
  SBR_HEADER,
  SBR_ACTIVE
}
SBR_SYNC_STATE;

typedef enum
{
  COUPLING_OFF = 0,
  COUPLING_LEVEL,
  COUPLING_BAL
}
COUPLING_MODE;

typedef struct
{
  UCHAR nSfb[2];           /*!< Number of SBR-bands for low and high freq-resolution */
  UCHAR nNfb;              /*!< Actual number of noise bands to read from the bitstream*/
  UCHAR numMaster;         /*!< Number of SBR-bands in v_k_master */
  UCHAR lowSubband;        /*!< QMF-band where SBR frequency range starts */
  UCHAR highSubband;       /*!< QMF-band where SBR frequency range ends */
  UCHAR limiterBandTable[MAX_NUM_LIMITERS+1]; /*!< Limiter band table. */
  UCHAR noLimiterBands;    /*!< Number of limiter bands. */
  UCHAR nInvfBands;        /*!< Number of bands for inverse filtering */
  UCHAR *freqBandTable[2]; /*!< Pointers to freqBandTableLo and freqBandTableHi */
  UCHAR freqBandTableLo[MAX_FREQ_COEFFS/2+1];
                                   /*!< Mapping of SBR bands to QMF bands for low frequency resolution */
  UCHAR freqBandTableHi[MAX_FREQ_COEFFS+1];
                                   /*!< Mapping of SBR bands to QMF bands for high frequency resolution */
  UCHAR freqBandTableNoise[MAX_NOISE_COEFFS+1];
                                   /*!< Mapping of SBR noise bands to QMF bands */
  UCHAR v_k_master[MAX_FREQ_COEFFS+1];
                                   /*!< Master BandTable which freqBandTable is derived from */
}
FREQ_BAND_DATA;

typedef FREQ_BAND_DATA *HANDLE_FREQ_BAND_DATA;

#define SBRDEC_ELD_GRID        1
#define SBRDEC_SYNTAX_SCAL     2
#define SBRDEC_SYNTAX_USAC     4
#define SBRDEC_SYNTAX_RSVD50   8
#define SBRDEC_LOW_POWER      16  /* Flag indicating that Low Power QMF mode shall be used. */
#define SBRDEC_PS_DECODED     32  /* Flag indicating that PS was decoded and rendered. */
#define SBRDEC_LD_MPS_QMF    512  /* Flag indicating that the LD-MPS QMF shall be used. */
#define SBRDEC_DOWNSAMPLE   8192  /* Flag indicating that the downsampling mode is used. */
#define SBRDEC_FLUSH       16384  /* Flag is used to flush all elements in use. */
#define SBRDEC_FORCE_RESET 32768  /* Flag is used to force a reset of all elements in use. */

#define SBRDEC_HDR_STAT_RESET  1
#define SBRDEC_HDR_STAT_UPDATE 2

typedef struct {
  UCHAR ampResolution;       /*!< Amplitude resolution of envelope values (0: 1.5dB, 1: 3dB) */
  UCHAR xover_band;          /*!< Start index in #v_k_master[] used for dynamic crossover frequency */
  UCHAR sbr_preprocessing;   /*!< SBR prewhitening flag. */
} SBR_HEADER_DATA_BS_INFO;

typedef struct {
  /* Changes in these variables causes a reset of the decoder */
  UCHAR startFreq;           /*!< Index for SBR start frequency */
  UCHAR stopFreq;            /*!< Index for SBR highest frequency */
  UCHAR freqScale;           /*!< 0: linear scale,  1-3 logarithmic scales */
  UCHAR alterScale;          /*!< Flag for coarser frequency resolution */
  UCHAR noise_bands;         /*!< Noise bands per octave, read from bitstream*/

  /* don't require reset */
  UCHAR limiterBands;        /*!< Index for number of limiter bands per octave */
  UCHAR limiterGains;        /*!< Index to select gain limit */
  UCHAR interpolFreq;        /*!< Select gain calculation method (1: per QMF channel, 0: per SBR band) */
  UCHAR smoothingLength;     /*!< Smoothing of gains over time (0: on  1: off) */

} SBR_HEADER_DATA_BS;

typedef struct
{
  SBR_SYNC_STATE syncState;    /*!< The current initialization status of the header */

  UCHAR status;                /*!< Flags field used for signaling a reset right before the processing starts and an update from config (e.g. ASC). */
  UCHAR frameErrorFlag;        /*!< Frame data valid flag. CAUTION: This variable will be overwritten by the flag stored in the element structure.
                                    This is necessary because of the frame delay. There it might happen that different slots use the same header. */
  UCHAR numberTimeSlots;       /*!< AAC: 16,15 */
  UCHAR numberOfAnalysisBands; /*!< Number of QMF analysis bands */
  UCHAR timeStep;              /*!< Time resolution of SBR in QMF-slots */
  UINT  sbrProcSmplRate;       /*!< SBR processing sampling frequency (!= OutputSamplingRate)
                                     (always: CoreSamplingRate * UpSamplingFactor; even in single rate mode) */

  SBR_HEADER_DATA_BS      bs_data;  /*!< current SBR header. */
  SBR_HEADER_DATA_BS_INFO bs_info;  /*!< SBR info. */

  FREQ_BAND_DATA freqBandData;  /*!< Pointer to struct #FREQ_BAND_DATA */
}
SBR_HEADER_DATA;

typedef SBR_HEADER_DATA *HANDLE_SBR_HEADER_DATA;

typedef struct
{
  UCHAR frameClass;               /*!< Select grid type */
  UCHAR nEnvelopes;               /*!< Number of envelopes */
  UCHAR borders[MAX_ENVELOPES+1]; /*!< Envelope borders (in SBR-timeslots, e.g. mp3PRO: 0..11) */
  UCHAR freqRes[MAX_ENVELOPES];   /*!< Frequency resolution for each envelope (0=low, 1=high) */
  SCHAR  tranEnv;                 /*!< Transient envelope, -1 if none */
  UCHAR nNoiseEnvelopes;          /*!< Number of noise envelopes */
  UCHAR bordersNoise[MAX_NOISE_ENVELOPES+1];/*!< borders of noise envelopes */
}
FRAME_INFO;

typedef struct
{
  FIXP_SGL sfb_nrg_prev[MAX_FREQ_COEFFS];    /*!< Previous envelope (required for differential-coded values) */
  FIXP_SGL prevNoiseLevel[MAX_NOISE_COEFFS]; /*!< Previous noise envelope (required for differential-coded values) */
  COUPLING_MODE coupling;                    /*!< Stereo-mode of previous frame */
  INVF_MODE sbr_invf_mode[MAX_INVF_BANDS];   /*!< Previous strength of filtering in transposer */
  UCHAR ampRes;                              /*!< Previous amplitude resolution (0: 1.5dB, 1: 3dB) */
  UCHAR stopPos;                             /*!< Position in time where last envelope ended */
  UCHAR frameErrorFlag;                      /*!< Previous frame status */
}
SBR_PREV_FRAME_DATA;

typedef SBR_PREV_FRAME_DATA *HANDLE_SBR_PREV_FRAME_DATA;

typedef struct
{
  int nScaleFactors;                    /*!< total number of scalefactors in frame */

  FRAME_INFO frameInfo;                 /*!< time grid for current frame */
  UCHAR domain_vec[MAX_ENVELOPES];      /*!< Bitfield containing direction of delta-coding for each envelope (0:frequency, 1:time) */
  UCHAR domain_vec_noise[MAX_NOISE_ENVELOPES]; /*!< Same as above, but for noise envelopes */

  INVF_MODE sbr_invf_mode[MAX_INVF_BANDS]; /*!< Strength of filtering in transposer */
  COUPLING_MODE coupling;                  /*!< Stereo-mode */
  int ampResolutionCurrentFrame;           /*!< Amplitude resolution of envelope values (0: 1.5dB, 1: 3dB) */

  UCHAR addHarmonics[MAX_FREQ_COEFFS];     /*!< Flags for synthetic sine addition */

  FIXP_SGL iEnvelope[MAX_NUM_ENVELOPE_VALUES];       /*!< Envelope data */
  FIXP_SGL sbrNoiseFloorLevel[MAX_NUM_NOISE_VALUES]; /*!< Noise envelope data */
}
SBR_FRAME_DATA;

typedef SBR_FRAME_DATA *HANDLE_SBR_FRAME_DATA;

void initSbrPrevFrameData (HANDLE_SBR_PREV_FRAME_DATA h_prev_data,
                           int timeSlots);

int sbrGetSingleChannelElement (HANDLE_SBR_HEADER_DATA hHeaderData,
                                HANDLE_SBR_FRAME_DATA  hFrameData,
                                HANDLE_FDK_BITSTREAM   hBitBuf,
                                HANDLE_PS_DEC hParametricStereoDec,
                                const UINT             flags,
                                const int              overlap
                               );

int sbrGetChannelPairElement (HANDLE_SBR_HEADER_DATA hHeaderData,
                              HANDLE_SBR_FRAME_DATA  hFrameDataLeft,
                              HANDLE_SBR_FRAME_DATA  hFrameDataRight,
                              HANDLE_FDK_BITSTREAM   hBitBuf,
                              const UINT             flags,
                              const int              overlap);

SBR_HEADER_STATUS
sbrGetHeaderData (HANDLE_SBR_HEADER_DATA headerData,
                  HANDLE_FDK_BITSTREAM   hBitBuf,
                  const UINT             flags,
                  const int              fIsSbrData);

/*!
  \brief     Initialize SBR header data

  Copy default values to the header data struct and patch some entries
  depending on the core codec.
*/
SBR_ERROR
initHeaderData (
        HANDLE_SBR_HEADER_DATA  hHeaderData,
        const int               sampleRateIn,
        const int               sampleRateOut,
        const int               samplesPerFrame,
        const UINT              flags
        );
#endif


text:
import pify from 'pify'
import { loadModule } from './utils/load-module'

/* eslint import/no-anonymous-default-export: [2, {"allowObject": true}] */
export default {
  name: 'stylus',
  test: /\.(styl|stylus)$/,
  async process({ code }) {
    const stylus = loadModule('stylus')
    if (!stylus) {
      throw new Error('You need to install "stylus" packages in order to process Stylus files')
    }

    const style = stylus(code, {
      ...this.options,
      filename: this.id,
      sourcemap: this.sourceMap && {}
    })

    const css = await pify(style.render.bind(style))()
    const deps = style.deps()
    for (const dep of deps) {
      this.dependencies.add(dep)
    }

    return {
      code: css,
      map: style.sourcemap
    }
  }
}


text: """General purpose flows."""


text:
import glob
import json
import os
import sys
import time
# Third-party
import requests

class ServiceConfig(object):
    class CheckResult(object):
        """Result of checking a service.
        For ones that fail, status code is 0 for network errors and an HTTP code
        for HTTP errors.
        """
        def __init__(self, service, url, elapsed, code=200, error=""):
            self.service, self.url, self.elapsed = service, url, elapsed
            self.status_code, self.reason = code, error
        def is_success(self):
            return self.status_code == 200
        def is_network_failure(self):
            return self.status_code == 0
        def __str__(self):
            ok = ("failed", "succeeded")[self.is_success()]
            e = [" ({})".format(self.reason), ""][self.is_success()]
            return "{} [{}] {} = {}{}".format(ok, self.status_code, self.service, self. url, e)
        __repr__  = __str__

    def __init__(self, basepath=None):
        d = json.load(open(os.path.join(basepath, "services.json")))
        self.mode = d['config']
        self.conf = d[self.mode]
        self.services = {k:v for k,v in self.conf.items()
                                          if hasattr(v, 'startswith') and v.startswith("http")}

    def check_all(self):
        """Check all services. This may take a while.
        Runs as a generator that yields a ServiceConfig.CheckResult object.
        """
        for service in sorted(self.services.keys()):
            yield self.check(service)

    def check(self, service):
        """Check one service.
        TODO: Replace generic HTTP GET with service-specific operation.
        """
        url = self.services[service]
        try:
            t0 = time.time()
            r = requests.get(url, timeout=4)
            t1 = time.time()
            if r.status_code == 200:
                return self.CheckResult(service, url, t1 - t0)
            else:
                return self.CheckResult(service, url, -1, r.status_code, r.reason)
        except Exception, e:
            return self.CheckResult(service, url,  -1, 0, e)

    def __str__(self):
        s = "Mode '{}':\n".format(self. mode)
        for k in sorted(self.conf.keys()):
            s += "  {:32} {}\n".format(k, self.conf[k])
        return s


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using Liveo.Framework.Model;
using Liveo.Framework.Model.Service;
using Liveo.Platform.Data;

namespace Liveo.Platform.Services
{
    public class LiveoSurveyQuestionService : SurveyQuestionService, ILiveoSurveyQuestionService
    {
        public LiveoSurveyQuestionService(ILiveoSurveyQuestionRepository repository) : base(repository) {}

        public override void Add(SurveyQuestion entity)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.Suppress)) {
                base.Add(entity);
                scope.Complete();
            }

        }

        public override void Save(SurveyQuestion entity)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
            {
                base.Save(entity);
                scope.Complete();
            }

        }

        public override void Delete(SurveyQuestion entity)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
            {
                base.Delete(entity);
                scope.Complete();
            }

        }

        public override SurveyQuestion GetById(int id) {
            SurveyQuestion entity = null;
            using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
            {
                entity = base.GetById(id);
            }
            return entity;
        }
    }
}


text:
package fi.bitrite.android.ws.persistence.impl;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import fi.bitrite.android.ws.model.Feedback;
import fi.bitrite.android.ws.model.Host;
import fi.bitrite.android.ws.model.HostBriefInfo;
import fi.bitrite.android.ws.persistence.StarredHostDao;

import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class StarredHostDaoImpl implements StarredHostDao {

    private SQLiteDatabase database;
    private DbHelper dbHelper;

    public void open() throws SQLException {
        if (dbHelper == null) {
            dbHelper = new DbHelper();
        }
        database = dbHelper.getWritableDatabase();
    }

    public void close() {
        if (database != null && database.isOpen()) {
            database.close();
        }
    }

    public void insert(int id, String name, Host host, List<Feedback> feedback) {
        ContentValues values = new ContentValues();
        values.put(DbHelper.COLUMN_ID, id);
        values.put(DbHelper.COLUMN_NAME, name);
        values.put(DbHelper.COLUMN_UPDATED, System.currentTimeMillis() / 1000L); // As expected to be used later

        Gson gson = new Gson();
        String details = gson.toJson(host);
        values.put(DbHelper.COLUMN_DETAILS, details);

        String feedbackJson = gson.toJson(feedback);
        values.put(DbHelper.COLUMN_FEEDBACK, feedbackJson);

        database.insert(DbHelper.TABLE_HOSTS, null, values);
    }

    public Host getHost(int id) {
        Cursor cursor;

        if (id > 0) {
            cursor = database.query(DbHelper.TABLE_HOSTS, new String[]{DbHelper.COLUMN_ID, DbHelper.COLUMN_DETAILS,
                    DbHelper.COLUMN_UPDATED}, DbHelper.COLUMN_ID + " = " + id, null, null, null, null);
        } else {
            cursor = database.query(DbHelper.TABLE_HOSTS, new String[]{DbHelper.COLUMN_NAME, DbHelper.COLUMN_DETAILS,
                    DbHelper.COLUMN_UPDATED}, DbHelper.COLUMN_NAME + " = '" + id + "'", null, null, null, null);
        }

        if (cursor.getCount() == 0) {
            cursor.close();
            return null;
        }

        cursor.moveToFirst();
        Host host = cursorToHost(cursor);

        cursor.close();
        return host;
    }

    private Host cursorToHost(Cursor cursor) {
        String json = cursor.getString(1);
        Gson gson = new Gson();
        try {
            Host host = gson.fromJson(json, Host.class);
            host.setUpdated(cursor.getLong(cursor.getColumnIndex(DbHelper.COLUMN_UPDATED)));
            return host;
        } catch (Exception e) {
            throw new PersistenceException("Could not load starred host details");
        }
    }

    public ArrayList<Feedback> getFeedback(int id, String name) {
        Cursor cursor;

        if (id > 0) {
            cursor = database.query(DbHelper.TABLE_HOSTS, new String[]{DbHelper.COLUMN_FEEDBACK},
                    DbHelper.COLUMN_ID + " = " + id, null, null, null, null);
        } else {
            cursor = database.query(DbHelper.TABLE_HOSTS, new String[]{DbHelper.COLUMN_FEEDBACK},
                    DbHelper.COLUMN_NAME + " = '" + name + "'", null, null, null, null);
        }

        if (cursor.getCount() == 0) {
            cursor.close();
            return null;
        }

        cursor.moveToFirst();
        ArrayList<Feedback> feedback = cursorToFeedback(cursor);

        cursor.close();
        return feedback;
    }

    private ArrayList<Feedback> cursorToFeedback(Cursor cursor) {
        String json = cursor.getString(0);
        Gson gson = new Gson();
        try {
            Type listType = new TypeToken<List<Feedback>>() {
            }.getType();
            ArrayList<Feedback> feedback = gson.fromJson(json, listType);
            return feedback;
        } catch (Exception e) {
            throw new PersistenceException("Could not load host feedback");
        }
    }

    public List<HostBriefInfo> getAllBrief() {
        Cursor cursor = database.query(DbHelper.TABLE_HOSTS, new String[]{DbHelper.COLUMN_ID,
                DbHelper.COLUMN_DETAILS, DbHelper.COLUMN_UPDATED}, null, null, null, null, null);

        if (cursor.getCount() == 0) {
            cursor.close();
            return Collections.emptyList();
        }

        List<HostBriefInfo> hosts = new ArrayList<HostBriefInfo>();

        while (!cursor.isLast()) {
            cursor.moveToNext();
            Host host = cursorToHost(cursor);
            hosts.add(new HostBriefInfo(cursor.getInt(0), host));
        }

        cursor.close();

        return hosts;
    }

    public void delete(int id, String name) {
        if (id > 0) {
            database.delete(DbHelper.TABLE_HOSTS, DbHelper.COLUMN_ID + " = " + id, null);
        } else {
            database.delete(DbHelper.TABLE_HOSTS, DbHelper.COLUMN_NAME + " = '" + name + "'", null);
        }
    }

    public void update(int id, String name, Host host, List<Feedback> feedback) {
        delete(id, name);
        insert(id, name, host, feedback);
    }

    public boolean isHostStarred(int id, String name) {
        return (getHost(id) != null);
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<link rel="stylesheet" href="../../resources/js-test-style.css"/>

<title>WebGL 2 Object Expandos Conformance Test</title>

<canvas id="canvas" width="8" height="8" style="width: 8px; height: 8px;"></canvas>


text:
package org.rabix.executor.execution;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import org.rabix.bindings.model.Job;
import org.rabix.executor.engine.EngineStub;
import org.rabix.executor.handler.JobHandlerFactory;
import org.rabix.executor.model.JobData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Job execution command dispatcher.
 */
public class JobHandlerCommandDispatcher {

  private static final Logger logger = LoggerFactory.getLogger(JobHandlerCommandDispatcher.class);

  private final JobHandlerFactory jobHandlerFactory;

  private final Map<String, Map<String, JobHandlerRunnable>> jobHandlerRunnables = new HashMap<>();

  private final ThreadFactory jobHandlerThreadFactory;
  private final ExecutorService jobHandlerThreadExecutor;
  private final ScheduledExecutorService jobHandlerThreadCleanExecutor;

  @Inject
  public JobHandlerCommandDispatcher(JobHandlerFactory jobHandlerFactory) {
    this.jobHandlerFactory = jobHandlerFactory;
    this.jobHandlerThreadFactory = buildJobHandlerThreadFactory();
    this.jobHandlerThreadExecutor = Executors.newCachedThreadPool(jobHandlerThreadFactory);
    this.jobHandlerThreadCleanExecutor = Executors.newScheduledThreadPool(1);
    init();
  }

  /**
   * Initializes dispatcher
   */
  private void init() {
    scheduleCleaner();
  }

  /**
   * Dispatch commands to appropriate runnable threads
   */
  public void dispatch(JobData jobData, JobHandlerCommand command, EngineStub<?,?,?> engineStub) {
    synchronized (jobHandlerRunnables) {
      String contextId = jobData.getJob().getRootId();
      JobHandlerRunnable jobHandlerRunnable = getJobs(contextId).get(jobData.getJob().getId());

      if (jobHandlerRunnable == null) {
        Job job = jobData.getJob();
        jobHandlerRunnable = new JobHandlerRunnable(job.getId(), job.getRootId(), jobHandlerFactory.createHandler(job, engineStub));
        getJobs(contextId).put(job.getId(), jobHandlerRunnable);
        jobHandlerThreadExecutor.execute(jobHandlerRunnable);
        logger.info("JobHandlerRunnable created for {}.", job.getId());
      }
      jobHandlerRunnable.addCommand(command);
    }
  }

  private Map<String, JobHandlerRunnable> getJobs(String contextId) {
    synchronized (jobHandlerRunnables) {
      Map<String, JobHandlerRunnable> jobList = jobHandlerRunnables.get(contextId);
      if (jobList == null) {
        jobList = new HashMap<>();
        jobHandlerRunnables.put(contextId, jobList);
      }
      return jobList;
    }
  }

  /**
   * Creates simple Job handler thread factory
   */
  private ThreadFactory buildJobHandlerThreadFactory() {
    return new JobHandlerThreadFactoryBuilder()
      .setNamePrefix("JobHandler-Thread")
      .setDaemon(false)
      .setPriority(Thread.MAX_PRIORITY)
      .setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
          logger.error(String.format("Thread %s threw exception - %s", t.getName(), e.getMessage()));
        }
      }).build();
  }

  /**
   * Schedule cleaner thread that will go through the list of Job threads
   */
  private void scheduleCleaner() {
    jobHandlerThreadCleanExecutor.scheduleWithFixedDelay(new Runnable() {
      @Override
      public void run() {
        synchronized (jobHandlerRunnables) {
          logger.debug("Cleaner thread is executing. There are {} runnable(s) in the pool.", jobHandlerRunnables.size());

          List<Pair> stoppedIds = new ArrayList<>();
          List<Pair> runningIds = new ArrayList<>();

          for (Entry<String, Map<String, JobHandlerRunnable>> runnableEntry : jobHandlerRunnables.entrySet()) {
            String contextId = runnableEntry.getKey();
            for (Entry<String, JobHandlerRunnable> runnable : runnableEntry.getValue().entrySet()) {
              String id = runnable.getKey();
              JobHandlerRunnable thread = runnable.getValue();

              if (thread.isStopped()) {
                stoppedIds.add(new Pair(id, contextId));
              } else {
                runningIds.add(new Pair(id, contextId));
              }
            }
          }

          for (Pair stopped : stoppedIds) {
            logger.debug("Cleaner thread removes JobHandlerRunnable for context {} and job {}.", stopped.contextId, stopped.jobId);
            jobHandlerRunnables.get(stopped.contextId).remove(stopped.jobId);
          }
        }
      }

      class Pair {
        private String jobId;
        private String contextId;

        public Pair(String jobId, String contextId) {
          this.jobId = jobId;
          this.contextId = contextId;
        }
      }

    }, 1, 1, TimeUnit.MINUTES);
  }

}


text:
// ReSharper disable All

namespace OpenTl.Schema
{
	using System;
	using System.Collections;
	using System.Text;

	using OpenTl.Schema;
	using OpenTl.Schema.Serialization.Attributes;

	[Serialize(0xef02ce6)]
	public sealed class TDocumentAttributeVideo : IDocumentAttribute
	{
       [SerializationOrder(0)]
       public BitArray Flags {get; set;}

       [SerializationOrder(1)]
       [FromFlag("Flags", 0)]
       public bool RoundMessage {get; set;}

       [SerializationOrder(2)]
       [FromFlag("Flags", 1)]
       public bool SupportsStreaming {get; set;}

       [SerializationOrder(3)]
       public int Duration {get; set;}

       [SerializationOrder(4)]
       public int W {get; set;}

       [SerializationOrder(5)]
       public int H {get; set;}

	}
}


text:
. /etc/rc.d/init.d/functions

APP_ROOT=/home/ec2-user/applications/application/production/current
SHARED_ROOT=/home/ec2-user/applications/application/production/shared
DAEMON=/usr/local/bin/node
SERVER=$APP_ROOT/server.js

pidfile=$SHARED_ROOT/tmp/node.pid
logfile=$SHARED_ROOT/log/server.log
lockfile=$SHARED_ROOT/tmp/node.lock

do_start() {
  [ -x $DAEMON ] || exit 5
  [ -f $SERVER ] || exit 6
  echo -n $"Starting Node.js: "
  daemon "NODE_ENV=production $DAEMON $SERVER >> $logfile &"
  retval=$?
  pid=`ps -aefw | grep "$DAEMON $SERVER" | grep -v " grep " | awk '{print $2}'`
  echo "$pid" > $pidfile
  echo
  [ $retval -eq 0 ] && touch $lockfile && echo "$pid" > $pidfile
  return $retval
}

do_stop() {
  echo -n $"Stopping Node.js: "
  killproc -p $pidfile
  retval=$?
  echo
  [ $retval -eq 0 ] && rm -f $lockfile && rm -f $pidfile
  return $retval
}

case "$1" in
  start)
    do_start || exit 0
  ;;

  stop)
    do_stop || exit 0
  ;;

  restart)
    do_stop
    do_start
  ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 2
  ;;
esac


text:
using System;
using System.IO;
using System.Reflection;
using Cirrious.CrossCore.Exceptions;

namespace MvvmCross.Plugins.JsonLocalisation
{
    public class MvxEmbeddedJsonDictionaryTextProvider
        : MvxJsonDictionaryTextProvider
    {
        public MvxEmbeddedJsonDictionaryTextProvider(bool maskErrors = true)
            : base(maskErrors)
        {
        }

        public override void LoadJsonFromResource(string namespaceKey, string typeKey, string resourcePath)
        {
            var json = GetTextFromEmbeddedResource(namespaceKey, resourcePath);
            if (string.IsNullOrEmpty(json))
                throw new FileNotFoundException("Unable to find resource file " + resourcePath);
            LoadJsonFromText(namespaceKey, typeKey, json);
        }

        private string GetTextFromEmbeddedResource(string namespaceKey, string resourcePath)
        {
            var path = namespaceKey + "." + resourcePath.Replace("/", ".");
            try
            {
                string text = null;
                Stream stream = Assembly.Load(new AssemblyName(namespaceKey)).GetManifestResourceStream(path);
                if (stream == null)
                    return null;

                using (var textReader = new StreamReader(stream))
                {
                    text = textReader.ReadToEnd();
                }

                return text;
            }
            catch (Exception ex)
            {
                throw ex.MvxWrap("Cannot load resource {0}", path);
            }
        }
    }
}


text:
layout: post
title: SF True Story Project - 7/11
date: '2013-07-14T22:51:00-04:00'
---

Original post can be found in
[sftruestoryproject](http://sftruestoryproject.tumblr.com/post/55483414885/transcription-i-hadnt-been-to-a-7-11-for-the):

![](/assets/images/essays/sftruestoryproject-7-11.jpg)

> **Transcription:**
>
> "I hadn't been to a 7-11 for the longest time, and as I passed by one today on my way to work, I decided to stop by and check it out. I remember liking their coffee a lot, so I went straight to the coffee bar. As I poured myself a cup, the guy next to me accidentally spilled coffee everywhere.
>
> He was a very stoic fellow. Very serious looking, expressionless. He wore a very interesting black hat.
>
> Anyways, seeing the spill, I started helping him out. I took a bunch of napkins and gave him some. We both began cleaning vigorously. His expression unchanging the entire time. Not saying a word.
>
> Once we were done he left to pay for his coffee. I still had to finish setting up mine, but as I walked to the cashier, she told me that the guy with the hat paid for my coffee. I quickly rushed out the door to look for him, but he was gone.
>
> Thanks stoic hat guy, you made my day feel better!"

I was meaning to make a blog post about this but decided to write it as a story for [sftruestoryproject.tumblr.com](http://sftruestoryproject.tumblr.com/)

I remember the coffee tasting terrible, but I couldn't help but smile almost the entire day.  The little things truly have a huge impact.

But oh man, my handwriting…that's pretty horrible.


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

class Model_Good extends ORM {

    protected $_table_name = 'good_items';

    protected $_has_many = array(
        'prices' => array(
            'model'   => 'price'
        )
    );

} // End


text:
var React = require('react');
var ReactDOM = require('react-dom');
var ExecutionEnvironment = require('exenv');
var ModalPortal = React.createFactory(require('./ModalPortal'));
var ariaAppHider = require('../helpers/ariaAppHider');
var elementClass = require('element-class');
var renderSubtreeIntoContainer = require("react-dom").unstable_renderSubtreeIntoContainer;
var Assign = require('lodash.assign');

var SafeHTMLElement = ExecutionEnvironment.canUseDOM ? window.HTMLElement : {};
var AppElement = ExecutionEnvironment.canUseDOM ? document.body : {appendChild: function() {}};

var Modal = React.createClass({

  displayName: 'Modal',
  statics: {
    setAppElement: function(element) {
        AppElement = ariaAppHider.setElement(element);
    },
    injectCSS: function() {
      "production" !== process.env.NODE_ENV
        && console.warn('React-Modal: injectCSS has been deprecated ' +
                        'and no longer has any effect. It will be removed in a later version');
    }
  },

  propTypes: {
    isOpen: React.PropTypes.bool.isRequired,
    style: React.PropTypes.shape({
      content: React.PropTypes.object,
      overlay: React.PropTypes.object
    }),
    portalClassName: React.PropTypes.string,
    appElement: React.PropTypes.instanceOf(SafeHTMLElement),
    onAfterOpen: React.PropTypes.func,
    onRequestClose: React.PropTypes.func,
    closeTimeoutMS: React.PropTypes.number,
    ariaHideApp: React.PropTypes.bool,
    shouldCloseOnOverlayClick: React.PropTypes.bool,
    nesting: React.PropTypes.bool,
  },

  getDefaultProps: function () {
    return {
      isOpen: false,
      portalClassName: 'ReactModalPortal',
      ariaHideApp: true,
      closeTimeoutMS: 0,
      shouldCloseOnOverlayClick: true,
      nesting: false
    };
  },

  componentDidMount: function() {
    this.node = document.createElement('div');
    this.node.className = this.props.portalClassName;
    document.body.appendChild(this.node);
    this.renderPortal(this.props);
  },

  componentWillReceiveProps: function(newProps) {
    this.renderPortal(newProps);
  },

  componentWillUnmount: function() {
    ReactDOM.unmountComponentAtNode(this.node);
    document.body.removeChild(this.node);
    elementClass(document.body).remove('ReactModal__Body--open');
  },

  renderPortal: function(props) {
    if (this.props.isOpen !== props.isOpen) {
      if (props.isOpen) {
        elementClass(document.body).add('ReactModal__Body--open');
      } else if(!props.nesting){
        elementClass(document.body).remove('ReactModal__Body--open');
      }

      if (props.ariaHideApp) {
        ariaAppHider.toggle(props.isOpen, props.appElement);
      }
    }

    this.portal = renderSubtreeIntoContainer(this, ModalPortal(Assign({}, props, {defaultStyles: Modal.defaultStyles})), this.node);
  },

  render: function () {
    return React.DOM.noscript();
  }
});

Modal.defaultStyles = {
  overlay: {
    position        : 'fixed',
    top             : 0,
    left            : 0,
    right           : 0,
    bottom          : 0,
    backgroundColor : 'rgba(255, 255, 255, 0.75)'
  },
  content: {
    position                : 'absolute',
    top                     : '40px',
    left                    : '40px',
    right                   : '40px',
    bottom                  : '40px',
    border                  : '1px solid #ccc',
    background              : '#fff',
    overflow                : 'auto',
    WebkitOverflowScrolling : 'touch',
    borderRadius            : '4px',
    outline                 : 'none',
    padding                 : '20px'
  }
}

module.exports = Modal


text:
FROM ruby:2.6.10-buster

RUN cd /tmp && \
    wget --no-verbose https://github.com/wjdp/htmltest/releases/download/v0.16.0/htmltest_0.16.0_linux_amd64.tar.gz && \
    tar xvzf htmltest_0.16.0_linux_amd64.tar.gz && \
    mv htmltest /usr/local/bin

RUN mkdir /root/gems

ENV GEM_HOME=/root/gems
ENV PATH="/root/gems/bin:${PATH}"
# python md script needs that :S
ENV LC_ALL=C.UTF-8

RUN gem install bundler:2.3.25

VOLUME /docs
WORKDIR /docs
COPY Gemfile /docs
COPY Gemfile.lock /docs

RUN bundler install

EXPOSE 4000

CMD ["bundler", "exec", "jekyll", "serve", "-H", "0.0.0.0", "--incremental", "--trace"]


text:
package com.google.protoeditor.psi;

import java.util.Collection;

public interface ProtoLiteral extends ProtoElement {

  Collection<? extends ProtoType> getPossibleTypes();
}


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

<title>Uses of Interface org.eclipse.emf.cdo.spi.common.branch.InternalCDOBranchManager (CDO Model Repository Documentation)</title>
<meta name="date" content="">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.eclipse.emf.cdo.spi.common.branch.InternalCDOBranchManager

Packages that use InternalCDOBranchManager

Package
Description

org.eclipse.emf.cdo.spi.common.branch

Common service provider interfaces and useful base implementations for dealing with branches.

org.eclipse.emf.cdo.spi.server

Server service provider interfaces and useful base implementations.

org.eclipse.emf.spi.cdo

Client service provider interfaces and useful base implementations.

Uses of InternalCDOBranchManager in org.eclipse.emf.cdo.spi.common.branch

Methods in org.eclipse.emf.cdo.spi.common.branch that return InternalCDOBranchManager

Modifier and Type
Method and Description

static InternalCDOBranchManager
CDOBranchUtil.createBranchManager()

InternalCDOBranchManager
InternalCDOBranch.getBranchManager()

Uses of InternalCDOBranchManager in org.eclipse.emf.cdo.spi.server

Methods in org.eclipse.emf.cdo.spi.server that return InternalCDOBranchManager

Modifier and Type
Method and Description

InternalCDOBranchManager
InternalRepository.getBranchManager()

Methods in org.eclipse.emf.cdo.spi.server with parameters of type InternalCDOBranchManager

Modifier and Type
Method and Description

void
InternalRepository.initMainBranch(InternalCDOBranchManager branchManager,
              long timeStamp)

void
InternalRepository.setBranchManager(InternalCDOBranchManager branchManager)

Uses of InternalCDOBranchManager in org.eclipse.emf.spi.cdo

Methods in org.eclipse.emf.spi.cdo that return InternalCDOBranchManager

Modifier and Type
Method and Description

InternalCDOBranchManager
InternalCDOSession.getBranchManager()

Methods in org.eclipse.emf.spi.cdo with parameters of type InternalCDOBranchManager

Modifier and Type
Method and Description

void
InternalCDOSession.setBranchManager(InternalCDOBranchManager branchManager)

Skip navigation links

Overview

Package

Class

Use

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright (c) 2011-2015 Eike Stepper (Berlin, Germany) and others.


text:
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")

. "$here\TestSetup.ps1"
. "$here\..\PSRabbitMQ\$sut"

Describe "Set-RabbitMqConfig" {

    context "Setting current RabbitMQ Configuration" {
        It "sets the current Configuration"{
            $Script:RabbitMqConfig = [pscustomobject]@{
                ComputerName = $null
            }
            $computerName = "rabbitmq.contoso.com"
            Set-RabbitMqConfig -ComputerName $computerName -NoPersist
            $Script:RabbitMqConfig.ComputerName | Should be $computerName
        }
    }

    context "Persisting the RabbitMQ Configuration"{

        It "persists the current Configuration to AppData"{
            Mock Export-CliXml {}
            Set-RabbitMqConfig -Scope CurrentUser
            Assert-MockCalled -CommandName Export-CliXml -Times 1
        }

        It "persists the current Configuration to ProgramData"{
            Mock Export-CliXml {}
            Set-RabbitMqConfig -Scope System
            Assert-MockCalled -CommandName Export-CliXml -Times 1
        }
    }
}


text:
//
//  MUNotificationAction.h
//  MUNotifications
//
//  Created by Muer on 16/7/26.
//  Copyright © 2016年 Muer. All rights reserved.
//

#import <Foundation/Foundation.h>

typedef NS_OPTIONS(NSUInteger, MUNotificationActionOptions) {
    MUNotificationActionOptionNone                      = 0,

    /** Whether this action should require unlocking before being performed */
    MUNotificationActionOptionAuthenticationRequired    = 1 << 0,

    /** Whether this action should be indicated as destructive */
    MUNotificationActionOptionDestructive               = 1 << 1,

    /** Whether this action should cause the application to launch in the foreground */
    MUNotificationActionOptionForeground                = 1 << 2,
};

NS_ASSUME_NONNULL_BEGIN

/**
 *  Defines a task to perform in response to a delivered notification. Equivalent to UNNotificationAction or UIUserNotificationAction
 */
NS_CLASS_AVAILABLE_IOS(8_0)
@interface MUNotificationAction : NSObject <NSCopying, NSSecureCoding>

/** Creates an action with the specified title and options */
+ (instancetype)actionWithIdentifier:(NSString *)identifier title:(NSString *)title options:(MUNotificationActionOptions)options;

- (instancetype)init NS_UNAVAILABLE;

/** The unique identifier for this action */
@property (nonatomic, readonly) NSString *identifier;

/** The title to display for this action */
@property (nonatomic, readonly) NSString *title;

/** The options configured for this action */
@property (nonatomic, readonly) MUNotificationActionOptions options;

@end

/**
 *  Defines an action that contains user-specified text. Equivalent to UNTextInputNotificationAction
 */
NS_CLASS_AVAILABLE_IOS(9_0)
@interface MUTextInputNotificationAction : MUNotificationAction

/** Creates and returns an action that accepts text input from the user */
+ (instancetype)actionWithIdentifier:(NSString *)identifier title:(NSString *)title options:(MUNotificationActionOptions)options textInputButtonTitle:(nullable NSString *)textInputButtonTitle;

/** Creates and returns an action that accepts text input from the user */
+ (instancetype)actionWithIdentifier:(NSString *)identifier title:(NSString *)title options:(MUNotificationActionOptions)options textInputButtonTitle:(nullable NSString *)textInputButtonTitle textInputPlaceholder:(nullable NSString *)textInputPlaceholder NS_AVAILABLE_IOS(10_0);

/** The title of the text input button that is displayed to the user */
@property (nonatomic, readonly) NSString *textInputButtonTitle;

/** The placeholder text to display in the text input field */
@property (nonatomic, readonly) NSString *textInputPlaceholder NS_AVAILABLE_IOS(10_0);

@end

NS_ASSUME_NONNULL_END


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { MatFormFieldModule, MatDialog, MatDialogRef } from '@angular/material';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing';

import { DynamicFormComponent } from './dynamic-form.component';
import { ReviewService } from '../review.service';
import { CourseService } from '../../course/course.service';
import { TeacherService } from '../../teacher/teacher.service';

describe('DynamicFormComponent', () => {
    let component: DynamicFormComponent;
    let fixture: ComponentFixture<DynamicFormComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [ReactiveFormsModule, MatFormFieldModule, HttpModule],
            declarations: [DynamicFormComponent],
            providers: [ReviewService, CourseService, TeacherService, MatDialog],
            schemas: [NO_ERRORS_SCHEMA],
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(DynamicFormComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });
});


text:
package io.cattle.platform.core.dao;

import io.cattle.platform.core.model.Host;
import io.cattle.platform.core.model.StoragePool;
import io.cattle.platform.core.model.StoragePoolHostMap;

import java.util.List;
import java.util.Map;

public interface StoragePoolDao {

    List<? extends StoragePool> findExternalActivePools();

    StoragePool mapNewPool(Host host, Map<String, Object> properties);

    StoragePool findStoragePoolByDriverName(Long accountId, String driverName);

    List<? extends StoragePoolHostMap> findMapsToRemove(Long id);

    StoragePoolHostMap findNonremovedMap(Long storagePoolId, Long hostId);

    void createStoragePoolHostMap(StoragePoolHostMap m);
}


text:
@interface RKManagedObjectMappingSpec : RKSpec {
    NSAutoreleasePool *_autoreleasePool;
}

@end

@implementation RKManagedObjectMappingSpec

//- (void)setUp {
//    _autoreleasePool = [NSAutoreleasePool new];
//}
//
//- (void)tearDown {
//    [_autoreleasePool drain];
//}

- (void)testShouldReturnTheDefaultValueForACoreDataAttribute {
    // Load Core Data
    RKSpecNewManagedObjectStore();

    RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKCat"];
    id value = [mapping defaultValueForMissingAttribute:@"name"];
    assertThat(value, is(equalTo(@"Kitty Cat!")));
}

- (void)testShouldCreateNewInstancesOfUnmanagedObjects {
    RKSpecNewManagedObjectStore();
    RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKMappableObject class]];
    id object = [mapping mappableObjectForData:[NSDictionary dictionary]];
    assertThat(object, isNot(nilValue()));
    assertThat([object class], is(equalTo([RKMappableObject class])));
}

- (void)testShouldCreateNewInstancesOfManagedObjectsWhenTheMappingIsAnRKObjectMapping {
    RKSpecNewManagedObjectStore();
    RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKMappableObject class]];
    id object = [mapping mappableObjectForData:[NSDictionary dictionary]];
    assertThat(object, isNot(nilValue()));
    assertThat([object class], is(equalTo([RKMappableObject class])));
}

- (void)testShouldFindExistingManagedObjectsByPrimaryKey {
    RKManagedObjectStore* store = RKSpecNewManagedObjectStore();
    RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class]];
    mapping.primaryKeyAttribute = @"railsID";
    [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"railsID"]];

    RKHuman* human = [RKHuman object];
    human.railsID = [NSNumber numberWithInt:123];
    [store save];
    assertThatBool([RKHuman hasAtLeastOneEntity], is(equalToBool(YES)));

    NSDictionary* data = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:123] forKey:@"id"];
    id object = [mapping mappableObjectForData:data];
    assertThat(object, isNot(nilValue()));
    assertThat(object, is(equalTo(human)));
}

- (void)testShouldFindExistingManagedObjectsByPrimaryKeyPath {
    RKManagedObjectStore* store = RKSpecNewManagedObjectStore();
    [RKHuman truncateAll];
    RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class]];
    mapping.primaryKeyAttribute = @"railsID";
    [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"monkey.id" toKeyPath:@"railsID"]];

    [RKHuman truncateAll];
    RKHuman* human = [RKHuman object];
    human.railsID = [NSNumber numberWithInt:123];
    [store save];
    assertThatBool([RKHuman hasAtLeastOneEntity], is(equalToBool(YES)));

    NSDictionary* data = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:123] forKey:@"id"];
    NSDictionary* nestedDictionary = [NSDictionary dictionaryWithObject:data forKey:@"monkey"];
    id object = [mapping mappableObjectForData:nestedDictionary];
    assertThat(object, isNot(nilValue()));
    assertThat(object, is(equalTo(human)));
}

- (void)testShouldCreateNewManagedObjectInstancesWhenThereIsNoPrimaryKeyInTheData {
    RKSpecNewManagedObjectStore();
    RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class]];
    mapping.primaryKeyAttribute = @"railsID";

    NSDictionary* data = [NSDictionary dictionary];
    id object = [mapping mappableObjectForData:data];
    assertThat(object, isNot(nilValue()));
    assertThat(object, is(instanceOf([RKHuman class])));
}

- (void)testShouldCreateNewManagedObjectInstancesWhenThereIsNoPrimaryKeyAttribute {
    RKSpecNewManagedObjectStore();
    RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class]];

    NSDictionary* data = [NSDictionary dictionary];
    id object = [mapping mappableObjectForData:data];
    assertThat(object, isNot(nilValue()));
    assertThat(object, is(instanceOf([RKHuman class])));
}

- (void)testShouldCreateANewManagedObjectWhenThePrimaryKeyValueIsNSNull {
    RKSpecNewManagedObjectStore();
    RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class]];
    mapping.primaryKeyAttribute = @"railsID";
    [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"railsID"]];

    NSDictionary* data = [NSDictionary dictionaryWithObject:[NSNull null] forKey:@"id"];
    id object = [mapping mappableObjectForData:data];
    assertThat(object, isNot(nilValue()));
    assertThat(object, is(instanceOf([RKHuman class])));
}

- (void)testShouldMapACollectionOfObjectsWithDynamicKeys {
    RKManagedObjectStore *objectStore = RKSpecNewManagedObjectStore();
    RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class]];
    mapping.forceCollectionMapping = YES;
    mapping.primaryKeyAttribute = @"name";
    [mapping mapKeyOfNestedDictionaryToAttribute:@"name"];
    RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"(name).id" toKeyPath:@"railsID"];
    [mapping addAttributeMapping:idMapping];
    RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease];
    [provider setMapping:mapping forKeyPath:@"users"];

    id mockObjectStore = [OCMockObject partialMockForObject:objectStore];
    [[[mockObjectStore expect] andForwardToRealObject] findOrCreateInstanceOfEntity:OCMOCK_ANY withPrimaryKeyAttribute:@"name" andValue:@"blake"];
    [[[mockObjectStore expect] andForwardToRealObject] findOrCreateInstanceOfEntity:mapping.entity withPrimaryKeyAttribute:@"name" andValue:@"rachit"];
    id userInfo = RKSpecParseFixture(@"DynamicKeys.json");
    RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider];
    [mapper performMapping];
    [mockObjectStore verify];
}

- (void)testShouldPickTheAppropriateMappingBasedOnAnAttributeValue {
    RKSpecNewManagedObjectStore();
    RKDynamicObjectMapping* dynamicMapping = [RKDynamicObjectMapping dynamicMapping];
    RKManagedObjectMapping* childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class]];
    childMapping.primaryKeyAttribute = @"railsID";
    [childMapping mapAttributes:@"name", nil];

    RKManagedObjectMapping* parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class]];
    parentMapping.primaryKeyAttribute = @"railsID";
    [parentMapping mapAttributes:@"name", @"age", nil];

    [dynamicMapping setObjectMapping:parentMapping whenValueOfKeyPath:@"type" isEqualTo:@"Parent"];
    [dynamicMapping setObjectMapping:childMapping whenValueOfKeyPath:@"type" isEqualTo:@"Child"];

    RKObjectMapping* mapping = [dynamicMapping objectMappingForDictionary:RKSpecParseFixture(@"parent.json")];
    assertThat(mapping, is(notNilValue()));
    assertThatBool([mapping isKindOfClass:[RKManagedObjectMapping class]], is(equalToBool(YES)));
    assertThat(NSStringFromClass(mapping.objectClass), is(equalTo(@"RKParent")));
    mapping = [dynamicMapping objectMappingForDictionary:RKSpecParseFixture(@"child.json")];
    assertThat(mapping, is(notNilValue()));
    assertThatBool([mapping isKindOfClass:[RKManagedObjectMapping class]], is(equalToBool(YES)));
    assertThat(NSStringFromClass(mapping.objectClass), is(equalTo(@"RKChild")));
}

- (void)testShouldIncludeTransformableAttributesInPropertyNamesAndTypes {
    RKSpecNewManagedObjectStore();
    NSDictionary *attributesByName = [[RKHuman entity] attributesByName];
    NSDictionary *propertiesByName = [[RKHuman entity] propertiesByName];
    NSDictionary *relationshipsByName = [[RKHuman entity] relationshipsByName];
    assertThat([attributesByName objectForKey:@"favoriteColors"], is(notNilValue()));
    assertThat([propertiesByName objectForKey:@"favoriteColors"], is(notNilValue()));
    assertThat([relationshipsByName objectForKey:@"favoriteColors"], is(nilValue()));

    NSDictionary *propertyNamesAndTypes = [[RKObjectPropertyInspector sharedInspector] propertyNamesAndTypesForEntity:[RKHuman entity]];
    assertThat([propertyNamesAndTypes objectForKey:@"favoriteColors"], is(notNilValue()));
}

@end


text:
var os = require('os');
var util = require('util');

var _ = require('underscore');

var files = require('../fs/files.js');
var auth = require('../meteor-services/auth.js');
var config = require('../meteor-services/config.js');
var release = require('../packaging/release.js');
var Console = require('../console/console.js').Console;
var timeoutScaleFactor = require('./utils.js').timeoutScaleFactor;

import { Writable } from "stream";

class ConcatStream extends Writable {
  constructor() {
    super();
    this.chunks = [];
    this.size = 0;
  }

  _write(chunk, encoding, next) {
    this.chunks.push(chunk);
    this.size += chunk.length;
    next();
  }

  getBuffer() {
    if (this.chunks.length !== 1) {
      this.chunks[0] = Buffer.concat(this.chunks);
      this.chunks.length = 1;
    }

    return this.chunks[0];
  }
}

// Helper that tracks bytes written to a writable
var WritableWithProgress = function (writable, listener) {
  var self = this;
  self._inner = writable;
  self._listener = listener;
};

_.extend(WritableWithProgress.prototype, {
  write: function (chunk, encoding, callback) {
    var self = this;
    self._listener(chunk.length, false);
    return self._inner.write(chunk, encoding);
  },

  end: function (chunk, encoding, callback) {
    var self = this;
    self._listener(chunk ? chunk.length : 0, true);
    return self._inner.end(chunk, encoding);
  },

  _progress: function (n, done) {
    var self = this;

    var state = self._state;
    state.current += n;
    if (done) {
      state.current.done = true;
    }
    self.progress.reportProgress(state);
  },

  on: function (name, callback) {
    return this._inner.on(name, callback);
  },

  once: function () {
    return this._inner.once(...arguments);
  },

  emit: function () {
    return this._inner.emit(...arguments);
  }
});

// Compose a User-Agent header.
var getUserAgent = function () {
  var version;

  if (release.current) {
    version = release.current.isCheckout() ? 'checkout' : release.current.name;
  } else {
    // This happens when we haven't finished starting up yet (say, the
    // user passed --release 1.2.3 and we have to download 1.2.3
    // before we can get going), or if we are using an installed copy
    // of Meteor to 'meteor update'ing a project that was created by a
    // checkout and doesn't have a version yet.
    version = files.inCheckout() ? 'checkout' : files.getToolsVersion();
  }

  return util.format('Meteor/%s OS/%s (%s; %s; %s;)', version,
                     os.platform(), os.type(), os.release(), os.arch());
};

var httpHelpers = exports;
_.extend(exports, {
  getUserAgent: getUserAgent,

  // A wrapper around request with the following improvements:
  //
  // - It will respect proxy environment variables if present
  //   (HTTP_PROXY or HTTPS_PROXY as appropriate).
  //
  // - It will set a reasonable User-Agent header.
  //
  // - If you omit the callback it will run synchronously. The return
  //   value will be an object with keys 'response' and 'body' (with
  //   the same meaning as the arguments to request's normal
  //   callback), or it will throw.
  //
  // - If Set-Cookie headers are present on the response, *and* you
  //   are using a callback, it will parse the cookies and include
  //   them as a setCookie attribute on the object passed to the
  //   callback. setCookie is a simple map from cookie name to cookie
  //   value. If you want expiration time and attributes you'll have
  //   to parse it yourself. If there are multiple Set-Cookie headers
  //   for the same cookie it is unspecified which one you'll get.
  //
  // - You can provide a 'bodyStream' option which is a stream that
  //   will be used for the body of the request.
  //
  // - For authenticated MDG services, you can set the
  //   'useSessionHeader' and/or 'useAuthHeader' options (to true) to
  //   send X-Meteor-Session/X-Meteor-Auth headers using values from
  //   the session file.
  //
  // - forceSSL is always set to true. Always. And followRedirect is
  //   set to false since it doesn't understand origins (see comment
  //   in implementation).
  //
  // - An optional options.onRequest callback may be provided if the
  //   caller desires access to the request object.
  //
  // NB: With useSessionHeader and useAuthHeader, this function will
  // read *and possibly write to* the session file, so if you are
  // writing auth code (in auth.js) and you call it, be sure to reread
  // the session file afterwards.
  request: function (urlOrOptions, callback) {
    var options;
    if (!_.isObject(urlOrOptions)) {
      options = { url: urlOrOptions };
    } else {
      options = _.clone(urlOrOptions);
    }

    var outputStream;
    if (_.has(options, 'outputStream')) {
      outputStream = options.outputStream;
      delete options.outputStream;
    }

    var bodyStream;
    if (_.has(options, 'bodyStream')) {
      bodyStream = options.bodyStream;
      delete options.bodyStream;
    }

    // Body stream length for progress
    var bodyStreamLength = 0;
    if (_.has(options, 'bodyStreamLength')) {
      bodyStreamLength = options.bodyStreamLength;
      delete options.bodyStreamLength;
    } else {
      // Guess the body stream length as 1MB
      // Hopefully if it's much bigger the caller will set it
      // If it is much small, we will pleasantly surprise the user!
      if (bodyStream) {
        bodyStreamLength = 1024 * 1024;
      }
    }

    // Response length for progress
    var responseLength = 128 * 1024;
    if (_.has(options, 'responseLength')) {
      responseLength = options.responseLength;
      delete options.responseLength;
    }

    var progress = null;
    if (_.has(options, 'progress')) {
      progress = options.progress;
      delete options.progress;

      if (callback) {
        throw new Error("Not safe to use progress with callback");
      }
    }

    options.headers = _.extend({
      'User-Agent': getUserAgent()
    }, options.headers || {});

    // This should never, ever be false, or else why are you using SSL?
    options.forceSSL = true;
    if (process.env.CAFILE) {
      options.ca = files.readFile(process.env.CAFILE);
    }

    // followRedirect is very dangerous because request does not
    // appear to segregate cookies by origin, so any cookies (and
    // apparently headers as well, eg X-Meteor-Auth) sent on the
    // original request could get forwarded to an unexpected domain in
    // a redirect. This is almost certainly not something you ever
    // want.
    options.followRedirect = false;

    var useSessionHeader = options.useSessionHeader;
    delete options.useSessionHeader;
    var useAuthHeader = options.useAuthHeader;
    delete options.useAuthHeader;
    if (useSessionHeader || useAuthHeader) {
      var sessionHeader = auth.getSessionId(config.getAccountsDomain());
      if (sessionHeader) {
        options.headers['X-Meteor-Session'] = sessionHeader;
      }
      if (callback) {
        throw new Error("session header can't be used with callback");
      }
    }
    if (useAuthHeader) {
      var authHeader = auth.getSessionToken(config.getAccountsDomain());
      if (authHeader) {
        options.headers['X-Meteor-Auth'] = authHeader;
      }
    }

    var promise;
    if (! callback) {
      promise = new Promise(function (resolve, reject) {
        callback = function (err, response, body) {
          if (err) {
            reject(err);
            return;
          }

          var setCookie = {};
          _.each(response.headers["set-cookie"] || [], function (h) {
            var match = h.match(/^([^=\s]+)=([^;\s]+)/);
            if (match) {
              setCookie[match[1]] = match[2];
            }
          });

          if (useSessionHeader && _.has(response.headers, "x-meteor-session")) {
            auth.setSessionId(config.getAccountsDomain(),
                              response.headers['x-meteor-session']);
          }

          resolve({
            response: response,
            body: body,
            setCookie: setCookie
          });
        };
      });
    }

    // try to get proxy from environment.
    // similar code is in packages/ddp/stream_client_nodejs.js
    var proxy = process.env.HTTP_PROXY || process.env.http_proxy || null;
    // if we're going to an https url, try the https_proxy env variable first.
    if (/^https/i.test(options.url)) {
      proxy = process.env.HTTPS_PROXY || process.env.https_proxy || proxy;
    }
    if (proxy && !options.proxy) {
      options.proxy = proxy;
    }

    if (! _.has(options, "timeout")) {
      // 60 seconds for timeout between initial response headers and data,
      // and between chunks of data while reading the rest of the response.
      options.timeout = 60 * 1000 * timeoutScaleFactor;
    } else if (! (typeof options.timeout === "number" &&
                  options.timeout > 0)) {
      // The timeout can be disabled by passing anything other than a
      // positive number, e.g. { timeout: null }.
      delete options.timeout;
    }

    let onRequest;
    if (_.has(options, "onRequest")) {
      onRequest = options.onRequest;
      delete options.onRequest;
    }

    // request is the most heavy-weight of the tool's npm dependencies; don't
    // require it until we definitely need it.
    Console.debug("Doing HTTP request: ", options.method || 'GET', options.url);
    var request = require('request');
    var req = request(options, callback);

    if (_.isFunction(onRequest)) {
      onRequest(req);
    }

    var totalProgress = { current: 0, end: bodyStreamLength + responseLength, done: false };

    if (bodyStream) {
      var dest = req;
      if (progress) {
        dest = new WritableWithProgress(dest, function (n, done) {
          if (!totalProgress.done) {
            totalProgress.current += n;
            progress.reportProgress(totalProgress);
          }
        });
      }
      bodyStream.pipe(dest);
    }

    if (outputStream) {
      req.pipe(outputStream);
    }

    if (progress) {
      httpHelpers._addProgressEvents(req);
      req.on('progress', function (state) {
        if (!totalProgress.done) {
          totalProgress.current = bodyStreamLength + state.current;
          totalProgress.end = bodyStreamLength + state.end;
          totalProgress.done = state.done;

          progress.reportProgress(totalProgress);
        }
      });
    }

    if (promise) {
      try {
        return promise.await();
      } finally {
        if (progress) {
          progress.reportProgressDone();
        }
      }
    } else {
      return req;
    }
  },

  // Adds progress callbacks to a request
  // Based on request-progress
  _addProgressEvents: function (request) {
    var state = {};

    var emitProgress = function () {
      request.emit('progress', state);
    };

    request
      .on('response', function (response) {
        state.end = undefined;
        state.done = false;
        state.current = 0;
        var contentLength = response.headers['content-length'];
        if (contentLength) {
          state.end = Number(contentLength);
        }
        emitProgress();
      })
      .on('data', function (data) {
        state.current += data.length;
        emitProgress();
      })
      .on('end', function (data) {
        state.done = true;
        emitProgress();
      });
  },

  // A synchronous wrapper around request(...) that returns the response "body"
  // or throws.
  //
  // (This has gone through a few refactors and it might be possible
  // to fully roll it into httpHelpers.request() at this point.)
  getUrl: function (urlOrOptions) {
    try {
      var result = httpHelpers.request(urlOrOptions);
    } catch (e) {
      throw new files.OfflineError(e);
    }

    const response = result.response;
    const body = result.body;
    const href = response.request.href;

    if (response.statusCode >= 400 && response.statusCode < 600) {
      throw Error(
        body ||
          `Could not get ${href}; server returned [${response.statusCode}]`);
    } else {
      return body;
    }
  },

  // More or less as above, except with support for multiple attempts per
  // request and resuming on retries. This means if the connection is bad,
  // we can sometimes complete a request, even if each individual attempt fails.
  // We only use this for package downloads. In theory we could use it for
  // all requests but that seems like overkill and it isn't well tested in
  // other scenarioes.
  getUrlWithResuming(urlOrOptions) {
    const options = _.isObject(urlOrOptions) ? _.clone(urlOrOptions) : {
      url: urlOrOptions,
    };

    const maxAttempts =
      _.has(options, "maxAttempts")
      ? options.maxAttempts : 10;

    const retryDelaySecs =
      _.has(options, "retryDelaySecs")
      ? options.retryDelaySecs : 5;

    const masterProgress = options.progress;
    const outputStream = new ConcatStream();

    function attempt(triesRemaining = maxAttempts, startAt = 0) {
      if (startAt > 0) {
        options.headers = {
          ...options.headers,
          Range: `bytes=${startAt}-`
        };
      }

      if (masterProgress &&
          masterProgress.addChildTask) {
        options.progress = masterProgress.addChildTask({
          title: masterProgress._title
        });
      }

      try {
        return Promise.resolve(httpHelpers.request({
          outputStream,
          ...options,
        }));

      } catch (e) {
        const size = outputStream.size;
        const useTry = size === startAt;
        const change = size - startAt;

        if (!useTry || triesRemaining > 0) {
          if (useTry) {
            Console.debug(`Request failed, ${triesRemaining - 1} attempts left`);
          } else {
            Console.debug(`Request failed after ${change} bytes, retrying`);
          }

          return new Promise(
            resolve => setTimeout(resolve, retryDelaySecs * 1000)
          ).then(() => attempt(triesRemaining - (useTry ? 1 : 0), size));
        }

        Console.debug(`Request failed ${maxAttempts} times: failing`);
        return Promise.reject(new files.OfflineError(e));
      }
    }

    const result = attempt().await();
    const response = result.response
    if (response.statusCode >= 400 && response.statusCode < 600) {
      const href = response.request.href;
      throw Error(`Could not get ${href}; server returned [${response.statusCode}]`);
    }

    return outputStream.getBuffer();
  }
});


text:
API documentation
=================

.. toctree::
   :maxdepth: 2

   queryutils.query
   queryutils.user
   queryutils.splunktypes
   queryutils.parse
   queryutils.source
   queryutils.databases
   queryutils.files
   queryutils.csvparser
   queryutils.jsonparser


text:
from django.core.management.base import BaseCommand, CommandError
import requests
import json
import datetime
from datetime import date
from results.models import Drawing, GroupTicket
from results.services import checkprize

class Command(BaseCommand):
    help = 'Checks the internet for drawing results and check the group''s tickets'

    def handle(self, *args, **options):
        url = 'https://data.ny.gov/resource/h6w8-42p9.json'
        payload = {'$order':'draw_date DESC', '$limit': 306}
        r = requests.get(url=url,params=payload)
        data = json.loads(r.text)
        for result in data:
            drawdate = result['draw_date'].split('T')[0]
            if not Drawing.objects.filter(drawingDate=drawdate):
                a = Drawing(numbers=str(result['winning_numbers']),megaBall=int(result['mega_ball']),multiplier=result['multiplier'],drawingDate=drawdate)
                a.save()
                for ticket in GroupTicket.objects.all():
                    if ticket.agreementPeriod.startDate <=  (datetime.datetime.strptime(drawdate, '%Y-%m-%d').date()) <= ticket.agreementPeriod.endDate:
                        checkprize(drawingid=a.id,ticketid=ticket.id)


text:
package app.repositories;

import app.domains.entities.accessories.Accessory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface AccessoryRepository extends JpaRepository<Accessory, Long> {
}


text:
#ifndef CLICK_RFC2507D_HH
#define CLICK_RFC2507D_HH
#include <click/element.hh>
#include <click/glue.hh>
#include <clicknet/ip.h>
#include <clicknet/tcp.h>
CLICK_DECLS

/* =c
 * RFC2507Decomp
 *
 * =s tcp
 * RFC2507 IPv4/TCP header decompressor.
 *
 * =d
 * Input packets should be as produced by RFC2507c.
 * Spits out IP packets.
 *
 * =a
 * RFC2507Comp
 */

class RFC2507d : public Element {
public:

  /* used to store context as well as hash key */
  struct tcpip {
    click_ip _ip;
    click_tcp _tcp;
    operator bool() const { return(_ip.ip_src.s_addr != 0); }
    tcpip() { _ip.ip_src.s_addr = 0; }
  };

  RFC2507d();
  ~RFC2507d();

  const char *class_name() const		{ return "RFC2507Decomp"; }
  const char *port_count() const		{ return PORTS_1_1; }

  Packet *simple_action(Packet *);

private:
  /* constants specified in the RFC */
  enum { TCP_SPACE = 15 }; /* max CID value for TCP. 3..255 are legal. */

  /* first byte of packet indicates type */
  enum { PT_OTHER = 0, /* ordinary packet (not compressed, no CID) */
	 PT_FULL_HEADER = 1, /* one byte CID, then full ip/tcp */
	 PT_COMPRESSED_TCP = 2 }; /* CID, compressed packet */

  /* per-connection control block, indexed by CID */
  struct ccb {
    struct tcpip _context;
  };
  struct ccb _ccbs[TCP_SPACE];

  void decode(const u_char * &in, unsigned short &);
  void decode(const u_char * &in, unsigned int &);
};

CLICK_ENDDECLS
#endif