text:
"""
Copyright 2017-present, Airbnb Inc.

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.
"""
import json
import uuid

from botocore.exceptions import ClientError

class AthenaQueryExecutionError(Exception):
    """Exception to be raised when an Athena query fails"""

# FIXME (ryxias)
#   At some point we should DRY out the implementation of this API client with the one in
#   streamalert/shared/athena.py
class AthenaClient:
    """A StreamAlert Athena Client for creating tables, databases, and executing queries"""

    def __init__(self, logger=None, client=None, database=None, results_bucket=None):
        """Initialize the Boto3 Athena Client, and S3 results bucket/key"""
        self._logger = logger
        self._client = client
        self._database = database
        self._s3_results_bucket = results_bucket

    def _execute_query(self, query, options):
        """Execute an Athena query on the current database. This operation is non-blocking

        See:
            https://docs.aws.amazon.com/cli/latest/reference/athena/start-query-execution.html

        Args:
            query (str): SQL query to execute
            options (dict): Configuration options

                - database (str): The Athena database to connect to.

        Returns:
            str: Athena execution ID for the query that was started

        Raises:
            AthenaQueryExecutionError: If any failure occurs during the execution of the
                query, this exception will be raised
        """
        self._logger.debug('Executing query: %s', query)
        try:
            output_location = 's3://{bucket}/{key}.csv'.format(
                bucket=self._s3_results_bucket,
                key=uuid.uuid4()
            )
            result = self._client.start_query_execution(
                QueryString=query,
                QueryExecutionContext={'Database': options.get('database', self._database)},
                ResultConfiguration={'OutputLocation': output_location}
            )
            query_execution_id = result['QueryExecutionId']
            self._logger.debug('Query dispatched. ID returned: %s', query_execution_id)

            return query_execution_id
        except ClientError as err:
            raise AthenaQueryExecutionError('Athena query failed:\n{}'.format(err))

    def get_query_execution(self, query_execution_id):
        """Gets an AthenaQueryExecution object encapsulating the result of a query

        Check the result.is_still_running() and result.is_succeeded() for the statuses
        of the queries.

        Args:
            query_execution_id (str): The Athena-returned query execution id

        Returns:
            AthenaQueryExecution
        """
        return AthenaQueryExecution(self._client.get_query_execution(
            QueryExecutionId=query_execution_id
        ))

    def get_query_result(self, query_execution):
        """Returns a query result payload, wrapped in a AthenaQueryResult object

        Args:
            query_execution (AthenaQueryExecution)

        Returns:
            AthenaQueryResult
            Returns None if the given query_execution is not completed
        """
        if not query_execution.is_succeeded():
            return None
        return AthenaQueryResult(
            query_execution,
            self._client.get_query_results(QueryExecutionId=query_execution.query_execution_id)
        )

    def run_async_query(self, query, options=None):
        """Run an Athena query in an asynchronous fashion. This operation is non-blocking

        Args:
            query (str): SQL query to execute
            options (dict): Configuration options

        Returns:
            str: Athena query execution ID

        Raises:
            AthenaQueryExecutionError: If any failure occurs during the execution of the
                query, this exception will be raised
        """
        if options is None:
            options = {}

        return self._execute_query(query, options)

class AthenaQueryExecution:
    """Encapsulation of a query execution response

    See:
        https://docs.aws.amazon.com/cli/latest/reference/athena/get-query-execution.html
    """

    def __init__(self, response):
        self._response = response

    @property
    def query_execution_id(self):
        return self._response['QueryExecution']['QueryExecutionId']

    @property
    def database(self):
        return self._response['QueryExecution']['QueryExecutionContext']['Database']

    @property
    def status(self):
        return self._response['QueryExecution']['Status']['State']

    @property
    def status_description(self):
        return self._response['QueryExecution']['Status'].get('StateChangeReason', None)

    @property
    def completion_datetime(self):
        return self._response['QueryExecution']['Status']['CompletionDateTime']

    @property
    def data_scanned_in_bytes(self):
        return self._response['QueryExecution']['Statistics']['DataScannedInBytes']

    @property
    def engine_execution_time_in_millis(self):
        return self._response['QueryExecution']['Statistics']['EngineExecutionTimeInMillis']

    @property
    def output_location(self):
        return self._response['QueryExecution']['ResultConfiguration']['OutputLocation']

    @property
    def query(self):
        return self._response['QueryExecution']['Query']

    def is_still_running(self):
        return self.status in {'QUEUED', 'RUNNING'}

    def is_succeeded(self):
        return self.status == 'SUCCEEDED'

class AthenaQueryResult:
    """Encapsulation of a query execution's result"""

    def __init__(self, query_execution, result):
        self._query_execution = query_execution
        self._result = result

    @property
    def query_execution(self):
        """
        Returns:
            AthenaQueryExecution
        """
        return self._query_execution

    @property
    def headers(self):
        """Returns the headers of the query result, as a list

        Returns:
            list
        """
        return self._raw_row_to_list(self.raw_rows[0])

    @property
    def data_as_list(self):
        """Returns the data of the query result, as a list of lists

        The result set is a list of rows, in the order they appear in the query result.
        Each row is a list of column values, in the order they appear from left-to-right. This
        should match the ordering in the "headers".

        Returns:
            list[list]
        """
        return [self._raw_row_to_list(row) for row in self.raw_rows[1:]]

    @property
    def data_as_dicts(self):
        """Returns the data of the query results as a list of dicts mapping headers to values

        An alternative to data_as_list. The returned result is a list of rows, but in this method
        the rows are dicts, mapping the headers (keys) to their respective values.

        This method results in a larger data set and is more CPU intensive but the returned data
        is easier to use.

        Returns:
            list[dict]
        """
        headers = self.headers

        data = []
        for row in self.data_as_list:
            dict_row = {}
            for index, header in enumerate(headers):
                dict_row[header] = row[index]
            data.append(dict_row)
        return data

    @property
    def data_as_human_string(self):
        return json.dumps(self.data_as_dicts, indent=2, separators=(',', ': '))

    @property
    def raw_rows(self):
        return self._result['ResultSet']['Rows']

    @property
    def count(self):
        """Returns the number of rows in the result set"""
        return len(self.raw_rows) - 1  # Remove 1 to account for the header, which is always around

    @staticmethod
    def _raw_row_to_list(row):
        # For empty cells, there is no VarCharValue key
        return [cell.get('VarCharValue', None) for cell in row['Data']]

redpajama_set_name: RedPajamaGithub


text:
import { findBestMatch } from "../lib/find-best-match";

import { createFakeCreditCardType } from "./helper";

describe("findBestMatch", () => {
  it("returns nothing if there are not enough results to try to match", () => {
    expect(findBestMatch([])).toBeNull();
  });

  it("returns nothing if not every element has a matchStrength property", () => {
    expect(
      findBestMatch([
        createFakeCreditCardType({ matchStrength: 4 }),
        createFakeCreditCardType({}),
        createFakeCreditCardType({ matchStrength: 5 }),
      ])
    ).toBeNull();
  });

  it("returns the result with the greatest matchStrength value", () => {
    const a = createFakeCreditCardType({ matchStrength: 4 });
    const b = createFakeCreditCardType({ matchStrength: 1 });
    const c = createFakeCreditCardType({ matchStrength: 40 });
    const d = createFakeCreditCardType({ matchStrength: 7 });
    const results = [a, b, c, d];

    expect(findBestMatch(results)).toBe(c);
  });
});


text:
@implementation DKFancyDividerView

- (void)drawRect:(NSRect)dirtyRect
{
    // Drawing code here.
    CGFloat scale = self.window == nil ? 1.0 : self.window.backingScaleFactor;
    CGFloat lineHeight = 1.0 / scale;

    [[NSColor colorWithRed:0.784 green:0.780 blue:0.800 alpha:1.0] set];

    NSBezierPath *path = [NSBezierPath new];
    path.lineWidth = lineHeight;
    [path moveToPoint:NSMakePoint(NSMinX(self.bounds), NSMaxY(self.bounds) - 0.5)];
    [path lineToPoint:NSMakePoint(NSMaxX(self.bounds), NSMaxY(self.bounds) - 0.5)];
    [path stroke];
}

@end


text:
require_relative "../actions/delete_profile"

