text:
package org.apache.beam.sdk.values;

import static com.google.common.base.Preconditions.checkState;

import javax.annotation.Nullable;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.annotations.Internal;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.util.NameUtils;

/**
 * For internal use. No backwards compatibility guarantees.
 *
 *
An abstract base class that provides default implementations for some methods of
 * {@link PValue}.
 */
@Internal
public abstract class PValueBase implements PValue {

  private final transient @Nullable Pipeline pipeline;

  /**
   * Returns the name of this {@link PValueBase}.
   *
   *
By default, the name of a {@link PValueBase} is based on the
   * name of the {@link PTransform} that produces it.  It can be
   * specified explicitly by calling {@link #setName}.
   *
   * @throws IllegalStateException if the name hasn't been set yet
   */
  @Override
  public String getName() {
    if (name == null) {
      throw new IllegalStateException("name not set");
    }
    return name;
  }

  /**
   * Sets the name of this {@link PValueBase}. Returns {@code this}.
   *
   * @throws IllegalStateException if this {@link PValueBase} has
   * already been finalized and may no longer be set.
   */
  public PValueBase setName(String name) {
    checkState(!finishedSpecifying, "cannot change the name of %s once it's been used", this);
    this.name = name;
    return this;
  }

  /////////////////////////////////////////////////////////////////////////////

  protected PValueBase(Pipeline pipeline) {
    this.pipeline = pipeline;
  }

  /**
   * No-arg constructor to allow subclasses to implement {@link java.io.Serializable}.
   * The resulting {@link PValueBase} is not valid as a {@link PValue}, but may have other
   * properties that are still usable, such as the tag in a {@link PCollectionView}.
   */
  protected PValueBase() {
    this.pipeline = null;
  }

  /** The name of this {@link PValueBase}, or {@code null} if not yet set. */
  @Nullable private String name;

  /**
   * Whether this {@link PValueBase} has been finalized, and its core
   * properties, e.g., name, can no longer be changed.
   */
  private boolean finishedSpecifying = false;

  /**
   * Returns whether this {@link PValueBase} has been finalized, and
   * its core properties, e.g., name, can no longer be changed.
   *
   *
For internal use only.
   */
  boolean isFinishedSpecifying() {
    return finishedSpecifying;
  }

  @Override
  public void finishSpecifying(PInput input, PTransform<?, ?> transform) {
    finishedSpecifying = true;
  }

  @Override
  public String toString() {
    return (name == null ? "<unnamed>" : getName())
        + " [" + getKindString() + "]";
  }

  /**
   * Returns a {@link String} capturing the kind of this
   * {@link PValueBase}.
   *
   *
By default, uses the base name of the current class as its kind string.
   */
  protected String getKindString() {
    return NameUtils.approximateSimpleName(getClass());
  }

  @Override
  public Pipeline getPipeline() {
    checkState(
        pipeline != null,
        "Pipeline was null for %s. "
            + "this probably means it was used as a %s after being deserialized, "
            + "which not unsupported.",
        getClass().getCanonicalName(),
        PValue.class.getSimpleName());
    return pipeline;
  }

  @Override
  public void finishSpecifyingOutput(
      String transformName, PInput input, PTransform<?, ?> transform) {
    if (name == null) {
      setName(defaultName(transformName));
    }
  }

  static String defaultName(String transformName) {
    return String.format("%s.%s", transformName, "out");
  }
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";

var convict = require('convict');
// load configurations schema
var configurationSchemaFile = loadConfigurationsSchema();
// load configurations file
var configurationJSONFile = loadConfigurationsFile();
// load and validate configurations
var configurations = convict(configurationSchemaFile).load(configurationJSONFile).validate();

/**
 * Loads the configurations schema.
 * The schema can be overridden using the 'NODE_APP_SCHEMA' environment variable.
 *
 * @returns {*}
 */
function loadConfigurationsSchema() {
  var schema = process.env.NODE_APP_CONF_SCHEMA || './configurations-schema.json';
  return require(schema);
}

/**
 * Tries to load the configurations file, if it does not exist returns an empty object and thus default
 * configuration from the configuration schema applies.
 *
 * @returns {*}
 */
function loadConfigurationsFile() {
  try {
    return require(process.env.NODE_APP_CONF);
  }
  catch (err) {
    console.warn('Cannot load configurations file. An empty object will be used instead.');
    console.warn(err);
    return {};
  }
}

/**
 * Configurations are loaded from a file defined as an environment variable 'NODE_APP_CONF'
 *
 * e.g.: /home/webap/portal/conf/development.json
 */
module.exports = configurations;


text:
package com.qualogy.qafe.bind.resource.query;

import java.io.Serializable;

import org.apache.commons.lang.StringUtils;

/**
 *
 * @author
 *
 */
//TODO: order by
public abstract class SQLQuery extends Query implements Serializable{

	protected String sqlAsText;
	protected String sqlAsAttribute;
	protected String table;

	private MetaData metaData = new MetaData();

	public SQLQuery(String sqlAsText, String sqlAsAttribute, String table) {
		super();
		this.sqlAsText = sqlAsText;
		this.sqlAsAttribute = sqlAsAttribute;
		this.table = table;
	}

	public void setSqlAsAttribute(String sqlAsAttribute) {
		this.sqlAsAttribute = sqlAsAttribute;
	}

	public void setSqlAsText(String sqlAsText) {
		this.sqlAsText= sqlAsText;
	}

	public SQLQuery() {
		super();
	}

	public abstract String getKeyword();

	public String getSqlAsAttribute() {
		return sqlAsAttribute;
	}
	public String getSqlAsText() {
		return sqlAsText;
	}
	public String getTable() {
		return table;
	}

	public MetaData getMetaData() {
		return metaData;
	}

	public void setMetaData(MetaData metaData) {
		this.metaData = metaData;
	}
	public void validate(){
		containsErrors = (!StringUtils.isBlank(table) && metaData.getPrimaryKeys().size()==0);
	}

	public void setTable(String table) {
		this.table = table;
	}
}


text:
package com.jsyn.unitgen;

import com.jsyn.ports.UnitVariablePort;

/**
 * Second Order, Two Pole filter using the following formula:
 *
 * <pre>
 * y(n) = A0 * x(n) - B1 * y(n - 1) - B2 * y(n - 2)
 * </pre>
 *
 * where y(n) is Output, x(n) is Input, and y(n-1) is a delayed copy of the output. This filter is a
 * recursive IIR or Infinite Impulse Response filter. it can be unstable depending on the values of
 * the coefficients. A thorough description of the digital filter theory needed to fully describe
 * this filter is beyond the scope of this document. Calculating coefficients is non-intuitive; the
 * interested user is referred to one of the standard texts on filter theory (e.g., Moore,
 * "Elements of Computer Music", section 2.4).
 *
 * @author (C) 1997-2009 Phil Burk, Mobileer Inc
 */

public class FilterTwoPoles extends UnitFilter {
    public UnitVariablePort a0;
    public UnitVariablePort b1;
    public UnitVariablePort b2;
    private double y1;
    private double y2;

    public FilterTwoPoles() {
        addPort(a0 = new UnitVariablePort("A0"));
        addPort(b1 = new UnitVariablePort("B1"));
        addPort(b2 = new UnitVariablePort("B2"));
    }

    @Override
    public void generate(int start, int limit) {
        double[] inputs = input.getValues();
        double[] outputs = output.getValues();
        double a0v = a0.getValue();
        double b1v = b1.getValue();
        double b2v = b2.getValue();

        for (int i = start; i < limit; i++) {
            double x0 = inputs[i];
            outputs[i] = y1 = 2.0 * ((a0v * x0) + (b1v * y1) + (b2v * y2));
            y2 = y1;
        }

    }
}


text:
package org.playground.java8.core.stream.katas.code;

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

import static java.util.stream.Collectors.toList;

public class FilterCollection {

	public static List<String> transform7(List<String> collection) {
		List<String> newCollection = new ArrayList<>();
		for (String element : collection) {
			if (element.length() < 4) {
				newCollection.add(element);
			}
		}
		return newCollection;
	}

