text:
default_target: all

.PHONY : default_target

# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:

#=============================================================================
# Special targets provided by cmake.

# Disable implicit rules so canonical targets will work.
.SUFFIXES:

# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =

.SUFFIXES: .hpux_make_needs_suffix_list

# Suppress display of executed commands.
$(VERBOSE).SILENT:

# A target that is always out of date.
cmake_force:

.PHONY : cmake_force

#=============================================================================
# Set environment variables for the build.

# The shell in which to execute make rules.
SHELL = /bin/sh

# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake

# The command to remove a file.
RM = /usr/bin/cmake -E remove -f

# Escaping for special characters.
EQUALS = =

# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/sudartion/workspace/Q-learning-for-2D-Occupancy-Grid

# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/sudartion/workspace/Q-learning-for-2D-Occupancy-Grid/gnuplot-cpp

#=============================================================================
# Targets provided globally by CMake.

# Special rule for the target install
install: preinstall
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
	/usr/bin/cmake -P cmake_install.cmake
.PHONY : install

# Special rule for the target install
install/fast: preinstall/fast
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
	/usr/bin/cmake -P cmake_install.cmake
.PHONY : install/fast

# Special rule for the target list_install_components
list_install_components:
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Unspecified\""
.PHONY : list_install_components

# Special rule for the target list_install_components
list_install_components/fast: list_install_components

.PHONY : list_install_components/fast

# Special rule for the target install/strip
install/strip: preinstall
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..."
	/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake
.PHONY : install/strip

# Special rule for the target install/strip
install/strip/fast: install/strip

.PHONY : install/strip/fast

# Special rule for the target install/local
install/local: preinstall
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..."
	/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake
.PHONY : install/local

# Special rule for the target install/local
install/local/fast: install/local

.PHONY : install/local/fast

# Special rule for the target rebuild_cache
rebuild_cache:
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
	/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache

# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache

.PHONY : rebuild_cache/fast

# Special rule for the target edit_cache
edit_cache:
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
	/usr/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available.
.PHONY : edit_cache

# Special rule for the target edit_cache
edit_cache/fast: edit_cache

.PHONY : edit_cache/fast

# The main all target
all: cmake_check_build_system
	$(CMAKE_COMMAND) -E cmake_progress_start /home/sudartion/workspace/Q-learning-for-2D-Occupancy-Grid/gnuplot-cpp/CMakeFiles /home/sudartion/workspace/Q-learning-for-2D-Occupancy-Grid/gnuplot-cpp/CMakeFiles/progress.marks
	$(MAKE) -f CMakeFiles/Makefile2 all
	$(CMAKE_COMMAND) -E cmake_progress_start /home/sudartion/workspace/Q-learning-for-2D-Occupancy-Grid/gnuplot-cpp/CMakeFiles 0
.PHONY : all

# The main clean target
clean:
	$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean

# The main clean target
clean/fast: clean

.PHONY : clean/fast

# Prepare targets for installation.
preinstall: all
	$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall

# Prepare targets for installation.
preinstall/fast:
	$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast

# clear depends
depend:
	$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend

#=============================================================================
# Target rules for targets named shell-app

# Build rule for target.
shell-app: cmake_check_build_system
	$(MAKE) -f CMakeFiles/Makefile2 shell-app
.PHONY : shell-app

# fast build rule for target.
shell-app/fast:
	$(MAKE) -f app/CMakeFiles/shell-app.dir/build.make app/CMakeFiles/shell-app.dir/build
.PHONY : shell-app/fast

#=============================================================================
# Target rules for targets named cpp-test

# Build rule for target.
cpp-test: cmake_check_build_system
	$(MAKE) -f CMakeFiles/Makefile2 cpp-test
.PHONY : cpp-test

# fast build rule for target.
cpp-test/fast:
	$(MAKE) -f test/CMakeFiles/cpp-test.dir/build.make test/CMakeFiles/cpp-test.dir/build
.PHONY : cpp-test/fast

#=============================================================================
# Target rules for targets named gtest

# Build rule for target.
gtest: cmake_check_build_system
	$(MAKE) -f CMakeFiles/Makefile2 gtest
.PHONY : gtest

# fast build rule for target.
gtest/fast:
	$(MAKE) -f vendor/googletest/googletest/CMakeFiles/gtest.dir/build.make vendor/googletest/googletest/CMakeFiles/gtest.dir/build
.PHONY : gtest/fast

#=============================================================================
# Target rules for targets named gtest_main

# Build rule for target.
gtest_main: cmake_check_build_system
	$(MAKE) -f CMakeFiles/Makefile2 gtest_main
.PHONY : gtest_main

# fast build rule for target.
gtest_main/fast:
	$(MAKE) -f vendor/googletest/googletest/CMakeFiles/gtest_main.dir/build.make vendor/googletest/googletest/CMakeFiles/gtest_main.dir/build
.PHONY : gtest_main/fast

# Help Target
help:
	@echo "The following are some of the valid targets for this Makefile:"
	@echo "... all (the default if no target is provided)"
	@echo "... clean"
	@echo "... depend"
	@echo "... install"
	@echo "... list_install_components"
	@echo "... install/strip"
	@echo "... install/local"
	@echo "... rebuild_cache"
	@echo "... edit_cache"
	@echo "... shell-app"
	@echo "... cpp-test"
	@echo "... gtest"
	@echo "... gtest_main"
.PHONY : help

#=============================================================================
# Special targets to cleanup operation of make.

# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
	$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>8th Light UX Challenge | Travel Site</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">

        <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">

Flights

Hotels

Cars

                <form class="find_flight shadow_small gradient clearfix left" action="#" autocomplete="on">

Search for a car

Location:

                        <input type="text" name="from">
                        Enter a destination, hotel, landmark or address.

Pick-up:

                        <input type="text" name="from">

Time:

                        <input type="text" name="to">

Drop-off:

                        <input type="text" name="from">

Time:

                        <input type="text" name="to">

                  Find My Car
                </form>

Flights To The Maldives

Starting at $1499.

+ Book Now

Travel Deals

Travel Deals

Travel Deals

Share your appreciation

                        Tweet

Terms of Service • Privacy Policy

© 2013 8th Light UX

Learn More

Tour

How It Works

About

Our Team

Our Blog

Contact Us

redpajama_set_name: RedPajamaGithub


text:
module BulkActionJobs
  class AccessControl < ActiveJob::Base
    queue_as :bulk_access_control
    def perform(documents, params)
      errors = []
      successes = []
      documents.each do |id|
        media_object = MediaObject.find(id)
        media_object.hidden = params[:hidden] if !params[:hidden].nil?
        media_object.visibility = params[:visibility] unless params[:visibility].blank?
        # Limited access stuff
        ["group", "class", "user", "ipaddress"].each do |title|
          if params["submit_add_#{title}"].present?
            begin_time = params["add_#{title}_begin"].blank? ? nil : params["add_#{title}_begin"]
            end_time = params["add_#{title}_end"].blank? ? nil : params["add_#{title}_end"]
            create_lease = begin_time.present? || end_time.present?

            if params[title].present?
              val = params[title].strip
              if title=='user'
                if create_lease
                  begin
                    media_object.governing_policies += [ Lease.create(begin_time: begin_time, end_time: end_time, inherited_read_users: [val]) ]
                  rescue Exception => e
                    errors += [media_object]
                  end
                else
                  media_object.read_users += [val]
                end
              elsif title=='ipaddress'
                if ( IPAddr.new(val) rescue false )
                  if create_lease
                    begin
                      media_object.governing_policies += [ Lease.create(begin_time: begin_time, end_time: end_time, inherited_read_groups: [val]) ]
                    rescue Exception => e
                      errors += [media_object]
                    end
                  else
                    media_object.read_groups += [val]
                  end
                else
                  context[:error] = "IP Address #{val} is invalid. Valid examples: 124.124.10.10, 124.124.0.0/16, 124.124.0.0/255.255.0.0"
                end
              else
                if create_lease
                  begin
                    media_object.governing_policies += [ Lease.create(begin_time: begin_time, end_time: end_time, inherited_read_groups: [val]) ]
                  rescue Exception => e
                    errors += [media_object]
                  end
                else
                  media_object.read_groups += [val]
                end
              end
            end
          end
          if params["submit_remove_#{title}"].present?
            if params[title].present?
              if ["group", "class", "ipaddress"].include? title
                media_object.read_groups -= [params[title]]
                media_object.governing_policies.each do |policy|
                  if policy.class==Lease && policy.inherited_read_groups.include?(params[title])
                    media_object.governing_policies.delete policy
                    policy.destroy
                  end
                end
              else
                media_object.read_users -= [params[title]]
                media_object.governing_policies.each do |policy|
                  if policy.class==Lease && policy.inherited_read_users.include?(params[title])
                    media_object.governing_policies.delete policy
                    policy.destroy
                  end
                end
              end
            end
          end
        end
        if errors.empty? && media_object.save
          successes += [media_object]
        else
          errors += [media_object]
        end
      end
      return successes, errors
    end
  end

  class UpdateStatus < ActiveJob::Base
    def perform(documents, user_key, params)
      errors = []
      successes = []
      status = params['action']
      documents.each do |id|
        media_object = MediaObject.find(id)
        case status
        when 'publish'
          media_object.publish!(user_key)
          # additional save to set permalink
          if media_object.save
            successes += [media_object]
          else
            errors += [media_object]
          end
        when 'unpublish'
          if media_object.publish!(nil)
            successes += [media_object]
          else
            errors += [media_object]
          end
        end
      end
      return successes, errors
    end
  end

  class Delete < ActiveJob::Base
    def perform(documents, _params)
      errors = []
      successes = []
      documents.each do |id|
        media_object = MediaObject.find(id)
        if media_object.destroy
          successes += [media_object]
        else
          errors += [media_object]
        end
      end
      return successes, errors
    end
  end

  class Move < ActiveJob::Base
    def perform(documents, params)
      collection = Admin::Collection.find( params[:target_collection_id] )
      errors = []
      successes = []
      documents.each do |id|
        media_object = MediaObject.find(id)
        media_object.collection = collection
        if media_object.save
          successes += [media_object]
        else
          errors += [media_object]
        end
      end
      return successes, errors
    end
  end

  require 'avalon/intercom'

  class IntercomPush < ActiveJob::Base
    def perform(documents, user_key, params)
      errors = []
      successes = []
      intercom = Avalon::Intercom.new(user_key)
      documents.each do |id|
        media_object = MediaObject.find(id)
        result = intercom.push_media_object(media_object, params[:collection_id], params[:include_structure] == 'true')
        if result[:link].present?
          successes += [media_object]
        elsif result[:status].present?
          error = "There was an error pushing the item. (#{result[:status]}: #{result[:message]})"
          media_object.errors[:base] << [error]
          errors += [media_object]
        else
          media_object.errors[:base] << [result[:message]]
          errors += [media_object]
        end
      end
      [successes, errors]
    end
  end

  class Merge < ActiveJob::Base
    def perform(target_id, subject_ids)
      target = MediaObject.find target_id
      subjects = subject_ids.map { |id| MediaObject.find id }
      return target.merge!(subjects)
    end
  end

  class ApplyCollectionAccessControl < ActiveJob::Base
    queue_as :bulk_access_control
    def perform(collection_id, overwrite = true)
      errors = []
      successes = []
      collection = Admin::Collection.find collection_id
      collection.media_object_ids.each do |id|
        media_object = MediaObject.find(id)
        media_object.hidden = collection.default_hidden
        media_object.visibility = collection.default_visibility

        # Special access
        if overwrite
          media_object.read_groups = collection.default_read_groups.to_a
          media_object.read_users = collection.default_read_users.to_a
        else
          media_object.read_groups += collection.default_read_groups.to_a
          media_object.read_groups.uniq!
          media_object.read_users += collection.default_read_users.to_a
          media_object.read_users.uniq!
        end

        if media_object.save
          successes << media_object
        else
          errors << media_object
        end
      end

      [successes, errors]
    end
  end
