text:
package com.mortarnav;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.mortarnav.deps.WithAppDependencies;
import com.mortarnav.stackable.HomeStackable;
import com.mortarnav.view.MyPopup2View;
import com.mortarnav.view.MyPopupView;

import architect.Navigator;
import architect.NavigatorView;
import architect.TransitionsMapping;
import architect.commons.ActivityArchitector;
import architect.commons.Architected;
import architect.robot.DaggerService;
import architect.transition.BottomAppearTransition;
import architect.transition.Config;
import architect.transition.FadeModalTransition;
import architect.transition.LateralViewTransition;
import autodagger.AutoComponent;
import autodagger.AutoInjector;
import butterknife.Bind;
import butterknife.ButterKnife;
import mortar.MortarScope;
import mortar.bundler.BundleServiceRunner;

/**
 * Root activity
 *
 * @author Lukasz Piliszczuk - lukasz.pili@gmail.com
 */
@AutoComponent(
        dependencies = App.class,
        superinterfaces = WithAppDependencies.class
)
@AutoInjector
@DaggerScope(MainActivity.class)
public class MainActivity extends Activity {

    private MortarScope scope;
    private Navigator navigator;

    @Bind(R.id.navigator_container)
    protected NavigatorView containerView;

    @Override
    public Object getSystemService(String name) {
        if (scope != null && scope.hasService(name)) {
            return scope.getService(name);
        }

        return super.getSystemService(name);
    }

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

        scope = ActivityArchitector.onCreateScope(this, savedInstanceState, new Architected() {
            @Override
            public Navigator createNavigator(MortarScope scope) {
                Navigator navigator = Navigator.create(scope, new Parceler());
                navigator.transitions().register(new TransitionsMapping()
                        .byDefault(new LateralViewTransition(new Config().duration(300)))
                        .show(MyPopupView.class).withTransition(new FadeModalTransition(new Config().duration(250)))
                        .show(MyPopup2View.class).withTransition(new BottomAppearTransition(new Config().duration(250))));
                return navigator;
            }

            @Override
            public void configureScope(MortarScope.Builder builder, MortarScope parentScope) {
                MainActivityComponent component = DaggerMainActivityComponent.builder()
                        .appComponent(parentScope.<AppComponent>getService(DaggerService.SERVICE_NAME))
                        .build();
                component.inject(MainActivity.this);

                builder.withService(DaggerService.SERVICE_NAME, component);
            }
        });

        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        navigator = ActivityArchitector.onCreateNavigator(this, savedInstanceState, containerView, new HomeStackable("Default home path"));
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        navigator.delegate().onNewIntent(intent);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        BundleServiceRunner.getBundleServiceRunner(scope).onSaveInstanceState(outState);
        navigator.delegate().onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
        super.onStart();
        navigator.delegate().onStart();
    }

    @Override
    protected void onStop() {
        navigator.delegate().onStop();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        navigator.delegate().onDestroy();
        navigator = null;

        if (isFinishing() && scope != null) {
            scope.destroy();
            scope = null;
        }

        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (navigator.delegate().onBackPressed()) {
            return;
        }

        super.onBackPressed();
    }
}


text:
package android.support.v17.leanback.streamingapp.presenter;

import android.support.v17.leanback.streamingapp.model.CardRow;
import android.support.v17.leanback.streamingapp.utils.CardListRow;
import android.support.v17.leanback.streamingapp.utils.OldCardListRow;
import android.support.v17.leanback.widget.ListRowPresenter;
import android.support.v17.leanback.widget.Presenter;
import android.support.v17.leanback.widget.PresenterSelector;

public class ShadowRowPresenterSelector extends PresenterSelector {
    private ListRowPresenter mShadowEnabledRowPresenter = new ListRowPresenter();
    private ListRowPresenter mShadowDisabledRowPresenter = new ListRowPresenter();

    public ShadowRowPresenterSelector() {
        mShadowEnabledRowPresenter.setNumRows(1);
        mShadowDisabledRowPresenter.setShadowEnabled(false);
    }

    @Override public Presenter getPresenter(Object item) {
        if (!(item instanceof OldCardListRow)) return mShadowDisabledRowPresenter;
        CardListRow listRow = (CardListRow) item;
        CardRow row = listRow.getCardRow();
        if (row.useShadow()) return mShadowEnabledRowPresenter;
        return mShadowDisabledRowPresenter;
    }