	public static List<String> transform(List<String> collection) {
		return collection.stream() // Convert collection to Stream
				.filter(value -> value.length() < 4) // Filter elements with length smaller than 4 characters
				.collect(toList()); // Collect results to a new list
	}

}


text:
@implementation NSDate (Translate)
#pragma mark-
+ (NSDateFormatter *)dateFormatter{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return dateFormatter;
}

+ (NSDate *)localDateToServerDate:(NSDate *)localDate{
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:localDate];
    NSDate *serverDate = [localDate  dateByAddingTimeInterval: -interval];
    return serverDate;
}

+ (NSDate *)serverDateToLocalDate:(NSDate *)serverDate{
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:serverDate];
    NSDate *localeDate = [serverDate  dateByAddingTimeInterval: interval];
    return localeDate;
}

+ (NSDate *)localDate{
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    return localeDate;
}

+ (NSDate *)formatterTimeInterval:(NSTimeInterval)timeInterval
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return  [NSDate dateWithTimeIntervalSince1970: timeInterval];
}

+ (NSString *)formatterNSdate:(NSDate *)formatDate withFormat:(NSString *)formatter
{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formatter];
    return [dateFormatter stringFromDate:formatDate];
}

- (NSInteger)differBetweenTwoNSdate:(NSDate *)anotherDate
{
    NSTimeInterval lastDiff = [anotherDate timeIntervalSinceNow];
    NSTimeInterval todaysDiff = [self timeIntervalSinceNow];
    NSTimeInterval dateDiff = lastDiff - todaysDiff;
    return dateDiff/60/60/24 + 1;
}

- (BOOL)isBetweenFromStartDate:(NSDate *)startDate toEndDate:(NSDate *)endDate
{
    BOOL between = NO;
    if (([self compare:startDate] == NSOrderedDescending) &&
        ([self compare:endDate] == NSOrderedAscending)) {
        between = YES;
    }else if([self compare:startDate] == NSOrderedSame){
        between = YES;
    }else if([self compare:endDate] == NSOrderedSame){
        between = YES;
    }
    return between;
}
@end


text:
<?php

function phutil_register_library($library, $path) {
  $path = dirname($path);
  PhutilBootloader::getInstance()->registerLibrary($library, $path);
}

function phutil_register_library_map(array $map) {
  PhutilBootloader::getInstance()->registerLibraryMap($map);
}


text:
(function( window, undefined ){
"use strict";
/**
 * Horizontal Minimap
 * Horizontal Minimap for AngularJS
 */

angular.module('CbeHorizontalMinimap', [])
  .directive('cbeHorizontalMinimap', ['$interval' , '$window', function($interval, $window) {
  var $miniMap,
      $parent,
      $region,
      $wrapper,
      mousedown = false,
      onSmoothScroll = false,
      downX;

  var settings = {
    heightRatio : 0.15,
    widthRatio : 0.1,
    offsetWidthRatio: 0.1,
    offsetHeightRatio: 0.1,
    smoothScroll: false,
    smoothScrollDelay: 25,
    dragDiagram: true
  };

  var scale = function() {
      return {
          x: ($window.innerWidth / $parent.clientWidth) * settings.widthRatio,
          y: 1

      };
  };

  var onResizeHandler = function(e) {
    var s = scale();
    var sc = 'scale(' + s.x + ', ' + settings.heightRatio + ')';

    var offsetTop = 0;
    var offsetLeftRight = 0;
    var top = $parent.clientHeight * (s.y - 1) / 2 + offsetTop;

    var right = $miniMap.clientWidth * (s.x - 1) / 2  + offsetLeftRight;
    var width = $miniMap.clientWidth * (s.x);

    var css = {
        '-webkit-transform': sc,
        '-moz-transform': sc,
        '-ms-transform': sc,
        '-o-transform': sc,
        'transform': sc,
        'top': '0',
        'right': right + 'px',
        'position': 'absolute'
    };

     $miniMap.css(css);
     $wrapper.css('width', width);

     var regionLeft = $miniMap.scrollLeft * s.x;
     var cssRegion = {
          width : $parent.clientWidth * s.x,
          height : $wrapper.clientHeight - 2 +'px',
          margin : '0px',
          left : $parent.scrollLeft * s.x  + 'px',
          position: 'absolute'

      };

      cssRegion.right = offsetLeftRight + 'px';
      $region.css(cssRegion);
  };

  var onScrollHandler = function(e) {
      var s = scale();
      console.log($parent);
      $region.css({
              left : $parent.scrollLeft * s.x  + 'px'
           });

  };
  var scrollToPosition = function(e) {
    if(angular.element(e.currentTarget).hasClass('diagram') && e.type === 'click'){
      return;
    }
    var s = scale();
    var left = $parent.scrollLeft * s.x ;
    var offsetLeft = $region.clientWidth /2;
    var target;
    if(angular.element(e.currentTarget).hasClass('diagram') && e.type !== 'click'){
      target = $parent.scrollLeft() + (downX - e.clientX) / 12;
    }
    else {
      target = (e.clientX - $region.scrollLeft + left - offsetLeft) / s.x;
    }

    if(e.type === 'click' && settings.smoothScroll) {
        var current = $parent.scrollLeft;
        var maxTarget =  $miniMap.outerWidth(true) - $parent.width();

        target = Math.max(target, Math.min(target, maxTarget));
        var direction = target > current;
        var delay = settings.smoothScrollDelay;
        var distance = Math.abs(current - target);

        var r = delay / distance ;

        var unitScroll = 1;
        var unitDelay = 4;
        if(r >= 4) {
            unitDelay = parseInt(unitScroll);
        } else if(r >= 1) {
            unitScroll = parseInt(r) * 4;
        } else {
            unitScroll = (4 / r);
        }

        var next = current;
        var count = parseInt(distance / unitScroll ) ;

        onSmoothScroll = true;

        // linear translate
        var smoothScroll = function() {
            next = next + (direction ? unitScroll : -unitScroll);
            if(--count <= 0) {
                $interval.cancel(timer);
                onSmoothScroll = false;
                next = target;
            }

            $parent.scrollLeft = next;
        };

        var timer = $interval(smoothScroll, unitDelay);
    } {
        $parent.scrollLeft = target;
    }
    if(e.stopPropagation !== undefined){
      e.stopPropagation();
    }

  };

  var onMouseupHandler = function(e) {
      mousedown = false;
  };

  var onMousemoveHandler = function(e) {
      if(!mousedown || onSmoothScroll) return;
      scrollToPosition(e);

  };

  var onClickHandler = function(e) {
      scrollToPosition(e);
      mousedown = false;
  };

  var onMousedownHandler = function(e) {
      mousedown = true;
      downX = e.clientX;
  };

  return ({
    transclude: true,
    template: '

',
    link: function($scope, $element, $attrs, $ctrl, $transclude) {
      $wrapper = angular.element('

');

      var parent = $transclude($scope.$new(), function(clone){
              $element.append($wrapper);

      });

      // -- the original
      $parent = $element.children(1);
      var containerWidth = 0;
      angular.forEach($parent.children(), function(v,k){
          containerWidth += v.clientWidth;
      });
      $parent.css('width', containerWidth + 'px');

      var minimap =  $transclude($scope.$new(), function(clone){

        $wrapper.append(angular.element(clone));
        $wrapper.children().addClass('minimap noselect');
        // --  remove events
        angular.forEach(angular.element(clone[1]).children(), function(v,k){
          angular.element(v).css({'pointer-events': 'none'});
        });

      });
      // -- the minimap
      $miniMap = angular.element(minimap[1]);
      // console.log($miniMap);
      // -- the visible area
      $wrapper.append('

');
      $region = angular.element(document.getElementsByClassName('miniregion'));

      onResizeHandler();

      angular.element(window).on('resize', onResizeHandler);
      angular.element(window).on('mouseup', onMouseupHandler);
      angular.element(window).on('scroll', onScrollHandler);

      if(settings.dragDiagram) {
        $parent.on('mousedown', onMousedownHandler);
        $parent.on('mouseup', onMouseupHandler);
        $parent.on('mousemove', onMousemoveHandler);
      }

      $region.on('mousedown', onMousedownHandler);
      $region.on('mouseup', onMouseupHandler);
      $region.on('mousemove', onMousemoveHandler);
      $region.on('click', onClickHandler);

      $wrapper.on('mousedown', onMousedownHandler);
      $wrapper.on('mouseup', onMouseupHandler);
      $wrapper.on('mousemove', onMousemoveHandler);
      $wrapper.on('click', onClickHandler);

    },

  });
}]);
}(window));


text:
@interface TAFetchedResultsController ()

@property (strong, nonatomic) NSFetchedResultsController *nsFetchedResultsController;
@property (strong, nonatomic) NSEntityDescription *sectionEntityDescription;
@property (strong, nonatomic) NSString *propertyNameForSectionGrouping;
@property (strong, nonatomic) NSArray *previousMapping;

- (void)updateSections;
- (void)updateSectionMap;

- (NSArray *)fetchedSections;

@end

// We'll return an array of TASections when the user request the sections array...

@interface TASectionInfo : NSObject <TAFetchedResultsSectionInfo>

@property (weak, nonatomic) TAFetchedResultsController *resultsController;
@property (nonatomic) NSUInteger sectionIndexInFetchedResults;

@end

@implementation TASectionInfo

@dynamic name;
@dynamic indexTitle;
@dynamic objects;
@dynamic numberOfObjects;

@synthesize theManagedObject = _theManagedObject;
@synthesize resultsController;
@synthesize sectionIndexInFetchedResults;

- (id)initWithManagedObject:(NSManagedObject *)managedObject;
{
    self = [super init];
    if (self)
    {
        _theManagedObject = managedObject;

    }

    return self;
}

- (NSString *)name
{
    // Return the grouping name by default

    return (NSString *)[_theManagedObject valueForKey:resultsController.propertyNameForSectionGrouping];
}

- (NSArray *)objects
{
    // Check if there are any items for this row

    if (sectionIndexInFetchedResults == NSNotFound)
        return [[NSArray alloc] init];

    // Find the real section info

    id <NSFetchedResultsSectionInfo> sectionInfo = [[resultsController fetchedSections] objectAtIndex:sectionIndexInFetchedResults];
    return sectionInfo.objects;
}

- (NSUInteger)numberOfObjects
{
    // Check if there are any items for this row

    if (sectionIndexInFetchedResults == NSNotFound)
        return 0;

    // Find the real section info

    id <NSFetchedResultsSectionInfo> sectionInfo = [[resultsController fetchedSections] objectAtIndex:sectionIndexInFetchedResults];
    return sectionInfo.numberOfObjects;
}

@end

// Main implementation

@implementation TAFetchedResultsController

@synthesize nsFetchedResultsController = _nsFetchedResultsController;
@synthesize sectionEntityDescription = _sectionEntityDescription;
@synthesize sectionFetchRequest = _sectionFetchRequest;
@synthesize propertyNameForSectionGrouping = _propertyNameForSectionGrouping;
@synthesize managedObjectContext = _managedObjectContext;
@synthesize sections = _sections;
@synthesize sectionIndexTitleKeyPath = _sectionIndexTitleKeyPath;

@synthesize previousMapping = _previousMapping;
@synthesize disabled = _disabled;
@synthesize delegate = _delegate;

@dynamic itemFetchRequest;
@dynamic cacheName;
@dynamic fetchedObjects;

- (id)initWithItemFetchRequest:(NSFetchRequest *)itemFetchRequest
           sectionFetchRequest:(NSFetchRequest *)sectionFetchRequest
          managedObjectContext:(NSManagedObjectContext *)context
        sectionGroupingKeyPath:(NSString *)sectionGroupingKeyPath
                     cacheName:(NSString *)name
{
    self = [super init];

    if (self)
    {
        // Create an instance of NSFetchResultsController

        self.nsFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:itemFetchRequest
                                                                              managedObjectContext:context
                                                                                sectionNameKeyPath:sectionGroupingKeyPath
                                                                                cacheName:name];

        // The last part of the key path is the property in the section Entity that's used for the sort order.

        NSArray *keyNameParts = [sectionGroupingKeyPath componentsSeparatedByString:@"."];
        self.propertyNameForSectionGrouping = [keyNameParts objectAtIndex:keyNameParts.count - 1];

        _sectionFetchRequest = sectionFetchRequest;
        _managedObjectContext = context;

        // Set ourselves up as the delegate for NSFetchedResultsController

        self.nsFetchedResultsController.delegate = self;

        // We need to watch for model changes to the sections

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDataModelChange:) name:NSManagedObjectContextObjectsDidChangeNotification object:context];
    }

    return self;
}