module AwsAssumeRole::Cli
    desc t "commands.delete.desc"
    command :delete do |c|
        c.flag [:p, "profile"], desc: t("options.profile_name")
        c.action do |global_options, options, args|
            AwsAssumeRole::Cli::Actions::DeleteProfile.new(global_options, options, args)
        end
    end
end


text:
package com.intellij.codeInsight.daemon.impl.quickfix;

import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.CodeInsightUtilCore;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author cdr
 */
public class CreateCastExpressionFromInstanceofAction extends CreateLocalVarFromInstanceofAction {
  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    boolean available = super.isAvailable(project, editor, file);
    if (!available) return false;
    PsiInstanceOfExpression instanceOfExpression = getInstanceOfExpressionAtCaret(editor, file);
    if (instanceOfExpression == null) return false;
    PsiTypeElement checkType = instanceOfExpression.getCheckType();
    if (checkType == null) return false;
    PsiType type = checkType.getType();
    String castTo = type.getPresentableText();
    setText(CodeInsightBundle.message("cast.to.0", castTo));
    return true;
  }

  @Override
  public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) {
    PsiInstanceOfExpression instanceOfExpression = getInstanceOfExpressionAtCaret(editor, file);
    assert instanceOfExpression.getContainingFile() == file : instanceOfExpression.getContainingFile() + "; file="+file;
    PsiElement decl = createAndInsertCast(instanceOfExpression, editor, file);
    if (decl == null) return;
    decl = CodeStyleManager.getInstance(project).reformat(CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(decl));
    editor.getCaretModel().moveToOffset(decl.getTextRange().getEndOffset());
  }

  @Nullable
  private static PsiElement createAndInsertCast(final PsiInstanceOfExpression instanceOfExpression, Editor editor, PsiFile file) throws IncorrectOperationException {
    PsiElementFactory factory = JavaPsiFacade.getInstance(instanceOfExpression.getProject()).getElementFactory();
    PsiExpressionStatement statement = (PsiExpressionStatement)factory.createStatementFromText("((a)b)", instanceOfExpression);

    PsiParenthesizedExpression paren = (PsiParenthesizedExpression)statement.getExpression();
    PsiTypeCastExpression cast = (PsiTypeCastExpression)paren.getExpression();
    PsiType castType = instanceOfExpression.getCheckType().getType();
    cast.getCastType().replace(factory.createTypeElement(castType));
    cast.getOperand().replace(instanceOfExpression.getOperand());

    final PsiStatement statementInside = isNegated(instanceOfExpression) ? null : getExpressionStatementInside(file, editor, instanceOfExpression.getOperand());
    if (statementInside != null) {
      return statementInside.replace(statement);
    }
    else {
      return insertAtAnchor(instanceOfExpression, statement);
    }
  }

  @Override
  @NotNull
  public String getFamilyName() {
    return CodeInsightBundle.message("cast.expression");
  }
}


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('d3-call', 'Integration | Helper | d3-call', {
  integration: true
});

test('executes callback without changing piped value', function(assert) {

  this.set('data', ['car', 'car', 'boat', 'boat']);

  this.render(hbs`
    {{d3-graph (pipe
      (d3-call (pipe
        (d3-select-all "i")
        (d3-data data)
        (d3-join enter=(pipe
          (d3-append "i")
          (d3-attr "class" (r/param))
        ))
      ))
      (d3-call (pipe
        (d3-select-all ".car")
        (d3-attr "color" "red")
      ))
      (d3-call (pipe
        (d3-select-all ".boat")
        (d3-attr "color" "blue")
      ))
      (d3-append 'i')
      (d3-attr "class" "truck")
    )}}
  `);

  assert.equal(this.$('.car[color=red]').length, 2, "color red was applied to cars");
  assert.equal(this.$('.boat[color=blue]').length, 2, "color blue was applied to boats");
  assert.equal(this.$('g > .truck').length, 1, "truck was added directly to the test-items container");

});


text:
      Date
      # of Feedings
      Average
      Total
      Diaper Count
      Nursing (min)

      {{day.date}}
      {{day.numberOfFeedings}}
      {{day.milkVolumeAverageMilliliters}}ml / {{day.milkVolumeAverageOunces}}oz
      {{day.milkVolumeTotalMilliliters}}ml / {{day.milkVolumeTotalOunces}}oz
      {{day.diaperCount}}
      {{day.nursingDurationMinutes}}


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// 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.

package com.google.devtools.build.lib.analysis;

import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.packages.PackageGroup;
import com.google.devtools.build.lib.packages.PackageSpecification;
import com.google.devtools.build.lib.packages.SkylarkClassObject;
import com.google.devtools.build.lib.packages.SkylarkClassObjectConstructor.Key;
import com.google.devtools.build.lib.util.Preconditions;
import javax.annotation.Nullable;

/**
 * Dummy ConfiguredTarget for package groups. Contains no functionality, since
 * package groups are not really first-class Targets.
 */
public final class PackageGroupConfiguredTarget extends AbstractConfiguredTarget
    implements PackageSpecificationProvider {
  private final NestedSet<PackageSpecification> packageSpecifications;

  PackageGroupConfiguredTarget(TargetContext targetContext, PackageGroup packageGroup) {
    super(targetContext);
    Preconditions.checkArgument(targetContext.getConfiguration() == null);

    NestedSetBuilder<PackageSpecification> builder =
        NestedSetBuilder.stableOrder();
    for (Label label : packageGroup.getIncludes()) {
      TransitiveInfoCollection include = targetContext.maybeFindDirectPrerequisite(
          label, targetContext.getConfiguration());
      PackageSpecificationProvider provider = include == null ? null :
          include.getProvider(PackageSpecificationProvider.class);
      if (provider == null) {
        targetContext.getAnalysisEnvironment().getEventHandler().handle(Event.error(getTarget().getLocation(),
            String.format("label '%s' does not refer to a package group", label)));
        continue;
      }

      builder.addTransitive(provider.getPackageSpecifications());
    }

    builder.addAll(packageGroup.getPackageSpecifications());
    packageSpecifications = builder.build();
  }

  @Override
  public PackageGroup getTarget() {
    return (PackageGroup) super.getTarget();
  }

  @Override
  public NestedSet<PackageSpecification> getPackageSpecifications() {
    return packageSpecifications;
  }

  @Override
  public Object get(String providerKey) {
    // No providers.
    return null;
  }

  @Nullable
  @Override
  public SkylarkClassObject get(Key providerKey) {
    // No providers.
    return null;
  }
}


text:
/**
 * Test running the 'captrunc' command on various kinds of collections:
 *   - indexed capped collections
 *   - nonexistent collections
 *   - non-capped collections
 *
 * This test fails with the ephemeralForTest storage engine.
 * @tags: [SERVER-21658]
 */
(function() {
    'use strict';

    db.capped_truncate.drop();
    assert.commandWorked(
        db.runCommand({create: "capped_truncate", capped: true, size: 1000, autoIndexId: true}));
    var t = db.capped_truncate;

    // It is an error to remove a non-positive number of documents.
    assert.commandFailed(db.runCommand({captrunc: "capped_truncate", n: -1}),
                         "captrunc didn't return an error when attempting to remove a negative " +
                             "number of documents");
    assert.commandFailed(db.runCommand({captrunc: "capped_truncate", n: 0}),
                         "captrunc didn't return an error when attempting to remove 0 documents");

    for (var j = 1; j <= 10; j++) {
        assert.writeOK(t.insert({x: j}));
    }

    // It is an error to try and remove more documents than what exist in the capped collection.
    assert.commandFailed(db.runCommand({captrunc: "capped_truncate", n: 20}),
                         "captrunc didn't return an error when attempting to remove more" +
                             " documents than what the collection contains");

    assert.commandWorked(db.runCommand({captrunc: "capped_truncate", n: 5, inc: false}));
    assert.eq(5, t.count(), "wrong number of documents in capped collection after truncate");
    assert.eq(5, t.distinct("_id").length, "wrong number of entries in _id index after truncate");

    var last = t.find({}, {_id: 1}).sort({_id: -1}).next();
    assert.neq(null,
               t.findOne({_id: last._id}),
               tojson(last) + " is in _id index, but not in capped collection after truncate");

    // It is an error to run the captrunc command on a nonexistent collection.
    assert.commandFailed(db.runCommand({captrunc: "nonexistent", n: 1}),
                         "captrunc didn't return an error for a nonexistent collection");

    // It is an error to run the captrunc command on a non-capped collection.
    var collName = "noncapped";
    db[collName].drop();

    assert.commandWorked(db.runCommand({create: collName, capped: false}));
    for (var j = 1; j <= 10; j++) {
        assert.writeOK(db[collName].insert({x: j}));
    }
    assert.commandFailed(db.runCommand({captrunc: collName, n: 5}),
                         "captrunc didn't return an error for a non-capped collection");
})();