end


text:
<ion-modal-view>
  <ion-header-bar class="bar-calm" padding="true">

Choose a Number For SMS

    <button id="close" name="close" class="button button-clear icon ion-android-cancel" ng-click="close(2)"></button>
  </ion-header-bar>
  <ion-content padding="true" has-header="true">

{{sendee.name}}'s Number(s)

    <form id="resetPass" name="resetPass" class="resetField">
      <ion-list>
        <ion-item>
          <ion-radio name="numbers" ng-repeat="item in phSend" ng-model="sendee.number" ng-value="item.value" ng-change="">{{item.type}}: {{item.value}}</ion-radio>
        </ion-item>

You Chose: {{sendee.number}}

        <ion-item>
          Message:
            <input name="msg" ng-model="sendee.msg" type="text" />

        </ion-item>
        <ion-item>
          <button class="button button-block button-calm" ng-click="smsSend()">Select Number</button>
        </ion-item>
      </ion-list>
    </form>
  </ion-content>
  <ion-footer-bar class="passFoot" padding="true">

©2015 by EBC Electionic Business Card

  </ion-footer-bar>
</ion-modal-view>


text:
const fs = require('fs');
const logger = require('console');
const Handlebars = require('handlebars');

const templateFile = 'site/index.html.tpl';
const pagesPath = 'site/pages/';
const MIN = process.env.CIRCLECI ? '.min' : '';

function capFirst (text) {
    return text.substring(0, 1).toUpperCase() + text.substring(1);
}

// read template
fs.readFile('package.json', 'utf8', (err, source) => {
    if (err) {
        return logger.error('Failed to read package.json');
    }
    const doc = JSON.parse(source);
    const version = doc['version'].split('.').join('_');

    fs.readFile(templateFile, 'utf8', (err, source) => {
        if (err) {
            return logger.error(`Failed to read template: ${templateFile}`);
        }
        const template = Handlebars.compile(source);

        // read pages
        fs.readdir(pagesPath, (err, pages) => {

            pages.forEach(page => {
                var title = page === 'index.html' ? 'Overview' : capFirst(page.split('.')[0]);

                var outFile = `website/${page}`,
                    contents = template({
                        version: version,
                        title: doc['title'] + ' ' + title
                    });

                fs.writeFile(outFile, contents, err => {
                    if (err) {
                        logger.error(`Failed to write ${outFile}: ${err}`);
                    } else {
                        logger.info(`Created ${outFile}`);
                    }
                });
            });

        });

    });

});


text:
<?php

namespace GeoJson\Tests;

use GeoJson\BoundingBox;

class BoundingBoxTest extends \PHPUnit_Framework_TestCase
{
    public function testIsJsonSerializable()
    {
        $this->assertTrue(is_subclass_of('GeoJson\BoundingBox', 'JsonSerializable'));
    }

    public function testIsJsonUnserializable()
    {
        $this->assertTrue(is_subclass_of('GeoJson\BoundingBox', 'GeoJson\JsonUnserializable'));
    }

    /**
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage BoundingBox requires at least four values
     */
    public function testConstructorShouldRequireAtLeastFourValues()
    {
        new BoundingBox(array(0, 0));
    }

    /**
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage BoundingBox requires an even number of values
     */
    public function testConstructorShouldRequireAnEvenNumberOfValues()
    {
        new BoundingBox(array(0, 0, 1, 1, 2));
    }

    /**
     * @dataProvider provideBoundsWithInvalidTypes
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage BoundingBox values must be integers or floats
     */
    public function testConstructorShouldRequireIntegerOrFloatValues()
    {
        new BoundingBox(func_get_args());
    }

    public function provideBoundsWithInvalidTypes()
    {
        return array(
            'strings' => array('0', '0.0', '1', '1.0'),
            'objects' => array(new \stdClass(), new \stdClass(), new \stdClass(), new \stdClass()),
            'arrays' => array(array(), array(), array(), array()),
        );
    }

    /**
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage BoundingBox min values must precede max values
     */
    public function testConstructorShouldRequireMinBeforeMaxValues()
    {
        new BoundingBox(array(1, 1, 0, 0));
    }

    public function testSerialization()
    {
        $bounds = array(-180.0, -90.0, 0.0, 180.0, 90.0, 100.0);
        $boundingBox = new BoundingBox($bounds);

        $this->assertSame($bounds, $boundingBox->getBounds());
        $this->assertSame($bounds, $boundingBox->jsonSerialize());
    }

    /**
     * @dataProvider provideJsonDecodeAssocOptions
     * @group functional
     */
    public function testUnserialization($assoc)
    {
        $json = '[-180.0, -90.0, 180.0, 90.0]';

        $json = json_decode($json, $assoc);
        $boundingBox = BoundingBox::jsonUnserialize($json);

        $this->assertInstanceOf('GeoJson\BoundingBox', $boundingBox);
        $this->assertSame(array(-180.0, -90.0, 180.0, 90.0), $boundingBox->getBounds());
    }