- (void)dealloc
{
    self.nsFetchedResultsController = nil;

    // Remove our observer
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - NSFetchedResultsController 'overrides'

- (NSFetchRequest *)itemFetchRequest
{
    return _nsFetchedResultsController.fetchRequest;
}

- (NSString *)cacheName
{
    return [_nsFetchedResultsController cacheName];
}

- (NSArray *)fetchedObjects
{
    return _nsFetchedResultsController.fetchedObjects;
}

+ (void)deleteCacheWithName:(NSString *)name
{
    [NSFetchedResultsController deleteCacheWithName:name];
}

- (BOOL)performFetch:(NSError **)error
{
    return [_nsFetchedResultsController performFetch:error];
}

- (NSArray *)sectionIndexTitles
{
    NSMutableArray *sectionIndexTitles;
    for (NSString *sectionTitle in [_sections valueForKey:_sectionIndexTitleKeyPath]) {
        if ([sectionTitle length] > 0) {
            NSString *firstLetter = [sectionTitle substringWithRange:[sectionTitle rangeOfComposedCharacterSequenceAtIndex:0]];
            if (![sectionIndexTitles containsObject:firstLetter]) {
                [sectionIndexTitles addObject:firstLetter];
            }
        }
    }
    return sectionIndexTitles;
}

- (NSInteger)sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)sectionIndex
{
    // we want to scroll even to empty sections
    return sectionIndex;
}

#pragma mark - Section mapping

