text:
<?php
include '../vendor/autoload.php';
use SymfonyXmlResponse\Responses\XmlResponse;
use SymfonyXmlResponse\Responses\XmlRepeater;

$xr = new XmlResponse();

// changing the default root element
$xr->root_element_name = 'lorem';

$data = [
    'ipsum' => 'dolor',
    'sit' => 'amet',
    // create a placeholder for the repeating group
    'files' => '@filesPlaceHolder@',
    'consectetur' => [
        'adipiscing' => [
            'elit' => 'sed',
            'do' => 'eiusmod',
            'tempor' => 'incididunt',
            'ut' => 'labore'
        ]
    ],
    'et' => 'dolore',
    'magna' => 'aliqua'
];

// use an indexed array for the repeating data
$file_array = [
    ['name' => 'file1.txt', 'size' => '10K'],
    ['name' => 'file2.txt', 'size' => '20K'],
    ['name' => 'file3.txt', 'size' => '8K']
];

$repeater = new XmlRepeater('@filesPlaceHolder@', 'file', $file_array);

// be sure to tell XmlResponse to run the decorator
// add as many decorators as needed
$xr->addDecorator($repeater);

// data must be set after the root element
$response = $xr->setData($data);

$response->send();


text:
import { EventEmitter, OnDestroy, OnInit } from '@angular/core';
import { BsDatepickerAbstractComponent } from '../../base/bs-datepicker-container';
import { BsDatepickerConfig } from '../../bs-datepicker.config';
import { DayViewModel } from '../../models/index';
import { BsDatepickerActions } from '../../reducer/bs-datepicker.actions';
import { BsDatepickerEffects } from '../../reducer/bs-datepicker.effects';
import { BsDatepickerStore } from '../../reducer/bs-datepicker.store';
import { Subscription } from 'rxjs/Subscription';
export declare class BsDaterangepickerContainerComponent extends BsDatepickerAbstractComponent implements OnInit, OnDestroy {
    private _config;
    private _store;
    private _actions;
    value: Date[];
    valueChange: EventEmitter<Date[]>;
    _rangeStack: Date[];
    _subs: Subscription[];
    constructor(_config: BsDatepickerConfig, _store: BsDatepickerStore, _actions: BsDatepickerActions, _effects: BsDatepickerEffects);
    ngOnInit(): void;
    daySelectHandler(day: DayViewModel): void;
    ngOnDestroy(): void;
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.javiersantos.appupdater.demo;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.github.javiersantos.appupdater.AppUpdater;
import com.github.javiersantos.appupdater.demo.databinding.ActivityMainBinding;
import com.github.javiersantos.appupdater.enums.Display;
import com.github.javiersantos.appupdater.enums.UpdateFrom;

public class MainActivity extends AppCompatActivity {
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        this.mContext = this;
        setSupportActionBar(binding.toolbar);

        binding.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/javiersantos/AppUpdater")));
            }
        });

        binding.included.dialogUpdateChangelog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AppUpdater(mContext)
                        //.setUpdateFrom(UpdateFrom.GITHUB)
                        //.setGitHubUserAndRepo("javiersantos", "AppUpdater")
                        .setUpdateFrom(UpdateFrom.JSON)
                        .setUpdateJSON("https://raw.githubusercontent.com/javiersantos/AppUpdater/master/app/update-changelog.json")
                        .setDisplay(Display.DIALOG)
                        .showAppUpdated(true)
                        .start();
            }
        });

        binding.included.dialogUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AppUpdater(mContext)
                        //.setUpdateFrom(UpdateFrom.GITHUB)
                        //.setGitHubUserAndRepo("javiersantos", "AppUpdater")
                        .setUpdateFrom(UpdateFrom.JSON)
                        .setUpdateXML("https://raw.githubusercontent.com/javiersantos/AppUpdater/master/app/update.json")
                        .setDisplay(Display.DIALOG)
                        .showAppUpdated(true)
                        .start();
            }
        });

        binding.included.snackbarUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AppUpdater(mContext)
                        //.setUpdateFrom(UpdateFrom.GITHUB)
                        //.setGitHubUserAndRepo("javiersantos", "AppUpdater")
                        .setUpdateFrom(UpdateFrom.XML)
                        .setUpdateXML("https://raw.githubusercontent.com/javiersantos/AppUpdater/master/app/update.xml")
                        .setDisplay(Display.SNACKBAR)
                        .showAppUpdated(true)
                        .start();
            }
        });

        binding.included.notificationUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AppUpdater(mContext)
                        //.setUpdateFrom(UpdateFrom.GITHUB)
                        //.setGitHubUserAndRepo("javiersantos", "AppUpdater")
                        .setUpdateFrom(UpdateFrom.XML)
                        .setUpdateXML("https://raw.githubusercontent.com/javiersantos/AppUpdater/master/app/update.xml")
                        .setDisplay(Display.NOTIFICATION)
                        .showAppUpdated(true)
                        .start();
            }
        });

        binding.included.dialogNoUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AppUpdater(mContext)
                        .setUpdateFrom(UpdateFrom.GOOGLE_PLAY)
                        .setDisplay(Display.DIALOG)
                        .showAppUpdated(true)
                        .start();
            }
        });

        binding.included.snackbarNoUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AppUpdater(mContext)
                        .setUpdateFrom(UpdateFrom.GOOGLE_PLAY)
                        .setDisplay(Display.SNACKBAR)
                        .showAppUpdated(true)
                        .start();
            }
        });

        binding.included.notificationNoUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AppUpdater(mContext)
                        .setUpdateFrom(UpdateFrom.GOOGLE_PLAY)
                        .setDisplay(Display.NOTIFICATION)
                        .showAppUpdated(true)
                        .start();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                startActivity(new Intent(this, SettingsActivity.class));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}


text:
@interface PodsDummy_Pods_AuctionApp_NSDate_RelativeTime : NSObject
@end
@implementation PodsDummy_Pods_AuctionApp_NSDate_RelativeTime
@end


text: /* here is a css file that you may fill with ... css */


text:
### How to see coverage reults for mocha