text:
using System;
using System.IO;
using System.Text;

namespace acPlugins4net.helpers
{
    public class FileLogWriter : IFileLog
    {
        public static string GetExceptionString(Exception ex)
        {
            StringBuilder sb = new StringBuilder();

            while (ex != null)
            {
                sb.Append("[");
                sb.Append(ex.GetType());
                sb.Append(": ");
                sb.Append(ex.Message);
                sb.Append("]");
                sb.AppendLine();
                sb.Append(ex.StackTrace);
                sb.AppendLine();

                ex = ex.InnerException;
            }
            sb.AppendLine();

            return sb.ToString();
        }

        private readonly object lockObject = new object();

        private readonly string defaultLogDirectory;
        private StreamWriter log;
        private string currentFile;

        /// <summary>
        /// Let's you paste every line into the Console as well
        /// </summary>
        public bool CopyToConsole { get; set; } = false;

        /// <summary>
        /// Toggles logging with a Timestamp (no date)
        /// </summary>
        public bool LogWithTimestamp { get; set; } = false;

        public string CurrentLogFile
        {
            get { return currentFile; }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="FileLogWriter"/> class.
        /// </summary>
        /// <param name="defaultLogDirectory">If not null and the filePaths are relative the log files will be created relative to this directory</param>
        /// <param name="filePath">The file path. Can be relative or absolute. If null, StartLoggingToFile needs to be called before any logging takes place.</param>
        public FileLogWriter(string defaultLogDirectory = null, string filePath = null)
        {
            this.defaultLogDirectory = defaultLogDirectory;
            this.SetCurrentFile(filePath);
        }

        private void SetCurrentFile(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                this.currentFile = null;
            }
            else
            {
                if (Path.IsPathRooted(filePath))
                {
                    this.currentFile = filePath;
                }
                else if (string.IsNullOrEmpty(defaultLogDirectory))
                {
                    this.currentFile = Path.GetFullPath(filePath);
                }
                else
                {
                    this.currentFile = Path.Combine(defaultLogDirectory, filePath);
                }
            }
        }

        public virtual void StartLoggingToFile(string filePath)
        {
            lock (lockObject)
            {
                this.StopLoggingToFile();
                this.SetCurrentFile(filePath);
            }
        }

        public virtual void StopLoggingToFile()
        {
            lock (lockObject)
            {
                if (this.log != null)
                {
                    this.log.Close();
                    this.log.Dispose();
                    this.log = null;
                    this.currentFile = null;
                }
            }
        }

        public virtual void Log(string message)
        {
            this.LogMessageToFile(message);
        }

        public virtual void Log(Exception ex)
        {
            this.LogMessageToFile(GetExceptionString(ex));
        }

        protected void LogMessageToFile(string message)
        {
            lock (lockObject)
            {
                if (currentFile != null && this.log == null)
                {
                    try
                    {
                        string directory = Path.GetDirectoryName(currentFile);
                        if (!Directory.Exists(directory))
                        {
                            Directory.CreateDirectory(directory);
                        }

                        this.log = new StreamWriter(currentFile);
                        this.log.AutoFlush = true;
                    }
                    catch (Exception ex)
                    {
                        currentFile = null;
                        Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
                    }
                }
                if (this.log != null)
                {
                    if(LogWithTimestamp)
                        this.log.WriteLine(string.Format("{0} {1}", DateTime.Now.ToString("HH:mm:ss.ffffff"), message));
                    else
                        this.log.WriteLine(message);
                }
                if (CopyToConsole)
                {
                    Console.WriteLine(message);
                }
            }
        }
    }
}


text:
package org.drools.core.factmodel.traits;

public enum TraitTypeEnum {

    TRAIT,                      // trait proxy
    TRAITABLE,                  // native traitable bean
    LEGACY_TRAITABLE,           // legacy class marked as traitable, bean not yet traited (needs wrapping/injection to provide data structures
    NON_TRAIT                   // not marked as trait/traitable

}


text:
 # -*- coding: utf-8 -*-

# daemon/pidlockfile.py
# Part of python-daemon, an implementation of PEP 3143.
#
# Copyright © 2008–2010 Ben Finney <ben+python@benfinney.id.au>
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Python Software Foundation License, version 2 or
# later as published by the Python Software Foundation.
# No warranty expressed or implied. See the file LICENSE.PSF-2 for details.

""" Lockfile behaviour implemented via Unix PID files.
    """

import os
import errno

from lockfile import (
    LinkFileLock,
    AlreadyLocked, LockFailed,
    NotLocked, NotMyLock,
    )

class PIDFileError(Exception):
    """ Abstract base class for errors specific to PID files. """

class PIDFileParseError(ValueError, PIDFileError):
    """ Raised when parsing contents of PID file fails. """

class PIDLockFile(LinkFileLock, object):
    """ Lockfile implemented as a Unix PID file.

        The PID file is named by the attribute `path`. When locked,
        the file will be created with a single line of text,
        containing the process ID (PID) of the process that acquired
        the lock.

        The lock is acquired and maintained as per `LinkFileLock`.

        """

    def read_pid(self):
        """ Get the PID from the lock file.
            """
        result = read_pid_from_pidfile(self.path)
        return result

    def acquire(self, *args, **kwargs):
        """ Acquire the lock.

            Locks the PID file then creates the PID file for this
            lock. The `timeout` parameter is used as for the
            `LinkFileLock` class.

            """
        super(PIDLockFile, self).acquire(*args, **kwargs)
        try:
            write_pid_to_pidfile(self.path)
        except OSError, exc:
            error = LockFailed("%(exc)s" % vars())
            raise error

    def release(self):
        """ Release the lock.

            Removes the PID file then releases the lock, or raises an
            error if the current process does not hold the lock.

            """
        if self.i_am_locking():
            remove_existing_pidfile(self.path)
        super(PIDLockFile, self).release()

    def break_lock(self):
        """ Break an existing lock.

            If the lock is held, breaks the lock and removes the PID
            file.

            """
        super(PIDLockFile, self).break_lock()
        remove_existing_pidfile(self.path)

class TimeoutPIDLockFile(PIDLockFile):
    """ Lockfile with default timeout, implemented as a Unix PID file.

        This uses the ``PIDLockFile`` implementation, with the
        following changes:

        * The `acquire_timeout` parameter to the initialiser will be
          used as the default `timeout` parameter for the `acquire`
          method.

        """

    def __init__(self, path, acquire_timeout=None, *args, **kwargs):
        """ Set up the parameters of a DaemonRunnerLock. """
        self.acquire_timeout = acquire_timeout
        super(TimeoutPIDLockFile, self).__init__(path, *args, **kwargs)

    def acquire(self, timeout=None, *args, **kwargs):
        """ Acquire the lock. """
        if timeout is None:
            timeout = self.acquire_timeout
        super(TimeoutPIDLockFile, self).acquire(timeout, *args, **kwargs)

def read_pid_from_pidfile(pidfile_path):
    """ Read the PID recorded in the named PID file.

        Read and return the numeric PID recorded as text in the named
        PID file. If the PID file does not exist, return ``None``. If
        the content is not a valid PID, raise ``PIDFileParseError``.

        """
    pid = None
    pidfile = None
    try:
        pidfile = open(pidfile_path, 'r')
    except IOError, exc:
        if exc.errno == errno.ENOENT:
            pass
        else:
            raise

    if pidfile:
        # According to the FHS 2.3 section on PID files in '/var/run':
        #
        #   The file must consist of the process identifier in
        #   ASCII-encoded decimal, followed by a newline character. …
        #
        #   Programs that read PID files should be somewhat flexible
        #   in what they accept; i.e., they should ignore extra
        #   whitespace, leading zeroes, absence of the trailing
        #   newline, or additional lines in the PID file.

        line = pidfile.readline().strip()
        try:
            pid = int(line)
        except ValueError:
            raise PIDFileParseError(
                "PID file %(pidfile_path)r contents invalid" % vars())
        pidfile.close()

    return pid