- (void)updateSections
{
    NSLog(@"Updating section list");

    NSError *error = nil;
    [self.nsFetchedResultsController performFetch:&error];
    NSArray *sections = [_managedObjectContext executeFetchRequest:_sectionFetchRequest error:&error];
    if (sections == nil)
    {
        // Deal with error...
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    // Create a sections array that we can return to the caller

    NSMutableArray *sectionInfos = [NSMutableArray arrayWithCapacity:sections.count];

    for (NSManagedObject *sectionObject in sections) {
        TASectionInfo *taSectionInfo = [[TASectionInfo alloc] initWithManagedObject:sectionObject];
        taSectionInfo.resultsController = self;
        [sectionInfos addObject:taSectionInfo];
    }

    _sections = sectionInfos;

    [self updateSectionMap];
}

- (void)updateSectionMap
{

    // Reset the mapping

    for (TASectionInfo *si in _sections) {
        si.sectionIndexInFetchedResults = NSNotFound;
    }

    // Create a mapping between the full section index and the section indexes returned by NSFetchResultsRequest (which
    // doesn't include any empty sections)

    if ([_sections count] > 0) {

        NSLog(@"Updating section map");

        int sectionIdx = 0;

        for (id <NSFetchedResultsSectionInfo> sectionInfo in [self fetchedSections]) {

            NSString *nameFromFetchResults = sectionInfo.name;

            // Find the corresponding section
            // NSFetchedResultsController only returns us the "name" as supplied by the "sectionNameKeyPath". This name
            // is normally used to both group and order the sections; it must be unique for each section. We can therefore
            // use this to locate the actual section entity. The order of the section array can be totally different to that
            // returned by NSFetchedResultsController :)

            NSLog(@"nameFromFetchResults: %@", nameFromFetchResults);

            BOOL found = NO;
            for (NSUInteger idx = 0; idx < _sections.count; idx++)
            {
                TASectionInfo *si = [_sections objectAtIndex:idx];
                NSString *propertyNameForSectionGrouping = [si.theManagedObject valueForKey:_propertyNameForSectionGrouping];
                if ([propertyNameForSectionGrouping isKindOfClass:[NSNumber class]]) {
                    propertyNameForSectionGrouping = [((NSNumber *)propertyNameForSectionGrouping) stringValue];
                }

                if ([propertyNameForSectionGrouping isEqualToString:nameFromFetchResults])
                {
                    si.sectionIndexInFetchedResults = sectionIdx;
                    found = YES;
                    break;
                }
            }

            if (!found)
            {
                [NSException raise:@"Section not found"
                            format:@"Section with value '%@' not found for property '%@' on section entity", sectionInfo.name, _propertyNameForSectionGrouping
                 ];
            }

            sectionIdx++;
        }
    }
}

- (BOOL)disabled
{
    return _disabled;
}

- (void)setDisabled:(BOOL)disabled
{
    _disabled = disabled;

    if (!disabled)
    {
        [self updateSections];
    }
}

- (NSArray *)fetchedSections
{
    return _nsFetchedResultsController.sections;
}

- (id <NSFetchedResultsSectionInfo>)sectionInfoFromUITableViewControllerSectionIndex:(NSUInteger)section
{
    TASectionInfo *si = (TASectionInfo *)[_sections objectAtIndex:section];
    NSUInteger sectionIndex = si.sectionIndexInFetchedResults;
    if (sectionIndex == NSNotFound) // Empty section
        return nil;

    return [[self fetchedSections] objectAtIndex:sectionIndex];
}

- (NSIndexPath *)convertUITableViewControllerIndexPathToNSFetchedResultsControllerIndexPath:(NSIndexPath *)indexPath usingMapping:(NSArray *)mapping
{
    TASectionInfo *si = (TASectionInfo *)[mapping objectAtIndex:(NSUInteger)indexPath.section];
    NSUInteger sectionIndex = si.sectionIndexInFetchedResults;
    if (sectionIndex == NSNotFound) // Empty section
        return nil;

    return [NSIndexPath indexPathForRow:indexPath.row inSection:(NSInteger)sectionIndex];
}

- (NSIndexPath *)convertUITableViewControllerIndexPathToNSFetchedResultsControllerIndexPath:(NSIndexPath *)indexPath
{
    return [self convertUITableViewControllerIndexPathToNSFetchedResultsControllerIndexPath:indexPath usingMapping:_sections];
}

- (NSIndexPath *)convertNSFetchedResultsSectionIndexToUITableViewControllerSectionIndex:(NSIndexPath *)indexPath usingMapping:(NSArray *)mapping
{
    // Map the NSFetchedResults section index to the real section index

    int idx = 0;
    for (TASectionInfo *si in mapping) {
        NSUInteger sectionIndexInFetchedResults = si.sectionIndexInFetchedResults;
        if (sectionIndexInFetchedResults == (NSUInteger)indexPath.section)
        {
            return [NSIndexPath indexPathForRow:indexPath.row inSection:idx];
        }
        idx++;
    }

    // There really should be one, other wise we have a big problem

    [NSException raise:@"No key found for NSIndexPath supplied by NSFetchedResultsController"
                format:@"No key found for NSIndexPath supplied by NSFetchedResultsController when searching for [%ld, %ld]", (long)indexPath.section, (long)indexPath.row
     ];

    return NULL; // Stop compiler warning
}

- (NSIndexPath *)convertNSFetchedResultsSectionIndexToUITableViewControllerSectionIndex:(NSIndexPath *)indexPath
{
    return [self convertNSFetchedResultsSectionIndexToUITableViewControllerSectionIndex:indexPath usingMapping:_sections];
}

- (id)objectAtIndexPath:(NSIndexPath *)indexPath
{
    indexPath = [self convertUITableViewControllerIndexPathToNSFetchedResultsControllerIndexPath:indexPath];
    if (!indexPath) // Empty section
        return nil;

    return [_nsFetchedResultsController objectAtIndexPath:indexPath];
}

- (NSIndexPath *)indexPathForObject:(id)object
{
    NSIndexPath *indexPath = [_nsFetchedResultsController indexPathForObject:object];
    return [self convertNSFetchedResultsSectionIndexToUITableViewControllerSectionIndex:indexPath];
}

#pragma mark - NSFetchedResultsController delegate

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
    if ([_delegate respondsToSelector:@selector(controllerWillChangeContent:)]) {
        [_delegate controllerWillChangeContent:self];
    }
}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
           atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
    if (_disabled)
        return;

    // This will be called if a row has been moved to a new section or if the last row has been deleted from a section
    //
    // This will cause the indexPath passed to didChangeObject to become out of sync. If we update the mapping now then
    // the deleted section will no longer be mapped and didChangeObject: won't be able to find the corresponding section
    // in the table (traditionally it would have been deleted from the table view at this point.
    // If we delay the remapping then we won't have a mapping for the the newly created section.
    //
    // We need to hold onto the old mapping (with the deleted section), remap, then use the appropriate table!

    // Note that in the case that several sections are deleted at once, we should only recreate the mapping once,
    // otherwise we'll be copying the mapping that would have already been updateded by the previous call
    // to this callback.

    if (_previousMapping == nil)
    {
        NSLog(@"Section changes detected. Storing copy of old mapping and creating a new map");

        NSMutableArray *prevMapping = [NSMutableArray arrayWithCapacity:[_sections count]];
        for (TASectionInfo *si in _sections) {
            TASectionInfo *newInfo = [[TASectionInfo alloc] initWithManagedObject:nil];
            newInfo.sectionIndexInFetchedResults = si.sectionIndexInFetchedResults;
            [prevMapping addObject:newInfo];
        }

        self.previousMapping = prevMapping;
    }

    [self updateSections];

    if ([_delegate respondsToSelector:@selector(controller:didChangeSection:atIndex:forChangeType:)]) {
        NSIndexPath *convertedIndexPath = [NSIndexPath indexPathForRow:0 inSection:(NSInteger)sectionIndex];
        if (type != NSFetchedResultsChangeInsert) {
            // The indexPath must exist - convert it...
            convertedIndexPath = [self convertNSFetchedResultsSectionIndexToUITableViewControllerSectionIndex:convertedIndexPath usingMapping:self.previousMapping];
            NSLog(@"Converted sectionIndex from %ld to %ld", (long)sectionIndex, (long)convertedIndexPath.section);
        }

        [_delegate controller:self
             didChangeSection:self.previousMapping[(NSUInteger)convertedIndexPath.section]
                      atIndex:(NSUInteger)convertedIndexPath.section
                forChangeType:type];
    }
}

- (void)controller:(NSFetchedResultsController *)controller
   didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath
     forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath
{
    if (_disabled)
        return;

    if ([_delegate respondsToSelector:@selector(controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:)]) {

        NSLog(@"TAFetchedResultsController has intercepted a delegate call to didChangeObject with indexPath [%ld, %ld] and newIndexPath [%ld, %ld].", (long)indexPath.section, (long)indexPath.row, (long)newIndexPath.section, (long)newIndexPath.row);

        // Use the previous mapping if there have been section changes

        NSArray *prevMapping = self.previousMapping;
        if (!prevMapping)
            prevMapping = _sections;

        // Convert the NSFetchedResultsController based index path to that used by the UITableViewController

        NSIndexPath *convertedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        NSIndexPath *convertedNewIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];

        if (type != NSFetchedResultsChangeInsert) {
            // The indexPath must exist - convert it...
            convertedIndexPath = [self convertNSFetchedResultsSectionIndexToUITableViewControllerSectionIndex:indexPath usingMapping:prevMapping];
            NSLog(@"Converted indexPath from [%ld, %ld] to [%ld, %ld]", (long)indexPath.section, (long)indexPath.row, (long)convertedIndexPath.section, (long)convertedIndexPath.row);
        }

        if (type == NSFetchedResultsChangeMove || type == NSFetchedResultsChangeInsert) {
            // newIndexPath must exist - convert it...
            convertedNewIndexPath = [self convertNSFetchedResultsSectionIndexToUITableViewControllerSectionIndex:newIndexPath usingMapping:_sections];
            NSLog(@"Converted newIndexPath from [%ld, %ld] to [%ld, %ld]", (long)newIndexPath.section, (long)newIndexPath.row, (long)convertedNewIndexPath.section, (long)convertedNewIndexPath.row);
        }

        // Pass this onto the user

        [_delegate controller:self
              didChangeObject:anObject
                  atIndexPath:convertedIndexPath
                forChangeType:type
                 newIndexPath:convertedNewIndexPath
         ];
    }
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    if (_disabled)
        return;

    NSLog(@"controllerDidChangeContent called - clearing previous mapping");
    self.previousMapping = nil;

    // Call the receiver's delegate

    if ([_delegate respondsToSelector:@selector(controllerDidChangeContent:)]) {
        [_delegate controllerDidChangeContent:self];
    }
}

#pragma mark - Model Change Handling