    public function provideJsonDecodeAssocOptions()
    {
        return array(
            'assoc=true' => array(true),
            'assoc=false' => array(false),
        );
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__char_environment_open_17.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-17.tmpl.cpp
*/
/*
 * @description
 * CWE: 36 Absolute Path Traversal
 * BadSource: environment Read input from an environment variable
 * GoodSource: Full path and file name
 * Sink: open
 *    BadSink : Open the file named in data using open()
 * Flow Variant: 17 Control flow: for loops
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

#define ENV_VARIABLE "ADD"

#ifdef _WIN32
#define GETENV getenv
#else
#define GETENV getenv
#endif

#ifdef _WIN32
#define OPEN _open
#define CLOSE _close
#else
#include <unistd.h>
#define OPEN open
#define CLOSE close
#endif

namespace CWE36_Absolute_Path_Traversal__char_environment_open_17
{

#ifndef OMITBAD

void bad()
{
    int i;
    char * data;
    char dataBuffer[FILENAME_MAX] = "";
    data = dataBuffer;
    for(i = 0; i < 1; i++)
    {
        {
            /* Append input from an environment variable to data */
            size_t dataLen = strlen(data);
            char * environment = GETENV(ENV_VARIABLE);
            /* If there is data in the environment variable */
            if (environment != NULL)
            {
                /* POTENTIAL FLAW: Read data from an environment variable */
                strncat(data+dataLen, environment, FILENAME_MAX-dataLen-1);
            }
        }
    }
    {
        int fileDesc;
        /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
        fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
        if (fileDesc != -1)
        {
            CLOSE(fileDesc);
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() - use goodsource in the for statement */
static void goodG2B()
{
    int h;
    char * data;
    char dataBuffer[FILENAME_MAX] = "";
    data = dataBuffer;
    for(h = 0; h < 1; h++)
    {
#ifdef _WIN32
        /* FIX: Use a fixed, full path and file name */
        strcat(data, "c:\\temp\\file.txt");
#else
        /* FIX: Use a fixed, full path and file name */
        strcat(data, "/tmp/file.txt");
#endif
    }
    {
        int fileDesc;
        /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
        fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
        if (fileDesc != -1)
        {
            CLOSE(fileDesc);
        }
    }
}

void good()
{
    goodG2B();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE36_Absolute_Path_Traversal__char_environment_open_17; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
package com.miraclewong.hack13;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mTextView = (TextView)findViewById(R.id.my_text_view);

        mTextView.post(new Runnable() {
            @Override
            public void run() {
                String size = String.format("TextView's width: %d, height: %d",
                        mTextView.getWidth(), mTextView.getHeight());
                Toast.makeText(MainActivity.this, size, Toast.LENGTH_SHORT)
                        .show();
            }
        });
    }
}


text:
/*
 * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
 * at the root of this project for more details.
 */
package io.github.nucleuspowered.nucleus.modules.teleport.commands;

import com.google.inject.Inject;
import io.github.nucleuspowered.nucleus.api.teleport.data.TeleportResult;
import io.github.nucleuspowered.nucleus.api.teleport.data.TeleportScanners;
import io.github.nucleuspowered.nucleus.modules.teleport.TeleportPermissions;
import io.github.nucleuspowered.nucleus.modules.teleport.config.TeleportConfig;
import io.github.nucleuspowered.nucleus.modules.teleport.services.PlayerTeleporterService;
import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandContext;
import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandExecutor;
import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandResult;
import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.Command;
import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.CommandModifier;
import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.EssentialsEquivalent;
import io.github.nucleuspowered.nucleus.core.scaffold.command.modifier.CommandModifiers;
import io.github.nucleuspowered.nucleus.core.services.INucleusServiceCollection;
import io.github.nucleuspowered.nucleus.core.services.interfaces.IPermissionService;
import io.github.nucleuspowered.nucleus.core.services.interfaces.IReloadableService;
import io.github.nucleuspowered.nucleus.modules.teleport.services.TPAResult;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.exception.CommandException;
import org.spongepowered.api.command.parameter.Parameter;
import org.spongepowered.api.command.parameter.managed.Flag;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
import org.spongepowered.api.world.server.ServerLocation;
import org.spongepowered.api.world.server.ServerWorld;

import java.util.Optional;
import java.util.UUID;
import java.util.function.Supplier;

@EssentialsEquivalent(value = {"tp", "tele", "tp2p", "teleport", "tpo"}, isExact = false,
        notes = "If you have permission, this will override '/tptoggle' automatically.")
@Command(
        aliases = {"teleport", "tele", "$tp"},
        basePermission = TeleportPermissions.BASE_TELEPORT,
        commandDescriptionKey = "teleport",
        modifiers = {
                @CommandModifier(
                        value = CommandModifiers.HAS_WARMUP,
                        exemptPermission = TeleportPermissions.EXEMPT_WARMUP_TELEPORT
                ),
                @CommandModifier(
                        value = CommandModifiers.HAS_COOLDOWN,
                        exemptPermission = TeleportPermissions.EXEMPT_COOLDOWN_TELEPORT
                ),
                @CommandModifier(
                        value = CommandModifiers.HAS_COST,
                        exemptPermission = TeleportPermissions.EXEMPT_COST_TELEPORT
                )
        },
        associatedPermissions = {
                TeleportPermissions.TELEPORT_OFFLINE,
                TeleportPermissions.TELEPORT_QUIET,
                TeleportPermissions.OTHERS_TELEPORT,
                TeleportPermissions.TPTOGGLE_EXEMPT
        }
)
public class TeleportCommand implements ICommandExecutor, IReloadableService.Reloadable {

    private final Parameter.Value<UUID> userToWarp;
    private final Parameter.Value<ServerPlayer> playerToWarp;

    private final Parameter.Value<UUID> userToWarpTo;
    private final Parameter.Value<ServerPlayer> playerToWarpTo;

    private final Parameter.Value<Boolean> quietOption = Parameter.bool().key("quiet").build();

    private boolean isDefaultQuiet = false;

    @Inject
    public TeleportCommand(final INucleusServiceCollection serviceCollection) {
        final IPermissionService permissionService = serviceCollection.permissionService();
        this.userToWarp = Parameter.user()
                .key("Offline player to warp")
                .requirements(cause ->
                        permissionService.hasPermission(cause, TeleportPermissions.OTHERS_TELEPORT) &&
                                permissionService.hasPermission(cause, TeleportPermissions.TELEPORT_OFFLINE))
                .build();
        this.playerToWarp = Parameter.player()
                .key("Player to warp")
                .requirements(cause -> permissionService.hasPermission(cause, TeleportPermissions.OTHERS_TELEPORT))
                .build();

        this.userToWarpTo = Parameter.user()
                .key("Offline player to warp to")
                .requirements(cause -> permissionService.hasPermission(cause, TeleportPermissions.TELEPORT_OFFLINE))
                .build();
        this.playerToWarpTo = Parameter.player()
                .key("Player to warp to")
                .build();
    }

    @Override public void onReload(final INucleusServiceCollection serviceCollection) {
        this.isDefaultQuiet = serviceCollection.configProvider().getModuleConfig(TeleportConfig.class).isDefaultQuiet();
    }

    @Override
    public Flag[] flags(final INucleusServiceCollection serviceCollection) {
        return new Flag[] {
                Flag.of("f"),
                Flag.builder().alias("q")
                        .setParameter(this.quietOption)
                        .setRequirement(commandCause -> serviceCollection.permissionService().hasPermission(commandCause, TeleportPermissions.TELEPORT_QUIET))
                        .build()
        };
    }

    @Override
    public Parameter[] parameters(final INucleusServiceCollection serviceCollection) {
       return new Parameter[] {
               Parameter.firstOf(
                   Parameter.seq(this.playerToWarp, Parameter.firstOf(this.playerToWarpTo, this.userToWarpTo)), // <player from> <to>
                   Parameter.seq(this.userToWarp, Parameter.firstOf(this.playerToWarpTo, this.userToWarpTo)), // <user from> <to>
                   this.playerToWarpTo,  // <player to>
                   this.userToWarpTo // <user to>
               )
       };
    }

    @Override
    public Optional<ICommandResult> preExecute(final ICommandContext context) {
        @Nullable final User source =
                context.getOptionalUserFromUUID(this.userToWarp)
                        .orElseGet(() -> context.getOne(this.playerToWarp).map(ServerPlayer::user).orElse(null));
        final boolean isOther = source != null && context.uniqueId().filter(x -> !x.equals(source.uniqueId())).isPresent();
        final User to = context.getOptionalUserFromUUID(this.userToWarpTo).orElseGet(() -> context.requireOne(this.playerToWarpTo).user());
        final TPAResult result = context.getServiceCollection()
                .getServiceUnchecked(PlayerTeleporterService.class)
                .canTeleportTo(context.audience(), source, to, isOther);
        if (result.isSuccess()) {
            return Optional.empty();
        }
        return Optional.of(context.errorResult(result.key(), result.name()));
    }

    @Override public ICommandResult execute(final ICommandContext context) throws CommandException {
        @Nullable final User externalSource =
                context.getOptionalUserFromUUID(this.userToWarp)
                        .orElseGet(() -> context.getOne(this.playerToWarp).map(ServerPlayer::user).orElse(null));
        @NonNull final User source;
        if (externalSource != null) {
            source = externalSource;
        } else {
            source = context.requirePlayer().user();
        }
        final boolean isOther = context.uniqueId().filter(x -> !x.equals(source.uniqueId())).isPresent();
        final User to = context.getOptionalUserFromUUID(this.userToWarpTo).orElseGet(() -> context.requireOne(this.playerToWarpTo).user());

        final boolean beQuiet = context.getOne(this.quietOption).orElse(this.isDefaultQuiet);

        if (source.isOnline() && to.isOnline()) {
            final TeleportResult result =
                    context.getServiceCollection()
                        .getServiceUnchecked(PlayerTeleporterService.class)
                            .teleportWithMessage(
                                    context.audience(),
                                    source.player().get(),
                                    to.player().get(),
                                    !context.hasFlag("f"),
                                    false,
                                    beQuiet
                            );
            return result.isSuccessful() ? context.successResult() : context.failResult();
        }

        // We have an offline player.
        if (!context.testPermission(TeleportPermissions.TELEPORT_OFFLINE)) {
            return context.errorResult("command.teleport.noofflineperms");
        }

        // Can we get a location?
        final Supplier<CommandException> r = () -> context.createException("command.teleport.nolastknown", to.name());

        if (!source.isOnline()) {
            if (source.setLocation(to.worldKey(), to.position())) {
                context.sendMessage("command.teleport.offline.other", source.name(), to.name());
                return context.successResult();
            }
        } else {
            final ServerWorld w = Sponge.server().worldManager().world(to.worldKey()).orElseThrow(r);
            final ServerLocation l = ServerLocation.of(w, to.position());

            final boolean result = context.getServiceCollection()
                    .teleportService()
                    .teleportPlayerSmart(
                            source.player().get(),
                            l,
                            false,
                            true,
                            TeleportScanners.NO_SCAN.get()
                    ).isSuccessful();
            if (result) {
                if (isOther) {
                    context.sendMessage("command.teleport.offline.other", source.name(), to.name());
                }

                context.sendMessage("command.teleport.offline.self", to.name());
                return context.successResult();
            }
        }

        return context.errorResult("command.teleport.error");
    }

}


text:
# Add the directory where pydevs lives to Python's import path
import sys

# Import code for DEVS model representation:
from pypdevs.infinity import *
from pypdevs.DEVS import *

# Import for uniform random number generators
from random import uniform
from random import randint

#    ======================================================================    #

class TrafficLightMode:

  """Encapsulates the system's state
  """

  ###
  def __init__(self, current="red"):
    """Constructor (parameterizable).
    """
    self.set(current)

  def set(self, value="red"):
    self.__colour=value

  def get(self):
    return self.__colour

  def __str__(self):
    return self.get()

class TrafficLight(AtomicDEVS):
  """A traffic light
  """

  ###
  def __init__(self, name=None):
    """Constructor (parameterizable).
    """

    # Always call parent class' constructor FIRST:
    AtomicDEVS.__init__(self, name)

    # STATE:
    #  Define 'state' attribute (initial sate):
    self.state = TrafficLightMode("red")

    # PORTS:
    #  Declare as many input and output ports as desired
    #  (usually store returned references in local variables):
    self.INTERRUPT = self.addInPort(name="INTERRUPT")
    self.OBSERVED = self.addOutPort(name="OBSERVED")

  ###
  def extTransition(self, inputs):
    """External Transition Function."""

    # Compute the new state 'Snew' based (typically) on current
    # State, Elapsed time parameters and calls to 'self.peek(self.IN)'.
    #input = self.peek(self.INTERRUPT)
    input = inputs[self.INTERRUPT][0]

    state = self.state.get()

    if input == "toManual":
      if state == "manual":
       # staying in manual mode
       return TrafficLightMode("manual")
      if state in ("red", "green", "yellow"):
       return TrafficLightMode("manual")
      else:
       raise DEVSException(\
        "unknown state <%s> in TrafficLight external transition function"\
        % state)

    if input == "toAutonomous":
      if state == "manual":
        return TrafficLightMode("red")
      else:
       raise DEVSException(\
        "unknown state <%s> in TrafficLight external transition function"\
        % state)

    raise DEVSException(\
      "unknown input <%s> in TrafficLight external transition function"\
      % input)

  ###
  def intTransition(self):
    """Internal Transition Function.
    """

    state = self.state.get()

    if state == "red":
      return TrafficLightMode("green")
    elif state == "green":
      return TrafficLightMode("yellow")
    elif state == "yellow":
      return TrafficLightMode("red")
    else:
      raise DEVSException(\
        "unknown state <%s> in TrafficLight internal transition function"\
        % state)

  ###
  def outputFnc(self):
    """Output Funtion.
    """

    # A colourblind observer sees "grey" instead of "red" or "green".

    # BEWARE: ouput is based on the OLD state
    # and is produced BEFORE making the transition.
    # We'll encode an "observation" of the state the
    # system will transition to !

    # Send messages (events) to a subset of the atomic-DEVS'
    # output ports by means of the 'poke' method, i.e.:
    # The content of the messages is based (typically) on current State.

    state = self.state.get()

    if state == "red":
      return {self.OBSERVED: ["grey"]}
      #self.poke(self.OBSERVED, "grey")
      # NOT self.poke(self.OBSERVED, "grey")
    elif state == "green":
      return {self.OBSERVED: ["yellow"]}
      #self.poke(self.OBSERVED, "yellow")
      # NOT self.poke(self.OBSERVED, "grey")
    elif state == "yellow":
      return {self.OBSERVED: ["grey"]}
      #self.poke(self.OBSERVED, "grey")
      # NOT self.poke(self.OBSERVED, "yellow")
    else:
      raise DEVSException(\
        "unknown state <%s> in TrafficLight external transition function"\
        % state)

  ###
  def timeAdvance(self):
    """Time-Advance Function.
    """

    # Compute 'ta', the time to the next scheduled internal transition,
    # based (typically) on current State.

    state = self.state.get()

    if state == "red":
      return 3
    elif state == "green":
      return 2
    elif state == "yellow":
      return 1
    elif state == "manual":
      return INFINITY
    else:
      raise DEVSException(\
        "unknown state <%s> in TrafficLight time advance transition function"\
        % state)

#    ======================================================================    #

class PolicemanMode:

  """Encapsulates the Policeman's state
  """

  ###
  def __init__(self, current="idle"):
    """Constructor (parameterizable).
    """
    self.set(current)

  def set(self, value="idle"):
    self.__mode=value

  def get(self):
    return self.__mode

  def __str__(self):
    return self.get()

class Policeman(AtomicDEVS):
  """A policeman producing "toManual" and "toAutonomous" events:
      "toManual" when going from "idle" to "working" mode
      "toAutonomous" when going from "working" to "idle" mode
  """

  ###
  def __init__(self, name=None):
    """Constructor (parameterizable).
    """

    # Always call parent class' constructor FIRST:
    AtomicDEVS.__init__(self, name)

    # STATE:
    #  Define 'state' attribute (initial sate):
    self.state = PolicemanMode("idle")

    # ELAPSED TIME:
    #  Initialize 'elapsed time' attribute if required
    #  (by default, value is 0.0):
    self.elapsed = 0

    # PORTS:
    #  Declare as many input and output ports as desired
    #  (usually store returned references in local variables):
    self.OUT = self.addOutPort(name="OUT")

  ###
  # Autonomous system (no input ports),
  # so no External Transition Function required
  #

  ###
  def intTransition(self):
    """Internal Transition Function.
       The policeman works forever, so only one mode.
    """

    state = self.state.get()

    if state == "idle":
      return PolicemanMode("working")
    elif state == "working":
      return PolicemanMode("idle")
    else:
      raise DEVSException(\
        "unknown state <%s> in Policeman internal transition function"\
        % state)

  ###
  def outputFnc(self):
    """Output Funtion.
    """

    # Send messages (events) to a subset of the atomic-DEVS'
    # output ports by means of the 'poke' method, i.e.:
    # The content of the messages is based (typically) on current State.

    state = self.state.get()

    if state == "idle":
      return {self.OUT: ["toManual"]}
      #self.poke(self.OUT, "toManual")
    elif state == "working":
      return {self.OUT: ["toAutonomous"]}
      #self.poke(self.OUT, "toAutonomous")
    else:
      raise DEVSException(\
        "unknown state <%s> in Policeman output function"\
        % state)

  ###
  def timeAdvance(self):
    """Time-Advance Function.
    """

    # Compute 'ta', the time to the next scheduled internal transition,
    # based (typically) on current State.

    state = self.state.get()

    if state == "idle":
      return 200
    elif state == "working":
      return 100
    else:
      raise DEVSException(\
        "unknown state <%s> in Policeman time advance function"\
        % state)

#    ======================================================================    #

class TrafficSystem(CoupledDEVS):

  def __init__(self, name=None):
    """ A simple traffic system consisting of a Policeman and a TrafficLight.
    """

    # Always call parent class' constructor FIRST:
    CoupledDEVS.__init__(self, name)

    # Declare the coupled model's output ports:
    # Autonomous, so no output ports
    #self.OUT = self.addOutPort(name="OUT")

    # Declare the coupled model's sub-models:

    # The Policeman generating interrupts
    self.policeman = self.addSubModel(Policeman(name="policeman"))

    # The TrafficLight
    self.trafficLight = self.addSubModel(TrafficLight(name="trafficLight"))

    # Only connect ...
    self.connectPorts(self.policeman.OUT, self.trafficLight.INTERRUPT)
    #self.connectPorts(self.trafficLight.OBSERVED, self.OUT)

  def select(self, immList):
    """Give the Policeman highest priority.
       Note how the technique used below can
       be generalized to encode priorities based on model type.
       To distinguish between models of the same type,
       the name or unique ID should be used.
    """
    # return the first Policeman instance in the immList
    for i in range(len(immList)):
      #if immList[i].__class__ == TrafficLight:
      if immList[i].__class__ == Policeman:
        return immList[i]

    # if no Policeman instances found, return the last entry
    return immList[-1]

    # Alternative: randomly choose among imminent submodels
    #return immList[randint(0,len(immList))]

    # If the select method is not defined, the immList[0]
    # will be chosen by default.

#    ======================================================================    #


text:
<?php

namespace Macghriogair\Support\Tests;

use Macghriogair\Support\Parser\PropertiesParser;

class PropertiesParserTest extends \PHPUnit\Framework\TestCase
{
    /** @test */
    public function itParsesAJavaStylePropertiesString()
    {
        $text = "#This file is automatically generated - DO NOT EDIT\n#Tue, 03 May 2016 15:23:07 +0200\nbuildtime=03-05-2016 15\:23\nversion=my-php-project.develop\nbuild=78\nbuilder=pmacgregor\nsystem=MINGW32_NT-6.1\n";

        $this->assertEquals(
            PropertiesParser::fromString($text),
            [
                "buildtime" => "03-05-2016 15\:23",
                "version" => "my-php-project.develop",
                "build" => "78",
                "builder" => "pmacgregor",
                "system" => "MINGW32_NT-6.1"
            ]);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sbml xmlns="http://www.sbml.org/sbml/level1" level="1" version="2">
  <model name="case00554">
    <listOfCompartments>
      <compartment name="C" volume="1" units="volume"/>
    </listOfCompartments>
    <listOfSpecies>
      <species name="S1" compartment="C" initialAmount="0.1" units="substance"/>
      <species name="S2" compartment="C" initialAmount="0.2" units="substance"/>
      <species name="S3" compartment="C" initialAmount="0.1" units="substance"/>
      <species name="S4" compartment="C" initialAmount="0.1" units="substance" boundaryCondition="true"/>
    </listOfSpecies>
    <listOfParameters>
      <parameter name="k1" value="0.75"/>
      <parameter name="k2" value="0.25"/>
    </listOfParameters>
    <listOfRules>
      <algebraicRule formula="S4 + -1 * S1"/>
    </listOfRules>
    <listOfReactions>
      <reaction name="reaction1" reversible="false">
        <listOfReactants>
          <speciesReference species="S1"/>
          <speciesReference species="S2"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="S3"/>
        </listOfProducts>
        <kineticLaw formula="C * k1 * S1 * S2"/>
      </reaction>
      <reaction name="reaction2" reversible="false">
        <listOfReactants>
          <speciesReference species="S3"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="S1"/>
          <speciesReference species="S2"/>
        </listOfProducts>
        <kineticLaw formula="C * k2 * S3"/>
      </reaction>
    </listOfReactions>
  </model>
</sbml>


text:
'use strict';

const ko = require('knockout');

// Knockout bindings root object.
let view = null;
let SELECTOR = '#rebuild-expand-links-cache-task';
let finished_tasks = {};

function update_task_status(task_info) {
  if (!view) return;
  if (finished_tasks[task_info.uid]) return;

  if (typeof task_info.current !== 'undefined') {
    view.current(task_info.current);
  }

  if (typeof task_info.total !== 'undefined') {
    view.total(task_info.total);
  }

  if (task_info.finished) {
    view.current(0);
    view.total(1);
    view.started(false);

    finished_tasks[task_info.uid] = true;
  } else {
    view.started(true);
  }
}

N.wire.on('navigate.done:admin.core.rebuild', function rebuild_expand_links_cache_widget_setup() {
  if (!$(SELECTOR).length) return;

  let current = N.runtime.page_data.expand_links_cache_task.current || 0;
  let total   = N.runtime.page_data.expand_links_cache_task.total || 1;

  view = {
    started:  ko.observable(current > 0 && current < total),
    current:  ko.observable(current),
    total:    ko.observable(total)
  };

  ko.applyBindings(view, $(SELECTOR)[0]);

  N.live.on('admin.core.rebuild.expand_links_cache', update_task_status);
});

N.wire.on('navigate.exit:admin.core.rebuild', function rebuild_expand_links_cache_widget_teardown() {
  if (!$(SELECTOR).length) return;

  view = null;
  ko.cleanNode($(SELECTOR)[0]);

  N.live.off('admin.core.rebuild.expand_links_cache', update_task_status);
});

N.wire.once('navigate.done:admin.core.rebuild', function rebuild_expand_links_cache_widget_setup_handlers() {

  // Click on "start" button
  //
  N.wire.on(module.apiPath + '.start', function rebuild_start() {
    N.io.rpc('admin.core.rebuild.expand_links_cache.start').then(() => {
      // reset progress bar to zero
      view.current(0);
      view.total(1);
      view.started(true);
    });
  });

  // Click on "stop" button
  //
  N.wire.on(module.apiPath + '.stop', function rebuild_stop() {
    N.io.rpc('admin.core.rebuild.expand_links_cache.stop').then(() => {
      // reset progress bar to zero
      view.current(0);
      view.total(1);
      view.started(false);
    });
  });
});


text:
from __future__ import absolute_import, division, print_function, unicode_literals

import numpy as np
import pytest

from pyedgar import data_manipulation as manip
from pyedgar.data_manipulation import delay_embed

def test_tlist_to_flat(working_flat_and_tlist):
    flat, traj_edges, tlist = working_flat_and_tlist
    test_flat, test_traj_edges = manip.tlist_to_flat(tlist)
    assert(np.all(test_flat == flat))
    assert(list(test_traj_edges) == traj_edges)

def test_flat_to_tlist(working_flat_and_tlist):
    flat, traj_edges, tlist = working_flat_and_tlist
    test_tlist = manip.flat_to_tlist(flat, traj_edges)
    for test_traj, traj in zip(test_tlist, tlist):
        assert(np.all(test_traj == traj))

def test__as_flat(working_flat_and_tlist):
    flat, traj_edges, tlist = working_flat_and_tlist
    from_tlist, from_tlist_edges, from_tlist_type = manip._as_flat(tlist)
    assert(np.array_equal(from_tlist, flat))
    assert(np.array_equal(from_tlist_edges, traj_edges))
    assert(from_tlist_type == "list_of_trajs")

    from_flat, from_flat_edges, from_flat_type = manip._as_flat((flat, traj_edges))
    assert(np.array_equal(from_flat, flat))
    assert(np.array_equal(from_flat_edges, traj_edges))
    assert(from_flat_type == "flat")

@pytest.mark.parametrize('input_type', ['list_of_trajs', 'flat'])
def test__flat_to_orig(working_flat_and_tlist, input_type):
    flat, traj_edges, tlist = working_flat_and_tlist
    rebuilt_data = manip._flat_to_orig(flat, traj_edges, input_type)
    if input_type is 'list_of_trajs':
        for rebuilt_i, tlist_i in zip(rebuilt_data, tlist):
            assert(np.array_equal(rebuilt_i, tlist_i))
    elif input_type is 'flat':
        new_flat, new_edges = rebuilt_data
        assert(np.array_equal(new_flat, flat))
        assert(np.array_equal(traj_edges, new_edges))

class TestDelayEmbedding():
    test_data = np.empty((30, 2))
    test_data[:, 0] = np.arange(30)
    test_data[:, 1] = -np.arange(30)
    traj_edges = [0, 10, 25, 30]
    pt_1 = test_data[:10]
    pt_2 = test_data[10:25]
    pt_3 = test_data[25:]
    n_embed = 2
    lag = 3
    pt_1_embedded = np.concatenate((pt_1[6:], pt_1[3:-3], pt_1[:-6]), axis=1)
    pt_2_embedded = np.concatenate((pt_2[6:], pt_2[3:-3], pt_2[:-6]), axis=1)

    def test_delay_embed_on_tlist(self):
        tlist = [self.pt_1, self.pt_2, self.pt_3]
        print(tlist)
        embedded_tlist = delay_embed(tlist, self.n_embed, lag=self.lag)
        assert(type(embedded_tlist) is list)
        assert(len(embedded_tlist) == 2)
        assert(np.all(embedded_tlist[0] == self.pt_1_embedded))
        assert(np.all(embedded_tlist[1] == self.pt_2_embedded))

    def test_delay_embed_on_flat(self):
        true_embed_traj_flat = np.concatenate((self.pt_1_embedded,
                                               self.pt_2_embedded), axis=0)
        true_embed_traj_edges = [0, 4, 13]
        flat_data = (self.test_data, self.traj_edges)
        embed_traj, embed_edges = delay_embed(flat_data, self.n_embed,
                                              lag=self.lag)
        assert(np.all(embed_traj == true_embed_traj_flat))
        assert(list(embed_edges) == true_embed_traj_edges)

class TestDatasetSplit(object):
    flat_data = np.ones((20, 2))
    traj_edges = [0, 10, 13, 20]
    init_indices_lag_2 = np.array(list(range(0, 8)) + [10] + list(range(13, 18)))
    final_indices_lag_2 = np.array(list(range(2, 10)) + [12]
                                   + list(range(15, 20)))
    init_indices_lag_4 = np.array(list(range(0, 6)) + list(range(13, 16)))
    final_indices_lag_4 = np.array(list(range(4, 10)) + list(range(17, 20)))

    def test_use_custom_lag(self):
        init_indices, final_indices = manip.get_initial_final_split(self.traj_edges, lag=2)
        assert(np.all(init_indices == self.init_indices_lag_2))
        assert(np.all(final_indices == self.final_indices_lag_2))

    def test_lag_longer_than_traj(self):
        init_indices, final_indices = manip.get_initial_final_split(self.traj_edges, lag=4)
        assert(np.all(init_indices == self.init_indices_lag_4))
        assert(np.all(final_indices == self.final_indices_lag_4))


text:
from __future__ import absolute_import

import voeventparse as vp
import datetime
from copy import copy

ivorn_base = 'voevent.4pisky.org'
test_trigger_substream = 'TEST-TRIGGER'
test_response_substream = 'TEST-RESPONSE'
alarrm_request_substream = 'ALARRM-REQUEST'
datetime_format_short = '%y%m%d-%H%M.%S'

def create_skeleton_4pisky_voevent(substream, stream_id,
                                   role=vp.definitions.roles.test,
                                   date=None):
    author_ivorn = ivorn_base+'/robots'
    if date is None:
        date = datetime.datetime.utcnow()

    v = vp.Voevent(stream=ivorn_base+ '/' + substream,
               stream_id=stream_id, role=role)

    vp.set_who(v, date=date,
               author_ivorn=author_ivorn)
    vp.set_author(v,
                  shortName="4PiSkyBot",
                  contactName="Tim Staley",
                  contactEmail="tim.staley@physics.ox.ac.uk"
                  )
    return v

def create_4pisky_test_trigger_voevent():
    now = datetime.datetime.utcnow()
    test_packet = create_skeleton_4pisky_voevent(
        substream=test_trigger_substream,
        stream_id=now.strftime(datetime_format_short),
        role=vp.definitions.roles.test,
        date=now,
    )
    return test_packet

def create_4pisky_test_response_voevent(stream_id, date):
    response = create_skeleton_4pisky_voevent(
        substream=test_response_substream,
        stream_id=stream_id,
        role=vp.definitions.roles.test,
        date=date
    )
    return response

def create_ami_followup_notification(alert, stream_id,
                                request_status,
                                superseded_ivorns=None):

    orig_pkt = alert.voevent
    voevent = create_skeleton_4pisky_voevent(
        substream=alarrm_request_substream,
        stream_id=stream_id,
        role=vp.definitions.roles.utility)
    vp.add_how(voevent, descriptions="AMI Large Array, Cambridge",
               references=vp.Reference(
                   "http://www.mrao.cam.ac.uk/facilities/ami/ami-technical-information/"),
    )
    voevent.Why = copy(orig_pkt.Why)
    vp.add_citations(voevent, citations=vp.Citation(ivorn=orig_pkt.attrib['ivorn'],
                              cite_type=vp.definitions.cite_types.followup))
    voevent.What.Description = "A request for AMI-LA follow-up has been made."

    request_params = [vp.Param(key, val)
                      for key, val in request_status.iteritems()]
    g = vp.Group(request_params, name='request_status')
    voevent.What.append(g)

    # Also copy target location into WhereWhen
    voevent.WhereWhen = copy(orig_pkt.WhereWhen)
    # But the time marker should refer to the AMI observation:
    # (We are already citing the original Swift alert)
    ac = voevent.WhereWhen.ObsDataLocation.ObservationLocation.AstroCoords
    del ac.Time
    voevent.WhereWhen.Description = "Target co-ords from original Swift BAT alert"

    return voevent


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>labyrinth2015: gui/qdialogloading.cpp Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

labyrinth2015
    1.0

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

gui

qdialogloading.cpp

Go to the documentation of this file.

    1

    8 #include "qdialogloading.h"

    9 #include "ui_qdialogloading.h"

   10

   11 QDialogLoading::QDialogLoading(QWidget *parent) : QDialog(parent), ui(new Ui::QDialogLoading){

   12     ui->setupUi(this);

   13

   14     this->move(parent->window()->frameGeometry().topLeft() + parent->window()->rect().center() - rect().center());

   15 }

   16

   17 QDialogLoading::~QDialogLoading(){

   18     delete ui;

   19 }

Ui

Definition: qdebuglog.h:13

QDialogLoading

Class QDialogLoading - used as progressbar.

Definition: qdialogloading.h:20

<address class="footer">
Generated on Sun May 10 2015 17:58:40 for labyrinth2015 by

 1.8.9.1
</address>


text:
$(function(){
	// using jQuery
	var player = new MediaElementPlayer('#player',{
		startVolume: 0.8,
		// useful for <audio> player loops
		loop: false,
		// enables Flash and Silverlight to resize to content size
		enableAutosize: true,
		// the order of controls you want on the control bar (and other plugins below)
		features: ['playpause','volume'],
		audioWidth: 130,
		// Hide controls when playing and mouse is not over the video
		alwaysShowControls: false,
		// force iPad's native controls
		iPadUseNativeControls: false,
		// force iPhone's native controls
		iPhoneUseNativeControls: false,
		// force Android's native controls
		AndroidUseNativeControls: false,
		pluginPath: '/assets/mediaelement_rails/',
		// name of flash file
		flashName: 'flashmediaelement.swf',
		// name of silverlight file
		silverlightName: 'silverlightmediaelement.xap',
		// default if the <video width> is not specified
		enableKeyboard: true,
		// when this player starts, it will pause other players
		pauseOtherPlayers: true,
		// array of keyboard commands
		keyActions: []
	});

	// get all the available buttons
	var livestreambuttons = $(".livestreambutton");

	// initialize the buttons
	livestreambuttons.each(function() {
		$(this).click(liveStreamButtonClicked);
		$(this).html(' Livestream starten');
	});

	var isLivestreamPlaying = false;

	function liveStreamButtonClicked() {
		if(isLivestreamPlaying) {
			// the button was clicked to STOP the livestream
			player.pause();
			livestreambuttons.each(function() {
				// change look and feel of the button
				$(this).html(' Livestream starten');
				$(this).removeClass('on');
				$(this).addClass('off');
			});
			// remember status
			isLivestreamPlaying = false;
		} else {
			// the button was clicked to START the livestream
			player.play();
			livestreambuttons.each(function() {
				// change look and feel of the button
				$(this).html(' Livestream stoppen');
				$(this).removeClass('off');
				$(this).addClass('on');
			});
			// remember status
			isLivestreamPlaying = true;
		}
	}
});


text:
module VagrantPlugins
  module ProviderLibvirt
    module Action
      # This can be used with "Call" built-in to check if the machine
      # is suspended and branch in the middleware.
      class IsSuspended
        def initialize(app, env)
          @app = app
        end

        def call(env)
          domain = env[:libvirt_compute].servers.get(env[:machine].id.to_s)
          raise Errors::NoDomainError if domain == nil
          env[:result] = domain.state.to_s == 'paused'

          @app.call(env)
        end
      end
    end
  end
end


text:
/**
 <!-- tag::intent[] -->
   `bikes` provides the external API for reading, creating and manipulating
   bikes and their milages as well as computing statistics and generating charts.
 <!-- end::intent[] -->
 */
package ac.simons.biking2.bikes;


text:
[![statique](http://i.imgur.com/fzIIqbG.png)](#)

# `$ statique`

 [![Support me on Patreon][badge_patreon]][patreon] [![Buy me a book][badge_amazon]][amazon] [![PayPal][badge_paypal_donate]][paypal-donations] [![Ask me anything](https://img.shields.io/badge/ask%20me-anything-1abc9c.svg)](https://github.com/IonicaBizau/ama) [![Travis](https://img.shields.io/travis/IonicaBizau/statique.svg)](https://travis-ci.org/IonicaBizau/statique/) [![Version](https://img.shields.io/npm/v/statique.svg)](https://www.npmjs.com/package/statique) [![Downloads](https://img.shields.io/npm/dt/statique.svg)](https://www.npmjs.com/package/statique) [![Get help on Codementor](https://cdn.codementor.io/badges/get_help_github.svg)](https://www.codementor.io/johnnyb?utm_source=github&utm_medium=button&utm_term=johnnyb&utm_campaign=github)

> A Node.JS static server module with built-in cache options and route features.

## :cloud: Installation

You can install the package globally and use it as command line tool:

```sh
# Using npm
npm install --global statique

# Using yarn
yarn global add statique
```

Then, run `statique --help` and see what the CLI tool can do.

```
$ statique --help
Usage: statique [options]

A Node.JS static server module with built-in cache options and route features.

Options:
  -p, --port <port>    The port where the server will run.
  -c, --cache <cache>  The cache value in seconds.
  -r, --root <root>    The server public directory.
  -h, --help           Displays this help.
  -v, --version        Displays version information.

Examples:
  $ statique # opens the server on port 9000 serving files from the current dir
  $ statique -p 5000 -r path/to/public -c 0 # without cache

Documentation can be found at https://github.com/IonicaBizau/statique.
```

## :clipboard: Example

Here is an example how to use this package as library. To install it locally, as library, you can use `npm install statique` (or `yarn add statique`):

```js
// Dependencies
var Statique = require("statique/lib/index")
  , Http = require('http')
  ;

// Create *Le Statique* server
var server = new Statique({
    root: __dirname + "/public"
  , cache: 36000
}).setRoutes({
    "/": "/html/index.html"
  , "/test1/": { get: "/html/test1.html" }
  , "/test2": "/html/test2.html"
  , "/some/api": function (req, res) {
        res.end("Hello World!");
    }
  , "/buffer": function (req, res) {
        server.sendRes(res, 200, "text/plain", new Buffer("I am a buffer."));
    }
  , "/some/test1-alias": function (req, res) {
        server.serveRoute("/test1", req, res);
    }
  , "/method-test": {
        get: function (req, res) { res.end("GET"); }
      , post: function (req, res, form) {
            form.on("done", function (form) {
                console.log(form.data);
            });
            res.end();
        }
    }
  , "/crash": {
        get: function (req, res) { undefined.something; }
    }
  , "/anynumber-[0-9]": {
        re: true
      , handler: function (req, res) {
            res.end("Hi");
        }
    }
  , "r1": {
        re: /anyletter\-[a-z]/i
      , handler: function (req, res) {
            res.end("Case insensitive is important. ;)");
        }
    }
}).setErrors({
    404: "/html/errors/404.html"
  , 500: "/html/errors/500.html"
});

// create server
Http.createServer(server.serve.bind(server)).listen(8000, function (err) {
    // Output
    console.log("Listening on 8000.");
});
```

## :question: Get Help

There are few ways to get help:

 1. Please [post questions on Stack Overflow](https://stackoverflow.com/questions/ask). You can open issues with questions, as long you add a link to your Stack Overflow question.
 2. For bug reports and feature requests, open issues. :bug:
 3. For direct and quick help, you can [use Codementor](https://www.codementor.io/johnnyb). :rocket:

## :memo: Documentation

For full API reference, see the [DOCUMENTATION.md][docs] file.

## :yum: How to contribute
Have an idea? Found a bug? See [how to contribute][contributing].

## :sparkling_heart: Support my projects
I open-source almost everything I can, and I try to reply to everyone needing help using these projects. Obviously,
this takes time. You can integrate and use these projects in your applications *for free*! You can even change the source code and redistribute (even resell it).

However, if you get some profit from this or just want to encourage me to continue creating stuff, there are few ways you can do it:

 - Starring and sharing the projects you like :rocket:
 - [![Buy me a book][badge_amazon]][amazon]—I love books! I will remember you after years if you buy me one. :grin: :book:
 - [![PayPal][badge_paypal]][paypal-donations]—You can make one-time donations via PayPal. I'll probably buy a ~~coffee~~ tea. :tea:
 - [![Support me on Patreon][badge_patreon]][patreon]—Set up a recurring monthly donation and you will get interesting news about what I'm doing (things that I don't share with everyone).
 - **Bitcoin**—You can send me bitcoins at this address (or scanning the code below): `1P9BRsmazNQcuyTxEqveUsnf5CERdq35V6`

    ![](https://i.imgur.com/z6OQI95.png)

Thanks! :heart:

## :dizzy: Where is this library used?
If you are using this library in one of your projects, add it in this list. :sparkles:

 - `xhr-form-submitter-test`
 - `bac-results`

## :scroll: License

[MIT][license] © [Ionică Bizău][website]

[license]: /LICENSE
[website]: https://ionicabizau.net
[contributing]: /CONTRIBUTING.md
[docs]: /DOCUMENTATION.md
[badge_patreon]: https://ionicabizau.github.io/badges/patreon.svg
[badge_amazon]: https://ionicabizau.github.io/badges/amazon.svg
[badge_paypal]: https://ionicabizau.github.io/badges/paypal.svg
[badge_paypal_donate]: https://ionicabizau.github.io/badges/paypal_donate.svg
[patreon]: https://www.patreon.com/ionicabizau
[amazon]: http://amzn.eu/hRo9sIZ
[paypal-donations]: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=RVXDDLKKLQRJW


text:
REM Run the script from the command line
cscript.exe PdfToXls-CommandLine.vbs "../../sample3.pdf" "output.xlsx"
pause


text:
'use strict';

module.exports = function(app) {
	// Routing logic
	// ...

	  var categories = require('../../app/controllers/categories.server.controller');

    app.route('/categories')
      .get(categories.list)
      .post(categories.create);

         app.route('/categories/:categoryId')
    .get(categories.read);
};


text:
var Emitter = require('events/')
var map = [
    'left'
  , 'middle'
  , 'right'
]

module.exports = pressed

function pressed(element, preventDefault) {
  var mouse = new Emitter

  mouse.left = false
  mouse.right = false
  mouse.middle = false

  if (typeof window !== 'undefined') {
    element = element || window
    element.addEventListener('mousedown', mousedown, false)
    element.addEventListener('mouseup', mouseup, false)

    if (preventDefault) {
      element.addEventListener('contextmenu', function(e) {
        return e.preventDefault && e.preventDefault() && false
      }, false)
    }
  }

  return mouse

  function mousedown(e) {
    mouse.right = false
    mouse[map[e.button]] = true
    mouse.emit('down', e)

    if (!preventDefault) return
    if (!e.preventDefault) return false
    e.preventDefault()
    e.stopPropagation()
  }

  function mouseup(e) {
    mouse.right = false
    mouse[map[e.button]] = false
    mouse.emit('up', e)

    if (!preventDefault) return
    if (!e.preventDefault) return
    e.preventDefault()
    e.stopPropagation()
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ControlStyles
{
    /// <summary>
    /// Interaction logic for ArcGISProControlStylesDockPaneView.xaml
    /// </summary>
    public partial class ArcGISProControlStylesDockPaneView : UserControl
    {
        public ArcGISProControlStylesDockPaneView()
        {
            InitializeComponent();
        }
    }
}


text:
package api_client

import io.circe.generic.semiauto._
import io.circe.{Decoder, Encoder}

case class MediaServicePage(
  totalNumEntries: Int,
  values: Option[Seq[Option[MediaServiceValue]]])

object MediaServicePage {
  implicit val encoder: Encoder[MediaServicePage] = deriveEncoder
  implicit val decoder: Decoder[MediaServicePage] = deriveDecoder
}


text: FPGA synthesizable VHDL for a parity generator.


text:
using Autofac;
using Autofac.Configuration;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ys.samples.shared;

namespace ys.samples.mocks {
    public abstract class AutofacMockBase : IMockSetup {
        private ILifetimeScope rootScope {
            get;
            set;
        }
        public AutofacMockBase( string configFile ) {
            var builder = new Autofac.ContainerBuilder();

            var config = new ConfigurationBuilder();
            config.AddJsonFile(configFile);
            var module = new ConfigurationModule(config.Build());
            builder.RegisterModule(module);
            registerComponents(builder);
            this.rootScope = builder.Build();
        }
        protected abstract void registerComponents( Autofac.ContainerBuilder builder );
        public ClassT Resolve<ClassT>( ) {
            try {
                return this.rootScope.Resolve<ClassT>();
            } catch ( Exception x ) {
                Trace.WriteLine(x);
                throw;
            }
        }

        public ILifetimeScope beginMethodScope( ) {
            var scope = this.rootScope.BeginLifetimeScope();
            return scope;
        }
        public void Dispose( ) {
            this.rootScope.Dispose();
        }

    }
}


text:
/*
 * 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 io.trino.parquet.reader;

import io.trino.parquet.RichColumnDescriptor;
import io.trino.spi.TrinoException;
import io.trino.spi.block.BlockBuilder;
import io.trino.spi.type.LongTimestamp;
import io.trino.spi.type.Timestamps;
import io.trino.spi.type.Type;

import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
import static io.trino.spi.type.BigintType.BIGINT;
import static io.trino.spi.type.TimestampType.TIMESTAMP_MICROS;
import static io.trino.spi.type.TimestampType.TIMESTAMP_MILLIS;
import static io.trino.spi.type.TimestampType.TIMESTAMP_NANOS;
import static io.trino.spi.type.Timestamps.NANOSECONDS_PER_MICROSECOND;
import static io.trino.spi.type.Timestamps.PICOSECONDS_PER_NANOSECOND;
import static java.lang.Math.floorDiv;
import static java.lang.Math.floorMod;
import static java.lang.String.format;

public class Int64TimestampNanosColumnReader
        extends PrimitiveColumnReader
{
    public Int64TimestampNanosColumnReader(RichColumnDescriptor descriptor)
    {
        super(descriptor);
    }

    @Override
    protected void readValue(BlockBuilder blockBuilder, Type type)
    {
        long epochNanos = valuesReader.readLong();
        // TODO: specialize the class at creation time
        if (type == TIMESTAMP_MILLIS) {
            type.writeLong(blockBuilder, Timestamps.round(epochNanos, 6) / NANOSECONDS_PER_MICROSECOND);
        }
        else if (type == TIMESTAMP_MICROS) {
            type.writeLong(blockBuilder, Timestamps.round(epochNanos, 3) / NANOSECONDS_PER_MICROSECOND);
        }
        else if (type == TIMESTAMP_NANOS) {
            type.writeObject(blockBuilder, new LongTimestamp(
                    floorDiv(epochNanos, NANOSECONDS_PER_MICROSECOND),
                    floorMod(epochNanos, NANOSECONDS_PER_MICROSECOND) * PICOSECONDS_PER_NANOSECOND));
        }
        else if (type == BIGINT) {
            type.writeLong(blockBuilder, epochNanos);
        }
        else {
            throw new TrinoException(NOT_SUPPORTED, format("Unsupported Trino column type (%s) for Parquet column (%s)", type, columnDescriptor));
        }
    }
}


text: * It can configure space-id instead of site.


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Indian bot. Soc. 35: 85 (1956)

#### Original name
Tharoopama trina Subram., 1956

### Remarks
null


text:
namespace Mgc {

class MAGICFM Box3
{
public:
    Box3 ();

    Vector3& Center ();
    const Vector3& Center () const;

    Vector3& Axis (int i);
    const Vector3& Axis (int i) const;
    Vector3* Axes ();
    const Vector3* Axes () const;

    Real& Extent (int i);
    const Real& Extent (int i) const;
    Real* Extents ();
    const Real* Extents () const;

    void ComputeVertices (Vector3 akVertex[8]) const;

protected:
    Vector3 m_kCenter;
    Vector3 m_akAxis[3];
    Real m_afExtent[3];
};

#include "MgcBox3.inl"

} // namespace Mgc

#endif


text:
package com.samebug.clients.swing.ui.base.button;

import com.samebug.clients.swing.ui.base.interaction.ForegroundColorChanger;
import com.samebug.clients.swing.ui.base.interaction.InteractionColors;
import com.samebug.clients.swing.ui.modules.ColorService;
import com.samebug.clients.swing.ui.modules.DrawService;

import javax.swing.*;
import java.awt.*;

/**
 * Samebug style button
 *

 * By not extending the swing AbstractButton, we have lost couple of functionality, e.g. tab selection, mnemonics, accessibility.
 * However, atm we don't need those, and the features that we actually need are much easier to implement on a clean JComponent.
 *

 * If it happens that we need those features from AbstractButton, still don't try to extend it, it is simply not suitable for
 * this level of reusability. Simply lift the necessary code.
 *

 * The features this button provides:
 * - samebug-style interaction (separate colors for normal/rollover/pressed states)
 * - intellij-style themes (separate colors for light/dark theme)
 * - arbitrary component as content
 * - samebug-style filled/not filled state
 */
public abstract class BasicButton extends JComponent {
    protected ForegroundColorChanger interactionListener;
    protected InteractionColors interactionColors;
    protected Color[] backgroundColor;
    protected boolean filled;
    protected Color currentChildrenColor;

    public BasicButton(boolean filled) {
        this.filled = filled;

        setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
        setOpaque(false);
        addMouseListener(new BasicButtonListener());

        setBackgroundColor(ColorService.Background);
    }

    public void setInteractionColors(InteractionColors c) {
        interactionColors = c;
        if (interactionListener != null) interactionListener.uninstall();
        interactionListener = new ForegroundColorChanger(c, this);
        if (isEnabled()) {
            interactionListener.install();
            updateColors();
        }
    }

    public void setBackgroundColor(Color[] c) {
        backgroundColor = c;
        updateColors();
    }

    public void setFilled(boolean filled) {
        this.filled = filled;
        if (!filled) setChildrenForeground(getForeground());
        else setChildrenForeground(getBackground());
        repaint();
    }

    public boolean isFilled() {
        return filled;
    }

    @Override
    public void setFont(Font f) {
        super.setFont(f);
        setChildrenFont(f);
    }

    @Override
    public void setForeground(Color c) {
        super.setForeground(c);
        if (!filled) setChildrenForeground(c);
    }

    @Override
    public void setBackground(Color c) {
        super.setBackground(c);
        if (filled) setChildrenForeground(c);
    }

    @Override
    public void setEnabled(boolean enabled) {
        // TODO this should happen only when the property actually changes, would be better to use property change listener?
        if (isEnabled() == enabled) return;
        super.setEnabled(enabled);
        if (interactionListener != null) {
            if (enabled) interactionListener.install();
            else interactionListener.uninstall();
        }
        updateColors();
    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = DrawService.init(g);
        paintBorder(g2);
        paintContent(g2);
    }

    private void paintBorder(Graphics2D g2) {
        // draw the rounded border
        g2.setColor(getForeground());
        if (filled)
            g2.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, DrawService.RoundingDiameter, DrawService.RoundingDiameter);
        else
            g2.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, DrawService.RoundingDiameter, DrawService.RoundingDiameter);
    }

    private void paintContent(Graphics2D g2) {
        // let the children paint themselves
        super.paint(g2);
    }

    @Override
    public void updateUI() {
        super.updateUI();
        updateColors();
    }

    // TODO maybe interaction listener should handle the disabled state also?
    private void updateColors() {
        if (isEnabled() && interactionListener != null) setForeground(interactionListener.getColor());
        else if (!isEnabled() && interactionColors != null)
            setForeground(ColorService.forCurrentTheme(interactionColors.disabled));
        setBackground(ColorService.forCurrentTheme(backgroundColor));
    }

    protected void setChildrenForeground(Color foreground) {
        currentChildrenColor = foreground;
        for (Component c : getComponents()) c.setForeground(currentChildrenColor);
    }

    protected void setChildrenFont(Font font) {
        for (Component c : getComponents()) c.setFont(font);
    }
}


text:
package com.thoughtworks.xstream.converters.basic;

import com.thoughtworks.xstream.converters.SingleValueConverter;

/**
 * Base abstract implementation of  {@link com.thoughtworks.xstream.converters.SingleValueConverter}.
 *

 *
Subclasses should implement methods canConvert(Class) and fromString(String) for the conversion.

 *
 * @author Joe Walnes
 * @author Jörg Schaible
 * @author Mauro Talevi
 * @see com.thoughtworks.xstream.converters.SingleValueConverter
 */
public abstract class AbstractSingleValueConverter implements SingleValueConverter {

    public abstract boolean canConvert(Class type);

    public String toString(Object obj) {
        return obj == null ? null : obj.toString();
    }

    public abstract Object fromString(String str);

}


text:
package pomf.api.route

import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.model.headers.CacheDirectives._
import akka.http.scaladsl.server._
import Directives._

object FilesRoute {

  val build =
    pathSingleSlash {
      respondWithHeader(`Cache-Control`(`public`, `max-age`(60L * 60L * 24L * 31L))) {
        getFromResource("frontend/web/dist/index.html")
      }
    } ~
      respondWithHeader(`Cache-Control`(`public`, `max-age`(60L * 60L * 24L * 31L))) {
        getFromResourceDirectory("frontend/web/dist")
      }
}


text:
package modals;

import java.util.ArrayList;

/**
 * Created by manishautomatic on 20/05/16.
 */
public class GetAddressBookResponseTemplate {

    private int response_code=1;  // 1 = failure, 0=success
    private String type="";

    public int getResponse_code() {
        return response_code;
    }

    public void setResponse_code(int response_code) {
        this.response_code = response_code;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getResponse_message() {
        return response_message;
    }

    public void setResponse_message(String response_message) {
        this.response_message = response_message;
    }

    public LoginDetailsObject getDetails() {
        return details;
    }

    public void setDetails(LoginDetailsObject details) {
        this.details = details;
    }

    public ArrayList<ContactTemplate> getResult() {
        return result;
    }

    public void setResult(ArrayList<ContactTemplate> result) {
        this.result = result;
    }

    private String response_message ="";
    private LoginDetailsObject details = new LoginDetailsObject();
    private ArrayList<ContactTemplate> result = new ArrayList<>();

}


text:
@implementation STListViewController {

}

#pragma mark - lifeCycle

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {

    }
    return self;
}

-(void)loadView{
    [super loadView];
    _tableView = [[UITableView alloc]init];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorColor = [UIColor ST_F0E9E6_separatorColor];
    _tableView.separatorInset = UIEdgeInsetsMake(0, 12, 0, 12);
    _tableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:_tableView];

    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self customRefresh];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadDataIsFirst:YES];
}

- (void)updateViewConstraints {
    [_tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];

    [super updateViewConstraints];
}

#pragma mark - API

- (void)loadDataWithUrl:(NSString *)url
             HTTPMethod:(STHTTPMethodType)method
            pageEnabled:(BOOL)enable
                 params:(NSMutableDictionary *)params
            isFirstLoad:(BOOL)firstLoad{
    switch (method) {
        case STHTTPMethodTypeGet:{
            [self getDataWithUrl:url pageEnabled:enable params:[params mutableCopy] isFirstLoad:firstLoad isDefaultApi:YES];
            break;
        }
        case STHTTPMethodTypePost:{
            [self postDataWithUrl:url pageEnabled:enable params:[params mutableCopy] isFirstLoad:firstLoad isDefaulApi:YES];
            break;
        }

        default:
            break;
    }

}

- (void)loadAnotherDataWithUrl:(NSString *)url
                    HTTPMethod:(STHTTPMethodType)method
                   pageEnabled:(BOOL)enable
                        params:(NSMutableDictionary *)params
                   isFirstLoad:(BOOL)firstLoad {
    switch (method) {
        case STHTTPMethodTypeGet:{
            [self getDataWithUrl:url pageEnabled:enable params:[params mutableCopy] isFirstLoad:firstLoad isDefaultApi:NO];
            break;
        }
        case STHTTPMethodTypePost:{
            [self postDataWithUrl:url pageEnabled:enable params:[params mutableCopy] isFirstLoad:firstLoad isDefaulApi:NO];
            break;
        }

        default:
            break;
    }
}

- (void)getDataWithUrl:(NSString *)url
           pageEnabled:(BOOL)enable
                params:(NSMutableDictionary *)params
           isFirstLoad:(BOOL)firsLoad
          isDefaultApi:(BOOL)isDefault {
    if (enable) {
        if (firsLoad) {
            params[@"page"] = @1;
        } else {
            params[@"page"] = @(_dataSource.page + 1);
        }
        if (_dataSource.pageSize == 0) {
            params[@"page_size"] = @10;
        } else {
            params[@"page_size"] = @(_dataSource.pageSize);
        }
    }
    [[LPNetworkRequest sharedInstance]GET:url parameters:params startImmediately:YES configurationHandler:^(LPNetworkRequestConfiguration *configuration) {
        NSNumber *flag = [NSNumber numberWithBool:([self.dataSource count]>0)?1:0];
        configuration.userInfo = @{kLPNetworkRequestShowLoadingDisable:flag};
    } completionHandler:^(NSError *error, id result, BOOL isFromCache, AFHTTPRequestOperation *operation) {
        [self dealWithData:result isFirstLoad:firsLoad];
        [self generateViewWithResult:result isFirstLoad:firsLoad];
    }];
}

- (void)postDataWithUrl:(NSString *)url
            pageEnabled:(BOOL)enable
                 params:(NSMutableDictionary *)params
            isFirstLoad:(BOOL)firsLoad
            isDefaulApi:(BOOL)isDefault {
    if (enable) {
        if (firsLoad) {
            params[@"page"] = @1;
        } else {
            params[@"page"] = @(_dataSource.page + 1);
        }
        if (_dataSource.pageSize == 0) {
            params[@"page_size"] = @10;
        } else {
            params[@"page_size"] = @(_dataSource.pageSize);
        }
    }
    [[LPNetworkRequest sharedInstance]POST:url parameters:params startImmediately:YES configurationHandler:^(LPNetworkRequestConfiguration *configuration) {
        NSNumber *flag = [NSNumber numberWithBool:([self.dataSource count]>0)?1:0];
        configuration.userInfo = @{kLPNetworkRequestShowLoadingDisable:flag};
    } completionHandler:^(NSError *error, id result, BOOL isFromCache, AFHTTPRequestOperation *operation) {
        [self dealWithData:result isFirstLoad:firsLoad];
        [self generateViewWithResult:self.dataSource isFirstLoad:firsLoad];
    }];
}

#pragma mark - generateData

- (void)dealWithData:(id)result isFirstLoad:(BOOL)firstLoad{
    NSArray *array = [MTLJSONAdapter modelsOfClass:[self.dataModel class] fromJSONArray:result[@"data"] error:nil];

    //分页
    if (firstLoad) {
        _dataSource = [[LLArray alloc] init];
    } else {
        _totalCount = [self.dataSource count];
    }
    [_dataSource addObjectsFromArray:array];
    _dataSource.page = [result[@"page"] integerValue];
    _dataSource.pageSize = [result[@"page_size"] integerValue];
    _dataSource.totalSize = [result[@"total_size"] integerValue];
}

- (void)generateViewWithResult:(id)result isFirstLoad:(BOOL)firstLoad {
    NSLog(@"mustOverrideThisMethod");
    NSArray *array = result[@"data"];

    if (firstLoad) {
        [self.tableView reloadData];
    } else {
        NSMutableArray *indexPathArray = [[NSMutableArray alloc] init];
        for (int i = 0; i < array.count; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.totalCount + i inSection:0];
            [indexPathArray addObject:indexPath];
        }
        if (indexPathArray.count > 0) {
            [self.tableView beginUpdates];
            [self.tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView endUpdates];
        }
    }

    [self.tableView.pullToRefreshView stopAnimating];
    [self.tableView.infiniteScrollingView stopAnimating];
    if (![self.dataSource hasMore]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.tableView.infiniteScrollingView.enabled = NO;
            self.tableView.showsInfiniteScrolling = NO;
        });
    } else {
        self.tableView.infiniteScrollingView.enabled = YES;
        self.tableView.showsInfiniteScrolling = YES;
    }
}

- (void)loadDataIsFirst:(BOOL)first {

}

-(void)customRefresh{
    WeakSelf;
    [self.tableView addPullToRefreshWithActionHandler:^{
        [weakSelf loadDataIsFirst:YES];
    }];

    [self.tableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf loadDataIsFirst:NO];
    }];
}

@end


text:
$(document).ready(function() {
    closePool();
});

function closePool() {
    $('.close-pool-btn').click(function() {

        alertConfirmEndPool("Terminer la poule","Etes-vous sur de vouloir terminer la poule, le changement de score sera impossible après cette action !");

    });
}

// Display the popup
function alertConfirmEndPool(title, text) {
    swal({
        title: title,
        text: text,
        type: "warning",
        showCancelButton: true,
        cancelButtonText: "Annuler",
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Confirmer"
    },
    function(isConfirm){
        if(isConfirm) {

            // Create the loader
            var opac = document.createElement("div");
            opac.id += "opac";
            var imgLoader = document.createElement('img');
            imgLoader.className += "loader";
            imgLoader.src = '/images/loader.gif';
            opac.prepend(imgLoader);
            document.body.prepend(opac);

            var tournament_id = $("table#matches").data("tournament");
            var pool_id       = $("table#matches").data("pool");

            $("#pool-rankings-table tbody tr").each(function() {

                $.ajax({
                    url         : '/admin/tournaments/' + tournament_id + '/pools/' + pool_id,
                    method      : 'PUT',
                    dataType    : 'json',
                    cache       : false,
                    headers     : {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data        : {
                        team_id         : $(this).data("id"),
                        rank_in_pool    : $(this).data("rank")
                    },
                    success : function(data) {

                        // limit number of alerts to one. This is done because multiple request are made.
                        if (!$('.alert.alert-success.end-pool').length) {
                            // Display success message
                            var success = $("
Le poule à bien été terminée
");
                            $("#match-block").prepend(success);
                            // After 2sec, the alert will disappear
                            success.fadeTo(3000, 500).slideUp(500, function(){
                                success.slideUp(500);
                            });
                        }

                        $('.action i').each(function() {
                            $(this).remove();
                        });

                        $('.close-pool-btn').remove();

                        $('input#shiftTime').parent().remove();

                        // Remove loader
                        opac.remove();
                    },
                    error : function(xhr) {
                        console.error('readyState: ' + xhr.readyState);
                        console.error('status: ' + xhr.status);
                        console.error('responseText: ' + xhr.responseText);
                        // Remove loader
                        opac.remove();
                    }
                });

            });

        }

    });
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>intermol.tests.test_lammps module — InterMol 0.2a1 documentation</title>

    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="InterMol 0.2a1 documentation" href="index.html" />

Navigation

          index

          modules |

InterMol 0.2a1 documentation »

intermol.tests.test_lammps module¶

<tt class="descclassname">intermol.tests.test_lammps.</tt><tt class="descname">lammps</tt><big>(</big>flags, test_type='unit'<big>)</big>[source]¶

<col class="field-name" />
<col class="field-body" />

Parameters:	args –

Returns:

<tt class="descclassname">intermol.tests.test_lammps.</tt><tt class="descname">test_lammps_stress</tt><big>(</big><big>)</big>[source]¶

<col class="field-name" />
<col class="field-body" />

Parameters:	lammps –

Returns:

<tt class="descclassname">intermol.tests.test_lammps.</tt><tt class="descname">test_lammps_unit</tt><big>(</big><big>)</big>[source]¶

<col class="field-name" />
<col class="field-body" />

Parameters:	lammps –

Returns:

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

InterMol 0.2a1 documentation »

        © Copyright 2015, Christoph Klein, Christopher Lee, Ellen Zhong, and Michael Shirts.
      Created using Sphinx 1.2.3.