def write_pid_to_pidfile(pidfile_path):
    """ Write the PID in the named PID file.

        Get the numeric process ID ("PID") of the current process
        and write it to the named file as a line of text.

        """
    open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    open_mode = (
        ((os.R_OK | os.W_OK) << 6) |
        ((os.R_OK) << 3) |
        ((os.R_OK)))
    pidfile_fd = os.open(pidfile_path, open_flags, open_mode)
    pidfile = os.fdopen(pidfile_fd, 'w')

    # According to the FHS 2.3 section on PID files in '/var/run':
    #
    #   The file must consist of the process identifier in
    #   ASCII-encoded decimal, followed by a newline character. For
    #   example, if crond was process number 25, /var/run/crond.pid
    #   would contain three characters: two, five, and newline.

    pid = os.getpid()
    line = "%(pid)d\n" % vars()
    pidfile.write(line)
    pidfile.close()

def remove_existing_pidfile(pidfile_path):
    """ Remove the named PID file if it exists.

        Remove the named PID file. Ignore the condition if the file
        does not exist, since that only means we are already in the
        desired state.

        """
    try:
        os.remove(pidfile_path)
    except OSError, exc:
        if exc.errno == errno.ENOENT:
            pass
        else:
            raise


text:
---
layout: post
title: 出现次数最多的字符串
categories: ACM
tags: ACM
author: NoPerfectName
excerpt: 获得出现次数最多的字符串
---

* content
{:toc}

```java

/**
 * 问题来源:http://acm.hdu.edu.cn/showproblem.php?pid=1004
 */

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class BallonRise {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
            int ballons = scanner.nextInt();
            if (ballons == 0) break;

            int max = 0;
            String color = null;
            Map<String, Integer> map = new HashMap<>();
            while (ballons-- > 0) {
                String ballonColor = scanner.next();
                int num = map.getOrDefault(ballonColor, 0);
                num ++;
                if (num > max){
                    max = num;
                    color = ballonColor;
                }
                map.put(ballonColor, num);
            }
            System.out.println(color);
        }

    }
}

```


text:
<template name="splash">

Find the perfect daycare.

      <form>
        <input type="text" name="zipcode" placeholder="Enter your home address" />
        <input class="button text-center" type="submit" id="submit" />
      </form>

    {{> googleMap name="splashMap" options=customMap}}

</template>


text:
<?php
namespace Store;

require_once __DIR__.'/Product.php';

/**
 * Generated from NGS DSL
 *
 * Converts an object of class Store\Product into a simple array and backwards.
 *
 * @package Store
 * @version 0.9.9 beta
 */
abstract class ProductArrayConverter
{/**
     * @param array|\Store\Product An object or an array of objects of type "Store\Product"
     *
     * @return array A simple array representation
     */
    public static function toArray($item, $allowNullValues=false)
    {
        if ($item instanceof \Store\Product)
            return self::toArrayObject($item);
        if (is_array($item))
            return self::toArrayList($item, $allowNullValues);

        throw new \InvalidArgumentException('Argument was not an instance of class "Store\Product" nor an array of said instances!');
    }

    private static function toArrayObject($item)
    {
        $ret = array();
        $ret['URI'] = $item->URI;
        $ret['ID'] = $item->ID;
        $ret['name'] = $item->name;
        $ret['price'] = $item->price->__toString();
        return $ret;
    }

    private static function toArrayList(array $items, $allowNullValues=false)
    {
        $ret = array();

        foreach($items as $key => $val) {
            if ($allowNullValues && $val===null) {
                $ret[] = null;
            }
            else {
                if (!$val instanceof \Store\Product)
                    throw new \InvalidArgumentException('Element with index "'.$key.'" was not an object of class "Store\Product"! Type was: '.\NGS\Utils::getType($val));

                $ret[] = $val->toArray();
            }
        }

        return $ret;
    }

    public static function fromArray($item)
    {
        if ($item instanceof \Store\Product)
            return $item;
        if (is_array($item))
            return new \Store\Product($item, 'build_internal');

        throw new \InvalidArgumentException('Argument was not an instance of class "Store\Product" nor an array of said instances!');
    }

    public static function fromArrayList(array $items, $allowNullValues=false)
    {
        try {
            foreach($items as $key => &$val) {
                if($allowNullValues && $val===null)
                    continue;
                if($val === null)
                    throw new \InvalidArgumentException('Null value found in provided array');
                if(!$val instanceof \Store\Product)
                    $val = new \Store\Product($val, 'build_internal');
            }
        }
        catch (\Exception $e) {
            throw new \InvalidArgumentException('Element at index '.$key.' could not be converted to object "Store\Product"!', 42, $e);
        }

        return $items;
    }
}


text:
#pragma checksum "C:\Users\d.delaire\Documents\GitHub\CustomRateMyApp-Universal\CustomRateMyApp-Demo\CustomRateMyAppLib\RateUserControl.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "4BE7649F600575952C4142B4DE51BA86"
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace CustomRateMyAppLib
{
    partial class RateUserControl : global::Windows.UI.Xaml.Controls.UserControl, global::Windows.UI.Xaml.Markup.IComponentConnector
    {
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]

        public void Connect(int connectionId, object target)
        {
            switch(connectionId)
            {
            case 1:
                #line 38 "..\..\RateUserControl.xaml"
                ((global::Windows.UI.Xaml.UIElement)(target)).Tapped += this.tbDoNotAsk_Tapped;
                 #line default
                 #line hidden
                break;
            case 2:
                #line 45 "..\..\RateUserControl.xaml"
                ((global::Windows.UI.Xaml.UIElement)(target)).Tapped += this.tbLater_Tapped;
                 #line default
                 #line hidden
                break;
            case 3:
                #line 24 "..\..\RateUserControl.xaml"
                ((global::Windows.UI.Xaml.UIElement)(target)).Tapped += this.grRating_Tapped;
                 #line default
                 #line hidden
                break;
            }
            this._contentLoaded = true;
        }
    }
}


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

  <title>Description of rdivide</title>
  <meta name="keywords" content="rdivide">
  <meta name="description" content="C = A./B">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html v1.5 © 2003-2005 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../../m2html.css">

Home >  tt2 > @tt_tensor > rdivide.m

rdivide

PURPOSE

C = A./B

SYNOPSIS

function [c] = rdivide(a,b)

DESCRIPTION

 C = A./B
[C]=RDIVIDE(A,B) Divides TT-tensor by a complex/double number

 TT-Toolbox 2.2, 2009-2012

This is TT Toolbox, written by Ivan Oseledets et al.
Institute of Numerical Mathematics, Moscow, Russia
webpage: http://spring.inm.ras.ru/osel

For all questions, bugs and suggestions please mail
ivan.oseledets@gmail.com
---------------------------

CROSS-REFERENCE INFORMATION

This function calls:

This function is called by:

SOURCE CODE

0001 function [c] = rdivide(a,b)
0002 % C = A./B
0003 %[C]=RDIVIDE(A,B) Divides TT-tensor by a complex/double number
0004 %
0005 %
0006 % TT-Toolbox 2.2, 2009-2012
0007 %
0008 %This is TT Toolbox, written by Ivan Oseledets et al.
0009 %Institute of Numerical Mathematics, Moscow, Russia
0010 %webpage: http://spring.inm.ras.ru/osel
0011 %
0012 %For all questions, bugs and suggestions please mail
0013 %ivan.oseledets@gmail.com
0014 %---------------------------
0015
0016 if isa(a,'tt_tensor') && numel(b) == 1
0017 c=a*(1.0./b);
0018 else
0019     error('Use rdivide(full(A),full(B)).');
0020 end

<address>Generated on Wed 08-Feb-2012 18:20:24 by m2html © 2005</address>


text:
// This code is auto-generated, do not modify
package com.spectralogic.ds3client.commands.spectrads3;

import com.spectralogic.ds3client.models.DataPolicyList;
import com.spectralogic.ds3client.models.ChecksumType;
import com.spectralogic.ds3client.commands.interfaces.AbstractResponse;