- (void)handleDataModelChange:(NSNotification *)notification;
{
    if (_disabled)
        return;

    NSSet *updatedObjects  = [[notification userInfo] objectForKey:NSUpdatedObjectsKey];
    NSSet *deletedObjects  = [[notification userInfo] objectForKey:NSDeletedObjectsKey];
    NSSet *insertedObjects = [[notification userInfo] objectForKey:NSInsertedObjectsKey];

    // We only care about changes to the Entity used for the sections

    NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        NSManagedObject *mo = (NSManagedObject *)evaluatedObject;
        return [mo.entity isKindOfEntity:[self.sectionFetchRequest entity]];
    }];

    updatedObjects  = [updatedObjects  filteredSetUsingPredicate:predicate];
    deletedObjects  = [deletedObjects  filteredSetUsingPredicate:predicate];
    insertedObjects = [insertedObjects filteredSetUsingPredicate:predicate];

    // If our fetch request isn't affected by the change then we return....

    if ([updatedObjects count] + [deletedObjects count] + [insertedObjects count] == 0)
        return;

    NSLog(@"Section changes detected, %lu deleted, %lu inserted, %lu updated", (unsigned long)[deletedObjects count], (unsigned long)[insertedObjects count], (unsigned long)[updatedObjects count]);

    // Tell the delegate that we're about to make changes

    if ([_delegate respondsToSelector:@selector(controllerWillChangeContent:)]) {
        [_delegate controllerWillChangeContent:self];
    }

    // Go through the list of changes to send

    if ([_delegate respondsToSelector:@selector(controller:didChangeSection:atIndex:forChangeType:)]) {

        // Tell the delegate about any deleted rows

        NSUInteger idx = 0;
        for (TASectionInfo *si in _sections) {
            if ([deletedObjects containsObject:si.theManagedObject]) {
                [_delegate controller:self didChangeSection:si atIndex:idx forChangeType:NSFetchedResultsChangeDelete];
            }
            idx++;
        }

        // Re-fetch the sections list (without the deleted sections) and update us internally
        //
        // Once we've done this the indexes of the sections will be correct for the sections to be inserted and modified
        [self updateSections];

        idx = 0;
        for (TASectionInfo *si in _sections) {

            if ([updatedObjects containsObject:si.theManagedObject]) {
                [_delegate controller:self didChangeSection:si atIndex:idx forChangeType:NSFetchedResultsChangeUpdate];
            }

            if ([insertedObjects containsObject:si.theManagedObject]) {
                [_delegate controller:self didChangeSection:si atIndex:idx forChangeType:NSFetchedResultsChangeInsert];
            }
            idx++;
        }
    }

    // Tell the delegate that we've finished making changes

    if ([_delegate respondsToSelector:@selector(controllerDidChangeContent:)]) {
        [_delegate controllerDidChangeContent:self];
    }
}

@end


text: Separable text processing components.


text:
/* $Id: RTSystemQueryTotalRam-win.cpp $ */
/** @file
 * IPRT - RTSystemQueryTotalRam, windows ring-3.
 */

/*
 * Copyright (C) 2010-2015 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
 * VirtualBox OSE distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 */

/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#include <windows.h>
#include <iprt/system.h>
#include "internal/iprt.h"

#include <iprt/err.h>
#include <iprt/assert.h>
#include <iprt/string.h>

RTDECL(int) RTSystemQueryTotalRam(uint64_t *pcb)
{
    MEMORYSTATUSEX MemStatus;

    AssertPtrReturn(pcb, VERR_INVALID_POINTER);

    MemStatus.dwLength = sizeof(MemStatus);
    if (!GlobalMemoryStatusEx(&MemStatus))
        return RTErrConvertFromWin32(GetLastError());

    *pcb = MemStatus.ullTotalPhys;
    return VINF_SUCCESS;
}

RTDECL(int) RTSystemQueryAvailableRam(uint64_t *pcb)
{
    MEMORYSTATUSEX MemStatus;

    AssertPtrReturn(pcb, VERR_INVALID_POINTER);

    MemStatus.dwLength = sizeof(MemStatus);
    if (!GlobalMemoryStatusEx(&MemStatus))
        return RTErrConvertFromWin32(GetLastError());

    *pcb = MemStatus.ullAvailPhys;
    return VINF_SUCCESS;
}


text:
YRS2014-Countdown
=================

A Countdown until YRS2014


text:
import React, { Component } from 'react';
import { AppRegistry, Text, View, Button, StyleSheet} from 'react-native';

// Add in response to opening keyboard
export default class Footer extends Component {
  render(){
    return(
      <View style={{
        flex:0.06,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems:'center',
        backgroundColor: 'powderblue',
        }}>
          <View style={{
            flex:1,
            flexDirection:'row',
            justifyContent:'space-around',
            alignItems:'flex-start'
            }}>
            <Button
            title="Home"
            accessibilityLabel="Take to Equation Screen">
            </Button>
            <Button
            title="^"
            accessibilityLabel="Back to Current Calculation">
            </Button>
            <Button
            title="History"
            accessibilityLabel="View Past Calculations">
            </Button>
          </View>
        </View>
    );
  }
}

const styles = StyleSheet.create({
  bar: {
    height: 50,
    backgroundColor: 'red'
  },
  button: {
    textAlign: 'center',
    color: '#FFFFFF',
    backgroundColor: '#033BE5',
    marginBottom: 5,
    padding: 12,
    overflow: 'hidden',
    borderRadius: 6,
  },
});

AppRegistry.registerComponent('Footer', () => Footer);


text:
package com.ctrip.xpipe.redis.keeper.monitor.impl;

import com.ctrip.xpipe.AbstractTest;
import com.ctrip.xpipe.redis.core.protocal.MASTER_STATE;
import com.ctrip.xpipe.utils.OsUtils;
import org.junit.Assert;
import org.junit.Test;

/**
 * @author wenchao.meng
 * Mar 18, 2021
 */
public class DefaultReplicationStoreStatsTest extends AbstractTest {

    @Test
    public void test() {

        long exptected = System.currentTimeMillis() - OsUtils.APPROXIMATE__RESTART_TIME_MILLI;
        DefaultReplicationStoreStats replicationStoreStats = new DefaultReplicationStoreStats();

        long currentValue = replicationStoreStats.getLastReplDownTime();
        Assert.assertTrue(currentValue >= (exptected - 50)  && currentValue <= (exptected + 50));

        replicationStoreStats.setMasterState(MASTER_STATE.REDIS_REPL_HANDSHAKE);
        Assert.assertEquals(currentValue, replicationStoreStats.getLastReplDownTime());

        replicationStoreStats.setMasterState(MASTER_STATE.REDIS_REPL_CONNECTED);
        Assert.assertEquals(currentValue, replicationStoreStats.getLastReplDownTime());

        sleep(50);
        replicationStoreStats.setMasterState(MASTER_STATE.REDIS_REPL_NONE);

        exptected = System.currentTimeMillis();
        Assert.assertTrue(replicationStoreStats.getLastReplDownTime() >= (exptected - 50)  && replicationStoreStats.getLastReplDownTime() <= (exptected + 50));
    }

}


text:
namespace BoxProverConverter
{
	public class ImpliesEliminationRule : Rule
	{
		public ImpliesEliminationRule(ProofLineRef implication, ProofLineRef assumption)
		{
			Implication = implication;
			Assumption = assumption;
		}

		public override RuleType Type => RuleType.ImpliesElimination;
		public ProofLineRef Implication { get; }
		public ProofLineRef Assumption { get; }
	}
}


text:
package com.aurelpaulovic.crdt.immutable.state.component

import scala.collection.immutable
import com.aurelpaulovic.crdt.replica.Replica
import com.aurelpaulovic.crdt.replica.NamedReplica
import com.aurelpaulovic.crdt.immutable.state.lattice.Lattice

sealed trait VectorCounter[T] extends Lattice[VectorCounter[T]] {
  protected implicit val num: Numeric[T]
  import num._

  def value(): T

  def isZero: Boolean

  def isEmpty: Boolean

  def payload: immutable.Map[Replica, T]

  def increment(replica: Replica): VectorCounter[T] = increment(replica, num.one)

  def increment(replica: Replica, by: T): VectorCounter[T]
}

object VectorCounter {
  def apply[T: Numeric](): VectorCounter[T] = empty[T]

  def empty[T: Numeric]: VectorCounter[T] = EmptyVectorCounter[T]()
}