    @Override
    public Presenter[] getPresenters() {
        return new Presenter [] {
                mShadowDisabledRowPresenter,
                mShadowEnabledRowPresenter
        };
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.AutoScaling.Model
{
    ///
    /// Container for the parameters to the DescribePolicies operation.
    /// Describes the policies for the specified Auto Scaling group.
    ///
    ///
    /// <para>
    /// You can specify a maximum number of items to be returned with a single call. If there
    /// are more items to return, the call returns a token. To get the next set of items,
    /// repeat the call with the returned token in the NextToken parameter.
    /// </para>
    ///
    public partial class DescribePoliciesRequest : AmazonAutoScalingRequest
    {
        private string _autoScalingGroupName;
        private int? _maxRecords;
        private string _nextToken;
        private List<string> _policyNames = new List<string>();

        ///
        /// Gets and sets the property AutoScalingGroupName.
        /// <para>
        /// The name of the group.
        /// </para>
        ///
        public string AutoScalingGroupName
        {
            get { return this._autoScalingGroupName; }
            set { this._autoScalingGroupName = value; }
        }

        // Check to see if AutoScalingGroupName property is set
        internal bool IsSetAutoScalingGroupName()
        {
            return this._autoScalingGroupName != null;
        }

        ///
        /// Gets and sets the property MaxRecords.
        /// <para>
        /// The maximum number of items to be returned with each call.
        /// </para>
        ///
        public int MaxRecords
        {
            get { return this._maxRecords.GetValueOrDefault(); }
            set { this._maxRecords = value; }
        }

        // Check to see if MaxRecords property is set
        internal bool IsSetMaxRecords()
        {
            return this._maxRecords.HasValue;
        }

        ///
        /// Gets and sets the property NextToken.
        /// <para>
        /// The token for the next set of items to return. (You received this token from a previous
        /// call.)
        /// </para>
        ///
        public string NextToken
        {
            get { return this._nextToken; }
            set { this._nextToken = value; }
        }

        // Check to see if NextToken property is set
        internal bool IsSetNextToken()
        {
            return this._nextToken != null;
        }

        ///
        /// Gets and sets the property PolicyNames.
        /// <para>
        /// One or more policy names or policy ARNs to be described. If you omit this list, all
        /// policy names are described. If an group name is provided, the results are limited
        /// to that group. This list is limited to 50 items. If you specify an unknown policy
        /// name, it is ignored with no error.
        /// </para>
        ///
        public List<string> PolicyNames
        {
            get { return this._policyNames; }
            set { this._policyNames = value; }
        }

        // Check to see if PolicyNames property is set
        internal bool IsSetPolicyNames()
        {
            return this._policyNames != null && this._policyNames.Count > 0;
        }

    }
}


text:
package com.shinemo.mpush.alloc;

import java.io.IOException;

/**
 * Created by ohun on 16/10/14.
 *
 * @author ohun@live.cn (夜色)
 */
public class AllocServerMainTest {

    public static void main(String[] args) {
        Main.main(args);
    }
}


text:
#include "tensorflow/core/data/dataset_utils.h"
#include "tensorflow/core/data/root_dataset.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/function_handle_cache.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/io/record_writer.h"
#include "tensorflow/core/platform/file_system.h"
#include "tensorflow/core/platform/resource.h"

namespace tensorflow {
namespace data {
namespace experimental {
namespace {

class ToTFRecordOp : public AsyncOpKernel {
 public:
  explicit ToTFRecordOp(OpKernelConstruction* ctx)
      : AsyncOpKernel(ctx),
        background_worker_(ctx->env(), "tf_data_to_tf_record") {}

  template <typename T>
  Status ParseScalarArgument(OpKernelContext* ctx,
                             const StringPiece& argument_name, T* output) {
    const Tensor* argument_t;
    TF_RETURN_IF_ERROR(ctx->input(argument_name, &argument_t));
    if (!TensorShapeUtils::IsScalar(argument_t->shape())) {
      return errors::InvalidArgument(argument_name, " must be a scalar");
    }
    *output = argument_t->scalar<T>()();
    return Status::OK();
  }

  void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override {
    // The call to `iterator->GetNext()` may block and depend on an inter-op
    // thread pool thread, so we issue the call using a background thread.
    background_worker_.Schedule([this, ctx, done = std::move(done)]() {
      OP_REQUIRES_OK_ASYNC(ctx, DoCompute(ctx), done);
      done();
    });
  }

 private:
  Status DoCompute(OpKernelContext* ctx) {
    tensorflow::ResourceTagger tag(kTFDataResourceTag,
                                   ctx->op_kernel().type_string());
    tstring filename;
    TF_RETURN_IF_ERROR(
        ParseScalarArgument<tstring>(ctx, "filename", &filename));
    tstring compression_type;
    TF_RETURN_IF_ERROR(ParseScalarArgument<tstring>(ctx, "compression_type",
                                                    &compression_type));
    std::unique_ptr<WritableFile> file;
    TF_RETURN_IF_ERROR(ctx->env()->NewWritableFile(filename, &file));
    auto writer = absl::make_unique<io::RecordWriter>(
        file.get(),
        io::RecordWriterOptions::CreateRecordWriterOptions(compression_type));

    DatasetBase* dataset;
    TF_RETURN_IF_ERROR(GetDatasetFromVariantTensor(ctx->input(0), &dataset));

    IteratorContext::Params params(ctx);
    FunctionHandleCache function_handle_cache(params.flr);
    params.function_handle_cache = &function_handle_cache;
    ResourceMgr resource_mgr;
    params.resource_mgr = &resource_mgr;
    CancellationManager cancellation_manager(ctx->cancellation_manager());
    params.cancellation_manager = &cancellation_manager;

    IteratorContext iter_ctx(std::move(params));
    DatasetBase* finalized_dataset;
    TF_RETURN_IF_ERROR(FinalizeDataset(ctx, dataset, &finalized_dataset));
    core::ScopedUnref unref(finalized_dataset);

    std::unique_ptr<IteratorBase> iterator;
    TF_RETURN_IF_ERROR(finalized_dataset->MakeIterator(
        &iter_ctx, /*parent=*/nullptr, "ToTFRecordOpIterator", &iterator));

    const int num_output_dtypes = finalized_dataset->output_dtypes().size();
    if (num_output_dtypes != 1) {
      return errors::InvalidArgument(
          "ToTFRecordOp currently only support datasets of 1 single column, ",
          "but got ", num_output_dtypes);
    }
    const DataType dt = finalized_dataset->output_dtypes()[0];
    if (dt != DT_STRING) {
      return errors::InvalidArgument(
          "ToTFRecordOp currently only supports DT_STRING dataypes, but got ",
          DataTypeString(dt));
    }
    std::vector<Tensor> components;
    components.reserve(num_output_dtypes);
    bool end_of_sequence;
    do {
      TF_RETURN_IF_ERROR(
          iterator->GetNext(&iter_ctx, &components, &end_of_sequence));

      if (!end_of_sequence) {
        TF_RETURN_IF_ERROR(
            writer->WriteRecord(components[0].scalar<tstring>()()));
      }
      components.clear();
    } while (!end_of_sequence);
    return Status::OK();
  }

  BackgroundWorker background_worker_;
};

REGISTER_KERNEL_BUILDER(Name("DatasetToTFRecord").Device(DEVICE_CPU),
                        ToTFRecordOp);
REGISTER_KERNEL_BUILDER(
    Name("ExperimentalDatasetToTFRecord").Device(DEVICE_CPU), ToTFRecordOp);

}  // namespace
}  // namespace experimental
}  // namespace data
}  // namespace tensorflow


text:
Using Aldryn FAQ
################

The documentation in these two sections focuses on the basics of content
creation and editing using Aldryn FAQ. It's suitable for non-technical
and technical audiences alike.


text:
package sbtorgpolicies.rules

import cats.kernel.instances.unit._
import cats.instances.list._
import cats.syntax.foldable._
import cats.syntax.validated._
import sbtorgpolicies.exceptions.ValidationException
import sbtorgpolicies.io.FileReader

class FileValidation(fileReader: FileReader = FileReader) {

  def validateFile(inputPath: String, validations: ValidationFunction*): ValidationResult =
    fileReader.getFileContent(inputPath) match {
      case Right(v) => validations.toList.map(_(v)).combineAll
      case Left(e)  => ValidationException(s"Can't read $inputPath", Some(e)).invalidNel
    }
}


text: Plugin to generate timeline view of Gradle build run


text:
@interface MTJSONUtilsTests : SenTestCase
@property (strong, nonatomic) NSDictionary *testDictionary;
@end


text:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
    <TextView android:id="@+id/template_list_item_titleTextView"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:textStyle="bold"
              android:paddingLeft="4dp"
              android:paddingRight="4dp"
              android:text="Template Title" />
    <TextView android:id="@+id/template_list_item_textTextView"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:layout_below="@id/template_list_item_titleTextView"
              android:paddingLeft="4dp"
              android:paddingRight="4dp"
              android:paddingTop="4dp"
              android:text="Crime date" />
</RelativeLayout>


text:
class LogsController < ApplicationController
  def show
    @log = Log.find(params[:job_id])
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background1">
</LinearLayout><!-- From: file:/Users/xiaohan/react-native/TransPal/android/app/src/main/res/layout/launch_screen.xml -->


text:
from flask import Flask

app = Flask(__name__,
            template_folder='../templates')
app.config.from_object('src.settings')


text:
import hashlib
import hmac
import json
import unittest

from django.core.exceptions import ImproperlyConfigured
from django.http import (
    HttpResponseNotAllowed,
    HttpResponseBadRequest,
    JsonResponse
)
from django.test import RequestFactory

from django_github_webhook.views import WebHookView

class TestNoSecretView(unittest.TestCase):

    def setUp(self):
        class NoSecretView(WebHookView):
            pass

        self.factory = RequestFactory()
        self.view = NoSecretView.as_view()

    def test_raises_exception(self):
        #import pudb; pu.db
        request = self.factory.post('/fake')
        with self.assertRaises(ImproperlyConfigured):
            self.view(request)

class TestSimpleView(unittest.TestCase):

    def setUp(self):
        class SimpleView(WebHookView):
            secret = 'foobar'

            def ping(self, payload, request):
                return payload

        self.factory = RequestFactory()
        self.view = SimpleView.as_view()
        self.payload = json.dumps({'success': True})
        self.mac_valid = hmac.new(
            self.view.view_class.secret.encode('utf-8'),
            msg=self.payload.encode('utf-8'),
            digestmod=hashlib.sha1
        )
        self.mac_invalid = hmac.new(
            'malicious'.encode('utf-8'),
            msg=self.payload.encode('utf-8'),
            digestmod=hashlib.sha1
        )

    def test_get(self):
        request = self.factory.get('/fake')
        response = self.view(request)
        self.assertIsInstance(response, HttpResponseNotAllowed)

    def test_post(self):
        request = self.factory.post('/fake')
        response = self.view(request)
        self.assertIsInstance(response, HttpResponseBadRequest)

    def test_valid_signature(self):
        request = self.factory.post(
            '/fake',
            self.payload,
            content_type='application/json',
            HTTP_X_GITHUB_EVENT='ping',
            HTTP_X_HUB_SIGNATURE='sha1={mac}'.format(mac=self.mac_valid.hexdigest())
        )
        response = self.view(request)
        self.assertIsInstance(response, JsonResponse)

    def test_invalid_signature(self):
        request = self.factory.post(
            '/fake',
            self.payload,
            content_type='application/json',
            HTTP_X_GITHUB_EVENT='ping',
            HTTP_X_HUB_SIGNATURE='sha1={mac}'.format(mac=self.mac_invalid.hexdigest())
        )
        response = self.view(request)
        self.assertIsInstance(response, HttpResponseBadRequest)

    def test_no_event(self):
        request = self.factory.post(
            '/fake',
            self.payload,
            content_type='application/json',
            HTTP_X_HUB_SIGNATURE='sha1=x'
        )
        response = self.view(request)
        self.assertIsInstance(response, HttpResponseBadRequest)

    def test_invalid_digest(self):
        request = self.factory.post(
            '/fake',
            self.payload,
            content_type='application/json',
            HTTP_X_GITHUB_EVENT='ping',
            HTTP_X_HUB_SIGNATURE='md5=x'
        )
        response = self.view(request)
        self.assertIsInstance(response, HttpResponseBadRequest)

    def test_event_not_allowed(self):
        request = self.factory.post(
            '/fake',
            self.payload,
            content_type='application/json',
            HTTP_X_GITHUB_EVENT='merge',
            HTTP_X_HUB_SIGNATURE='sha1={mac}'.format(mac=self.mac_valid.hexdigest())
        )
        response = self.view(request)
        self.assertIsInstance(response, HttpResponseBadRequest)

    def test_event_not_supported(self):
        request = self.factory.post(
            '/fake',
            self.payload,
            content_type='application/json',
            HTTP_X_GITHUB_EVENT='push',
            HTTP_X_HUB_SIGNATURE='sha1={mac}'.format(mac=self.mac_valid.hexdigest())
        )
        response = self.view(request)
        self.assertIsInstance(response, HttpResponseBadRequest)


text:
package com.miraclehu.baisibudeqijie.util;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.SurfaceHolder;
import android.view.View;

import java.io.IOException;

/**
 * Created by hasee on 2016/9/22.
 */
public class PlayerManager {
    private MediaPlayer mPlayer;

    private static PlayerManager sManager;

    private PlayerManager() {
        mPlayer = new MediaPlayer();
    }

    private static PlayerManager getInstance() {
        if (sManager == null) {
            synchronized (PlayerManager.class) {
                if (sManager == null) {
                    sManager = new PlayerManager();
                }
            }
        }
        return sManager;
    }

    /**
     * 开始
     */
    private void _start() {
        if (mPlayer != null)
            mPlayer.start();
    }

    /**
     * 暂停
     */
    private void _pause() {
        if (mPlayer != null) {
            if (mPlayer.isPlaying())
                mPlayer.pause();
        }
    }

    /**
     * 停止
     */
    private void _stop() {
        if (mPlayer != null) {
            if (mPlayer.isPlaying()) {
                mPlayer.pause();
                mPlayer.stop();
            }
        }
    }

    /**
     * 释放资源
     */
    private void _release() {
        if (mPlayer != null)
            mPlayer.release();
    }

    private void _setDisplay(SurfaceHolder holder) {
        if (mPlayer != null)
            mPlayer.setDisplay(holder);
    }

    /**
     * 设置数据资源
     */
    private void _setDataUrl(String url) {
        try {
            if (mPlayer != null)
                mPlayer.setDataSource(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 重置
     */
    private void _reset() {
        if (mPlayer != null) {
            if (mPlayer.isPlaying()) {
                _stop();
            }
            mPlayer.reset();
        }
    }

    /**
     * 同步准备
     */
    private void _prepare() {
        try {
            mPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 异步准备
     */
    private void _prepareAsyn() {
        mPlayer.prepareAsync();
    }

    private MediaPlayer getPlayer() {
        return mPlayer;
    }

    // ---------------------------为外界提供的方法----------------------------------
    public static void start() {
        getInstance()._start();
    }

    public static void pause() {
        getInstance()._pause();
    }

    public static void prepare() {
        getInstance()._prepare();
    }

    public static void prepareAsyn() {
        getInstance()._prepareAsyn();
    }

    public static void stop() {
        getInstance()._stop();
    }

    public static void setDataUrl(String url) {
        getInstance()._setDataUrl(url);
    }

    public static void reset() {
        getInstance()._reset();
    }

    public static void release() {
        getInstance()._release();
    }

    public static void setDisplay(SurfaceHolder holder) {
        getInstance()._setDisplay(holder);
    }

    // 为外界提供设置准备监听
    public static void setOnPreparedListener(MediaPlayer.OnPreparedListener listener) {
        getInstance().getPlayer().setOnPreparedListener(listener);
    }

}


text:
{% extends "base.html" %}

{% block js %}

{% endblock %}

{% block css %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/table.css') }}">
{% endblock %}

{% block body %}

Todolist overview

      {% if form.errors %}

Todos should neither be empty nor be longer than 128 characters.

      {% endif %}
      <form action="{{ url_for('main.add_todolist') }}" method=post>
        {{ form.hidden_tag() }}

{{ form.title(class_="u-full-width", placeholder="Enter a title to start a new todolist", value="", maxlength=128) }}

{{ form.submit }}

      </form>

All your todolists

            Todolist title
            # Open
            # Finished
            Created at

          {% for todolist in current_user.todolists %}

              {{ todolist.title }}
              {{ todolist.count_open() }}
              {{ todolist.count_finished() }}
              {{ todolist.created_at|humanize }}

          {% endfor %}

{% endblock %}


text:
<?php

namespace NS\SentinelBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\Groups;
use NS\SecurityBundle\Annotation\Secured;
use NS\SecurityBundle\Annotation\SecuredCondition;
use NS\SentinelBundle\Form\Types\TripleChoice;
use Serializable;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Country
 *
 * @ORM\Table(name="countries")
 * @ORM\Entity(repositoryClass="\NS\SentinelBundle\Repository\CountryRepository")
 * @Secured(conditions={
 *      @SecuredCondition(roles={"ROLE_SUPER_ADMIN"},enabled=false),
 *      @SecuredCondition(roles={"ROLE_REGION"},relation="region",class="NSSentinelBundle:Region"),
 *      @SecuredCondition(roles={"ROLE_COUNTRY","ROLE_RRL_LAB","ROLE_NL_LAB"},field="code"),
 *      @SecuredCondition(roles={"ROLE_SITE","ROLE_LAB"},relation="site",class="NSSentinelBundle:Site"),
 *      })
 * @SuppressWarnings(PHPMD.ShortVariable)
 * @UniqueEntity(fields={"code"})
 */
class Country implements Serializable
{
    /**
     * @var string
     *
     * @ORM\Column(name="code", type="string", length=15)
     * @ORM\Id
     * @Assert\NotBlank(message="This field cannot be blank")
     * @Groups({"api"})
     */
    private $code;

    /**
     * @var boolean
     *
     * @ORM\Column(name="active",type="boolean")
     */
    private $active;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     * @Groups({"api"})
     */
    private $name;

    /**
     * @var TripleChoice
     * @ORM\Column(name="gaviEligible",type="TripleChoice",nullable=true)
     */
    private $gaviEligible;

    /**
     * @var string $hibVaccineIntro
     * @ORM\Column(name="hibVaccineIntro",type="string",nullable=true)
     */
    private $hibVaccineIntro;

    /**
     * @var string $pcvVaccineIntro
     * @ORM\Column(name="pcvVaccineIntro",type="string",nullable=true)
     */
    private $pcvVaccineIntro;

    /**
     * @var string $rvVaccineIntro
     * @ORM\Column(name="rvVaccineIntro",type="string",nullable=true)
     */
    private $rvVaccineIntro;

    /**
     * @var Site
     *
     * @ORM\OneToMany(targetEntity="Site", mappedBy="country")
     */
    private $sites;

    /**
     * @var Region
     *
     * @ORM\ManyToOne(targetEntity="Region",inversedBy="countries")
     * @ORM\JoinColumn(referencedColumnName="code")
     */
    private $region;

    /**
     * @var boolean $tracksPneumonia
     * @ORM\Column(name="tracksPneumonia",type="boolean")
     */
    private $tracksPneumonia = true;

    /**
     * @var boolean $hasReferenceLab
     * @ORM\Column(name="hasReferenceLab",type="boolean")
     */
    private $hasReferenceLab;

    /**
     * @var boolean $hasNationalLab
     * @ORM\Column(name="hasNationalLab",type="boolean")
     */
    private $hasNationalLab;

    /**
     * @var string $language
     * @ORM\Column(name="language",type="string",nullable=true)
     */
    private $language;

    /**
     * @var ReferenceLab $referenceLab
     * @ORM\ManyToOne(targetEntity="ReferenceLab",inversedBy="countries")
     */
    private $referenceLab;

    /**
     * @param string|null $code
     * @param string|null $name
     */
    public function __construct($code = null, $name = null)
    {
        $this->name  = $name;
        $this->code  = $code;
        $this->sites = new ArrayCollection();
    }

    /**
     * @return null|string
     */
    public function __toString()
    {
        return $this->name ?? '';
    }

    /**
     * Set code
     *
     * @param string $code
     * @return Country
     */
    public function setCode($code)
    {
        $this->code = $code;

        return $this;
    }

    /**
     * Get code
     *
     * @return string
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * @return string
     */
    public function getId()
    {
        return $this->code;
    }

    /**
     * @param $id
     * @return Country
     */
    public function setId($id)
    {
        return $this->setCode($id);
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Country
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Add sites
     *
     * @param Site $sites
     *
     * @return Country
     */
    public function addSite(Site $sites)
    {
        $this->sites[] = $sites;

        return $this;
    }

    /**
     * Remove sites
     *
     * @param Site $sites
     */
    public function removeSite(Site $sites)
    {
        $this->sites->removeElement($sites);
    }

    /**
     * Get sites
     *
     * @return Collection
     */
    public function getSites()
    {
        return $this->sites;
    }

    /**
     * Set region
     *
     * @param Region $region
     *
     * @return Country
     */
    public function setRegion(Region $region = null)
    {
        $this->region = $region;

        return $this;
    }

    /**
     * Get region
     *
     * @return Region
     */
    public function getRegion()
    {
        return $this->region;
    }

    /**
     * Set active
     *
     * @param boolean $active
     * @return Country
     */
    public function setActive($active)
    {
        $this->active = $active;

        return $this;
    }

    /**
     * Get active
     *
     * @return boolean
     */
    public function isActive()
    {
        return $this->active;
    }

    /**
     * Set gaviEligible
     *
     * @param TripleChoice $gaviEligible
     * @return Country
     */
    public function setGaviEligible(TripleChoice $gaviEligible)
    {
        $this->gaviEligible = $gaviEligible;

        return $this;
    }

    /**
     * Get gaviEligible
     *
     * @return TripleChoice
     */
    public function getGaviEligible()
    {
        return $this->gaviEligible;
    }

    /**
     * Get tracksPneumonia
     *
     * @return boolean
     */
    public function getTracksPneumonia()
    {
        return $this->tracksPneumonia;
    }

    /**
     * Set tracksPneumonia
     *
     * @param boolean $tracksPneumonia
     * @return Country
     */
    public function setTracksPneumonia($tracksPneumonia)
    {
        $this->tracksPneumonia = $tracksPneumonia;

        return $this;
    }

    /**
     * Get hasReferenceLab
     *
     * @return boolean
     */
    public function hasReferenceLab()
    {
        return $this->hasReferenceLab;
    }

    /**
     * Get hasNationalLab
     *
     * @return boolean
     */
    public function hasNationalLab()
    {
        return $this->hasNationalLab;
    }

    /**
     * Set hasReferenceLab
     *
     * @param boolean $hasReferenceLab
     * @return Country
     */
    public function setHasReferenceLab($hasReferenceLab)
    {
        $this->hasReferenceLab = $hasReferenceLab;
        return $this;
    }

    /**
     * Set hasNationalLab
     *
     * @param boolean $hasNationalLab
     * @return Country
     */
    public function setHasNationalLab($hasNationalLab)
    {
        $this->hasNationalLab = $hasNationalLab;
        return $this;
    }

    /**
     * @return string
     */
    public function serialize()
    {
        return serialize([
            $this->code,
            $this->active,
            $this->name,
            $this->gaviEligible,
            $this->region,
            $this->hasNationalLab,
            $this->hasReferenceLab,
            $this->tracksPneumonia,
            $this->language,
            $this->hibVaccineIntro,
            $this->pcvVaccineIntro,
            $this->rvVaccineIntro,
        ]);
    }

    /**
     * @param string $serialized
     */
    public function unserialize($serialized)
    {
        [$this->code,
            $this->active,
            $this->name,
            $this->gaviEligible,
            $this->region,
            $this->hasNationalLab,
            $this->hasReferenceLab,
            $this->tracksPneumonia,
            $this->language,
            $this->hibVaccineIntro,
            $this->pcvVaccineIntro,
            $this->rvVaccineIntro,
        ] = unserialize($serialized, [__CLASS__]);
    }

    /**
     * @return string
     */
    public function getLanguage()
    {
        return $this->language;
    }

    /**
     * @param $language
     */
    public function setLanguage($language)
    {
        $this->language = $language;
    }

    /**
     * @return string
     */
    public function getHibVaccineIntro()
    {
        return $this->hibVaccineIntro;
    }

    /**
     * @return string
     */
    public function getPcvVaccineIntro()
    {
        return $this->pcvVaccineIntro;
    }

    /**
     * @return string
     */
    public function getRvVaccineIntro()
    {
        return $this->rvVaccineIntro;
    }

    /**
     * @param $hibVaccineIntro
     * @return $this
     */
    public function setHibVaccineIntro($hibVaccineIntro)
    {
        $this->hibVaccineIntro = $hibVaccineIntro;
        return $this;
    }

    /**
     * @param $pcvVaccineIntro
     * @return $this
     */
    public function setPcvVaccineIntro($pcvVaccineIntro)
    {
        $this->pcvVaccineIntro = $pcvVaccineIntro;
        return $this;
    }

    /**
     * @param $rvVaccineIntro
     * @return $this
     */
    public function setRvVaccineIntro($rvVaccineIntro)
    {
        $this->rvVaccineIntro = $rvVaccineIntro;
        return $this;
    }

    /**
     * @return ReferenceLab
     */
    public function getReferenceLab()
    {
        return $this->referenceLab;
    }

    /**
     * @param ReferenceLab $referenceLab
     * @return $this
     */
    public function setReferenceLab(ReferenceLab $referenceLab)
    {
        $this->referenceLab = $referenceLab;
        return $this;
    }
}


text:
using System;
using System.IO;

namespace Chutzpah.Models
{
    /// <summary>
    /// Determines what types of files we are testing
    /// </summary>
    [Flags]
    public enum TestingMode
    {
        JavaScript = 1,
        CoffeeScript = 2,
        TypeScript = 4,
        AllExceptHTML = 8,
        HTML = 16,
        All = 32
    }
}


text:
namespace content {

class WebContents;

// Android implementation of ScreenOrientationDelegate. The functionality of
// ScreenOrientationProvider is always supported.
class ScreenOrientationDelegateAndroid : public ScreenOrientationDelegate {
 public:
  ScreenOrientationDelegateAndroid();
  ~ScreenOrientationDelegateAndroid() override;

  // Ask the ScreenOrientationListener (Java) to start accurately listening to
  // the screen orientation. It keep track of the number of start request if it
  // is already running an accurate listening.
  static void StartAccurateListening();

  // Ask the ScreenOrientationListener (Java) to stop accurately listening to
  // the screen orientation. It will actually stop only if the number of stop
  // requests matches the number of start requests.
  static void StopAccurateListening();

  // ScreenOrientationDelegate:
  bool FullScreenRequired(WebContents* web_contents) override;
  void Lock(WebContents* web_contents,
            blink::WebScreenOrientationLockType lock_orientation) override;
  bool ScreenOrientationProviderSupported() override;
  void Unlock(WebContents* web_contents) override;

 private:
  DISALLOW_COPY_AND_ASSIGN(ScreenOrientationDelegateAndroid);
};

} // namespace content

#endif  // CONTENT_BROWSER_SCREEN_ORIENTATION_SCREEN_ORIENTATION_DELEGATE_ANDROID_H_


text:
export ARES_PORT=8080
export ARES_HOSTNAME=localhost
export APHRODITE_PORT=3000

go run main.go

unset APHRODITE_PORT
unset ARES_PORT
unset ARES_HOSTNAME


text:
import React, { Component } from 'react'
import {
  StyleSheet,
  View,
  Linking,
  ActivityIndicator,
} from 'react-native'
import Button from 'react-native-button'
import { responsiveFontSize } from 'react-native-responsive-dimensions'
import SafariView from 'react-native-safari-view'
import { Navigation } from 'react-native-navigation'

class Login extends Component {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      authUrl: '',
    }
    this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this))
    this._handleOpenURL = this._handleOpenURL.bind(this)
    this._connectToPocket = this._connectToPocket.bind(this)
  }

  componentDidMount() {
    // After authorization, Pocket site will redirect with the custom URL Scheme.
    // Linking receives the event and pass the process to handler.
    Linking.addEventListener('url', this._handleOpenURL)
  }

  _handleOpenURL(event) {
    // No longer listen to Linking event.
    Linking.removeEventListener('url', this._handleOpenURL)
    // Pass the process to action.
    this.props.actions.doAfterRedirect(event.url)
  }

  onNavigatorEvent(event) {
    // After this modal has disappeared, open Pocket auth page.
    switch(event.id) {
      case 'willDisappear':
        this._safari(this.state.authUrl)
        break
    }
  }

  _safari(authUrl) {
    console.tron.tmp('authUrl', authUrl)
    SafariView.isAvailable()
      .then(SafariView.show({
        url: authUrl,
        fromBottom: true
      }))
      .catch(err => {
        // Fallback WebView code for iOS 8 and earlier
        console.tron.error(err)
      });
  }

  async _connectToPocket() {
    this.setState({ loading: true })
    const authUrl = await this.props.actions.getPocketAuthUrl()
    this.setState({ authUrl })
    // Trigger NavigatorEvent.
    // because SafariView is not working on Modal.
    Navigation.dismissAllModals({
      animationType: 'slide-down'
    })
  }

  render() {
    const { actions } = this.props
    const indicator = this.state.loading ? <ActivityIndicator /> : null
    return (
      <View style={styles.container}>
        <Button
          onPress={this._connectToPocket}
          style={styles.btn}
          disabled={this.state.loading}
        >
          Connect to Pocket
        </Button>
        { indicator }
     </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
    backgroundColor: '#F5FCFF',
  },
  btn: {
    padding: 10,
    fontSize: responsiveFontSize(3),
  },
})

import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as allActions from '../actions/allActions'

export default connect(
  (state) => ({
  }),
  (dispatch) => ({
    actions: bindActionCreators(allActions, dispatch),
  })
)(Login)


text:
extern crate diesel;

pub mod handler;

pub mod global;
pub mod inmemory;
pub mod sfs;
pub mod note;

pub mod model;
pub mod schema;
pub mod datacli;


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ClusterTree.cs" company="KlusterKite">
//   All rights reserved
// </copyright>
// <summary>
//   Global cluster actors tree scan result
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace KlusterKite.Monitoring.Messages
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using JetBrains.Annotations;

    using KlusterKite.API.Attributes;
    using KlusterKite.API.Client.Converters;
    using KlusterKite.Monitoring.Client.Messages;

    /// <summary>
    /// Global cluster actors tree scan result
    /// </summary>
    [ApiDescription("Global cluster actors tree scan result", Name = "ClusterTree")]
    public class ClusterTree
    {
        /// <summary>
        /// Gets the maximum queue size among tree nodes
        /// </summary>
        [UsedImplicitly]
        [DeclareField("Gets the maximum queue size among tree nodes")]
        public int MaxQueueSize
        {
            get
            {
                return (this.Nodes?.Count ?? 0) == 0
                           ? 0

                           // ReSharper disable once PossibleNullReferenceException
                           : this.Nodes.Values.Max(n => Math.Max(n.MaxQueueSize, n.QueueSize));
            }
        }

        /// <summary>
        /// Gets the list of nodes
        /// </summary>
        [DeclareField("Gets the list of nodes", Converter = typeof(DictionaryConverter<string, Node>))]
        public Dictionary<string, Node> Nodes { get; } = new Dictionary<string, Node>();

        /// <summary>
        /// Gets the nodes flat list
        /// </summary>
        [UsedImplicitly]
        [DeclareField("Gets the  nodes flat list")]
        public IEnumerable<Node> NodesFlat => this.FlattenTree(this.Nodes.Values);

        /// <summary>
        /// Gets the sum of queue size across tree
        /// </summary>
        [UsedImplicitly]
        [DeclareField("Gets the sum of queue size across tree")]
        public int QueueSizeSum
        {
            get
            {
                return (this.Nodes?.Count ?? 0) == 0
                           ? 0

                           // ReSharper disable once PossibleNullReferenceException
                           : this.Nodes.Values.Sum(n => n.QueueSizeSum + n.QueueSize);
            }
        }

        /// <summary>
        /// Flattens tree of nodes
        /// </summary>
        /// <param name="nodesValues">The list of nodes</param>
        /// <returns>The flattened tree of nodes</returns>
        private IEnumerable<Node> FlattenTree(IEnumerable<Node> nodesValues)
        {
            foreach (var node in nodesValues)
            {
                yield return node;
                if (node.Children != null)
                {
                    foreach (var child in this.FlattenTree(node.Children))
                    {
                        yield return child;
                    }
                }
            }
        }
    }
}


text:
d3.scale.linear = function() {
  return d3_scale_linear([0, 1], [0, 1], d3.interpolate, false);
};

function d3_scale_linear(domain, range, interpolate, clamp) {
  var output,
      input;

  function rescale() {
    var linear = domain.length == 2 ? d3_scale_bilinear : d3_scale_polylinear,
        uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber;
    output = linear(domain, range, uninterpolate, interpolate);
    input = linear(range, domain, uninterpolate, d3.interpolate);
    return scale;
  }

  function scale(x) {
    return output(x);
  }

  // Note: requires range is coercible to number!
  scale.invert = function(y) {
    return input(y);
  };

  scale.domain = function(x) {
    if (!arguments.length) return domain;
    domain = x.map(Number);
    return rescale();
  };

  scale.range = function(x) {
    if (!arguments.length) return range;
    range = x;
    return rescale();
  };

  scale.rangeRound = function(x) {
    return scale.range(x).interpolate(d3.interpolateRound);
  };

  scale.clamp = function(x) {
    if (!arguments.length) return clamp;
    clamp = x;
    return rescale();
  };

  scale.interpolate = function(x) {
    if (!arguments.length) return interpolate;
    interpolate = x;
    return rescale();
  };

  scale.ticks = function(m) {
    return d3_scale_linearTicks(domain, m);
  };

  scale.tickFormat = function(m) {
    return d3_scale_linearTickFormat(domain, m);
  };

  scale.nice = function() {
    d3_scale_nice(domain, d3_scale_linearNice);
    return rescale();
  };

  scale.copy = function() {
    return d3_scale_linear(domain, range, interpolate, clamp);
  };

  return rescale();
};

function d3_scale_linearRebind(scale, linear) {
  scale.range = d3.rebind(scale, linear.range);
  scale.rangeRound = d3.rebind(scale, linear.rangeRound);
  scale.interpolate = d3.rebind(scale, linear.interpolate);
  scale.clamp = d3.rebind(scale, linear.clamp);
  return scale;
}

function d3_scale_linearNice(dx) {
  dx = Math.pow(10, Math.round(Math.log(dx) / Math.LN10) - 1);
  return {
    floor: function(x) { return Math.floor(x / dx) * dx; },
    ceil: function(x) { return Math.ceil(x / dx) * dx; }
  };
}

// TODO Dates? Ugh.
function d3_scale_linearTickRange(domain, m) {
  var extent = d3_scaleExtent(domain),
      span = extent[1] - extent[0],
      step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)),
      err = m / span * step;

  // Filter ticks to get closer to the desired count.
  if (err <= .15) step *= 10;
  else if (err <= .35) step *= 5;
  else if (err <= .75) step *= 2;

  // Round start and stop values to step interval.
  extent[0] = Math.ceil(extent[0] / step) * step;
  extent[1] = Math.floor(extent[1] / step) * step + step * .5; // inclusive
  extent[2] = step;
  return extent;
}

function d3_scale_linearTicks(domain, m) {
  return d3.range.apply(d3, d3_scale_linearTickRange(domain, m));
}

function d3_scale_linearTickFormat(domain, m) {
  return d3.format(",." + Math.max(0, -Math.floor(Math.log(d3_scale_linearTickRange(domain, m)[2]) / Math.LN10 + .01)) + "f");
}


text:
L<http://davidbcalhoun.com/2011/new-mobile-safari-stuff-in-ios5-position-fixed-overflow-scroll-new-input-type-support-web-workers-ecmascript-5>

### overflow scrolling support

    overflow: scroll;
    -webkit-overflow-scrolling: touch;

Resource: <http://johanbrook.com/browsers/native-momentum-scrolling-ios-5/>

### fixed position

    position: fixed;

### range slider

    type="range"

### Web worker


text:
cy = cytoscape({
	container : document.getElementById('cy'),
	selectionType : 'single', // (isTouchDevice ? 'additive' : 'single'),
	// layout: {
	// name: 'circle',
	// padding: 10
	// },
	layout : {
		name : 'cose',
		animate : false,
		fit : true,
		randomize : true
	},
	zoom : 1,
	minZoom : 0,
	maxZoom : 100,
	zoomingEnabled : true,
	userZoomingEnabled : false,
	pan : {
		x : 0,
		y : 0
	},
	panningEnabled : true,
	userPanningEnabled : true,
	autoungrabifyNodes : false,
	hideEdgesOnViewport : false,
	hideLabelsOnViewport : false,
	textureOnViewport : false,

	style : [ {
		selector : ':parent',
		css : {
			'content' : 'data(name)',
			'font-family' : 'helvetica',
			'font-size' : 14,
			'text-outline-width' : 2,
			'text-outline-color' : '#000',
			'text-valign' : 'center',
			'color' : '#fff',
			'background-color' : '#0680C1',
			'background-color' : '#041B50',
			'line-color' : '#000',
			'text-outline-color' : '#000'
		}
	}, {
		selector : ':child',
		css : {
			'content' : 'data(name)',
			'font-family' : 'helvetica',
			'font-size' : 14,
			'text-outline-width' : 2,
			'text-outline-color' : '#000',
			'text-valign' : 'center',
			'color' : '#fff',
			'background-color' : '#0680C1',
			'background-color' : '#041B50',
			'line-color' : '#000',
			'text-outline-color' : '#000'
		}
	}, {
		selector : 'edge',
		css : {
			'opacity' : 0.9,
			'target-arrow-shape' : 'none'

		}
	}, {
		selector : '.faded',
		css : {
			'opacity' : 0.85,
			'text-opacity' : 0.9
		}
	}, {
		selector : '.isconnected',
		css : {
			'width' : 3,
			'line-color' : '#3F3',
			'line-style' : 'solid'
		}
	}, {
		selector : '.notconnected',
		css : {
			'width' : 3,
			'line-color' : '#AA0',
			'line-style' : 'dashed'
		}
	}, {
		selector : '.unconnectable',
		css : {
			'width' : 3,
			'opacity' : 0.3,
			'line-color' : '#A00',
			'line-style' : 'dotted'
		}
	} ],

	ready : function() {
		$("#cy div").css("z-index", "-1"); // fixes the menu
	}
});
function refresh() {
	$.get("/system/console/fpai-connection-manager/getGraph.json",
			function(json) {
				console.log(json);
				cy.load(json);
				console.log("connected:");
				console.log(cy.edges("[isconnected]"));
			}).fail(function(jqXHR, textStatus, errorThrown) {
		console.log("error: " + textStatus + ": " + errorThrown);
	});
	$("#connect").prop("disabled", true);
	$("#disconnect").prop("disabled", true);
	selectedEdgeId = null;
}
refresh();

function autoconnect() {
	console.log("Autoconnecting..");
	$.post("/system/console/fpai-connection-manager/autoconnect.json",
			function(result) {
				$("#status").text(result.status);
				$("#status").attr("class", result.class);
			}).fail(function(jqXHR, textStatus, errorThrown) {
		console.log("error: " + textStatus + ": " + errorThrown);
	});

	refresh();
}

var selectedEdgeId;
function connect() {
	console.log("Connecting " + selectedEdgeId);
	var postdata = {
		"id" : selectedEdgeId
	};
	$.post("/system/console/fpai-connection-manager/connect.json", postdata,
			function(result) {
				$("#status").text(result.status);
				$("#status").attr("class", result.class);
			}).fail(function(jqXHR, textStatus, errorThrown) {
		console.log("error: " + textStatus + ": " + errorThrown);
	}).always(refresh());
}

function disconnect() {
	console.log("Disconnecting " + selectedEdgeId);
	var postdata = {
		"id" : selectedEdgeId
	};
	$.post("/system/console/fpai-connection-manager/disconnect.json", postdata,
			function(result) {
				$("#status").text(result.status);
				$("#status").attr("class", result.class);
			}).fail(function(jqXHR, textStatus, errorThrown) {
		console.log("error: " + textStatus + ": " + errorThrown);
	}).always(refresh());
}

cy.on('tap', 'node', function(e) {
	var node = e.cyTarget;
	var neighborhood = node.neighborhood().add(node);
	cy.elements().addClass('faded');
	neighborhood.removeClass('faded');

	$("#connect").prop("disabled", true);
	$("#disconnect").prop("disabled", true);

	onNodeSelected(node.id());
});

cy.on('tap', 'edge', function(e) {
	var edge = e.cyTarget;
	var neighborhood = edge.connectedNodes().add(edge);
	cy.elements().addClass('faded');
	neighborhood.removeClass('faded');

	onEdgeSelected(edge.id());
});

cy.on('tap', function(e) {
	if (e.cyTarget === cy) {
		cy.elements().removeClass('faded');
		onNothingSelected();
	}
});

function onNothingSelected() {
	selectedEdgeId = null;
	$(".infotable").text("");
	$("#1a").text("Nothing selected");
}

function onEdgeSelected(elemid) {
	selectedEdgeId = elemid;
	var elem = cy.$('#' + elemid); // select element
	$(".infotable").text("");
	$("#1a").text("Possible connection");
	$("#2a").text("connects: ");
	$("#2b").text(elem.data("source"));
	$("#3a").text("with: ");
	$("#3b").text(elem.data("target"));
	$("#4a").text("Connected: ");
	$("#4b").text(elem.data("isconnected"));
	$("#5a").text("elemid: ");
	$("#5b").text(elemid);

	if (elem.data("isconnected") || elem.data("unconnectable")) {
		$("#connect").prop("disabled", true);
		$("#disconnect").prop("disabled", false);
	} else {
		$("#connect").prop("disabled", false);
		$("#disconnect").prop("disabled", true);
	}
}

function onNodeSelected(elemid) {
	selectedEdgeId = null;
	var elem = cy.$('#' + elemid); // select element
	$(".infotable").text("");
	$("#1a").text("node");
	console.log(elem.data());
}

function updateInfo(elemid) {

}


text:
namespace WarMachines.Machines
{
    public class Inheritor
    {
    }
}


text:
import XMonad
import XMonad.Hooks.DynamicLog
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.ManageHelpers
import XMonad.Hooks.EwmhDesktops
import XMonad.Layout.NoBorders
import XMonad.Util.Run(spawnPipe)
import XMonad.Util.EZConfig(additionalKeys)
import System.IO
import qualified XMonad.StackSet as W
import Graphics.X11.ExtraTypes.XF86

main = do
	xmproc <- spawnPipe "/usr/bin/xmobar ~/.xmobarrc --screen=0"
	xmonad $ defaultConfig
		{
			modMask = mod1Mask,
			manageHook = manageDocks <+> myManageHooks
				<+> manageHook defaultConfig,
      handleEventHook = fullscreenEventHook,
			layoutHook = lessBorders OnlyFloat $ avoidStruts $ layoutHook defaultConfig,
			{-startupHook = startup,-}
			logHook = dynamicLogWithPP $ xmobarPP
				{
					ppOutput = hPutStrLn xmproc,
					ppTitle = xmobarColor "green" "" . shorten 100
				},
				focusFollowsMouse = False,
				workspaces = myWorkspaces
		} `additionalKeys` myKeys

myManageHooks = composeAll . concat $
	[
		[ isFullscreen --> doFullFloat],
		[ className =? c --> doFloat | c <- classFloats],
		[ title =? t --> doFloat | t <- titleFloats],
		[ className =? c --> doF (W.shift "9") | c <- musicPlayers],
		[ className =? c --> doIgnore | c <- classIgnores]
	]
	where
		classFloats = ["Gimp","Vncviewer","Webots-bin","UTNaoTool","Tk","mplayer2", "python2.7"]
		titleFloats = ["Pursuit Simulation","Gesture Trainer", "Gesture Tester", "Teleop", "Figure 1", "Config Editor", "Soccer Visualizer", "Kanban"]
		musicPlayers = ["Songbird","Guayadeque","Pithos","Rythmbox","Ario"]
		classIgnores = ["stalonetray","trayer"]

myWorkspaces = ["1","2","3","4","5","6","7","8","9"]

myKeys =
	[
		((controlMask .|. mod1Mask, xK_t), spawn "gnome-terminal"),
		((controlMask .|. mod1Mask, xK_f), spawn "firefox"),
		((mod1Mask, xK_u), spawn "python /home/sam/programming/gestures/test.py"),
		((mod1Mask,xK_Print), spawn "sleep 0.2; scrot -s '/home/sam/.screenshot/%Y-%m-%d-%H-%M-%S-scrot.png'"),
		((0,xK_Print), spawn "scrot '/home/sam/.screenshot/%Y-%m-%d-%H-%M-%S-scrot.png'"),
    ((mod1Mask, xK_q), spawn "/usr/bin/xmonad --recompile; /usr/bin/xmonad --restart"),
    -- volume control
    ((0, xF86XK_AudioLowerVolume), spawn "amixer set Master 4-"),
    ((0, xF86XK_AudioRaiseVolume), spawn "amixer set Master 4+"),
    ((0, xF86XK_AudioMute),  spawn "amixer -D pulse set Master 1+ toggle"),
    ((0, xF86XK_AudioPlay),  spawn "dbus-send --print-reply --dest=org.mpris.MediaPlayer2.pithos /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.PlayPause"),
    ((shiftMask, xK_F3), spawn "dbus-send --print-reply --dest=org.mpris.MediaPlayer2.pithos /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Prev"),
    ((shiftMask, xK_F4), spawn "dbus-send --print-reply --dest=org.mpris.MediaPlayer2.pithos /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Next"),
    ((shiftMask, xK_F5), spawn "amixer set Master 4-"),
    ((shiftMask, xK_F6), spawn "amixer set Master 4+"),
    ((shiftMask, xK_F7),  spawn "amixer -D pulse set Master 1+ toggle"),
    ((shiftMask, xK_F8),  spawn "dbus-send --print-reply --dest=org.mpris.MediaPlayer2.pithos /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.PlayPause")
	]
	++ -- important since ff. is a list itself, can't just put inside above list
	[((otherModMasks .|. mod1Mask, key), windows $ action tag)
		| (tag, key) <- zip myWorkspaces [xK_1 .. xK_9]
		, (action, otherModMasks) <- [(W.greedyView, 0), (W.shift, controlMask)]]
	++
	[((m .|. mod1Mask, key), screenWorkspace sc >>= flip whenJust (windows . f))
		| (key, sc) <- zip [xK_comma, xK_period] [0..]
		, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]

{-startup :: X()-}
{-startup = do-}
  {---spawn "stalonetray"-}
  {-[>spawn "dbus-launch nm-applet --sm-disable"<]-}
  {---spawn "gnome-settings-daemon"-}
  {-spawn "trayer --edge bottom --align right --SetDockType true --widthtype pixel --width 190 --heighttype pixel --height 20"-}
  {-spawn "dropbox start"-}
  {-spawn "gnome-screensaver"-}
  {-spawn "gnome-volume-control-applet"-}
  {-spawn "gnome-power-manager"-}
  {-spawn "nm-applet --sm-disable"-}
  {-spawn "workrave"-}


text:
package javax.print.attribute.standard;

import java.io.Serial;

import javax.print.attribute.Attribute;
import javax.print.attribute.IntegerSyntax;
import javax.print.attribute.SupportedValuesAttribute;

/**
 * Class {@code JobPrioritySupported} is an integer valued printing attribute
 * class that specifies whether a Print Service instance supports the
 * {@link JobPriority JobPriority} attribute and the number of different job
 * priority levels supported.
 *

 * The client can always specify any {@link JobPriority JobPriority} value from
 * 1 to 100 for a job. However, the Print Service instance may support fewer
 * than 100 different job priority levels. If this is the case, the Print
 * Service instance automatically maps the client-specified job priority value
 * to one of the supported job priority levels, dividing the 100 job priority
 * values equally among the available job priority levels.
 *

 * IPP Compatibility: The integer value gives the IPP integer value. The
 * category name returned by {@code getName()} gives the IPP attribute name.
 *
 * @author Alan Kaminsky
 */
public final class JobPrioritySupported extends IntegerSyntax
    implements SupportedValuesAttribute {

    /**
     * Use serialVersionUID from JDK 1.4 for interoperability.
     */
    @Serial
    private static final long serialVersionUID = 2564840378013555894L;

    /**
     * Construct a new job priority supported attribute with the given integer
     * value.
     *
     * @param  value number of different job priority levels supported
     * @throws IllegalArgumentException if {@code value} is less than 1 or
     *         greater than 100
     */
    public JobPrioritySupported(int value) {
        super (value, 1, 100);
    }

    /**
     * Returns whether this job priority supported attribute is equivalent to
     * the passed in object. To be equivalent, all of the following conditions
     * must be true:
     *

     *
{@code object} is not {@code null}.
     *
{@code object} is an instance of class
     *   {@code JobPrioritySupported}.
     *
This job priority supported attribute's value and {@code object}'s
     *   value are equal.
     *

     *
     * @param  object {@code Object} to compare to
     * @return {@code true} if {@code object} is equivalent to this job priority
     *         supported attribute, {@code false} otherwise
     */
    public boolean equals (Object object) {

        return (super.equals(object) &&
               object instanceof JobPrioritySupported);
    }

    /**
     * Get the printing attribute class which is to be used as the "category"
     * for this printing attribute value.
     *

     * For class {@code JobPrioritySupported}, the category is class
     * {@code JobPrioritySupported} itself.
     *
     * @return printing attribute class (category), an instance of class
     *         {@link Class java.lang.Class}
     */
    public final Class<? extends Attribute> getCategory() {
        return JobPrioritySupported.class;
    }

    /**
     * Get the name of the category of which this attribute value is an
     * instance.
     *

     * For class {@code JobPrioritySupported}, the category name is
     * {@code "job-priority-supported"}.
     *
     * @return attribute category name
     */
    public final String getName() {
        return "job-priority-supported";
    }
}


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>
  Module: Asciidoctor::LaTeX::TeXBlock

    — Asciidoctor LaTeX Documentation

</title>

  <link rel="stylesheet" href="../../css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="../../css/common.css" type="text/css" charset="utf-8" />

    Index (T) »
    Asciidoctor » LaTeX
     »
    TeXBlock

(no frames)

      Class List

      Method List

      File List

Module: Asciidoctor::LaTeX::TeXBlock

Defined in:

lib/asciidoctor/latex/tex_block.rb

Constant Summary

INNER_TYPES =

The list of "inner environments" whose enclosing escaped braces are not to
be stripped.

["array", "matrix",  "none"]

      Class Method Summary
      (collapse)

      + (Object) environmemt_type_of_match(m)

Return the environment type from an element of the array produced by
get_tex_blocks – each element is a three-element array with the tex block
as the middle element.

      + (Object) environment_type(str)

Return the environment type of a tex block.

      + (Object) get_tex_blocks(str)

Find blocks delmited by [ … ].

      + (Object) process_environments(str)

Transform the input string by stripping or passing each tex block as
required.

      + (Object) process_tex_block(m, str)

Transform the input string for a given block m.

      + (Object) restore_match_data(m)

Return the block as-is – do not strip delimiters.

      + (Object) strip_match_data(m)

Return the block sans delimiters.

Class Method Details

    + (<tt>Object</tt>) environmemt_type_of_match(m)

Return the environment type from an element of the array produced by
get_tex_blocks – each element is a three-element array with the tex block
as the middle element.

67
68
69

# File 'lib/asciidoctor/latex/tex_block.rb', line 67

def self.environmemt_type_of_match m
  environment_type m[1]
end

    + (<tt>Object</tt>) environment_type(str)

Return the environment type of a tex block. Thus, if str = [beginfoo ho
ho ho endfoo], the string "foo" is returned.

51
52
53
54
55
56
57
58
59
60

# File 'lib/asciidoctor/latex/tex_block.rb', line 51

def self.environment_type str
  rx_env_block = /\\begin\{(.*?)\}/
  m = str.match rx_env_block
  if m
    env_type = m[1]
  else
    env_type = 'none'
  end
  env_type
end

    + (<tt>Object</tt>) get_tex_blocks(str)

Find blocks delmited by [ … ]

42
43
44
45

# File 'lib/asciidoctor/latex/tex_block.rb', line 42

def self.get_tex_blocks str
  rx_tex_block = /(\\\[)(.*?)(\\\])/m
  str.scan rx_tex_block
end

    + (<tt>Object</tt>) process_environments(str)

Transform the input string by stripping or passing each tex block as
required

95
96
97
98
99
100
101

# File 'lib/asciidoctor/latex/tex_block.rb', line 95

def self.process_environments str
  tbs = get_tex_blocks str
  tbs.each do |tb|
    str = process_tex_block tb, str
  end
  str
end

    + (<tt>Object</tt>) process_tex_block(m, str)

Transform the input string for a given block m

83
84
85
86
87
88
89
90
91

# File 'lib/asciidoctor/latex/tex_block.rb', line 83

def self.process_tex_block m, str
  block_type = environmemt_type_of_match m
  if INNER_TYPES.include? block_type
    output = str
  else
    output = str.gsub restore_match_data(m), strip_match_data(m)
  end
  output
end

    + (<tt>Object</tt>) restore_match_data(m)

Return the block as-is – do not strip delimiters.

73
74
75

# File 'lib/asciidoctor/latex/tex_block.rb', line 73

def self.restore_match_data m
  m.join()
end

    + (<tt>Object</tt>) strip_match_data(m)

Return the block sans delimiters

78
79
80

# File 'lib/asciidoctor/latex/tex_block.rb', line 78

def self.strip_match_data m
  m[1]
end

  Generated on Tue Jun  7 05:32:25 2016 by
  yard
  0.8.7.6 (ruby-2.2.3).


text:
using GTA;
using GTA.Math;
using Inferno.ChaosMode;
using System;
using System.Collections.Generic;
using Inferno.Utilities;
using UniRx;

namespace Inferno
{

    /// <summary>
    /// 市民を生成してパラシュート降下させる
    /// </summary>
    internal class SpawnParachuteCitizenArmy : InfernoScript
    {
        class SpawnParachuteCitizenArmyConfig : InfernoConfig
        {
            /// <summary>
            /// 生成間隔
            /// </summary>
            public int SpawnDurationSeconds { get; set; } = 5;

            public override bool Validate()
            {
                return SpawnDurationSeconds > 0;
            }
        }

        protected override string ConfigFileName { get; } = "SpawnParachuteCitizenArmy.conf";
        private SpawnParachuteCitizenArmyConfig config;
        private int SpawnDurationSeconds => config?.SpawnDurationSeconds ?? 5;

        protected override void Setup()
        {
            config = LoadConfig<SpawnParachuteCitizenArmyConfig>();
            CreateInputKeywordAsObservable("carmy")
                .Subscribe(_ =>
                {
                    IsActive = !IsActive;
                    DrawText("SpawnParachuteCitizenArmy:" + IsActive, 3.0f);
                });

            OnAllOnCommandObservable.Subscribe(_ => IsActive = true);

            CreateTickAsObservable(TimeSpan.FromSeconds(SpawnDurationSeconds))
                .Where(_ => IsActive)
                .Subscribe(_ => CreateParachutePed());
        }

        private void CreateParachutePed()
        {
            if (!PlayerPed.IsSafeExist()) return;
            var playerPosition = PlayerPed.Position;

            var velocity = PlayerPed.Velocity;
            //プレイヤが移動中ならその進行先に生成する
            var ped =
                NativeFunctions.CreateRandomPed(playerPosition + 3 * velocity + new Vector3(0, 0, 50).AroundRandom2D(50));

            if (!ped.IsSafeExist()) return;

            ped.MarkAsNoLongerNeeded();
            ped.Task.ClearAllImmediately();
            ped.TaskSetBlockingOfNonTemporaryEvents(true);
            ped.SetPedKeepTask(true);
            ped.AlwaysKeepTask = true;
            //プレイヤ周囲15mを目標に降下
            var targetPosition = playerPosition.AroundRandom2D(15);
            ped.ParachuteTo(targetPosition);

            //着地までカオス化させない
            StartCoroutine(PedOnGroundedCheck(ped));
        }

        /// <summary>
        /// 市民が着地するまで監視する
        /// </summary>
        /// <param name="ped"></param>
        /// <returns></returns>
        private IEnumerable<Object> PedOnGroundedCheck(Ped ped)
        {
            //市民無敵化
            ped.IsInvincible = true;
            ped.SetNotChaosPed(true);
            for (var i = 0; i < 10; i++)
            {
                yield return WaitForSeconds(1);

                //市民が消えていたり死んでたら監視終了
                if (!ped.IsSafeExist()) yield break;
                if (ped.IsDead) yield break;

                //着地していたら監視終了
                if (!ped.IsInAir)
                {
                    break;
                }
            }

            if (ped.IsSafeExist())
            {
                ped.SetNotChaosPed(false);
                ped.IsInvincible = false;
                ped.MarkAsNoLongerNeeded();
            }
        }
    }
}


text:
package org.apereo.portal.jdbc;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apereo.portal.utils.AbstractBeanLocator;
import org.apereo.portal.utils.PortalApplicationContextLocator;
import org.springframework.context.ApplicationContext;

/**
 * @deprecated code that needs an IDatabaseMetadata should use direct dependency injection where
 *     possible
 */
@Deprecated
public class PortalDbMetadataLocator extends AbstractBeanLocator<IDatabaseMetadata> {
    public static final String BEAN_NAME = RDBMServices.PORTAL_DB_METADATA;

    private static final Log LOG = LogFactory.getLog(PortalDbMetadataLocator.class);
    private static AbstractBeanLocator<IDatabaseMetadata> locatorInstance;

    public static IDatabaseMetadata getPortalDbMetadata() {
        AbstractBeanLocator<IDatabaseMetadata> locator = locatorInstance;
        if (locator == null) {
            LOG.info(
                    "Looking up bean '"
                            + BEAN_NAME
                            + "' in ApplicationContext due to context not yet being initialized");
            final ApplicationContext applicationContext =
                    PortalApplicationContextLocator.getApplicationContext();
            applicationContext.getBean(PortalDbMetadataLocator.class.getName());

            locator = locatorInstance;
            if (locator == null) {
                LOG.warn(
                        "Instance of '"
                                + BEAN_NAME
                                + "' still null after portal application context has been initialized");
                return applicationContext.getBean(BEAN_NAME, IDatabaseMetadata.class);
            }
        }

        return locator.getInstance();
    }

    public PortalDbMetadataLocator(IDatabaseMetadata instance) {
        super(instance, IDatabaseMetadata.class);
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.spring.locator.AbstractBeanLocator#getLocator()
     */
    @Override
    protected AbstractBeanLocator<IDatabaseMetadata> getLocator() {
        return locatorInstance;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.spring.locator.AbstractBeanLocator#setLocator(org.apereo.portal.spring.locator.AbstractBeanLocator)
     */
    @Override
    protected void setLocator(AbstractBeanLocator<IDatabaseMetadata> locator) {
        locatorInstance = locator;
    }
}


text:
#ifndef OC_PSTAT_H_
#define OC_PSTAT_H_

#include "oc_ri.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef struct oc_sec_pstat {
    bool isop;
    int cm;
    int tm;
    int om;
    int sm;
} oc_sec_pstat_t;

bool oc_sec_provisioned(void);
void oc_sec_decode_pstat(oc_rep_t *rep);
void oc_sec_encode_pstat(void);
oc_sec_pstat_t *oc_sec_get_pstat(void);
void oc_sec_pstat_default(void);
void get_pstat(oc_request_t *request, oc_interface_mask_t interface);
void post_pstat(oc_request_t *request, oc_interface_mask_t interface);

#ifdef __cplusplus
}
#endif

#endif /* OC_PSTAT_H_ */


text:
jsio('import net');
jsio('from net.protocols.buffered import BufferedProtocol');
jsio('import std.utf8 as utf8');

/*
works like this:
OPEN
upstream:
length_after_colon:id,0host,port

downstream:
length_after_colon:id,0
-----
CLOSE
upstream:
length_after_colon:id,1

downstream:
length_after_colon:id,1errcode
-----
DATA
upstream/downstream:
length_after_colon:id,2datadatadata
*/

var loggers = {};
loggers.stream = logging.getLogger('MSPPStream');
loggers.protocol = logging.getLogger('MSPPProtocol');

var frames = {
	'OPEN':  0,
	'CLOSE': 1,
	'DATA':  2
};

exports.MSPPStream = Class(function() {
	this.setMultiplexer = function(multiplexer) {
		loggers.stream.debug('setMultiplexer: '+multiplexer);
		this.multiplexer = multiplexer;
	}

	this.setEncoding = function(encoding) {
		loggers.stream.debug('setEncoding: '+encoding);
		this.encoding = encoding;
	}

	this.open = function(host, port, isBinary) {
		if (isBinary)
			this.encoding = 'utf8';
		this.id = this.multiplexer.openStream(this, host, port);
		loggers.stream.debug('open '+this.id+": "+host+" "+port+" "+isBinary);
	}

	this.close = function() {
		loggers.stream.debug('close '+this.id);
		this.multiplexer.close(this.id);
	}

	this.send = function(data, encoding) {
		loggers.stream.debug('send '+this.id+": "+data+" "+encoding);
		if ((encoding || this.encoding) == 'utf8')
			data = utf8.encode(data);
		this.multiplexer.writeToStream(this.id, data);
	}

	this._onreadraw = function(data) {
		if (this.encoding == 'utf8') {
			var raw = utf8.decode(data);
			var length = raw[1];
			// TODO: actually buffer this stuff properly
			if (length != data.length) {
				throw new Error("Incomplete utf8 codepoint");
			}
			data = raw[0]
		}
		loggers.stream.debug('_onreadraw '+data);
		this.onread(data);
	}

	this.onopen = function() {}
	this.onclose = function(err) {}
	this.onread = function(data) {}
});

var state = {};
state.closed = 0;
state.connecting = 1;
state.consuming = 2;

exports.MSPPProtocol = Class(BufferedProtocol, function(supr) {
	this.init = function() {
		loggers.protocol.debug('new MSPPProtocol');
		supr(this, 'init', []);
		this.state = state.closed;
		this.transportType = null;
		this.transportOptions = null;
		this.currentId = 0;
		this.streams = {};
		this.writeBuffer = [];
	}

	this.setTransport = function(transportType, transportOptions) {
		this.transportType = transportType;
		this.transportOptions = transportOptions;
	}

	this.connectionMade = function(isReconnect) {
		loggers.protocol.debug('connectionMade');
		this.state = state.consuming;
		for (var i = 0; i < this.writeBuffer.length; i++)
			this._write(this.writeBuffer[i]);
		writeBuffer = [];
	}

	this.connectionLost = function(reason) {
		loggers.protocol.debug('closed: '+reason);
		this.state = state.closed;
		for (stream in this.streams)
			this.streams[stream].onclose(reason);
	}

	this.openStream = function(stream, host, port) {
		if (this.state == state.closed) {
			this.state = state.connecting;
			net.connect(this, this.transportType, this.transportOptions);
		}
		var id = ++this.currentId;
		this.streams[id] = stream;
		this._write([id, frames.OPEN, host+","+port]);
		return id;
	}

	this.closeStream = function(id) {
		this._write([id, frames.CLOSE, ""]);
	}

	this.writeToStream = function(id, data) {
		this._write([id, frames.DATA, data]);
	}

	this.bufferUpdated = function() {
		loggers.protocol.debug("bufferUpdated. state: "+this.state+". buffer: "+this.buffer._rawBuffer);
		if (this.state != state.consuming)
			throw new Error("buffer update in invalid MSPP state: "+this.state);
		if (! this.buffer.hasDelimiter(':'))
			return;
		var lStr = this.buffer.peekToDelimiter(':');
		var len = parseInt(lStr);
		if (! this.buffer.hasBytes(len + lStr.length + 1))
			return;
		this.buffer.consumeThroughDelimiter(':');
		var streamId = this.buffer.consumeToDelimiter(',');
		this.buffer.consumeBytes(1);
		var frameType = parseInt(this.buffer.consumeBytes(1));
		len -= (streamId.length + 2);
		streamId = parseInt(streamId);
		var data = this.buffer.consumeBytes(len);
		switch(frameType) {
			case frames.OPEN:
				this.streams[streamId].onopen();
				break;
			case frames.CLOSE:
				this.streams[streamId].onclose(data);
				break;
			case frames.DATA:
				this.streams[streamId]._onreadraw(data);
				break;
			default:
				throw new Error('invalid MSPP data type!');
		}
	}

	this._write = function(data) {
		if (this.state != state.consuming) {
			loggers.protocol.debug("buffering write: "+data);
			this.writeBuffer.push(data);
			return;
		}
		var s = data[0] + "," + data[1] + data[2];
		s = s.length + ":" + s;
		loggers.protocol.debug('write: '+s);
		this.transport.write(s);
	}
});


text:
/*
 * PhraseTable.cpp
 *
 *  Created on: 23 Oct 2015
 *      Author: hieu
 */
#include <boost/foreach.hpp>
#include <queue>
#include "PhraseTable.h"
#include "../legacy/Util2.h"
#include "../TypeDef.h"
#include "../InputType.h"
#include "../PhraseBased/Manager.h"
#include "../PhraseBased/InputPath.h"
#include "../SCFG/InputPath.h"
#include "../SCFG/Manager.h"

using namespace std;

namespace Moses2
{

////////////////////////////////////////////////////////////////////////////
PhraseTable::PhraseTable(size_t startInd, const std::string &line) :
  StatelessFeatureFunction(startInd, line), m_tableLimit(20) // default
  , m_maxCacheSize(DEFAULT_MAX_TRANS_OPT_CACHE_SIZE)
{
  m_input.push_back(0);
}

PhraseTable::~PhraseTable()
{
  // TODO Auto-generated destructor stub
}

void PhraseTable::SetParameter(const std::string& key, const std::string& value)
{
  if (key == "cache-size") {
    m_maxCacheSize = Scan<size_t>(value);
  } else if (key == "path") {
    m_path = value;
  } else if (key == "input-factor") {
    m_input = Tokenize<FactorType>(value, ",");
  } else if (key == "output-factor") {
    m_output = Tokenize<FactorType>(value, ",");
  } else if (key == "table-limit") {
    m_tableLimit = Scan<size_t>(value);
  } else {
    StatelessFeatureFunction::SetParameter(key, value);
  }
}

bool PhraseTable::SatisfyBackoff(const Manager &mgr, const InputPath &path) const
{
  const InputType &input = mgr.GetInput();
  if ((mgr.system.options.input.xml_policy == XmlExclusive)
      && input.XmlOverlap(path.range.GetStartPos(), path.range.GetEndPos())) {
    return false;
  }

  //cerr << GetName() << "=" << GetPtInd() << "=" << decodeGraphBackoff << endl;
  if (decodeGraphBackoff == 0) {
    // always lookup
    return true;
  } else if (decodeGraphBackoff == -1) {
    // lookup only if there's no existing rules
    return path.GetNumRules() ? false : true;
  } else if (path.range.GetNumWordsCovered() <= decodeGraphBackoff) {
    return path.GetNumRules() ? false : true;
  }

  return false;
}

void PhraseTable::Lookup(const Manager &mgr, InputPathsBase &inputPaths) const
{
  BOOST_FOREACH(InputPathBase *pathBase, inputPaths) {
    InputPath *path = static_cast<InputPath*>(pathBase);
    //cerr << "path=" << path->range << " ";

    if (SatisfyBackoff(mgr, *path)) {
      TargetPhrases *tpsPtr = Lookup(mgr, mgr.GetPool(), *path);
      /*
      cerr << "tpsPtr=" << tpsPtr << " ";
       if (tps.get()) {
       cerr << tps.get()->GetSize();
       }
       cerr << endl;
       */

      path->AddTargetPhrases(*this, tpsPtr);
    }
  }

}

TargetPhrases *PhraseTable::Lookup(const Manager &mgr, MemPool &pool,
                                   InputPath &inputPath) const
{
  UTIL_THROW2("Not implemented");
}

void PhraseTable::EvaluateInIsolation(MemPool &pool, const System &system,
                                      const Phrase<Moses2::Word> &source, const TargetPhraseImpl &targetPhrase, Scores &scores,
                                      SCORE &estimatedScore) const
{
}

void PhraseTable::EvaluateInIsolation(MemPool &pool, const System &system, const Phrase<SCFG::Word> &source,
                                      const TargetPhrase<SCFG::Word> &targetPhrase, Scores &scores,
                                      SCORE &estimatedScore) const
{

}

// scfg
void PhraseTable::LookupUnary(MemPool &pool,
                              const SCFG::Manager &mgr,
                              const SCFG::Stacks &stacks,
                              SCFG::InputPath &path) const
{
  //cerr << "BEFORE LookupUnary" << path.Debug(mgr.system) << endl;
  size_t startPos = path.range.GetStartPos();
  const SCFG::InputPath *prevPath = mgr.GetInputPaths().GetMatrix().GetValue(startPos, 0);
  LookupNT(pool, mgr, path.range, *prevPath, stacks, path);
  //cerr << "AFTER LookupUnary" << path.Debug(mgr.system) << endl;
}

void PhraseTable::LookupNT(
  MemPool &pool,
  const SCFG::Manager &mgr,
  const Moses2::Range &subPhraseRange,
  const SCFG::InputPath &prevPath,
  const SCFG::Stacks &stacks,
  SCFG::InputPath &outPath) const
{
  size_t endPos = outPath.range.GetEndPos();

  const Range &prevRange = prevPath.range;

  size_t startPos = prevRange.GetEndPos() + 1;
  size_t ntSize = endPos - startPos + 1;

  const SCFG::Stack &ntStack = stacks.GetStack(startPos, ntSize);
  const SCFG::Stack::Coll &stackColl = ntStack.GetColl();

  BOOST_FOREACH (const SCFG::Stack::Coll::value_type &valPair, stackColl) {
    const SCFG::Word &ntSought = valPair.first;
    const Moses2::HypothesisColl *hypos = valPair.second;
    const Moses2::Hypotheses &sortedHypos = hypos->GetSortedAndPrunedHypos(mgr, mgr.arcLists);
    //cerr << "ntSought=" << ntSought << ntSought.isNonTerminal << endl;
    LookupGivenWord(pool, mgr, prevPath, ntSought, &sortedHypos, subPhraseRange, outPath);
  }
}

void PhraseTable::LookupGivenWord(
  MemPool &pool,
  const SCFG::Manager &mgr,
  const SCFG::InputPath &prevPath,
  const SCFG::Word &wordSought,
  const Moses2::Hypotheses *hypos,
  const Moses2::Range &subPhraseRange,
  SCFG::InputPath &outPath) const
{
  size_t ptInd = GetPtInd();

  BOOST_FOREACH(const SCFG::ActiveChartEntry *prevEntry, prevPath.GetActiveChart(ptInd).entries) {
    //cerr << "BEFORE LookupGivenNode=" << prevPath << endl;
    LookupGivenNode(pool, mgr, *prevEntry, wordSought, hypos, subPhraseRange, outPath);
    //cerr << "AFTER LookupGivenNode=" << prevPath << endl;
  }
}

}


text:
<?xml version="1.0"?>
<package>
  <name>strands_movebase</name>
  <version>0.0.23</version>
  <description>
    This package contains components for using the ROS move base together
    with the Scitos G5 robot. There is options for running obstacle avoidance
    both with only laser and with an additional depth-sensing camera
    mounted in front. The additional nodes in the package are for processing
    the incoming clouds from the camera for obstacle avoidance.
  </description>

  <!-- One maintainer tag required, multiple allowed, one person per tag -->
  <maintainer email="nilsbore@gmail.com">nbore</maintainer>

  <!-- One license tag required, multiple allowed, one license per tag -->
  <!-- Commonly used license strings: -->
  <!--   BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, LGPLv3 -->
  <license>MIT</license>

  <!-- Url tags are optional, but mutiple are allowed, one per tag -->
  <!-- Optional attribute type can be: website, bugtracker, or repository -->
  <url type="website">http://github.com/strands-project/strands_movebase</url>

  <!-- Author tags are optional, mutiple are allowed, one per tag -->
  <!-- Authors do not have to be maintianers, but could be -->
  <author email="nilsbore@gmail.com">Nils Bore</author>
  <author email="b.lacerda@cs.bham.ac.uk">Bruno Lacerda</author>

  <!-- The *_depend tags are used to specify dependencies -->
  <!-- Dependencies can be catkin packages or system dependencies -->
  <buildtool_depend>catkin</buildtool_depend>
  <build_depend>sensor_msgs</build_depend>
  <build_depend>roscpp</build_depend>
  <build_depend>std_msgs</build_depend>
  <build_depend>pcl_ros</build_depend>
  <build_depend>libpcl-all-dev</build_depend>
  <build_depend>tf</build_depend>
  <build_depend>nodelet</build_depend>
  <run_depend>sensor_msgs</run_depend>
  <run_depend>roscpp</run_depend>
  <run_depend>std_msgs</run_depend>
  <run_depend>pcl_ros</run_depend>
  <run_depend>libpcl-all</run_depend>
  <run_depend>tf</run_depend>
  <run_depend>amcl</run_depend>
  <run_depend>strands_description</run_depend>
  <run_depend>dwa_local_planner</run_depend>
  <run_depend>map_server</run_depend>
  <run_depend>movebase_state_service</run_depend>
  <run_depend>strands_navfn</run_depend>
  <run_depend>nodelet</run_depend>

  <!-- The export tag contains other, unspecified, tags -->
  <export>
    <nodelet plugin="${prefix}/plugins/nodelet_plugins.xml" />
  </export>
</package>


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      Home · 1% Remaining

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/hyde.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-144-precomposed.png">
                                 <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

1% Remaining

A collection of my notes and thoughts

        Home

              About

Download

GitHub project

Currently v

© 2014. All rights reserved.

        Spark Summit 2014 - Day 1

    30 Jun 2014

Matei Zaharia (CTO, Databricks)

More than 1000 attendees to the Summit! Very fast community growth.

The most active big data project!

Some stats from ohloh

New features that came in last months: security, monitoring, HA

Break for Lunch!

    Older

    Newer


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 数据库驱动包位置 -->
    <!-- <classPathEntry location="C:/Users/admin/.m2/repository/mysql/mysql-connector-java/5.1.41/mysql-connector-java-5.1.41.jar"
        /> -->
    <!-- <classPathEntry location="C:/oracle/product/10.2.0/db_1/jdbc/lib/ojdbc14.jar" /> -->

    <!-- 引入配置文件属性 -->
    <properties resource="generator.properties" />
    <!-- context:生成一组对象的环境 -->
    <!-- id:必选,上下文id,用于在生成错误时提示 -->
    <!-- defaultModelType:指定生成对象的样式 -->
    <!-- 1,conditional:类似hierarchical; -->
    <!-- 2,flat:所有内容(主键,blob)等全部生成在一个对象中; -->
    <!-- 3,hierarchical:主键生成一个XXKey对象(key class),Blob等单独生成一个对象,其他简单属性在一个对象中(record class) -->
    <!-- targetRuntime: -->
    <!-- 1,MyBatis3:默认的值,生成基于MyBatis3.x以上版本的内容,包括XXXBySample; -->
    <!-- 2,MyBatis3Simple:类似MyBatis3,只是不生成XXXBySample; -->
    <!-- introspectedColumnImpl:类全限定名,用于扩展MBG -->
    <context id="DB2Tables" targetRuntime="MyBatis3" defaultModelType="flat">

        <!-- 指定生成的java文件的编码,没有直接生成到项目时中文可能会乱码 -->
        <property name="javaFileEncoding" value="UTF-8" />
        <!-- 格式化java代码 -->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter" />
        <!-- 格式化XML代码 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter" />

        <!-- 覆盖生成的文件 -->
        <plugin type="com.tangjf.generator.OverIsMergeablePlugin" />
        <!-- 序列化 -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />

        <!-- 自定义注释 -->
        <commentGenerator type="com.tangjf.generator.MyCommentGenerator" />
        <!-- 数据库链接URL、用户名、密码 -->
        <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.url}" userId="${jdbc.userId}"
            password="${jdbc.password}">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- 生成实体类的包名和位置,这里配置将生成的实体类放在com.tangjf.dto这个包下 -->
        <javaModelGenerator targetPackage="${model.package}" targetProject="${target.project}">
            <property name="enableSubPackages" value="true" />
        </javaModelGenerator>
        <!-- 生成的SQL映射文件包名和位置,这里配置将生成的SQL映射文件放在com.tangjf.mapping这个包下 -->
        <sqlMapGenerator targetPackage="${xml.package}" targetProject="${target.project.resources}">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置,这里配置将生成的dao类放在com.tangjf.dao这个包下 -->
        <javaClientGenerator targetPackage="${mapper.package}" targetProject="${target.project}"
            type="XMLMAPPER">
            <property name="enableSubPackages" value="true" />
            <!-- 可以为所有生成的接口添加一个父接口,但是MBG只负责生成,不负责检查 -->
            <property name="rootInterface" value="com.tangjf.framework.dao.BaseMapper" />
        </javaClientGenerator>
        <!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
        <table tableName="${tableName}" domainObjectName="${domainObjectName}" enableCountByExample="false"
            enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false">
            <!-- 如果设置为true,生成的model类会直接使用column本身的名字,而不会再使用驼峰命名方法,比如BORN_DATE,生成的属性名字就是BORN_DATE,而不会是bornDate -->
            <property name="useActualColumnNames" value="true" />
        </table>
    </context>
</generatorConfiguration>


text:
'use strict';

/*
 *
 * given an array of functions, that may or may not return promises sequence
 * will invoke them sequentially. If a promise is encountered sequence will
 * wait until it fulfills before moving to the next entry.
 *
 * ```js
 * var tasks = [
 *   function() { return Promise.resolve(1); },
 *   2,
 *   function() { return timeout(1000).then(function() { return 3; } },
 * ];
 *
 * sequence(tasks).then(function(results) {
 *   results === [
 *     1,
 *     2,
 *     3
 *   ]
 * });
 * ```
 *
 * @method sequence
 * @param tasks
 * @return Promise<Array>
 *
 */
module.exports = function sequence(tasks) {
  let length = tasks.length;
  let current = Promise.resolve();
  let results = new Array(length);

  for (let i = 0; i < length; ++i) {
    current = results[i] = current.then(tasks[i]);
  }

  return Promise.all(results);
};


text:
package se.nullable.sbtix

import sbt._
import sbt.ProjectRef
import sbt.{ Logger, ModuleID, Resolver, PatternsBasedRepository }

object NixWriter {
  def apply(versioning: Set[(String,String)], repos: Set[NixRepo], artifacts: Set[NixArtifact]) = {
    s"""# This file was automatically generated by Sbtix. Do not edit manually.
        |{
        |  ${indent(Versioning(versioning.toSeq.sorted).toNix)}
        |  ${indent(NixRepoCollection(repos.toSeq.sortWith(_.toNixRef < _.toNixRef)).toNix)}
        |  ${indent(NixArtifactCollection(artifacts.toSeq.sortWith(_.toNixRef < _.toNixRef)).toNix)}
        |}
        |""".stripMargin
  }
}

trait NixBuilder {
  def toNix = s"$toNixRef = $toNixValue;"
  def toNixRef: String
  def toNixValue: String
}

case class Versioning(versioning: Seq[(String,String)]) extends NixBuilder {
  val toNixRef = quote("versioning")

  def toNixValue: String = indent(versioning.map{case (scalaVersion,sbtVersion) =>
    s"""{
        |  ${indent(Version("scalaVersion",scalaVersion).toNix)}
        |  ${indent(Version("sbtVersion",sbtVersion).toNix)}
        |}""".stripMargin}.mkString("[","\r\n", "]"))
}

case class Version(name:String, version: String) extends NixBuilder {
  val toNixRef = quote(name)

  def toNixValue: String = quote(version);
}

case class VersionList(name:String, versions: Seq[String]) extends NixBuilder {
  val toNixRef = quote(name)

  def toNixValue: String = versions.map(quote).mkString("[",",","]");
}

case class NixRepoCollection(repos: Seq[NixRepo]) extends NixBuilder {
  val toNixRef = quote("repos")

  def toNixValue: String =
    s"""{
        |  ${indent(repos.distinct.map(_.toNix).mkString("\r\n"))}
        |}""".stripMargin
}

case class NixRepo(name: String, pattern: Option[String]) extends NixBuilder {
  val toNixRef = quote(name)

  def toNixValue: String = quote(pattern.getOrElse(""));
}

case class NixArtifactCollection(artifacts: Seq[NixArtifact]) extends NixBuilder {
  val toNixRef = quote("artifacts")

  def toNixValue: String =
    s"""{
        |  ${indent(artifacts.distinct.map(_.toNix).mkString("\r\n"))}
        |}""".stripMargin

}

case class NixArtifact(repoName: String, relative: String, url: String, sha256: String) extends NixBuilder {
  val toNixRef = s"${quote(repoName + "/" + relative)}"

  def toNixValue =
    s"""{
        |  url = ${quote(url)};
        |  sha256 = ${quote(sha256)};
        |}""".stripMargin
}


text:
import {CardItem} from "./card-item";

export const CARD_ITEMS: CardItem[] = [];


text:
<?xml version="1.0" encoding="utf-8"?>

<it.gmariotti.cardslib.library.view.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card="http://schemas.android.com/apk/res-auto"
    android:id="@+id/list_cardId"
    style="@style/grid_card"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    card:card_layout_resourceID="@layout/base_staggered_layout" />