public class GetDs3TargetDataPoliciesSpectraS3Response extends AbstractResponse {

    private final DataPolicyList dataPolicyListResult;

    public GetDs3TargetDataPoliciesSpectraS3Response(final DataPolicyList dataPolicyListResult, final String checksum, final ChecksumType.Type checksumType) {
        super(checksum, checksumType);
        this.dataPolicyListResult = dataPolicyListResult;
    }

    public DataPolicyList getDataPolicyListResult() {
        return this.dataPolicyListResult;
    }

}


text:
@compat function (meshtype::Type{T}){T <: AbstractMesh}(c::Pyramid)
    T(decompose(vertextype(T), c), decompose(facetype(T), c))
end

"""
Standard way of creating a mesh from a primitive.
Just walk through all attributes of the mesh and try to decompose it.
If there are attributes missing, just hope it will get managed by the mesh constructor.
(E.g. normal calculation, which needs to have vertices and faces present)
"""
@compat function (meshtype::Type{T}){T <: AbstractMesh}(c::GeometryPrimitive, args...)
    attribs = attributes(T)
    newattribs = Dict{Symbol, Any}()
    for (fieldname, typ) in attribs
        if isdecomposable(eltype(typ), c)
            newattribs[fieldname] = decompose(eltype(typ), c, args...)
        end
    end
    T(homogenousmesh(newattribs))
end

@compat function (meshtype::Type{T}){T <: HMesh,HT}(
        c::Union{HyperCube{3,T}, HyperRectangle{3,HT}}

)    xdir = Vec{3, HT}(widths(c)[1],0f0,0f0)
    ydir = Vec{3, HT}(0f0,widths(c)[2],0f0)
    zdir = Vec{3, HT}(0f0,0f0,widths(c)[3])
    quads = [
        Quad(origin(c) + zdir,   xdir, ydir), # Top
        Quad(origin(c),          ydir, xdir), # Bottom
        Quad(origin(c) + xdir,   ydir, zdir), # Right
        Quad(origin(c),          zdir, ydir), # Left
        Quad(origin(c),          xdir, zdir), # Back
        Quad(origin(c) + ydir,   zdir, xdir) #Front
    ]
    merge(map(meshtype, quads))
end


text:
package org.apache.nifi.attribute.expression.language.evaluation;

import org.apache.nifi.expression.AttributeExpression.ResultType;

public class StringQueryResult implements QueryResult<String> {

    private final String value;

    public StringQueryResult(final String value) {
        this.value = value;
    }

    @Override
    public String getValue() {
        return value;
    }

    @Override
    public ResultType getResultType() {
        return ResultType.STRING;
    }

    @Override
    public String toString() {
        return String.valueOf(getValue());
    }
}


text:
class Pixel {

public:
	void setup (int id, int modx, int mody, int refx, int refy);
	void update ();
	void draw ();
    void clear();

//    void process(ofPixels& data, ofPixels ref);
    void buildCorrespTable(int* correspTable, int dataPt, int width, int height);
//    void buildCorrespTable(int* correspTable, int inW, int inH, int outW, int outH, int x, int y);
//    void buildCorrespTable(int* correspTable, int inW, int inH, int outW, int outH, int & dataPt);
private:
    int idPxl;
    int posX;
    int posY;
    int refX;
    int refY;
};


text:
import logging
import os
import subprocess
import csv
import sys
import ConfigParser

class Util(object):

	@classmethod
	def get_logger(cls,logger_name,create_file=False):

		# create logger for prd_ci
		log = logging.getLogger(logger_name)
		log.setLevel(level=logging.INFO)

		# create formatter and add it to the handlers
		formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

		if create_file:
				# create file handler for logger.
				fh = logging.FileHandler('oa.log')
				fh.setLevel(level=logging.DEBUG)
				fh.setFormatter(formatter)
		# reate console handler for logger.
		ch = logging.StreamHandler()
		ch.setLevel(level=logging.DEBUG)
		ch.setFormatter(formatter)

		# add handlers to logger.
		if create_file:
			log.addHandler(fh)

		log.addHandler(ch)
		return  log

	@classmethod
	def get_spot_conf(cls):

		conf_file = "/etc/spot.conf"
		config = ConfigParser.ConfigParser()
		config.readfp(SecHead(open(conf_file)))

		return config

	@classmethod
	def create_oa_folders(cls,type,date):

		# create date and ingest summary folder structure if they don't' exist.
		root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
		data_type_folder = "{0}/data/{1}/{2}"
		if not os.path.isdir(data_type_folder.format(root_path,type,date)): os.makedirs(data_type_folder.format(root_path,type,date))
		if not os.path.isdir(data_type_folder.format(root_path,type,"ingest_summary")): os.makedirs(data_type_folder.format(root_path,type,"ingest_summary"))

		# create ipynb folders.
		ipynb_folder = "{0}/ipynb/{1}/{2}".format(root_path,type,date)
		if not os.path.isdir(ipynb_folder): os.makedirs(ipynb_folder)

		# retun path to folders.
		data_path = data_type_folder.format(root_path,type,date)
		ingest_path = data_type_folder.format(root_path,type,"ingest_summary")
		return data_path,ingest_path,ipynb_folder

	@classmethod
	def get_ml_results_form_hdfs(cls,hdfs_file_path,local_path):

		# get results from hdfs.
		get_results_cmd = "hadoop fs -get {0} {1}/.".format(hdfs_file_path,local_path)
		subprocess.call(get_results_cmd,shell=True)
		return get_results_cmd

	@classmethod
	def read_results(cls,file,limit, delimiter=','):

		# read csv results.
		result_rows = []
		with open(file, 'rb') as results_file:
			csv_reader = csv.reader(results_file, delimiter = delimiter)
			for i in range(0, int(limit)):
				try:
					row = csv_reader.next()
				except StopIteration:
					return result_rows
				result_rows.append(row)
		return result_rows

	@classmethod
	def ip_to_int(self,ip):

		try:
			o = map(int, ip.split('.'))
			res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
			return res

		except ValueError:
			return None

	@classmethod
	def create_csv_file(cls,full_path_file,content,delimiter=','):
		with open(full_path_file, 'w+') as u_file:
			writer = csv.writer(u_file, quoting=csv.QUOTE_NONE, delimiter=delimiter)
			writer.writerows(content)

	@classmethod
    	def cast_val(self,value):
       	    try:
            	val = int(value)
            except:
            	try:
                    val = float(value)
            	except:
                    val = str(value)
            return val

class SecHead(object):
    def __init__(self, fp):
        self.fp = fp
        self.sechead = '[conf]\n'

    def readline(self):
        if self.sechead:
            try:
                return self.sechead
            finally:
                self.sechead = None
        else:
            return self.fp.readline()

class ProgressBar(object):

	def __init__(self,total,prefix='',sufix='',decimals=2,barlength=60):

		self._total = total
		self._prefix = prefix
		self._sufix = sufix
		self._decimals = decimals
		self._bar_length = barlength
		self._auto_iteration_status = 0

	def start(self):

		self._move_progress_bar(0)

	def update(self,iterator):

		self._move_progress_bar(iterator)

	def auto_update(self):

		self._auto_iteration_status += 1
		self._move_progress_bar(self._auto_iteration_status)

	def _move_progress_bar(self,iteration):

		filledLength    = int(round(self._bar_length * iteration / float(self._total)))
		percents        = round(100.00 * (iteration / float(self._total)), self._decimals)
		bar             = '#' * filledLength + '-' * (self._bar_length - filledLength)
		sys.stdout.write("{0} [{1}] {2}% {3}\r".format(self._prefix, bar, percents, self._sufix))
		sys.stdout.flush()

		if iteration == self._total:print("\n")


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using ProjectHekate.Core;
using ProjectHekate.GUI.DrawingHelpers;
using ProjectHekate.GUI.Interfaces;
using ProjectHekate.Scripting;
using SFML.Graphics;
using SFML.Window;
using Math = ProjectHekate.Core.Helpers.Math;

namespace ProjectHekate.GUI.Screens
{
    class Player
    {
        public float X { get; set; }
        public float Y { get; set; }

        public void SetPosition(float x, float y)
        {
            X = x;
            Y = y;

            if (Controller != null)
            {
                Controller.X = x;
                Controller.Y = y;
            }
        }