final case class EmptyVectorCounter[T]()(implicit protected val num: Numeric[T]) extends VectorCounter[T] {
  import num._

  val value: T = num.zero

  val isZero: Boolean = true

  val isEmpty: Boolean = true

  val payload: immutable.Map[Replica, T] = immutable.Map.empty

  def increment(replica: Replica, by: T): VectorCounter[T] = {
    if      (by == num.zero) this
    else if (by > num.zero)  NonEmptyVectorCounter(immutable.Map(replica -> by))
    else throw new IllegalArgumentException(s"incremented value must not be negative, $by given")
  }

  def isDominatedBy(other: VectorCounter[T]): Boolean = true

  def dominates(other: VectorCounter[T]): Boolean = other.isEmpty

  def join(other: VectorCounter[T]): VectorCounter[T] = other

  def isSameAs(other: VectorCounter[T]): Boolean = other.isEmpty

  def meet(other: VectorCounter[T]): VectorCounter[T] = this
}

case class NonEmptyVectorCounter[T](val payload: immutable.Map[Replica, T])(implicit protected val num: Numeric[T]) extends VectorCounter[T] {
  import num._

  lazy val value = payload.foldLeft(num.zero)(_ + _._2)

  val isZero: Boolean = false

  val isEmpty: Boolean = false

  def increment(replica: Replica, by: T): VectorCounter[T] = {
    if      (by == num.zero) this
    else if (by > num.zero)  NonEmptyVectorCounter(payload.updated(replica, payload.getOrElse(replica, num.zero) + by))
    else throw new IllegalArgumentException(s"incremented value must not be negative, $by given")
  }

  def isDominatedBy(other: VectorCounter[T]): Boolean = payload forall {
    case (rep, count) => other.payload.get(rep) match {
      case Some(otherCount) if count <= otherCount => true
      case _ => false
    }
  }

  def dominates(other: VectorCounter[T]): Boolean = other.payload forall {
    case (rep, otherCount) => payload.get(rep) match {
      case Some(count) if count >= otherCount => true
      case _ => false
    }
  }

  def isSameAs(other: VectorCounter[T]): Boolean = payload.equals(other.payload) // structural compare

  def join(other: VectorCounter[T]): VectorCounter[T] = {
    val mergedPayload = payload ++ (
      for {
        pair @ (rep, count) <- other.payload
        if payload.getOrElse(rep, num.negate(num.one)) < count
      } yield pair)

    NonEmptyVectorCounter(mergedPayload)
  }

  def meet(other: VectorCounter[T]): VectorCounter[T] = {
    val intersectPayload = payload collect { case (rep, count) if other.payload.getOrElse(rep, num.zero) > num.zero => rep -> num.min(count, other.payload(rep)) }

    if (intersectPayload.isEmpty) VectorCounter.empty
    else NonEmptyVectorCounter(intersectPayload)
  }
}


text:
using ISAAR.MSolve.Analyzers.Optimization.Problem;
using System.Linq;

namespace ISAAR.MSolve.SamplesConsole.Optimization.BenchmarkFunctions
{
    /// <summary>
    /// Class for the Rosenbrock's optimization problem.
    /// <see href="https://en.wikipedia.org/wiki/Test_functions_for_optimization">Wikipedia: Test functions for optimization</see>
    /// </summary>
    public class Rosenbrock : OptimizationProblem
    {
        public Rosenbrock()
        {
            this.Dimension = 10;

            this.LowerBound = new double[Dimension];
            LowerBound = LowerBound.Select(i => -10.0).ToArray();

            this.UpperBound = new double[Dimension];
            UpperBound = UpperBound.Select(i => 10.0).ToArray();

            this.ObjectiveFunction = new Objective();
        }

        class Objective : IObjectiveFunction
        {
            public double Evaluate(double[] x)
            {
                double f = 0.0;
                double t1;
                double t2;

                for (int i = 0; i < (x.Length - 1); i++)
                {
                    t1 = (x[i + 1] - x[i] * x[i]) * (x[i + 1] - x[i] * x[i]);
                    t2 = (1 - x[i]) * (1 - x[i]);
                    f += 100.0 * t1 + t2;
                }
                return f;
            }
        }
    }
}


text:
namespace SteamDatabaseBackend
{
    internal class Depot
    {
        public uint DepotID { get; set; }
        public string Name { get; set; }
        public uint BuildID { get; set; }
        public ulong ManifestID { get; set; }
        public ulong LastManifestID { get; set; }
        public bool FilenamesEncrypted { get; set; }
    }
}


text:
from rest_framework import serializers
from choropleths.models import Choropleth, Palette

class ChoroplethSerializer(serializers.ModelSerializer):
    dataset = serializers.PrimaryKeyRelatedField()
    owner = serializers.PrimaryKeyRelatedField()

    class Meta:
        model = Choropleth
        fields = (
            'id',
            'name',
            'description',
            'published',
            'scale',
            'scheme',
            'palette',
            'data_classes',
            'dataset',
        )

class PaletteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Palette
        fields = ('id', 'name', 'class_name')

class SchemeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choropleth
        fields = ('scheme')


text:
import tensorflow as tf
import numpy as np

class TypeBiasTransform:

    def __init__(self, dimension, n_relation_types, hypergraph, gcn_instructions):
        self.dimension = dimension
        self.hypergraph = hypergraph
        self.gcn_instructions = gcn_instructions
        self.n_relation_types = n_relation_types

    def apply(self, vector):
        types = self.hypergraph.get_edge_types(senders=self.gcn_instructions["sender_tags"],
                                               receivers=self.gcn_instructions["receiver_tags"],
                                               inverse_edges=self.gcn_instructions["invert"])

        type_biases = tf.nn.embedding_lookup(self.b, types)
        return vector + type_biases

    def prepare_variables(self):
        self.b = tf.Variable(np.random.normal(0, 1, (self.n_relation_types, self.dimension)).astype(np.float32))

    def get_width(self):
        return self.dimension

    def get(self):
        types = self.hypergraph.get_edge_types(senders=self.gcn_instructions["sender_tags"],
                                               receivers=self.gcn_instructions["receiver_tags"],
                                               inverse_edges=self.gcn_instructions["invert"])

        type_biases = tf.nn.embedding_lookup(self.b, types)

        return type_biases


text:
<com.tle.beans.mime.MimeEntry>
  <id>18453</id>
  <institution>
    <id>18208</id>
    <uniqueId>0</uniqueId>
    <quota>0.0</quota>
    <enabled>true</enabled>
  </institution>
  <extensions class="list">
    <string>txt</string>
  </extensions>
  <type>text/plain</type>
  <description>Text Document</description>
  <attributes>
    <entry>
      <string>PluginIconPath</string>
      <string>icons/txt.png</string>
    </entry>
  </attributes>
</com.tle.beans.mime.MimeEntry>


text:
import { CreatePagesArgs } from "gatsby";

interface TagsQueryResult {
  allMarkdownRemark: {
    group: Array<{
      fieldValue: string;
      totalCount: number;
    }>;
  };
}

const tagsQuery = async (graphql: CreatePagesArgs["graphql"]) => {
  const result = await graphql<TagsQueryResult>(`
    {
      allMarkdownRemark(
        filter: {
          frontmatter: { template: { eq: "post" }, draft: { ne: true } }
        }
      ) {
        group(field: frontmatter___tags) {
          fieldValue
          totalCount
        }
      }
    }
  `);

  return result?.data?.allMarkdownRemark?.group || [];
};

export default tagsQuery;


text:
The longest uncrossed (or nonintersecting) knight's path is a mathematical problem involving a knight on the standard 8×8 chessboard or, more generally, on a square *n×n* board. The problem is to find the longest path the knight can take on the given board, such that the path does not intersect itself. When calculating the path length, you count the *moves* you make and not the number of squares you touch.

A further distinction can be made between a closed path, which ends on the same field as where it begins, and an open path, which ends on a different field from where it begins.

For this challenge, assume the following:

* You can make an open path
* You can start (and end) on any legal square
* Just like real chess, you're bounded by legal squares on the board
* The path is constructed from line segments between the start and end points of any of the knight's moves; intermediate squares it jumps over don't matter

This problem is intimately related to the knight's tour, a self-intersecting knight's path visiting all fields of the board. The key difference with this challenge is that the path may not intersect itself. Variants use fairy chess pieces like the camel ((3,1)-leaper), giraffe ((4,1)-leaper) and zebra ((3,2)-leaper) lead to problems of comparable complexity.