To see how much the [mocha](https://github.com/visionmedia/mocha) tests cover the mocha code, copy the file `mocha_coveraje` into the `test` folder of mocha, go to this folder and run the new file.

On linux you need to make it executable by using `chmod`.

    ./mocha_coveraje

Alternatively you can use

    node mocha_coveraje

instead (that's the way it works on Windows, too).


text:
package com.raquo.domtypes.generic.defs.styles.keywords

/** @see https://developer.mozilla.org/en-US/docs/Web/CSS/text-underline-position */
trait TextUnderlinePositionStyle[T] extends AutoStyle[T] {

  /**
    * This keyword allows the browser to use an algorithm to choose between
    * under and alphabetic.  --MDN
    */
  override lazy val auto: T = buildStringValue("auto")

  /**
    * This keyword forces the line to be set below the alphabetic baseline, at
    * a position where it won't cross any descender. This is useful to prevent
    * chemical or mathematical formulas, which make a large use of subscripts,
    * to be illegible.  --MDN
    */
  lazy val under: T = buildStringValue("under")

  /**
    * In vertical writing-modes, this keyword forces the line to be placed on
    * the left of the characters. In horizontal writing-modes, it is a synonym
    * of under.  --MDN
    */
  lazy val left: T = buildStringValue("left")

  /**
    * In vertical writing-modes, this keyword forces the line to be placed on
    * the right of the characters. In horizontal writing-modes, it is a synonym
    * of under.  --MDN
    */
  lazy val right: T = buildStringValue("right")

  lazy val underLeft: T = buildStringValue("under left")

  lazy val underRight: T = buildStringValue("under right")
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Abstracts, First International Mycological Congress, Exeter, September 1971 (Exeter) 90 (1971)

#### Original name
Schizochytriaceae Sparrow

### Remarks
null


text:
//// [strictModeReservedWord.ts]
let let = 10;

function foo() {
    "use strict"
    var public = 10;
    var static = "hi";
    let let = "blah";
    var package = "hello"
    function package() { }
    function bar(private, implements, let) { }
    function baz<implements, protected>() { }
    function barn(cb: (private, public, package) => void) { }
    barn((private, public, package) => { });

    var myClass = class package extends public {}

    var b: public.bar;

    function foo(x: private.x) { }
    function foo1(x: private.package.x) { }
    function foo2(x: private.package.protected) { }
    let b: interface.package.implements.B;
    ublic();
    static();
}

//// [strictModeReservedWord.js]
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var let = 10;
function foo() {
    "use strict";
    var public = 10;
    var static = "hi";
    var let = "blah";
    var package = "hello";
    function package() { }
    function bar(private, implements, let) { }
    function baz() { }
    function barn(cb) { }
    barn(function (private, public, package) { });
    var myClass = /** @class */ (function (_super) {
        __extends(package, _super);
        function package() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return package;
    }(public));
    var b;
    function foo(x) { }
    function foo1(x) { }
    function foo2(x) { }
    var b;
    ublic();
    static();
}


text:
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package mobi.omegacentauri.ao.renderer;

import mobi.omegacentauri.ao.renderer.util.UpdateClosure;
import mobi.omegacentauri.ao.source.ImageSource;
import mobi.omegacentauri.ao.source.LineSource;
import mobi.omegacentauri.ao.source.PointSource;
import mobi.omegacentauri.ao.source.TextSource;
import mobi.omegacentauri.ao.units.GeocentricCoordinates;

import android.os.ConditionVariable;
import android.util.Log;

import java.util.EnumSet;
import java.util.List;

public abstract class RendererControllerBase {
  /**
   * Base class for all renderer managers.
   */
  public static abstract class RenderManager<E> {
    protected RendererObjectManager mManager;

    private RenderManager(RendererObjectManager mgr) {
      mManager = mgr;
    }

    public void queueEnabled(final boolean enable, RendererControllerBase controller) {
      final String msg = (enable ? "Enabling" : "Disabling") + " manager " + mManager;
      controller.queueRunnable(msg, CommandType.Data, new Runnable() { public void run() {
        mManager.enable(enable);
      }});
    }

    public void queueMaxFieldOfView(final float fov, RendererControllerBase controller) {
      final String msg = "Setting manager max field of view: " + fov;
      controller.queueRunnable(msg, CommandType.Data, new Runnable() { public void run() {
        mManager.setMaxRadiusOfView(fov);
      }});
    }

    public abstract void queueObjects(
        final List<E> objects,
        final EnumSet<RendererObjectManager.UpdateType> updateType,
        RendererControllerBase controller);
  }

  // TODO(brent): collapse these into a single class?

  /**
   * Class for managing a set of point objects.
   */
  public static class PointManager extends RenderManager<PointSource> {
    private PointManager(PointObjectManager manager) {
      super(manager);
    }

    @Override
    public void queueObjects(final List<PointSource> points,
                             final EnumSet<RendererObjectManager.UpdateType> updateType,
                             RendererControllerBase controller) {
      String msg = "Setting point objects";
      controller.queueRunnable(msg, CommandType.Data, new Runnable() { public void run() {
        ((PointObjectManager) mManager).updateObjects(points, updateType);
      }});
    }
  }

  /**
   * Class for managing a set of polyline objects.
   */
  public static class LineManager extends RenderManager<LineSource> {
    private LineManager(PolyLineObjectManager manager) {
      super(manager);
    }

    @Override
    public void queueObjects(final List<LineSource> lines,
                             final EnumSet<RendererObjectManager.UpdateType> updateType,
                             RendererControllerBase controller) {
      String msg = "Setting line objects";
      controller.queueRunnable(msg, CommandType.Data, new Runnable() { public void run() {
        ((PolyLineObjectManager) mManager).updateObjects(lines, updateType);
      }});
    }
  }

  /**
   * Class for managing a set of text label objects.
   */
  public static class LabelManager extends RenderManager<TextSource> {
    private LabelManager(LabelObjectManager manager) {
      super(manager);
    }

    @Override
    public void queueObjects(final List<TextSource> labels,
                             final EnumSet<RendererObjectManager.UpdateType> updateType,
                             RendererControllerBase controller) {
      String msg = "Setting label objects";
      controller.queueRunnable(msg, CommandType.Data, new Runnable() { public void run() {
        ((LabelObjectManager) mManager).updateObjects(labels, updateType);
      }});
    }
  }

  /**
   * Class for managing a set of image objects.
   */
  public static class ImageManager extends RenderManager<ImageSource> {
    private ImageManager(ImageObjectManager manager) {
      super(manager);
    }

    @Override
    public void queueObjects(final List<ImageSource> images,
                             final EnumSet<RendererObjectManager.UpdateType> updateType,
                             RendererControllerBase controller) {
      String msg = "Setting image objects";
      controller.queueRunnable(msg, CommandType.Data, new Runnable() { public void run() {
        ((ImageObjectManager) mManager).updateObjects(images, updateType);
      }});
    }
  }

  protected static interface EventQueuer {
    void queueEvent(Runnable r);
  }

  public RendererControllerBase(SkyRenderer renderer) {
    mRenderer = renderer;
  }

  // Used only to allow logging different types of events.  The distinction
  // can be somewhat ambiguous at times, so when in doubt, I tend to use
  // "view" for those things that change all the time (like the direction
  // the user is looking) and "data" for those that change less often
  // (like whether a layer is visible or not).
  protected enum CommandType {
    View,  // The command only changes the user's view.
    Data,  // The command changes what is actually rendered.
    Synchronization  // The command relates to synchronization.
  }

  private static final boolean SHOULD_LOG_QUEUE = false;
  private static final boolean SHOULD_LOG_RUN = false;
  private static final boolean SHOULD_LOG_FINISH = false;

  protected final SkyRenderer mRenderer;

  public PointManager createPointManager(int layer) {
    PointManager manager = new PointManager(mRenderer.createPointManager(layer));
    queueAddManager(manager);
    return manager;
  }

  public LineManager createLineManager(int layer) {
    LineManager manager = new LineManager(mRenderer.createPolyLineManager(layer));
    queueAddManager(manager);
    return manager;
  }

  public LabelManager createLabelManager(int layer) {
    LabelManager manager = new LabelManager(mRenderer.createLabelManager(layer));
    queueAddManager(manager);
    return manager;
  }

  public ImageManager createImageManager(int layer) {
    ImageManager manager = new ImageManager(mRenderer.createImageManager(layer));
    queueAddManager(manager);
    return manager;
  }

  public void queueNightVisionMode(final boolean enable) {
    final String msg = "Setting night vision mode: " + enable;
    queueRunnable(msg, CommandType.View, new Runnable() { public void run() {
      mRenderer.setNightVisionMode(enable);
    }});
  }

  public void queueFieldOfView(final float fov) {
    final String msg = "Setting fov: " + fov;
    queueRunnable(msg, CommandType.View, new Runnable() { public void run() {
      mRenderer.setRadiusOfView(fov);
    }});
  }

  public void queueTextAngle(final float angleInRadians) {
    final String msg = "Setting text angle: " + angleInRadians;
    queueRunnable(msg, CommandType.View, new Runnable() { public void run() {
      mRenderer.setTextAngle(angleInRadians);
    }});
  }

  public void queueViewerUpDirection(final GeocentricCoordinates up) {
    final String msg = "Setting up direction: " + up;
    queueRunnable(msg, CommandType.View, new Runnable() { public void run() {
      mRenderer.setViewerUpDirection(up);
    }});
  }

  public void queueSetViewOrientation(final float dirX, final float dirY, final float dirZ,
                                      final float upX, final float upY, final float upZ) {
    final String msg = "Setting view orientation";
    queueRunnable(msg, CommandType.Data, new Runnable() { public void run() {
    mRenderer.setViewOrientation(dirX, dirY, dirZ, upX, upY, upZ);
    }});
  }

  public void queueEnableSkyGradient(final GeocentricCoordinates sunPosition) {
    final String msg = "Enabling sky gradient at: " + sunPosition;
    queueRunnable(msg, CommandType.Data, new Runnable() { public void run() {
      mRenderer.enableSkyGradient(sunPosition);
    }});
  }

  public void queueDisableSkyGradient() {
    final String msg = "Disabling sky gradient";
    queueRunnable(msg, CommandType.Data, new Runnable() { public void run() {
      mRenderer.disableSkyGradient();
    }});
  }

  public void queueEnableSearchOverlay(final GeocentricCoordinates target,
                                       final String targetName) {
    final String msg = "Enabling search overlay";
    queueRunnable(msg, CommandType.Data, new Runnable() { public void run() {
      mRenderer.enableSearchOverlay(target, targetName);
    }});
  }

  public void queueDisableSearchOverlay() {
    final String msg = "Disabling search overlay";
    queueRunnable(msg, CommandType.Data, new Runnable() { public void run() {
      mRenderer.disableSearchOverlay();
    }});
  }

  public void addUpdateClosure(final UpdateClosure runnable) {
    final String msg = "Setting update callback";
    queueRunnable(msg, CommandType.Data, new Runnable() {
      @Override
      public void run() {
        mRenderer.addUpdateClosure(runnable);
      }
    });
  }

  public void removeUpdateCallback(final UpdateClosure update) {
    final String msg = "Removing update callback";
    queueRunnable(msg, CommandType.Data, new Runnable() {
      @Override
      public void run() {
        mRenderer.removeUpdateCallback(update);
      }
    });
  }

  /**
   * Must be called once to register an object manager to the renderer.
   * @param rom
   */
  public<E> void queueAddManager(final RenderManager<E> rom) {
    String msg = "Adding manager: " + rom;
    queueRunnable(msg, CommandType.Data, new Runnable() { public void run() {
      mRenderer.addObjectManager(rom.mManager);
    }});
  }

  public void waitUntilFinished() {
    final ConditionVariable cv = new ConditionVariable();
    String msg = "Waiting until operations have finished";
    queueRunnable(msg, CommandType.Synchronization, new Runnable() { public void run() {
      cv.open();
    }});
    cv.block();
  }

  abstract protected EventQueuer getQueuer();

  protected void queueRunnable(String msg, final CommandType type, final Runnable r) {
    EventQueuer queuer = getQueuer();
    String fullMessage = toString() + " - " + msg;
    RendererControllerBase.queueRunnable(queuer, fullMessage, type, r);
  }

  protected static void queueRunnable(EventQueuer queuer, final String msg,
                                      final CommandType type, final Runnable r) {
    // If we're supposed to log something, then wrap the runnable with the
    // appropriate logging statements.  Otherwise, just queue it.
    if (SHOULD_LOG_QUEUE || SHOULD_LOG_RUN || SHOULD_LOG_FINISH) {
      logQueue(msg, type);
      queuer.queueEvent(new Runnable() { public void run() {
        logRun(msg, type);
        r.run();
        logFinish(msg, type);
      }});
    } else {
      queuer.queueEvent(r);
    }
  }

  protected static void logQueue(String description, CommandType type) {
    if (SHOULD_LOG_QUEUE) {
      Log.d("RendererController-" + type.toString(), "Queuing: " + description);
    }
  }

  protected static void logRun(String description, CommandType type) {
    if (SHOULD_LOG_RUN) {
      Log.d("RendererController-" + type.toString(), "Running: " + description);
    }
  }

  protected static void logFinish(String description, CommandType type) {
    if (SHOULD_LOG_FINISH) {
      Log.d("RendererController-" + type.toString(), "Finished: " + description);
    }
  }
}


text:
package gwen.core.features

import gwen.GwenInterpreter
import gwen.core.BaseTest
import gwen.core.GwenOptions
import gwen.core.report.ReportFormat
import gwen.core.status._

import java.io.File

class RulesTest extends BaseTest {

  val interpreter = GwenInterpreter()

  "Scenario rules" should "evaluate without error" in {

    val options = GwenOptions(
      batch = true,
      reportDir = Some(new File("target/report/rules")),
      reportFormats = List(ReportFormat.html, ReportFormat.junit, ReportFormat.json),
      features = List(new File("src/test/features/rules"))
    )

    interpreter.run(options, None) match {
      case _: Passed => // excellent :)
      case Failed(_, error) => error.printStackTrace(); fail(error.getMessage)
      case _ => fail("evaluation expected but got noop")
    }
  }

  "Scenario rules" should "pass --dry-run test" in {

    val options = GwenOptions(
      batch = true,
      reportDir = Some(new File("target/report/rules-dry-run")),
      reportFormats = List(ReportFormat.html, ReportFormat.junit, ReportFormat.json),
      features = List(new File("src/test/features/rules")),
      dryRun = true
    )

    interpreter.run(options, None) match {
      case _: Passed => // excellent :)
      case Failed(_, error) => error.printStackTrace(); fail(error.getMessage)
      case _ => fail("evaluation expected but got noop")
    }
  }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Malpighia 10: 275 (1896)

#### Original name
Gloeosporium caricinum Sacc.

### Remarks
null


text:
package org.xbib.pipeline.element;

import org.xbib.pipeline.PipelineRequest;

import java.net.URI;

public class URIPipelineElement implements PipelineElement<URI>, PipelineRequest {

    private URI uri;

    @Override
    public URI get() {
        return uri;
    }

    @Override
    public URIPipelineElement set(URI uri) {
        this.uri = uri;
        return this;
    }

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


text:
package org.pbrt.openexr.types;

import org.pbrt.openexr.header.Attribute;
import org.pbrt.openexr.util.DataReader;

public class LineOrder extends Attribute {

	public static final byte INCREASING_Y = 0;
	public static final byte DECREASING_Y = 1;
	public static final byte RANDOM_Y = 2;

	public byte value;

	public LineOrder(DataReader data) {
		value = data.readByte();
	}

	@Override
	public String toString() {
		return name + " = " + getType();
	}

	private String getType() {
		switch (value) {
			case INCREASING_Y: return "INCREASING_Y";
			case DECREASING_Y: return "DECREASING_Y";
			case RANDOM_Y: return "RANDOM_Y";
		}
		return "unknown";
	}
}


text:
__author__ = 'abuddenberg'
from gcis_clients import Nca3Client, GcisClient, gcis_stage_auth, gcis_dev_auth
import pickle
import json
import requests
import bs4
from bs4 import BeautifulSoup

nca3_url = 'https://nca3.cicsnc.org'
nca3 = Nca3Client(nca3_url, 'andrew.buddenberg', 'Nz9O^00I', http_basic_user='nca3', http_basic_pass='avl-TSU')

gcis_url = 'https://data-stage.globalchange.gov'
gcis = GcisClient(gcis_url, *gcis_stage_auth)
# gcis = GcisClient('http://data.gcis-dev-front.joss.ucar.edu', *gcis_dev_auth)

def main():
    print gcis.test_login()
    for idx, list_item in enumerate([i for i in sorted(nca3.get_all_captions().json(), key=lambda f: f['Ordinal']) if i['Ordinal'] and i['Metadata URI'] and i['Caption']]):
        ordinal = list_item['Ordinal']
        gcis_fig_id = list_item['Metadata URI'].split('/')[-1]

        stripped_caption = strip_tags(list_item['Caption']['value'])

        fig = gcis.get_figure('nca3', gcis_fig_id)
        fig.caption = stripped_caption

        # print idx, list_item
        # print stripped_caption
        #Just to be safe...
        fig.contributors = []
        print gcis.update_figure('nca3', fig.chapter_identifier, fig, skip_images=True)

def strip_tags(caption):
    soup = BeautifulSoup(caption)

    for t in soup.find_all(name=lambda t: t.name not in ['tbib', 'sup', 'sub']):
        t.unwrap()

    return str(soup).strip()

def get_gcis_chapters():
    gcis_all_chapters = requests.get('{b}/report/nca3/chapter.json'.format(b=gcis_url), params={'all': 1}, verify=False).json()
    chapter_map = {c['identifier']: c for c in gcis_all_chapters}

    with open('chapter_map.pk1', 'wb') as fout:
        pickle.dump(chapter_map, fout)

    return pickle.load(open('chapter_map.pk1'))

def get_all_gcis_figures():
    gcis_all_figs = {}
    for f in gcis.get_figure_listing('nca3'):
        chapter_num = get_gcis_chapters()[f.chapter_identifier]['number']
        # print f.chapter_identifier, chapter_num, f.ordinal

        f.figure_num = '{0}.{1}'.format(chapter_num, f.ordinal)
        gcis_all_figs[f.figure_num] = f

    with open('fig_map.pk1', 'wb') as fout:
        pickle.dump(gcis_all_figs, fout)

    gcis_all_figs = pickle.load(open('fig_map.pk1'))
    return gcis_all_figs

def populate_uris_in_drupal():
    gcis_all_figs = get_all_gcis_figures()

    for list_item in sorted(nca3.get_all_captions().json(), key=lambda f: f['Ordinal']):
        nid = list_item['nid']
        ordinal = list_item['Ordinal']
        graphic_type = list_item['Graphic Type']

        if ordinal and ordinal in gcis_all_figs and graphic_type == 'Figure':
            print 'Found: ', graphic_type, ordinal, gcis_all_figs[ordinal].uri
            # nca3_fig = nca3.get_figure(nid)
            # print nca3_fig

            uri_frag = {
                'und': [
                    {
                        'value': gcis_all_figs[ordinal].uri[1:],
                        'format': None,
                        'safe_value': gcis_all_figs[ordinal].uri[1:]
                    }
                ]
            }
            # nca3_fig['field_metadata_uri'] = uri_frag

            resp = nca3.update_figure(nid, {'field_metadata_uri': uri_frag})
            print resp.status_code, resp.text
            print ''

        else:
            print '***NO URI FOUND***', graphic_type, ordinal

main()


text:
<?php

namespace App\Providers;

use App\Credentials;
use Illuminate\Contracts\View\Factory as View;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
use SebastianBergmann\Diff\Differ;

/**
 * This is the credentials service provider class.
 *
 * @author Graham Campbell <graham@mineuk.com>
 */
class CredentialsServiceProvider extends ServiceProvider
{
    /**
     * Boot the service provider.
     *
     * @return void
     */
    public function boot()
    {
        $this->setupPackage();

        $this->setupBlade($this->app->view);

        $this->setupRoutes($this->app->router);
    }

    /**
     * Setup the package.
     *
     * @return void
     */
    protected function setupPackage()
    {
        $configuration = realpath(__DIR__.'/../../config/credentials.php');
        $migrations = realpath(__DIR__.'/../migrations');

        $this->publishes([
            $configuration => config_path('credentials.php'),
            $migrations    => base_path('database/migrations'),
        ]);

        $this->mergeConfigFrom($configuration, 'credentials');

        $this->loadViewsFrom(realpath(__DIR__.'/../views'), 'credentials');
    }

    /**
     * Setup the blade compiler class.
     *
     * @param \Illuminate\Contracts\View\Factory $view
     *
     * @return void
     */
    protected function setupBlade(View $view)
    {
        $blade = $view->getEngineResolver()->resolve('blade')->getCompiler();

        $blade->extend(function ($value, $compiler) {
            $pattern = $compiler->createMatcher('auth');
            $replace = '$1<?php if (\App\Facades\Credentials::check() && \App\Facades\Credentials::hasAccess$2): ?>';

            return preg_replace($pattern, $replace, $value);
        });

        $blade->extend(function ($value, $compiler) {
            $pattern = $compiler->createPlainMatcher('endauth');
            $replace = '$1<?php endif; ?>$2';

            return preg_replace($pattern, $replace, $value);
        });
    }

    /**
     * Setup the routes.
     *
     * @param \Illuminate\Routing\Router $router
     *
     * @return void
     */
    public function setupRoutes(Router $router)
    {
        require __DIR__.'/../Http/filters.php';

        $router->group(['namespace' => 'App\Http\Controllers'], function (Router $router) {
            require __DIR__.'/../Http/routes.php';
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerDiffer();
        $this->registerRevisionRepository();
        $this->registerUserRepository();
        $this->registerGroupRepository();
        $this->registerCredentials();

        $this->registerAccountController();
        $this->registerLoginController();
        $this->registerRegistrationController();
        $this->registerResetController();
        $this->registerActivationController();
        $this->registerUserController();
    }

    /**
     * Register the differ class.
     *
     * @return void
     */
    protected function registerDiffer()
    {
        $this->app->singleton('differ', function ($app) {
            return new Differ();
        });

        $this->app->alias('differ', 'SebastianBergmann\Diff\Differ');
    }

    /**
     * Register the revision repository class.
     *
     * @return void
     */
    protected function registerRevisionRepository()
    {
        $this->app->singleton('revisionrepository', function ($app) {
            $model = $app['config']['credentials.revision'];
            $revision = new $model();

            $validator = $app['validator'];

            return new \App\Repositories\RevisionRepository($revision, $validator);
        });

        $this->app->alias('revisionrepository', 'App\Repositories\RevisionRepository');
    }

    /**
     * Register the user repository class.
     *
     * @return void
     */
    protected function registerUserRepository()
    {
        $this->app->singleton('userrepository', function ($app) {
            $model = $app['config']['sentry.users.model'];
            $user = new $model();

            $validator = $app['validator'];

            return new \App\Repositories\UserRepository($user, $validator);
        });

        $this->app->alias('userrepository', 'App\Repositories\UserRepository');
    }

    /**
     * Register the group repository class.
     *
     * @return void
     */
    protected function registerGroupRepository()
    {
        $this->app->singleton('grouprepository', function ($app) {
            $model = $app['config']['sentry.groups.model'];
            $group = new $model();

            $validator = $app['validator'];

            return new \App\Repositories\GroupRepository($group, $validator);
        });

        $this->app->alias('grouprepository', 'App\Repositories\GroupRepository');
    }

    /**
     * Register the credentials class.
     *
     * @return void
     */
    protected function registerCredentials()
    {
        $this->app->singleton('credentials', function ($app) {
            $sentry = $app['sentry'];
            $decorator = $app->make('McCool\LaravelAutoPresenter\PresenterDecorator');

            return new Credentials($sentry, $decorator);
        });

        $this->app->alias('credentials', 'App\Credentials');
    }

    /**
     * Register the account controller class.
     *
     * @return void
     */
    protected function registerAccountController()
    {
        $this->app->bind('App\Http\Controllers\AccountController', function ($app) {
            return new \App\Http\Controllers\AccountController();
        });
    }

    /**
     * Register the login controller class.
     *
     * @return void
     */
    protected function registerLoginController()
    {
        $this->app->bind('App\Http\Controllers\LoginController', function ($app) {
            $throttler = $app['throttle']->get($app['request'], 10, 10);

            return new \App\Http\Controllers\LoginController($throttler);
        });
    }

    /**
     * Register the registration controller class.
     *
     * @return void
     */
    protected function registerRegistrationController()
    {
        $this->app->bind('App\Http\Controllers\RegistrationController', function ($app) {
            $throttler = $app['throttle']->get($app['request'], 5, 30);

            return new \App\Http\Controllers\RegistrationController($throttler);
        });
    }

    /**
     * Register the reset controller class.
     *
     * @return void
     */
    protected function registerResetController()
    {
        $this->app->bind('App\Http\Controllers\ResetController', function ($app) {
            $throttler = $app['throttle']->get($app['request'], 5, 30);

            return new \App\Http\Controllers\ResetController($throttler);
        });
    }

    /**
     * Register the resend controller class.
     *
     * @return void
     */
    protected function registerActivationController()
    {
        $this->app->bind('App\Http\Controllers\ActivationController', function ($app) {
            $throttler = $app['throttle']->get($app['request'], 5, 30);

            return new \App\Http\Controllers\ActivationController($throttler);
        });
    }

    /**
     * Register the user controller class.
     *
     * @return void
     */
    protected function registerUserController()
    {
        $this->app->bind('App\Http\Controllers\UserController', function ($app) {
            return new \App\Http\Controllers\UserController();
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return string[]
     */
    public function provides()
    {
        return [
            'differ',
            'revisionrepository',
            'userrepository',
            'grouprepository',
            'credentials',
        ];
    }
}


text:
import Queue
import time
import threading

from django.core.cache import cache
from django.db import models
from django.http import HttpResponseForbidden

from djutils.decorators import async, memoize, throttle, cached_for_model
from djutils.test import RequestFactoryTestCase, TestCase
from djutils.tests.models import Simple

class ThrottleDecoratorTestCase(RequestFactoryTestCase):
    def test_throttle_decorator(self):
        get_request = self.request_factory.get('/')
        post_request = self.request_factory.post('/')

        get_request.META['REMOTE_ADDR'] = '127.0.0.1'
        post_request.META['REMOTE_ADDR'] = '127.0.0.1'

        # test first with no args
        @throttle
        def test_view(request, some_field):
            return some_field

        ten_gets = [test_view(get_request, 'test') for i in range(10)]
        self.assertEqual(['test'] * 10, ten_gets)

        ten_posts = [test_view(post_request, 'test') for i in range(10)]
        self.assertNotEqual(['test'] * 10, ten_posts)

        first_three, denied = ten_posts[:3], ten_posts[3:]
        self.assertEqual(['test'] * 3, first_three)
        self.assertTrue(all(isinstance(r, HttpResponseForbidden) for r in denied))

        cache.delete('127.0.0.1')

        # test throttle with some args now
        @throttle(('GET', 'POST'), 5)
        def test_view(request, some_field):
            return some_field

        ten_gets = [test_view(get_request, 'test') for i in range(10)]
        self.assertNotEqual(['test'] * 10, ten_gets)

        first_five, denied = ten_gets[:5], ten_gets[5:]
        self.assertEqual(['test'] * 5, first_five)
        self.assertTrue(all(isinstance(r, HttpResponseForbidden) for r in denied))

        cache.delete('127.0.0.1')

        ten_posts = [test_view(post_request, 'test') for i in range(10)]
        self.assertNotEqual(['test'] * 10, ten_posts)

        first_five, denied = ten_posts[:5], ten_posts[5:]
        self.assertEqual(['test'] * 5, first_five)
        self.assertTrue(all(isinstance(r, HttpResponseForbidden) for r in denied))

class DelayTestCase(TestCase):
    def test_delay_decorator(self):
        values_queue = Queue.Queue()
        write_lock = threading.Lock()

        @async
        def add_value(q, value):
            write_lock.acquire()
            values_queue.put(value)
            write_lock.release()

        write_lock.acquire()
        add_value(values_queue, 'test')
        self.assertEqual(values_queue.qsize(), 0)

        write_lock.release()
        time.sleep(.05) # <- give the worker a moment
        self.assertEqual(values_queue.qsize(), 1)

        self.assertEqual(values_queue.get(), 'test')

class MemoizeTestCase(TestCase):
    def test_memoize_decorator(self):
        @memoize
        def test_func(a):
            return a

        self.assertEqual(test_func('test'), 'test')

        test_func._memoize_cache[(('test',), ())] = 'from cache'

        self.assertEqual(test_func('test'), 'from cache')
        self.assertEqual(test_func('Test'), 'Test')

class CachedForModelTestCase(TestCase):
    def setUp(self):
        cache._cache = {}

    def test_cached_for_model_decorator(self):
        instance = Simple.objects.create(slug='test')

        self.assertEqual(instance.get_cached_data('some arg'), 'test')

        instance.slug = 'new'

        self.assertEqual(instance.get_cached_data('some arg'), 'test')
        self.assertEqual(instance.get_cached_data('another arg'), 'new')
        self.assertEqual(instance.get_cached_data('some arg'), 'test')


text:
@interface SetCard : Card

+ (NSArray *)validColors;
+ (NSArray *)validSymbols;
+ (NSArray *)validShadings;
+ (NSUInteger)maxNumber;

@property (strong, nonatomic) NSString *color;
@property (strong, nonatomic) NSString *symbol;
@property (strong, nonatomic) NSString *shading;
@property (nonatomic) NSUInteger number;

@end


text:
'use strict';

/* Directives */

angular.module('adocApp.directives', [])
  .directive('treeView', ['$compile','Doc', function($compile,Doc) {
  	return {
  		restrict: 'AE',
  		link: function(scope,element,attrs) {
        if(attrs.id) {
          scope.doc = Doc.get({id: attrs.id});
        }
        else {
          var doc = {children: scope.docs};
          scope.doc = doc;
        }
  			scope.expand = scope.expand || function(doc) {
          doc.expanded = true;
          if(!doc.loaded) {
            doc.loaded = true;
            var html = $compile('

')(scope.$new());
            var child = $("#tree\\."+doc.id).append(html);
          }
  			}
  			scope.collapse = scope.collapse || function(doc) {
  				doc.expanded = false;
  			}
  			var template =
  			'
' +
  				'
' +
    				'
' +
              '' +
              '' +
    				  '' +
  				    '{{doc.name}}' +
				    '
' +
            '

' +
          '
' +
        '
'

        element.html('').append($compile(template)(scope));
  		}
  	};
  }])
  .directive('dragDrop',[function() {
    return {
      link: function(scope,element,attrs) {
        jQuery.event.props.push("dataTransfer");

        function noDefault(event) {
          if(event.preventDefault)
            event.preventDefault();
          //if(event.preventPropogation)
          //  event.preventPropogation();
        }

        function dragover(event) {
          event.dataTransfer.dropEffect = 'copy';
          noDefault(event);
        }

        function drop(event) {
          noDefault(event);
          scope.file = event.dataTransfer.files[0];
          scope.$apply();
        }

        element.bind('drop',drop);
        element.bind('dragover',dragover);
        element.bind('dragcenter',dragover);
      }
    }
  }]);


text:
.. _readers.geowave:

readers.geowave
===============================================================================

.. index:: GeoWave

The **GeoWave reader** uses `GeoWave`_ to read from Accumulo.  GeoWave entries
are stored using `EPSG:4326 <http://epsg.io/4326/>`__.  Instructions for
configuring the GeoWave plugin can be found `here`_.

Example
-------

.. code-block:: json

    {
      "pipeline":[
        {
          "type":"readers.geowave",
          "zookeeper_url":"zookeeper1:2181,zookeeper2:2181,zookeeper3:2181",
          "instance_name":"GeoWave",
          "username":"user",
          "password":"pass",
          "table_namespace":"PDAL_Table",
          "feature_type_name":"PDAL_Point",
          "data_adapter":"FeatureCollectionDataAdapter",
          "points_per_entry":"5000u",
          "bounds":"([0,1000000],[0,1000000],[0,100])",
          "filename":"./pdal/test/data/autzen/autzen.jpg"
        },
        {
          "type":"writers.text",
          "filename":"outputfile.txt"
        }
      ]
    }

Options
-------

zookeeper_url
  The comma-delimited URLs for all zookeeper servers, this will be directly used to instantiate a ZookeeperInstance. [Required]

instance_name
  the zookeeper instance name, this will be directly used to instantiate a ZookeeperInstance. [Required]

username
  The username for the account to establish an Accumulo connector. [Required]

password
  The password for the account to establish an Accumulo connector. [Required]

table_namespace
  The table name to be used when interacting with GeoWave. [Required]

feature_type_name
  The feature type name to be used when ineracting GeoWave. [Default: PDAL_Point]

data_adapter
  FeatureCollectionDataAdapter stores multiple points per Accumulo entry. FeatureDataAdapter stores a single point per Accumulo entry. [Default: FeatureCollectionDataAdapter]

points_per_entry
  Sets the maximum number of points per Accumulo entry when using FeatureCollectionDataAdapter. [Default: 5000u]

bounds
  The extent of the bounding rectangle to use to query points, expressed as a string, eg: "([xmin,xmax],[ymin,ymax],[zmin,zmax])". [Default: unit cube]

.. _GeoWave: https://ngageoint.github.io/geowave/
.. _here: https://ngageoint.github.io/geowave/documentation.html#jace-jni-proxies-2


text:
'use strict';

let awsParamStore = require( '..'  /* 'aws-param-store' */ );

try {

    let parameters = awsParamStore.getParameterSync( '/whatever/test/getParameter', { region: 'us-east-1' } );

    console.log( parameters );
}
catch( err ) {

    console.log( err );
}


text:
import Expression from '../Expression';

export default class RegExpLiteral extends Expression {
    constructor(childNodes) {
        super('RegExpLiteral', childNodes);
    }

    _acceptChildren(children) {
        children.assertToken('RegularExpression');
        let pattern = children.currentElement.value.pattern;
        let flags = children.currentElement.value.flags;
        let extra = {
            rawValue: undefined,
            raw: children.currentElement.getSourceCode(),
        };

        children.moveNext();
        children.assertEnd();

        this.extra = extra;
        this.pattern = pattern;
        this.flags = flags;
    }
}


text:
<?php

namespace CommerceSignals;

use CURLFile;

class AudienceFile extends Resource {

  /**
   * Attributes can be an assoc array or
   * an object, if it's an object we pull
   * out the properties in to an array
   */
  public function __construct($attributes) {
    if (is_object($attributes)) {
      $attributes = get_object_vars($attributes);
    }

    foreach($attributes as $name => $value) {
      $this->__set($name, $value);
    }
  }

  /**
   * Magic method for setting generic attributes
   */
  public function __set($name, $value) {
    if ($name === 'file') {
      $value = new CURLFile($value, 'image/jpeg');
    }

    $this->attributes[$name] = $value;
  }
}


text:
package com.ylp.date.util;

import java.util.Collection;

public final class CollectionTool {
	public static final boolean checkNull(Collection co) {
		return co == null || co.isEmpty();
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>me.yumin</groupId>
    <artifactId>koubei-mongo</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <description>an ORM solution for MongoDB</description>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
    <dependencies>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.12.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring</artifactId>
            <version>2.5.6.SEC03</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.openjdk.jmh</groupId>
            <artifactId>jmh-core</artifactId>
            <version>1.4.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
<?php

namespace crm\mastercrm\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use crm\mastercrm\models\DraftPlanHeader;

/**
 * DraftPlanHeaderSearch represents the model behind the search form about `lukisongroup\master\models\DraftPlanHeader`.
 */
class DraftPlanHeaderSearch extends DraftPlanHeader
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ID', 'SCDL_GROUP', 'STATUS', 'STT_UBAH'], 'integer'],
            [['TGL', 'NOTE', 'USER_ID', 'CREATE_BY', 'CREATE_AT', 'UPDATE_BY', 'UPDATE_AT'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = DraftPlanHeader::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'ID' => $this->ID,
            'TGL' => $this->TGL,
            'SCDL_GROUP' => $this->SCDL_GROUP,
            'STATUS' => $this->STATUS,
            'CREATE_AT' => $this->CREATE_AT,
            'STT_UBAH' => $this->STT_UBAH,
            'UPDATE_AT' => $this->UPDATE_AT,
        ]);

        $query->andFilterWhere(['like', 'NOTE', $this->NOTE])
            ->andFilterWhere(['like', 'USER_ID', $this->USER_ID])
            ->andFilterWhere(['like', 'CREATE_BY', $this->CREATE_BY])
            ->andFilterWhere(['like', 'UPDATE_BY', $this->UPDATE_BY]);

        return $dataProvider;
    }
}


text:
<!DOCTYPE html>

    <title>scrap tests</title>
    <link href="vendor/mocha.css" rel="stylesheet"/>


text:
import DS from 'ember-data';
import BackboneElement from 'ember-fhir/models/backbone-element';

const { belongsTo } = DS;

export default BackboneElement.extend({
  itemCodeableConcept: belongsTo('codeable-concept', { async: false }),
  itemReference: belongsTo('reference', { async: false }),
  amount: belongsTo('quantity', { async: false })
});


text:
package io.skysail.server.app.hive2hive.test;

import java.io.*;
import java.net.InetAddress;
import java.nio.file.*;

import net.engio.mbassy.listener.*;

import org.apache.commons.io.FileUtils;
import org.hive2hive.core.api.H2HNode;
import org.hive2hive.core.api.configs.*;
import org.hive2hive.core.api.interfaces.*;
import org.hive2hive.core.events.framework.interfaces.IFileEventListener;
import org.hive2hive.core.events.framework.interfaces.file.*;
import org.hive2hive.core.model.PermissionType;
import org.hive2hive.core.security.UserCredentials;
import org.hive2hive.processframework.interfaces.IProcessComponent;
import org.junit.*;

public class HiveTest {

    private IH2HNode peerNode;

    @Test
    public void test_createInitial() throws Exception {
        setUpInitialNetwork();
    }

    @Test
    public void joining_existing_p2p_network() throws Exception {
        IFileConfiguration fileConfig = setUpInitialNetwork();

        INetworkConfiguration netConfig2 = NetworkConfiguration.create("second", InetAddress.getByName("127.0.0.1"));
        IH2HNode peerNode2 = H2HNode.createNode(fileConfig);
        peerNode2.connect(netConfig2);
    }

    @Test
    public void testName2() throws Exception {
        IFileConfiguration fileConfig = setUpInitialNetwork();
        IUserManager userManager = peerNode.getUserManager();

        UserCredentials credentials = new UserCredentials("userId", "password", "pin");
        Path rootDirectory = Paths.get("/Users/carsten/shared/aerofs/books/iText");

        if (!userManager.isRegistered(credentials.getUserId())) {
           userManager.createRegisterProcess(credentials);//.await();
        }
        //userManager.createLoginProcess(credentials, rootDirectory).await();
    }

    @Test
    public void testName3() throws Exception {
     // Create a node and open a new overlay network
        IH2HNode node = H2HNode.createNode(FileConfiguration.createDefault());
        node.connect(NetworkConfiguration.createInitial());

        // The register functionality is in the user manager API
        IUserManager userManager = node.getUserManager();

        // Create user credentials to register a new user 'Alice'
        UserCredentials alice = new UserCredentials("Alice", "very-secret-password", "secret-pin");

        // Create a new register process and start it (blocking)
        IProcessComponent<Void> registerAlice = userManager.createRegisterProcess(alice);
        registerAlice.execute();

        // Check if Alice is now registered
        boolean aliceRegistered = userManager.isRegistered("Alice");
        System.out.println("Alice is registered: " + aliceRegistered);

        // Let's login to Alice's user account (blocking)
        IProcessComponent<Void> loginAlice = userManager.createLoginProcess(alice, new ExampleFileAgent());
        loginAlice.execute();

        // Check if Alice is now logged in
        System.out.println("Alice is logged in: " + userManager.isLoggedIn());
    }

    @Test
    public void testName4() throws Exception {
        IFileConfiguration fileConfiguration = FileConfiguration.createDefault();

        // Initialize several nodes (not connected yet)
        IH2HNode node1 = H2HNode.createNode(fileConfiguration);
        IH2HNode node2 = H2HNode.createNode(fileConfiguration);
        IH2HNode node3 = H2HNode.createNode(fileConfiguration);
        IH2HNode node4 = H2HNode.createNode(fileConfiguration);

        // Create a new P2P network at the first (initial) peer
        node1.connect(NetworkConfiguration.createInitial());

        // Connect the 2nd peer to the network. This peer bootstraps to node1 running at the local host
        NetworkConfiguration node2Conf = NetworkConfiguration.create(InetAddress.getLocalHost());
        node2.connect(node2Conf);

        // The network configuration builder allows you to configure more details
        // here we set a custom (non-random) node id and a custom port that the node 3 binds to
        NetworkConfiguration node3Conf = NetworkConfiguration.create(InetAddress.getLocalHost()).setPort(4777)
                .setNodeId("node3");
        node3.connect(node3Conf);

        // Nodes can bootstrap to any of the connected peers. Therefore, we set that node4 should connect to
        // node3 to become a part of the P2P network
        NetworkConfiguration node4Conf = NetworkConfiguration.create(InetAddress.getLocalHost()).setBootstrapPort(4777);
        node4.connect(node4Conf);

        // We can test the connection status of these nodes
        System.out.println("Node 1 is connected: " + node1.isConnected());
        System.out.println("Node 2 is connected: " + node2.isConnected());
        System.out.println("Node 3 is connected: " + node3.isConnected());
        System.out.println("Node 4 is connected: " + node4.isConnected());
    }

 // A Strong reference is necessary if this object is not held in any variable, otherwise GC would clean it
    // and events are not triggered anymore. So keep either a reference to this listener object or add the
    // strong reference annotation.
    @Listener(references = References.Strong)
    private static class ExampleEventListener implements IFileEventListener {

        private final IFileManager fileManager;

        public ExampleEventListener(IFileManager fileManager) {
            this.fileManager = fileManager;
        }

        @Override
        @Handler
        public void onFileAdd(IFileAddEvent fileEvent) {
            System.out.println("File was added: " + fileEvent.getFile().getName());
            try {
                // download the new file
                fileManager.createDownloadProcess(fileEvent.getFile()).execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        @Handler
        public void onFileUpdate(IFileUpdateEvent fileEvent) {
            System.out.println("File was updated: " + fileEvent.getFile().getName());
            try {
                // download the newest version
                fileManager.createDownloadProcess(fileEvent.getFile()).execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        @Handler
        public void onFileDelete(IFileDeleteEvent fileEvent) {
            System.out.println("File was deleted: " + fileEvent.getFile().getName());
            // delete it at the event receiver as well
            fileEvent.getFile().delete();
        }

        @Override
        @Handler
        public void onFileMove(IFileMoveEvent fileEvent) {
            try {
                // Move the file to the new destination if it exists
                if (fileEvent.isFile() && fileEvent.getSrcFile().exists()) {
                    FileUtils.moveFile(fileEvent.getSrcFile(), fileEvent.getDstFile());
                    System.out.println("File was moved from " + fileEvent.getSrcFile() + " to " + fileEvent.getDstFile());
                } else if (fileEvent.isFolder() && fileEvent.getSrcFile().exists()) {
                    FileUtils.moveDirectory(fileEvent.getSrcFile(), fileEvent.getDstFile());
                    System.out.println("Folder was moved from " + fileEvent.getSrcFile() + " to " + fileEvent.getDstFile());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        @Handler
        public void onFileShare(IFileShareEvent fileEvent) {
            System.out.println("File was shared by " + fileEvent.getInvitedBy());
            // Currently, no further actions necessary. The invitation is accepted
            // automatically and 'onFileAdd' is called in an instant.
        }

    }

    @Test
    @Ignore
    public void testName5() throws Exception {
        IFileConfiguration fileConfiguration = FileConfiguration.createDefault();

        // Create two nodes and open a new overlay network
        IH2HNode node1 = H2HNode.createNode(fileConfiguration);
        IH2HNode node2 = H2HNode.createNode(fileConfiguration);
        node1.connect(NetworkConfiguration.createInitial());
        node2.connect(NetworkConfiguration.create(InetAddress.getLocalHost()));

        // These two file agents are used to configure the root directory of the logged in user
        ExampleFileAgent node1FileAgent = new ExampleFileAgent();
        ExampleFileAgent node2FileAgent = new ExampleFileAgent();

        // Register user 'Alice' and login her at node 1 and 2
        UserCredentials alice = new UserCredentials("Alice", "password", "pin");
        node1.getUserManager().createRegisterProcess(alice).execute();
        node1.getUserManager().createLoginProcess(alice, node1FileAgent).execute();
        node2.getUserManager().createLoginProcess(alice, node2FileAgent).execute();

        // In this example, a file event listener is registered at node 2. Therefore, we will listen to events
        // that happen by actions taken by node 1.
        node2.getFileManager().subscribeFileEvents(new ExampleEventListener(node2.getFileManager()));

        // To demonstrate the 'add' event, we will add a new file with node 1
        // Let's create a file and upload it at node 1
        File fileAtNode1 = new File(node1FileAgent.getRoot(), "test-file-event.txt");
        FileUtils.write(fileAtNode1, "Hello"); // add some content
        node1.getFileManager().createAddProcess(fileAtNode1).execute();

        // Let's trigger a deletion event
        fileAtNode1.delete();
        node1.getFileManager().createDeleteProcess(fileAtNode1).execute();
    }

    @Test
    @Ignore
    public void testName6() throws Exception {
        IFileConfiguration fileConfiguration = FileConfiguration.createDefault();

        // Create two nodes and open a new overlay network
        IH2HNode node1 = H2HNode.createNode(fileConfiguration);
        IH2HNode node2 = H2HNode.createNode(fileConfiguration);
        node1.connect(NetworkConfiguration.createInitial());
        node2.connect(NetworkConfiguration.create(InetAddress.getLocalHost()));

        // These two file agents are used to configure the root directory of the logged in users
        ExampleFileAgent node1FileAgent = new ExampleFileAgent();
        ExampleFileAgent node2FileAgent = new ExampleFileAgent();

        // Register and login user 'Alice' at node 1
        UserCredentials alice = new UserCredentials("Alice", "password", "pin");
        node1.getUserManager().createRegisterProcess(alice).execute();
        node1.getUserManager().createLoginProcess(alice, node1FileAgent).execute();

        // Also login user 'Alice' at node 2
        node2.getUserManager().createLoginProcess(alice, node2FileAgent).execute();

        // All file management operations are located at the file manager. Here we get the file managers of
        // each peer alice is connected to.
        IFileManager fileManager1 = node1.getFileManager(); // for node 1
        IFileManager fileManager2 = node2.getFileManager(); // for node 2

        // Let's create a file and upload it at node 1
        File fileAtNode1 = new File(node1FileAgent.getRoot(), "test-file.txt");
        FileUtils.write(fileAtNode1, "Hello"); // add some content
        fileManager1.createAddProcess(fileAtNode1).execute();

        // Normally, the node 2 would be notified about the new file through the event bus (shown in another
        // example). However, we just know that the file exists in the network and can download it at node 2.
        // This is only possible because Alice is logged in into node 2 as well.
        File fileAtNode2 = new File(node2FileAgent.getRoot(), "test-file.txt");
        // this file does not exist yet (as we did not start the download process yet)
        System.out.println("Existence of the file prior to download: " + fileAtNode2.exists());
        fileManager2.createDownloadProcess(fileAtNode2).execute();

        // We can now re-check whether the file exists or not
        System.out.println("Existence of the file after download: " + fileAtNode2.exists());
        System.out.println("Content of the first version at node 2: " + FileUtils.readFileToString(fileAtNode2));

        // Now, let's modify the file at node 2 and re-upload a new version of it
        FileUtils.write(fileAtNode2, " World!", true); // append the text
        fileManager2.createUpdateProcess(fileAtNode2).execute();

        // The file has now updated, therefore we should download the new version at node 1
        fileManager1.createDownloadProcess(fileAtNode1).execute();
        System.out.println("Content of the second version at node 1: " + FileUtils.readFileToString(fileAtNode1));

    }

    @Test
    @Ignore
    public void sharetest() throws Exception {
        IFileConfiguration fileConfiguration = FileConfiguration.createDefault();

        // Create two nodes and open a new overlay network
        IH2HNode node1 = H2HNode.createNode(fileConfiguration);
        IH2HNode node2 = H2HNode.createNode(fileConfiguration);
        node1.connect(NetworkConfiguration.createInitial());
        node2.connect(NetworkConfiguration.create(InetAddress.getLocalHost()));

        // These two file agents are used to configure the root directory of the logged in users
        ExampleFileAgent node1FileAgent = new ExampleFileAgent();
        ExampleFileAgent node2FileAgent = new ExampleFileAgent();

        // Register and login user 'Alice' at node 1
        UserCredentials alice = new UserCredentials("Alice", "password", "pin");
        node1.getUserManager().createRegisterProcess(alice).execute();
        node1.getUserManager().createLoginProcess(alice, node1FileAgent).execute();

        // Register and login user 'Bob' at node 2
        UserCredentials bob = new UserCredentials("Bob", "password", "pin");
        node2.getUserManager().createRegisterProcess(bob).execute();
        node2.getUserManager().createLoginProcess(bob, node2FileAgent).execute();

        // Let's create a folder at Alice and upload it
        IFileManager fileManager1 = node1.getFileManager(); // The file management of Alice's peer
        File folderAtAlice = new File(node1FileAgent.getRoot(), "shared-folder");
        folderAtAlice.mkdirs();
        fileManager1.createAddProcess(folderAtAlice).execute();

        // Let's share the folder with Bob giving him write permission
        fileManager1.createShareProcess(folderAtAlice, "Bob", PermissionType.WRITE).execute();

        // Wait some time in order to get the file share event propagated to Bob
        System.out.println("Alice shared a folder with Bob. We'll wait some time for its propagation...");
        Thread.sleep(20000);

        // Bob can now 'download' the folder (yes, sounds a little bit silly...)
        IFileManager fileManager2 = node2.getFileManager(); // The file management of Bob's peer
        File folderAtBob = new File(node2FileAgent.getRoot(), "shared-folder");
        fileManager2.createDownloadProcess(folderAtBob).execute();

        // Bob could for example upload a new file to the shared folder
        File fileAtBob = new File(folderAtBob, "shared-file.txt");
        FileUtils.write(fileAtBob, "This is a shared file of Alice and Bob");
        fileManager2.createAddProcess(fileAtBob).execute();

        // Wait some time in order to get the file share event propagated to Bob
        System.out.println("Waiting that Alice sees the file from Bob...");
        Thread.sleep(20000);

        // Alice now can obtain the shared file
        File fileAtAlice = new File(folderAtAlice, "shared-file.txt");
        fileManager1.createDownloadProcess(fileAtAlice).execute();
        System.out.println("Content of the file in the shared folder at Alice: " + FileUtils.readFileToString(fileAtAlice));

    }

    private IFileConfiguration setUpInitialNetwork() {
        INetworkConfiguration netConfig = NetworkConfiguration.createInitial("first");
        IFileConfiguration fileConfig = FileConfiguration.createDefault();

        peerNode = H2HNode.createNode(fileConfig);
        peerNode.connect(netConfig);
        return fileConfig;
    }

}


text:
layout: "aws"
page_title: "AWS: aws_autoscaling_schedule"
sidebar_current: "docs-aws-resource-autoscaling-schedule"
description: |-
  Provides an AutoScaling Schedule resource.
---

# aws\_autoscaling\_schedule

Provides an AutoScaling Schedule resource.

## Example Usage
```
resource "aws_autoscaling_group" "foobar" {
    availability_zones = ["us-west-2a"]
    name = "terraform-test-foobar5"
    max_size = 1
    min_size = 1
    health_check_grace_period = 300
    health_check_type = "ELB"
    force_delete = true
    termination_policies = ["OldestInstance"]
}

resource "aws_autoscaling_schedule" "foobar" {
    scheduled_action_name = "foobar"
    min_size = 0
    max_size = 1
    desired_capacity = 0
    start_time = "2016-12-11T18:00:00Z"
    end_time = "2016-12-12T06:00:00Z"
    autoscaling_group_name = "${aws_autoscaling_group.foobar.name}"
}
```

## Argument Reference

The following arguments are supported:

* `autoscaling_group_name` - (Required) The name or Amazon Resource Name (ARN) of the Auto Scaling group.
* `scheduled_action_name` - (Required) The name of this scaling action.
* `start_time` - (Optional) The time for this action to start, in "YYYY-MM-DDThh:mm:ssZ" format in UTC/GMT only (for example, 2014-06-01T00:00:00Z ).
                            If you try to schedule your action in the past, Auto Scaling returns an error message.
* `end_time` - (Optional) The time for this action to end, in "YYYY-MM-DDThh:mm:ssZ" format in UTC/GMT only (for example, 2014-06-01T00:00:00Z ).
                          If you try to schedule your action in the past, Auto Scaling returns an error message.
* `recurrence` - (Optional) The time when recurring future actions will start. Start time is specified by the user following the Unix cron syntax format.
* `min_size` - (Optional) The minimum size for the Auto Scaling group. Default
0.
* `max_size` - (Optional) The maximum size for the Auto Scaling group. Default
0.
* `desired_capacity` - (Optional) The number of EC2 instances that should be running in the group. Default 0.

~> **NOTE:** When `start_time` and `end_time` are specified with `recurrence` , they form the boundaries of when the recurring action will start and stop.

## Attribute Reference
* `arn` - The ARN assigned by AWS to the autoscaling schedule.