        public IController Controller { get; set; }
    }

    class TestScreen : GameScreen
    {
        private Random _random;
        private IEngine _engine;
        private Player _player = new Player();
        private Sprite _playerSprite;
        private List<Sprite> _bulletSprites = new List<Sprite>();
        private Font _textFont = new Font(@"Resources/Fonts/arial.ttf");
        private VertexArray _vertexArray = new VertexArray(PrimitiveType.TrianglesStrip);

        public TestScreen()
        {
            _random = new Random();

            ReloadScript();

            //_engine.CreateScriptedController(512, 120, Math.PiOver2, true, ScriptedController1)
            //    .Build();
        }

        private void ReloadScript()
        {
            var scriptBody = File.ReadAllText(@"Resources\Scripts\sample_bullet.txt");

            _engine = new Engine();

            _engine.VirtualMachine.AddType<Bullet>("bullet");
            _engine.VirtualMachine.AddProperty<Bullet, float>("bullet", b => b.Speed);
            _engine.VirtualMachine.AddProperty<Bullet, int>("bullet", b => b.SpriteIndex);
            _engine.VirtualMachine.AddFiringFunction("bullet", "fire", _engine.BulletSystem, bs => bs.FireBasicBullet(0,0,0,0,0));
            _engine.VirtualMachine.AddExternalFunction("GetRandomInt", GetRandomInt);
            _engine.VirtualMachine.AddGlobalSymbol("PI", Math.Pi);
            _engine.VirtualMachine.AddGlobalSymbol("PI_180", Math.Pi / 180.0f);
            _engine.VirtualMachine.AddGlobalSymbol("PI_90", Math.Pi / 90.0f);
            _engine.VirtualMachine.LoadCode(scriptBody);

            _player.Controller = _engine
                .CreateController(_player.X, _player.Y, 0, true)
                .WithEmitter(0, 0, 0, true, EmitterTestFunc)
                .Build();
        }

        private ScriptStatus GetRandomInt(ScriptState state)
        {
            var lowBound = (int)state.Stack[state.StackHead - 2];
            var highBound = (int)state.Stack[state.StackHead - 1];

            state.Stack[--state.StackHead - 1] = _random.Next(lowBound, highBound);

            return ScriptStatus.Ok;
        }

        private IEnumerator<WaitInFrames> ScriptedController1(IController controller, IEngine engine)
        {
            if (controller.FramesAlive == 60) {
                var baseEmitter = engine.CreateScriptedEmitter(controller.X, controller.Y, Math.PiOver2, true, MoveDown);
                var numShots = 3;
                var diffAngle = Math.TwoPi/numShots;
                for (int i = 0; i < numShots; i++) {
                    baseEmitter = baseEmitter.WithOrbittingEmitter(200, diffAngle*i, true, SomeCrap1);
                }
                var finalEmitter = baseEmitter.Build();

                for (int i = 0; i < numShots; i++)
                {
                    engine.BulletSystem.FireOrbitingCurvedLaser(finalEmitter, 200, diffAngle * i, 8, 50, 0, 0, 3, null);
                    engine.BulletSystem.FireOrbitingCurvedLaser(finalEmitter, 100, diffAngle * i, 8, 50, 0, 0, 2, null);
                }
            }

            yield return new WaitInFrames(0);
        }

        public IEnumerator<WaitInFrames> MoveDown(Emitter e, IEngine engine)
        {
            e.Y += 0.5f;
            e.Angle += 2*Math.Pi/180.0f;

            yield return new WaitInFrames(0);
        }

        public IEnumerator<WaitInFrames> EmitterTestFunc(Emitter e, IEngine engine)
        {
            var testAction = engine.VirtualMachine.GetActionCodeScope("UpdateBullet");

            var b = engine.BulletSystem.FireScriptedBullet(e.X - 5, e.Y, Math.ToRadians(-90), 3, 1, testAction);

            //engine.BulletSystem.FireBasicBullet(e.X - 5, e.Y, Math.ToRadians(-90), 5, 0);
            //engine.BulletSystem.FireBasicBullet(e.X + 5, e.Y, Math.ToRadians(-90), 5, 0);

            yield return new WaitInFrames(5);
        }

        public IEnumerator<WaitInFrames> SomeCrap1(Emitter e, IEngine engine)
        {
            const int numBullets = 9;
            const float angleDiff = Math.TwoPi / numBullets;
            const int delay = 30;

            if (e.FramesAlive == delay) {
                for (var i = 0; i < numBullets; i++) {
                    //bs.FireOrbitingBeam(e, 100, (angleDiff*i), 0, 32, 512, 60, 240, 0, 4);
                    engine.BulletSystem.FireOrbitingScriptedBullet(e, 32, angleDiff * i, 0, 3, 6, OrbitDistanceIncreaseToMax);
                }
                engine.BulletSystem.FireOrbitingBasicBullet(e, 0, 0, 0, 0, 5);
            }

            e.X += (float)System.Math.Cos(e.Angle) * 2.0f;
            e.Y += (float)System.Math.Sin(e.Angle) * 2.0f;

            yield return new WaitInFrames(0);
        }

        public IEnumerator<WaitInFrames> OrbitDistanceIncreaseToMax<T>(T proj, IInterpolationSystem ins) where T : AbstractProjectile
        {
            proj.OrbitDistance = 64 + 64*(float)System.Math.Sin(proj.FramesAlive*Math.Pi/30.0f);

            //if (proj.OrbitDistance < 128) {
                yield return new WaitInFrames(0);
            //}
            //else {
            //    yield return new WaitInFrames(1000);
            //}
        }

        public override void LoadContent()
        {
            Game.TextureManager.LoadTexture("tilemap", @"Resources/Textures/tilemap.png");
            Game.TextureManager.LoadSubTexture("laser", @"Resources/Textures/tilemap.png", 0, 32, 256, 32, true, true);

            _playerSprite = new Sprite(Game.TextureManager.GetTexture("tilemap"), new IntRect(0,0,32,32));

            //0
            _bulletSprites.Add(new Sprite(Game.TextureManager.GetTexture("tilemap"), new IntRect(32, 0, 16, 16)){ Origin = new Vector2f(8,8) });
            _bulletSprites.Add(new Sprite(Game.TextureManager.GetTexture("tilemap"), new IntRect(48, 0, 32, 16)){ Origin = new Vector2f(16,8) });
            _bulletSprites.Add(new Sprite(Game.TextureManager.GetTexture("tilemap"), new IntRect(48, 16, 32, 16)){ Origin = new Vector2f(16,8) });
            _bulletSprites.Add(new Sprite(Game.TextureManager.GetTexture("tilemap"), new IntRect(80, 0, 32, 16)){ Origin = new Vector2f(16,8) });

            //4
            _bulletSprites.Add(new Sprite(Game.TextureManager.GetTexture("laser")));

            //5
            _bulletSprites.Add(new Sprite(Game.TextureManager.GetTexture("tilemap"), new IntRect(0, 64, 64, 64)) { Origin = new Vector2f(32, 32) });

            //6
            _bulletSprites.Add(new Sprite(Game.TextureManager.GetTexture("tilemap"), new IntRect(112, 0, 32, 32)) { Origin = new Vector2f(16, 16) });
        }

        public override void HandleInput(IInputManager<Mouse.Button, Vector2i, Window, Keyboard.Key> input, TimeSpan gameTime)
        {
            base.HandleInput(input, gameTime);

            float dx=0, dy=0;

            var speed = 120;

            if (input.Keyboard.IsKeyDown(Keyboard.Key.Left))
            {
                dx -= speed;
            }
            if (input.Keyboard.IsKeyDown(Keyboard.Key.Right))
            {
                dx += speed;
            }
            if (input.Keyboard.IsKeyDown(Keyboard.Key.Up))
            {
                dy -= speed;
            }
            if (input.Keyboard.IsKeyDown(Keyboard.Key.Down))
            {
                dy += speed;
            }
            if (input.Keyboard.IsKeyPressed(Keyboard.Key.Back)) {
                ReloadScript();
            }

            dx *= (float)gameTime.TotalSeconds;
            dy *= (float)gameTime.TotalSeconds;

            _player.Controller.IsEnabled = input.Keyboard.IsKeyDown(Keyboard.Key.Z);
            //_engine.BulletSystem.FireScriptedBullet(_player.X, _player.Y, 0, 2, 0, TestFunc);

            _player.SetPosition(_player.X + dx, _player.Y + dy);
        }