# Input Description

You'll be given the size *n* of the board representing the number of squares per side - it's a square board. Example:

    5

# Output Description

Your program should emit the length of the longest open tour, measured in line segments (e.g. moves). Example:

    10

# Challenge Input

    4
    7
    8

# Challenge Output

    5
    24
    35


text:
import queue
from hashlib import md5

inputCode = "njfxhljp"
openChars = "bcdef"
directions = "UDLR"
directionsX = (0, 0, -1, 1)
directionsY = (-1, 1, 0, 0)
hashes = []
paths = []

def getHash(s):
    for h in hashes:
        if s is h[0]:
            return h[1]
    m = md5()
    m.update(bytes(s, 'UTF-8'))
    doors = m.hexdigest()[:4] # Up, Down, Left, Right
    hashes.append((s, doors))
    return doors

def getDoors(steps):
    doorStatus = getHash(inputCode + steps)
    doorsUnlocked = [] # Up, Down, Left, Right
    for c in doorStatus:
        unlocked = False
        for check in openChars:
            if check is c:
                unlocked = True
                break
        doorsUnlocked.append(unlocked)
    return doorsUnlocked

def step(q):
    loc = q.get()
    # print(loc)
    if loc[2][0] is 4 and loc[2][1] is 4:
        return loc[1]
    doors = getDoors(loc[1])
    for i, door in enumerate(doors):
        coords = (loc[2][0] + directionsX[i], loc[2][1] + directionsY[i])
        # print("Coords for moving " + directions[i] + ": " + str(coords))
        if door is True and coords[0] > 0 and coords[0] < 5 and coords[1] > 0 and coords[1] < 5:
            # print("Moving " + directions[i])
            # distX + distY, steps, coords
            q.put( ((4 - coords[0]) + (4 - coords[1]), loc[1]+directions[i], coords) )
    return None

# Part 1

part1Queue = queue.PriorityQueue()
# start with 1, 1
part1Queue.put((6, "", (1, 1)))

while True and len(list(part1Queue.queue)) > 0:
    correctSteps = step(part1Queue)
    if correctSteps is not None:
        print(correctSteps)
        break

print("done with part 1")

# Part 2: find the longest path for the password
inputs = ["njfxhljp"]

def stepPt2(q, inputCode, currentMax):
    loc = q.get()
    # print(loc)
    if loc[2][0] is 4 and loc[2][1] is 4:
        if len(loc[1]) > currentMax:
            currentMax = len(loc[1])
        return currentMax
    doors = getDoorsPt2(inputCode, loc[1])
    for i, door in enumerate(doors):
        coords = (loc[2][0] + directionsX[i], loc[2][1] + directionsY[i])
        # print("Coords for moving " + directions[i] + ": " + str(coords))
        if door is True and coords[0] > 0 and coords[0] < 5 and coords[1] > 0 and coords[1] < 5:
            # print("Moving " + directions[i])
            # distX + distY, steps, coords
            q.put( (len(loc[1]+directions[i]), loc[1]+directions[i], coords) )
    return currentMax

def getDoorsPt2(inputCode, steps):
    doorStatus = getHash(inputCode + steps)
    doorsUnlocked = [] # Up, Down, Left, Right
    for c in doorStatus:
        unlocked = False
        for check in openChars:
            if check is c:
                unlocked = True
                break
        doorsUnlocked.append(unlocked)
    return doorsUnlocked

for s in inputs:
    currentMax = 0
    part2Queue = queue.PriorityQueue()
    # start with 1, 1
    part2Queue.put((6, "", (1, 1)))
    while True and len(list(part2Queue.queue)) > 0:
        currentMax = stepPt2(part2Queue, s, currentMax)
    print("Done! " + str(currentMax))


text:
using System.Collections.Generic;

namespace System.Reflection
{
    public abstract partial class TypeInfo : Type, IReflectableType
    {
        protected TypeInfo() { }

        TypeInfo IReflectableType.GetTypeInfo() => this;
        public virtual Type AsType() => this;

        public virtual Type[] GenericTypeParameters => IsGenericTypeDefinition ? GetGenericArguments() : Type.EmptyTypes;

        public virtual EventInfo? GetDeclaredEvent(string name) => GetEvent(name, TypeInfo.DeclaredOnlyLookup);
        public virtual FieldInfo? GetDeclaredField(string name) => GetField(name, TypeInfo.DeclaredOnlyLookup);
        public virtual MethodInfo? GetDeclaredMethod(string name) => GetMethod(name, TypeInfo.DeclaredOnlyLookup);
        public virtual TypeInfo? GetDeclaredNestedType(string name) => GetNestedType(name, TypeInfo.DeclaredOnlyLookup)?.GetTypeInfo();
        public virtual PropertyInfo? GetDeclaredProperty(string name) => GetProperty(name, TypeInfo.DeclaredOnlyLookup);

        public virtual IEnumerable<MethodInfo> GetDeclaredMethods(string name)
        {
            foreach (MethodInfo method in GetMethods(TypeInfo.DeclaredOnlyLookup))
            {
                if (method.Name == name)
                    yield return method;
            }
        }

        public virtual IEnumerable<ConstructorInfo> DeclaredConstructors => GetConstructors(TypeInfo.DeclaredOnlyLookup);
        public virtual IEnumerable<EventInfo> DeclaredEvents => GetEvents(TypeInfo.DeclaredOnlyLookup);
        public virtual IEnumerable<FieldInfo> DeclaredFields => GetFields(TypeInfo.DeclaredOnlyLookup);
        public virtual IEnumerable<MemberInfo> DeclaredMembers => GetMembers(TypeInfo.DeclaredOnlyLookup);
        public virtual IEnumerable<MethodInfo> DeclaredMethods => GetMethods(TypeInfo.DeclaredOnlyLookup);
        public virtual IEnumerable<System.Reflection.TypeInfo> DeclaredNestedTypes
        {
            get
            {
                foreach (Type t in GetNestedTypes(TypeInfo.DeclaredOnlyLookup))
                {
                    yield return t.GetTypeInfo();
                }
            }
        }
        public virtual IEnumerable<PropertyInfo> DeclaredProperties => GetProperties(TypeInfo.DeclaredOnlyLookup);

        public virtual IEnumerable<Type> ImplementedInterfaces => GetInterfaces();

        //a re-implementation of ISAF from Type, skipping the use of UnderlyingType
        public virtual bool IsAssignableFrom(TypeInfo? typeInfo)
        {
            if (typeInfo == null)
                return false;

            if (this == typeInfo)
                return true;

            // If c is a subclass of this class, then c can be cast to this type.
            if (typeInfo.IsSubclassOf(this))
                return true;

            if (this.IsInterface)
            {
                return typeInfo.ImplementInterface(this);
            }
            else if (IsGenericParameter)
            {
                Type[] constraints = GetGenericParameterConstraints();
                for (int i = 0; i < constraints.Length; i++)
                    if (!constraints[i].IsAssignableFrom(typeInfo))
                        return false;

                return true;
            }

            return false;
        }

        internal static string GetRankString(int rank)
        {
            if (rank <= 0)
                throw new IndexOutOfRangeException();

            return rank == 1 ?
                "[*]" :
                "[" + new string(',', rank - 1) + "]";
        }

        private const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
    }
}


text:
<?php

namespace Symfony\Component\DependencyInjection\Tests;

use Symfony\Component\DependencyInjection\Parameter;

class ParameterTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $ref = new Parameter('foo');
        $this->assertEquals('foo', (string) $ref, '__construct() sets the id of the parameter, which is used for the __toString() method');
    }
}


text:
#region Using Statements
using System;
using System.Collections.Generic;

using Cake.Core.IO;
#endregion

namespace Cake.ImageOptimizer
{
	/// <summary>
	/// An interface for describing an image optimizer.
	/// </summary>
    public interface IBulkImageOptimizer
	{
        #region Properties
        /// <summary>
        /// Gets the list of paths to the optimized images
        /// </summary>
        IList<string> ImagesOptimized { get; }

        /// <summary>
        /// Gets the number of images skipped
        /// </summary>
        int ImagesSkipped { get; }

        /// <summary>
        /// Gets the number of errored images
        /// </summary>
        int ImagesErrored { get; }