        public IEnumerator<WaitInFrames> TestFunc(AbstractProjectile b, IInterpolationSystem ins)
        {
            const int delay = 30;
            ins.InterpolateProjectileAngle(b, b.Angle, b.Angle + Math.PiOver2, delay);
            yield return new WaitInFrames(delay);
            ins.InterpolateProjectileAngle(b, b.Angle, b.Angle - Math.PiOver2, delay);
            yield return new WaitInFrames(delay);
        }

        public IEnumerator<WaitInFrames> TestLaserFunc(CurvedLaser cv)
        {
            for (int i = 0; i < 30; i++) {
                cv.Angle += Math.Pi/50;
                yield return new WaitInFrames(0);
            }

            for (int i = 0; i < 30; i++)
            {
                cv.Angle -= Math.Pi / 180;
                yield return new WaitInFrames(0);
            }
        }

        public override void Update(TimeSpan gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            _playerSprite.Position = new Vector2f(_player.X, _player.Y);
            _engine.Update((float) gameTime.TotalSeconds);
        }

        public override void Draw(TimeSpan gameTime)
        {
            Game.Window.Clear();

            Game.Window.Draw(_playerSprite);

            DrawBullets();
            DrawCurvedLasers();
            DrawBeams();
            DrawLasers();

            DrawRenderFrameTime();
        }

        private void DrawRenderFrameTime()
        {
            var textStr = String.Format("Avg render time: {0}\nRender time: {1}\nAvg update time: {2}", Game.AverageRenderTimeForLastSecond.ToString("##.##"), Game.LastRenderTime.ToString("##.##"), Game.AverageUpdateTime.ToString("##.##"));
            var text = new Text(textStr, _textFont);
            text.CharacterSize = 16;

            Game.Window.Draw(text);
        }

        private void DrawBullets()
        {
            IBullet b;
            Sprite sprite;
            for (int i = 0; i < _engine.BulletSystem.Bullets.Count; i++)
            {
                b = _engine.BulletSystem.Bullets[i];

                if (b.IsActive)
                {
                    sprite = _bulletSprites[b.SpriteIndex];
                    sprite.Position = new Vector2f(b.X, b.Y);
                    sprite.Rotation = Math.ToDegrees(b.Angle + b.SpriteAngle);

                    Game.Window.Draw(sprite);
                }
            }
        }

        private void DrawCurvedLasers()
        {
            ICurvedLaser cv;
            Sprite sprite;

            int texLeft, texTop, texWidth, texHeight;
            for (int i = 0; i < _engine.BulletSystem.CurvedLasers.Count; i++)
            {
                cv = _engine.BulletSystem.CurvedLasers[i];

                // needs at least 2 points to draw [at least 2 coordinates]
                if (cv.IsActive && cv.FramesAlive >= 2) {
                    sprite = _bulletSprites[cv.SpriteIndex];
                    texLeft = sprite.TextureRect.Left;
                    texTop = sprite.TextureRect.Top;
                    texWidth = sprite.TextureRect.Width;
                    texHeight = sprite.TextureRect.Height;

                    uint limit = System.Math.Min(cv.FramesAlive, cv.Lifetime);
                    _vertexArray.Resize(limit * 2);

                    // 1st coordinate is always aimed at the 2nd coordinate
                    var firstToSecondAngle = System.Math.Atan2(
                        cv.Coordinates.ElementAt(1).Y - cv.Coordinates.ElementAt(0).Y,
                        cv.Coordinates.ElementAt(1).X - cv.Coordinates.ElementAt(0).X
                    );

                    _vertexArray[0] = new Vertex(
                        new Vector2f(
                            cv.Coordinates.ElementAt(0).X + (float)System.Math.Cos(firstToSecondAngle - Math.PiOver2) * cv.Radius,
                            cv.Coordinates.ElementAt(0).Y + (float)System.Math.Sin(firstToSecondAngle - Math.PiOver2) * cv.Radius
                        ),
                        Color.White,
                        new Vector2f(texLeft,texTop)
                    );
                    _vertexArray[1] = new Vertex(
                        new Vector2f(
                            cv.Coordinates.ElementAt(0).X + (float)System.Math.Cos(firstToSecondAngle + Math.PiOver2) * cv.Radius,
                            cv.Coordinates.ElementAt(0).Y + (float)System.Math.Sin(firstToSecondAngle + Math.PiOver2) * cv.Radius
                        ),
                        Color.White,
                        new Vector2f(texLeft, texTop+texHeight)
                    );

                    // the 'middle' coordinates are aimed slightly differently
                    // to calculate where the offsets are, use the previous point's "3rd-angle"
                    // "3rd-angle" refers to a point's angle to the point after the next point
                    // i.e. point 1 to point 3
                    for (var x = 1; x <= limit - 2; x++)
                    {
                        var xCoord = (float)x / (limit - 1);
                        var previousThirdAngle = System.Math.Atan2(
                            cv.Coordinates.ElementAt(x + 1).Y - cv.Coordinates.ElementAt(x - 1).Y,
                            cv.Coordinates.ElementAt(x + 1).X - cv.Coordinates.ElementAt(x - 1).X
                        );

                        _vertexArray[(uint)x*2] = new Vertex(
                            new Vector2f(
                                cv.Coordinates.ElementAt(x).X + (float)System.Math.Cos(previousThirdAngle - Math.PiOver2) * cv.Radius,
                                cv.Coordinates.ElementAt(x).Y + (float)System.Math.Sin(previousThirdAngle - Math.PiOver2) * cv.Radius
                            ),
                            Color.White,
                            new Vector2f(texLeft+xCoord*texWidth,texTop)
                        );
                        _vertexArray[(uint)x*2+1] = new Vertex(
                            new Vector2f(
                                cv.Coordinates.ElementAt(x).X + (float)System.Math.Cos(previousThirdAngle + Math.PiOver2) * cv.Radius,
                                cv.Coordinates.ElementAt(x).Y + (float)System.Math.Sin(previousThirdAngle + Math.PiOver2) * cv.Radius
                            ),
                            Color.White,
                            new Vector2f(texLeft + xCoord * texWidth, texTop+texHeight)
                        );
                    }

                    // penultimate coordinate is always aimed at last coordinate
                    var penultimateToLastAngle = System.Math.Atan2(
                        cv.Coordinates.ElementAt((int)limit-1).Y - cv.Coordinates.ElementAt((int)limit-2).Y,
                        cv.Coordinates.ElementAt((int)limit-1).X - cv.Coordinates.ElementAt((int)limit-2).X
                    );

                    _vertexArray[limit*2-2] = new Vertex(
                        new Vector2f(
                            cv.Coordinates.ElementAt((int)limit-1).X + (float)System.Math.Cos(penultimateToLastAngle - Math.PiOver2) * cv.Radius,
                            cv.Coordinates.ElementAt((int)limit-1).Y + (float)System.Math.Sin(penultimateToLastAngle - Math.PiOver2) * cv.Radius
                        ),
                        Color.White,
                        new Vector2f(texLeft + texWidth, texTop)
                    );
                    _vertexArray[limit*2-1] = new Vertex(
                        new Vector2f(
                            cv.Coordinates.ElementAt((int)limit-1).X + (float)System.Math.Cos(penultimateToLastAngle + Math.PiOver2) * cv.Radius,
                            cv.Coordinates.ElementAt((int)limit-1).Y + (float)System.Math.Sin(penultimateToLastAngle + Math.PiOver2) * cv.Radius
                        ),
                        Color.White,
                        new Vector2f(texLeft + texWidth, texTop + texHeight)
                    );

                    var renderStates = new RenderStates(sprite.Texture);

                    Game.Window.Draw(_vertexArray, renderStates);
                }
            }
        }

        private void DrawBeams()
        {
            IBeam b;
            Sprite sprite;
            _vertexArray.Resize(4);
            int texLeft, texTop, texWidth, texHeight;

            for (int i = 0; i < _engine.BulletSystem.Beams.Count; i++)
            {
                b = _engine.BulletSystem.Beams[i];

                if (b.IsActive)
                {
                    sprite = _bulletSprites[b.SpriteIndex];
                    texLeft = sprite.TextureRect.Left;
                    texTop = sprite.TextureRect.Top;
                    texWidth = sprite.TextureRect.Width;
                    texHeight = sprite.TextureRect.Height;

                    var texSkip = 0U;
                    var renderStates = new RenderStates(sprite.Texture);

                    // draw warning line
                    if (b.FramesAlive < b.DelayInFrames) {
                        var x2 = b.X + (float) System.Math.Cos(b.Angle)*b.Length;
                        var y2 = b.Y + (float) System.Math.Sin(b.Angle)*b.Length;

                        LineDrawer.Draw(b.X, b.Y, x2, y2, Game.Window);
                    }

                    // draw beam
                    // once the 'warning period' is 85% done, start drawing the beam
                    // at a lower alpha

                    var ratio = (float)b.FramesAlive/b.DelayInFrames;
                    var realRatio = 0.0f;
                    const float lowerLimit = 0.85f;
                    if (ratio < lowerLimit) {
                        realRatio = 0.0f;
                    }
                    else {
                        realRatio = (ratio - lowerLimit) / (1.0f-lowerLimit);
                    }

                    var radiusToUse = b.Radius;
                    var alpha = Math.SmoothStep(0.0f, 1.0f, realRatio);
                    var color = new Color(255, 255, 255, (byte) (alpha*255));

                    texSkip = b.FramesAlive * 16;
                    _vertexArray[0] = new Vertex(
                        new Vector2f(
                            b.X + (float)System.Math.Cos(b.Angle - Math.PiOver2) * radiusToUse,
                            b.Y + (float)System.Math.Sin(b.Angle - Math.PiOver2) * radiusToUse
                        ),
                        color,
                        new Vector2f(texSkip + texLeft, texTop)
                    );

                    _vertexArray[1] = new Vertex(
                        new Vector2f(
                            b.X + (float)System.Math.Cos(b.Angle + Math.PiOver2) * radiusToUse,
                            b.Y + (float)System.Math.Sin(b.Angle + Math.PiOver2) * radiusToUse
                        ),
                        color,
                        new Vector2f(texSkip + texLeft, texTop + texHeight)
                    );

                    _vertexArray[2] = new Vertex(
                        new Vector2f(
                            b.X + (float)System.Math.Cos(b.Angle) * b.Length + (float)System.Math.Cos(b.Angle - Math.PiOver2) * radiusToUse,
                            b.Y + (float)System.Math.Sin(b.Angle) * b.Length + (float)System.Math.Sin(b.Angle - Math.PiOver2) * radiusToUse
                        ),
                        color,
                        new Vector2f(texSkip + texLeft + texWidth * 1, texTop)
                    );

                    _vertexArray[3] = new Vertex(
                        new Vector2f(
                            b.X + (float)System.Math.Cos(b.Angle) * b.Length + (float)System.Math.Cos(b.Angle + Math.PiOver2) * radiusToUse,
                            b.Y + (float)System.Math.Sin(b.Angle) * b.Length + (float)System.Math.Sin(b.Angle + Math.PiOver2) * radiusToUse
                        ),
                        color,
                        new Vector2f(texSkip + texLeft + texWidth * 1, texTop + texHeight)
                    );
                    Game.Window.Draw(_vertexArray, renderStates);
                }
            }
        }

        private void DrawLasers()
        {
            ILaser l;
            Sprite sprite;
            _vertexArray.Resize(4);
            int texLeft, texTop, texWidth, texRight, texHeight;

            for (int i = 0; i < _engine.BulletSystem.Lasers.Count; i++)
            {
                l = _engine.BulletSystem.Lasers[i];

                if (l.IsActive)
                {
                    sprite = _bulletSprites[l.SpriteIndex];
                    texLeft = sprite.TextureRect.Left;
                    texTop = sprite.TextureRect.Top;
                    texWidth = sprite.TextureRect.Width;
                    texRight = texLeft + texWidth;
                    texHeight = sprite.TextureRect.Height;

                    // texLeft needs to be calculated
                    // for example, if the lasers CurrentLength is half of its Length, it should look like:
                    // ====>
                    // while if the lasers CurrentLength is 100% of its Length, it should look like:
                    // <========>
                    // texLeft = texRight - (int)((l.CurrentLength/l.Length)*texWidth);
                    // on second thought...maybe lets not do that

                    _vertexArray[0] = new Vertex(
                        new Vector2f(
                            l.X + (float)System.Math.Cos(l.Angle - Math.PiOver2) * l.Radius,
                            l.Y + (float)System.Math.Sin(l.Angle - Math.PiOver2) * l.Radius
                        ),
                        Color.White,
                        new Vector2f(texLeft, texTop)
                    );

                    _vertexArray[1] = new Vertex(
                        new Vector2f(
                            l.X + (float)System.Math.Cos(l.Angle + Math.PiOver2) * l.Radius,
                            l.Y + (float)System.Math.Sin(l.Angle + Math.PiOver2) * l.Radius
                        ),
                        Color.White,
                        new Vector2f(texLeft, texTop + texHeight)
                    );

                    _vertexArray[2] = new Vertex(
                        new Vector2f(
                            l.X - (float)System.Math.Cos(l.Angle) * l.CurrentLength + (float)System.Math.Cos(l.Angle - Math.PiOver2) * l.Radius,
                            l.Y - (float)System.Math.Sin(l.Angle) * l.CurrentLength + (float)System.Math.Sin(l.Angle - Math.PiOver2) * l.Radius
                        ),
                        Color.White,
                        new Vector2f(texRight, texTop)
                    );

                    _vertexArray[3] = new Vertex(
                        new Vector2f(
                            l.X - (float)System.Math.Cos(l.Angle) * l.CurrentLength + (float)System.Math.Cos(l.Angle + Math.PiOver2) * l.Radius,
                            l.Y - (float)System.Math.Sin(l.Angle) * l.CurrentLength + (float)System.Math.Sin(l.Angle + Math.PiOver2) * l.Radius
                        ),
                        Color.White,
                        new Vector2f(texRight, texTop + texHeight)
                    );

                    var renderStates = new RenderStates(sprite.Texture) { BlendMode = BlendMode.Add};

                    Game.Window.Draw(_vertexArray, renderStates);
                }
            }
        }
    }
}


text:
package ca.darkfusion.firstGame.graphics;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

public class SpriteSheet {
	private String path;
	public final int SIZE;
	public int[] pixels;
	public static SpriteSheet tiles = new SpriteSheet("/textures/Sprites.png", 256);

	public SpriteSheet(String path, int size) {
		this.path = path;
		this.SIZE = size;

		pixels = new int[SIZE * SIZE];

		loadImage();
	}

	private void loadImage() {
		try {
			BufferedImage image = ImageIO.read(SpriteSheet.class.getResource(path));
			int width = image.getWidth();
			int height = image.getHeight();
			image.getRGB(0, 0, width, height, pixels, 0, width);
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}

}


text:
```bash
.
├── README.md
├── backend.py
├── backend_rep.py
├── backend_test.py
├── gluon_backend_test.py
├── mxnet_backend_test.py
├── mxnet_export_test.py
├── test_cases.py
├── test_models.py
└── test_node.py
```

* `backend.py` - MXNetBackend. This file contains prepare(). \
This class can be used for both, MXNet and Gluon backend.
* `backend_rep.py` - MXNetBackendRep and GluonBackendRep for running inference
* `backend_test.py` - prepare tests by including tests from `test_cases.py`
* `gluon_backend_test.py` - Set backend as gluon and execute ONNX tests for ONNX->Gluon import.
* `mxnet_backend_test.py` - Set backend as gluon and add tests for ONNX->MXNet import/export.
Since MXNetBackend for export, tests both import and export, the test list in this file is
a union of tests that execute for import and export, export alone, and import alone.
* `mxnet_export_test.py` - Execute unit tests for testing MXNet export code - this is not specific to
any operator.
* `test_cases.py` - list of test cases for operators/models that are supported
for "both", import and export, "import" alone, or "export" alone.
* `test_models.py` - custom tests for models
* `test_node.py` - custom tests for operators. These tests are written independent of ONNX tests, in case
ONNX doesn't have tests yet or for MXNet specific operators.