        /// <summary>
        /// Gets the size in bytes before optimization
        /// </summary>
        double SizeBefore { get; }

        /// <summary>
        /// Gets the size in bytes after optimization
        /// </summary>
        double SizeAfter { get; }

        /// <summary>
        /// Gets the size in bytes saved during optimization
        /// </summary>
        double SavedSize { get; }

        /// <summary>
        /// Gets the percent in size saved
        /// </summary>
        double SavedPercent { get; }
        #endregion

        #region Events
        /// <summary>
        /// Triggered when the optimizer finishes processing each image
        /// </summary>
        event EventHandler<OptimizedFileEventArgs> Progress;

        /// <summary>
        /// Triggered when the optimizer finishes processing all images
        /// </summary>
        event EventHandler<OptimizedFileEventArgs> Completed;
        #endregion

        #region Methods
        /// <summary>
        /// Optimizes Images from the settings SourceDirectory
        /// </summary>
        /// <param name="sourceDirectory">The directory of the original images.</param>
        /// <param name="outputDirectory">The directory of the optimized images.</param>
        /// <param name="settings">The settings to use when optimizing the images.</param>
        IList<OptimizedFile> Optimize(DirectoryPath sourceDirectory, DirectoryPath outputDirectory,ImageOptimizerSettings settings);

        /// <summary>
        /// Clears all local flags
        /// </summary>
        void Clear();
        #endregion
	}
}


text:
var loadrepeater = function ( ed ) {
		//console.log(ed.startContent);

    if(ed.editorId != "content"){

		ed.editorDomLocation = "#wp-"+ed.editorId+"-wrap";
		ed.characterLimit = jQuery(ed.editorDomLocation).next(".progressBar").data('characterlimit');

	    if(ed.characterLimit != ""){
			cnt_cur = ed.startContent.replace(/<\/?[^>]+(>|$)/g,"").replace(/ /gi,"");

		    //alert(jQuery(ed.editorDomLocation).next(".progressBar").data('characterlimit'));

		    percentage = Math.floor((cnt_cur.length / ed.characterLimit)*100);
		    //alert(percentage);
			progressBar = jQuery(ed.editorDomLocation).next(".progressBar");

		    jQuery( progressBar ).progressbar({
		      value: percentage
		    });

		    jQuery(ed.editorDomLocation).next().next(".progressText").html( cnt_cur.length + " out of " + ed.characterLimit);

	    }

	}

}

var repeater = function ( e,ed ) {
	if(ed.characterLimit != ""){

		//console.log(e);
		console.log(ed);

	    var targetId = e.target.id;
	    var text = '';

		switch ( targetId ) {

			case 'content':
				text = jQuery('#content').val();
				break;

			case 'tinymce':
				if ( tinymce.activeEditor )
					text = tinymce.activeEditor.getContent();
				break;
		}

		//console.log(text.length);

		cnt_cur = text.replace(/<\/?[^>]+(>|$)/g,"").replace(/ /gi,"");

		//console.log(cnt_cur.length);
		//alert(targetId);
	    if(ed.editorId != "content"){

	    	if(e.type == 'keydown'){
			//}
			//alert(browserIsIE);

			//alert(text);
				if(cnt_cur.length <= ed.characterLimit){
					ed.TESTval = text;
				}
			}else{

				if(text != ed.TESTval){
					if(cnt_cur.length > ed.characterLimit){
						var bookmark = ed.selection.getBookmark(2, true);
						ed.setContent(ed.TESTval);
						ed.selection.moveToBookmark(bookmark);

					}
				}
			}
		}

	    percentage = Math.floor((cnt_cur.length / ed.characterLimit)*100);
		    //alert(percentage);
			progressBar = jQuery(ed.editorDomLocation).next(".progressBar");

		    jQuery( progressBar ).progressbar({
		      value: percentage
		    });

	    jQuery(ed.editorDomLocation).next().next(".progressText").html( cnt_cur.length + " out of " + ed.characterLimit);

    }
}


text:
from distutils.core import setup

for cmd in ('egg_info', 'develop'):
    import sys
    if cmd in sys.argv:
        from setuptools import setup

setup(
    name='django-qsstats-magic',
    version='1.1.0',
    description='A django microframework that eases the generation of aggregate data for querysets.',
    long_description = open('README.rst').read(),
    author='Matt Croydon, Mikhail Korobov',
    author_email='mcroydon@gmail.com, kmike84@gmail.com',
    url='https://github.com/PetrDlouhy/django-qsstats-magic',
    packages=['qsstats'],
    requires=['dateutil(>=1.4.1, < 2.0)', 'six'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)


text:
package org.eclipse.cft.server.standalone.internal.application;

import java.util.Set;

import org.eclipse.cft.server.core.internal.CloudFoundryPlugin;
import org.eclipse.cft.server.core.internal.CloudFoundryProjectUtil;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.wst.common.project.facet.core.IFacetedProject;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;
import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager;
import org.eclipse.wst.server.core.IModule;
import org.eclipse.wst.server.core.model.ModuleDelegate;
import org.eclipse.wst.server.core.util.ProjectModuleFactoryDelegate;
import org.osgi.framework.Bundle;

/**
 * Required factory to support Java applications in the Eclipse WST-based Cloud
 * Foundry server, including Spring boot applications.
 *
 */
public class StandAloneModuleFactory extends ProjectModuleFactoryDelegate {

	@Override
	public ModuleDelegate getModuleDelegate(IModule module) {
		return new JavaLauncherModuleDelegate(module.getProject());
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.wst.server.core.util.ProjectModuleFactoryDelegate#createModules
	 * (org.eclipse.core.resources.IProject)
	 */
	public IModule[] createModules(IProject project) {
		if (canCreateModule(project)) {
			IModule module = createModule(project.getName(), project.getName(),
					StandaloneFacetHandler.ID_MODULE_STANDALONE,
					StandaloneFacetHandler.ID_JAVA_STANDALONE_APP_VERSION,
					project);
			if (module != null) {
				return new IModule[] { module };
			}
		}
		// Return null if a module was not created. Returning an empty module
		// list will cache the empty list in WTP
		// preventing a new module from being created if the project state
		// changes in the future
		return null;
	}

	protected boolean canCreateModule(IProject project) {
		// Check if it is a Java project that isn't already supported by another
		// framework (Spring, Grails, etc..), as those
		// modules are created separately.
		return canHandle(project);
	}

	public static boolean canHandle(IProject project) {
		if (!CloudFoundryProjectUtil.hasNature(project, JavaCore.NATURE_ID)) {
			return false;
		}

		StandaloneFacetHandler handler = new StandaloneFacetHandler(project);

		// If it is Spring boot, and it doesn't have the facet, add it to avoid
		// having users manually add the facet. Auto-configuration of Spring
		// Boot is only
		// enabled if Spring IDE is installed and also if project has no other
		// facets as to avoid
		// corrupting the project and making it undeployable in other WST server
		// types that do not
		// support the Cloud Foundry facet.
		if (isSpringIDEInstalled() && hasNoFacets(project)
				&& CloudFoundryProjectUtil.isSpringBoot(project)) {

			handler.addFacet(new NullProgressMonitor());
		}

		return handler.hasFacet();
	}

	/**
	 * @return true if and only if it is possible to determine that the project
	 *         has no facets. False otherwise
	 */
	private static boolean hasNoFacets(IProject project) {
		// As adding facets can corrupt projects that are deployable to other
		// WST server instances, if facets
		// cannot be resolved, assume the project has facets.
		boolean hasNoFacets = false;
		try {
			IFacetedProject facetedProject = ProjectFacetsManager
					.create(project);
			if (facetedProject != null) {
				Set<IProjectFacetVersion> facets = facetedProject
						.getProjectFacets();
				hasNoFacets = facets == null || facets.isEmpty();
			} else {
				hasNoFacets = true;
			}
		} catch (CoreException e) {
			CloudFoundryPlugin.logError(e);
		}
		return hasNoFacets;
	}

	private static boolean isSpringIDEInstalled() {
		Bundle bundle = null;
		try {
			bundle = Platform.getBundle("org.springframework.ide.eclipse.core"); //$NON-NLS-1$
		} catch (Throwable e) {
			// Ignore. if it can't be resolved, assume not installed to avoid
			// errors in non-STS environments
		}

		return bundle != null;
	}
}