text:
package gr.rambou.myicarus;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

public class Statistics extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";

    // TODO: Rename and change types of parameters
    private Icarus mParam1;

    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @return A new instance of fragment Statistics.
     */
    // TODO: Rename and change types and number of parameters
    public static Statistics newInstance(String param1) {
        Statistics fragment = new Statistics();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    public Statistics() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = (Icarus) getArguments().getSerializable(ARG_PARAM1);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_statistics, container, false);

        GraphView graph = (GraphView) rootView.findViewById(R.id.graph);
        TextView mo = (TextView) rootView.findViewById(R.id.mo);

        mParam1 = (Icarus) getArguments().getSerializable("myicarus");
        DataPoint[] data = new DataPoint[0];
        ArrayList<Lesson> arraylist;
        GetGrades f = new GetGrades();
        try {
            arraylist = f.execute().get();
            data = new DataPoint[arraylist.size()];

            int i=0;
            double m = 0;
            for(Lesson l : arraylist){
                data[i] = new DataPoint(i,l.Get_Mark());
                m +=l.Get_Mark();
                i++;
            }
            Log.v("",arraylist.size() + " " + m);
            Double k = (double)m/arraylist.size();

            mo.setText("Ο μέσος όρος είναι: " + String.format("%.2f", k) + " και περασμένα μαθήματα "+ arraylist.size() + " από τα 56.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(data);
        graph.addSeries(series);

        // Inflate the layout for this fragment
        return rootView;
    }

    private class GetGrades extends AsyncTask<String, Void, ArrayList<Lesson>> {

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected ArrayList<Lesson> doInBackground(String... params) {
            System.setProperty("jsse.enableSNIExtension", "false");

            mParam1.LoadMarks(null);
            ArrayList<Lesson> arraylist = mParam1.getSucceed_Lessons();

            return arraylist;
        }

        @Override
        protected void onPostExecute(ArrayList<Lesson> result) {

        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    /*@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }*/

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

}


text:
"""
To run test on DirectRunner

python setup.py nosetests \
    --test-pipeline-options="
    --number_of_counter_operations=1000
    --input_options='{
    \"num_records\": 300,
    \"key_size\": 5,
    \"value_size\":15,
    \"bundle_size_distribution_type\": \"const\",
    \"bundle_size_distribution_param\": 1,
    \"force_initial_num_bundles\": 0
    }'" \
    --tests apache_beam.testing.load_tests.par_do_test

To run test on other runner (ex. Dataflow):

python setup.py nosetests \
    --test-pipeline-options="
        --runner=TestDataflowRunner
        --project=...
        --staging_location=gs://...
        --temp_location=gs://...
        --sdk_location=./dist/apache-beam-x.x.x.dev0.tar.gz
        --output=gc
        --number_of_counter_operations=1000
        --input_options='{
        \"num_records\": 1000,
        \"key_size\": 5,
        \"value_size\":15,
        \"bundle_size_distribution_type\": \"const\",
        \"bundle_size_distribution_param\": 1,
        \"force_initial_num_bundles\": 0
        }'" \
    --tests apache_beam.testing.load_tests.par_do_test

"""

from __future__ import absolute_import

import json
import logging
import time
import unittest

import apache_beam as beam
from apache_beam.metrics import Metrics
from apache_beam.testing import synthetic_pipeline
from apache_beam.testing.load_tests.load_test_metrics_utils import MeasureTime
from apache_beam.testing.test_pipeline import TestPipeline

class ParDoTest(unittest.TestCase):
  def parseTestPipelineOptions(self):
    return {'numRecords': self.inputOptions.get('num_records'),
            'keySizeBytes': self.inputOptions.get('key_size'),
            'valueSizeBytes': self.inputOptions.get('value_size'),
            'bundleSizeDistribution': {
                'type': self.inputOptions.get(
                    'bundle_size_distribution_type', 'const'
                ),
                'param': self.inputOptions.get(
                    'bundle_size_distribution_param', 0
                )
            },
            'forceNumInitialBundles': self.inputOptions.get(
                'force_initial_num_bundles', 0
            )
           }

  def setUp(self):
    self.pipeline = TestPipeline(is_integration_test=True)
    self.output = self.pipeline.get_option('output')
    self.iterations = self.pipeline.get_option('number_of_counter_operations')
    self.inputOptions = json.loads(self.pipeline.get_option('input_options'))

  class _MeasureTime(beam.DoFn):
    def __init__(self):
      self.runtime_start = Metrics.distribution('pardo', 'runtime.start')
      self.runtime_end = Metrics.distribution('pardo', 'runtime.end')

    def start_bundle(self):
      self.runtime_start.update(time.time())

    def finish_bundle(self):
      self.runtime_end.update(time.time())

    def process(self, element):
      yield element

  class _GetElement(beam.DoFn):
    def __init__(self):
      self.counter = Metrics.counter('pardo', 'total_bytes.count')

    def process(self, element):
      _, value = element
      for i in range(len(value)):
        self.counter.inc(i)
      yield element

  def testParDo(self):
    if self.iterations is None:
      num_runs = 1
    else:
      num_runs = int(self.iterations)

    with self.pipeline as p:
      pc = (p
            | 'Read synthetic' >> beam.io.Read(
                synthetic_pipeline.SyntheticSource(
                    self.parseTestPipelineOptions()
                ))
            | 'Measure time' >> beam.ParDo(MeasureTime())
           )

      for i in range(num_runs):
        label = 'Step: %d' % i
        pc = (pc
              | label >> beam.ParDo(self._GetElement()))

      if self.output is not None:
        # pylint: disable=expression-not-assigned
        (pc
         | "Write" >> beam.io.WriteToText(self.output)
        )

      result = p.run()
      result.wait_until_finish()
      metrics = result.metrics().query()
      for counter in metrics['counters']:
        logging.info("Counter: %s", counter)

      for dist in metrics['distributions']:
        logging.info("Distribution: %s", dist)

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.INFO)
  unittest.main()

redpajama_set_name: RedPajamaGithub


text:
/*@import url('https://fonts.googleapis.com/css?family=Roboto:100,700');
@import url('https://fonts.googleapis.com/css?family=Open+Sans:300,400,700');*/

@import '_base.css';

@import './core.css';

@import '../components/Header/Header.css';

@import '../routes/Home/components/HomeView.css';

@import './_core-layout.css';
@import './_error-layout.css';

@import './_home.css';
@import './_request-pre-approval.css';
@import './_request-payment.css';
@import './_pre-approvals.css';
@import './_payments.css';
@import './_user-management.css';


text:
var http = require('http'),
    util = require('util'),
    createError = require('createerror'),
    httpErrors = module.exports;

/// Map the error codes/names, as defined in Node's [http
/// module](http://nodejs.org/docs/latest/api/http.html).
Object.keys(http.STATUS_CODES).forEach(function (statusCode) {
    statusCode = +statusCode; // turn into a number
    var httpErrorName = http.STATUS_CODES[statusCode];

    // Only include 4xx and 5xx
    if (statusCode < 400) {
        return;
    }

    // Invent a type by camel casing the usual message and removing
    // non-alphabetical chars
    var name = httpErrorName.replace(/ ([a-z])/gi, function ($0, $1) {
        return $1.toUpperCase();
    }).replace(/[^a-z]/gi, '');

    // Add the error to the exported object and alias it as `statusCode`
    // allows for new httpErrors[res.statusCode] in a http proxying setting
    httpErrors[name] = httpErrors[statusCode] = createError({
        statusCode: statusCode,
        name: name
    });
});


text:
redirect_to: https://anvio.org/help/main/programs/anvi-split
---


text:
using Quilt4.Service.Entity;
using Quilt4Net.Core.DataTransfer;

namespace Quilt4.Service.Converters
{
    public static class IssueTypeConverter
    {
        public static IssueTypeResponse ToIssueTypeResponse(this IssueType x)
        {
            return new IssueTypeResponse { Ticket = x.Ticket, CreationServerTime = x.CreationServerTime, IssueTypeKey = x.IssueTypeKey, VersionKey = x.VersionKey, Message = x.Message, Type = x.Type, Level = x.Level, StackTrace = x.StackTrace };
        }
    }
}


text:
require "rails_helper"

RSpec.describe "Slack Teams", type: :model do
  it "can create and retrieve config vars" do
    team = Team.create(team_id: "T123YG08V")

    setting = team.setting("api-key")
    expect(setting.value).to eql(nil)
    setting.value = "sekret"
    setting.save

    team.reload
    setting = team.setting("api-key")
    expect(setting.value).to eql("sekret")
  end
end


text:
package tt.dao.business;

import tt.dao.BaseDaoI;
import tt.model.business.InspectPlan;

import java.util.List;

/**
 * Created by taotao on 2016/9/23.
 */
public interface InspectPlanDaoI extends BaseDaoI<InspectPlan> {
    List<InspectPlan> list(String name, Integer page, Integer pageSize,Integer dept_id);
    InspectPlan getByPrgStzhDevNB(String prg,String stzh, String DevNB);
    boolean isExistStzh(Integer project_id,String stzh,Integer dept_id);
}


text:
export interface IKeyWhitelist<T> {
    include: Array<keyof T>;
}
export interface IKeyBlacklist<T> {
    exclude: Array<keyof T>;
}
/**
 * Returns true if the arrays are equal. Elements will be shallowly compared by
 * default, or they will be compared using the custom `compare` function if one
 * is provided.
 */
export declare function arraysEqual(arrA: any[], arrB: any[], compare?: (a: any, b: any) => boolean): boolean;
/**
 * Shallow comparison between objects. If `keys` is provided, just that subset
 * of keys will be compared; otherwise, all keys will be compared.
 */
export declare function shallowCompareKeys<T extends object>(objA: T, objB: T, keys?: IKeyBlacklist<T> | IKeyWhitelist<T>): boolean;
/**
 * Deep comparison between objects. If `keys` is provided, just that subset of
 * keys will be compared; otherwise, all keys will be compared.
 */
export declare function deepCompareKeys(objA: any, objB: any, keys?: string[]): boolean;
/**
 * Returns a descriptive object for each key whose values are shallowly unequal
 * between two provided objects. Useful for debugging shouldComponentUpdate.
 */
export declare function getShallowUnequalKeyValues<T extends object>(objA: T, objB: T, keys?: IKeyBlacklist<T> | IKeyWhitelist<T>): {
    key: never;
    valueA: any;
    valueB: any;
}[];
/**
 * Returns a descriptive object for each key whose values are deeply unequal
 * between two provided objects. Useful for debugging shouldComponentUpdate.
 */
export declare function getDeepUnequalKeyValues<T extends object>(objA?: T, objB?: T, keys?: Array<keyof T>): {
    key: keyof T;
    valueA: T[keyof T];
    valueB: T[keyof T];
}[];


text:
Contributing to HELPq
=====================

Thank you for using HELPq, and we're really excited that you want to help out!

Development Process
-------------------

This project is developed mostly by me (Edwin Zhang), but quite a few hackathons have their own forks. Releases to master can be expected to be stable and ready to use (with configuration, of course), but dev will be the most up to date.

Pull Requests
-------------

We actively welcome your pull requests!

However, before you begin, please create an issue so we can determine if the work, feature, or bugfix either has someone is already working on it as a part of the current roadmap, or if the feature is not something that would belong in the HELPq as a core feature.

This is mostly meant for discussion, so we can discuss things fully and make a really awesome product :)

Issues
------

We use issues to track public bugs. Please make sure your description is clear and has sufficient instructions to be able to reproduce the issue.

We also use issues to track feature requests and discuss. Please mark your issue as 'Feature Request' in this case!

Coding Style
------------

Keep it clean, and keep things modular!


text:
package <%= managed_package %>;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.google.gwt.place.shared.PlaceController;

import static <%= gwt_rails_package %>.places.RestfulActionEnum.*;

import <%= gwt_rails_package %>.session.Guard;
import <%= gwt_rails_package %>.views.SessionMenu;

@Singleton
public class <%= application_class_name %>Menu extends SessionMenu {

    @Inject
    <%= application_class_name %>Menu(final PlaceController placeController,
                        final Guard guard){
        super(placeController, guard);
    }
}


text:
// DX8Keyboard.cpp
// Implementation of our DirectX 8 keyboard handling code
// (c) 2002 Marty Dill

#include "Fizz3d.h"
#include "DX8Keyboard.h"
#include "DirectX8.h"
#include "Engine.h"
#include "Log.h"

static const char* moduleName = "DX8Keyboard";

// Constructor
DX8Keyboard::DX8Keyboard() :
	device(NULL), acquired(false)
{
	memset(lastKeys, 0, 256);
}

// Destructor
DX8Keyboard::~DX8Keyboard()
{
}

// Sets up the keyboard device
int DX8Keyboard::initialize(void* initParameter)
{
	Trace("Creating keyboard device");
	DX8::CreateInputDevice(GUID_SysKeyboard, &device);

	HRESULT hr;

	Trace("Setting keyboard data format");
	hr = device->SetDataFormat(&c_dfDIKeyboard);
	if(FAILED(hr))
		CEngine::CriticalError("Unable to set keyboard data format!!");

	Trace("Setting keyboard cooperative level");
	hr = device->SetCooperativeLevel(NULL, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE);
	if(FAILED(hr))
		CEngine::CriticalError("Unable to set keyboard cooperative level!!");

	return 0;
}

// Updates keyboard position
int DX8Keyboard::update(KeyboardData* data)
{
	Assert(data != NULL);

	if(!acquired)
	{
		HRESULT hr = device->Acquire();
		if(FAILED(hr))
			return 1;

		acquired = true;
	}

	//memcpy(lastKeys, keys, 256);

	HRESULT hr = device->GetDeviceState(sizeof(unsigned char) * 256, (LPVOID)&keys);
	if(FAILED(hr))
	{
		acquired = false;
		return 1;
	}

	memcpy(data->keys, keys, 256);

	for(int i = 0; i < 256; ++i)
	{
		if(keys[i] != lastKeys[i])
		{
			data->changedKeys[i] = 1;
		}
		else
		{
			data->changedKeys[i] = 0;
		}
	}

	memcpy(lastKeys, keys, 256);

	return 0;
}

// Destroys/releases the keyboard device
int DX8Keyboard::destroy(void)
{
	if(device != NULL)
	{
		Trace("Releasing keyboard device");
		device->Unacquire();
		device->Release();
		device = NULL;
	}

	return 0;
}

char DX8Keyboard::getCharacterForKey(int scanCode)
{
	static HKL layout = GetKeyboardLayout(0);
	static UCHAR keyboardState[256];
	if (GetKeyboardState(keyboardState) == false)
		return 0;

	//translate keyboard press scan code identifier to a char
	UINT vk = MapVirtualKeyEx(scanCode, 1, layout);
	USHORT asciiValue;
	ToAscii(vk, scanCode, keyboardState, &asciiValue, 0);

	return static_cast<char>(asciiValue);

}


text:
Hilary does not depend on other libraries. All you need to do to use it in a web app is include it in a script tag.

```HTML
<script src="hilary.min.js"></script>
```

### The AMD extensions
By default, hilary's ``register`` and ``resolve`` functions accept AMD style arguments. AMD syntax, ``define`` and ``register``, can be added with the AMD extension.

```HTML
<script src="hilary.amd.min.js"></script>
```

> Note that hilary AMD excludes module loading. We might add a loader extension for that in the future - let us know if that's important to you via Github issues.


text:
EXPMatcherInterface(regexMatch, (id pattern))

#define regexMatch regexMatch


text:
require 'spec_helper'

describe ContactsHelper, :type => :helper do
  before do
    @user = FactoryGirl.create(:user)
    @template = FactoryGirl.create(:extra_detail_template, user: @user)
    @contact  = FactoryGirl.build(:contact, user: @user, extra_detail_template: @template)
  end

  describe '#extra_detail_forms_for' do
    it 'should return form inputs available for given user' do
      expect(extra_detail_forms_for(@user, @contact)).to have_selector(:css, "label[for=contact_extra_detail_template_#{@template.id}]")
      expect(extra_detail_forms_for(@user, @contact)).to have_selector(:css, "input[id=contact_extra_detail_template_#{@template.id}]")
    end
  end

end


text:
module UKMail
  module Service
    class ServiceBase
      attr_accessor :session

      def initialize(session)
        @session = session
      end

      protected

      def soap_service
        raise NotImplementedError
      end

      def make_request(request_class, params)
        request = request_class.new(self, params)
        request.build
        handle_validation_errors(request.validation_errors)
        response = request.get_response
        handle_uk_mail_errors(response) if response.result != 'Successful'
        response
      end

      def handle_validation_errors(validation_errors)
        missing_fields = validation_errors[:missing]
        return if missing_fields.nil? || missing_fields.empty?
        message = 'The following required fields are missing or empty: ' + missing_fields.join(', ')
        raise UKMail::ValidationError, message
      end

      def handle_uk_mail_errors(response)
        message = response.errors.map do |error|
          "#{error.code}: #{error.description}"
        end.join("\n")
        raise UKMail::UKMailError, message
      end
    end
  end
end


text:
package sbserver

import (
	"context"
	"fmt"
	"time"

	"github.com/containerd/containerd/errdefs"
	"github.com/containerd/containerd/log"

	"github.com/sirupsen/logrus"
	runtime "k8s.io/cri-api/pkg/apis/runtime/v1"
)

// RemovePodSandbox removes the sandbox. If there are running containers in the
// sandbox, they should be forcibly removed.
func (c *criService) RemovePodSandbox(ctx context.Context, r *runtime.RemovePodSandboxRequest) (*runtime.RemovePodSandboxResponse, error) {
	start := time.Now()
	sandbox, err := c.sandboxStore.Get(r.GetPodSandboxId())
	if err != nil {
		if !errdefs.IsNotFound(err) {
			return nil, fmt.Errorf("an error occurred when try to find sandbox %q: %w",
				r.GetPodSandboxId(), err)
		}
		// Do not return error if the id doesn't exist.
		log.G(ctx).Tracef("RemovePodSandbox called for sandbox %q that does not exist",
			r.GetPodSandboxId())
		return &runtime.RemovePodSandboxResponse{}, nil
	}
	// Use the full sandbox id.
	id := sandbox.ID

	// If the sandbox is still running, not ready, or in an unknown state, forcibly stop it.
	// Even if it's in a NotReady state, this will close its network namespace, if open.
	// This can happen if the task process associated with the Pod died or it was killed.
	logrus.Infof("Forcibly stopping sandbox %q", id)
	if err := c.stopPodSandbox(ctx, sandbox); err != nil {
		return nil, fmt.Errorf("failed to forcibly stop sandbox %q: %w", id, err)
	}

	// Return error if sandbox network namespace is not closed yet.
	if sandbox.NetNS != nil {
		nsPath := sandbox.NetNS.GetPath()
		if closed, err := sandbox.NetNS.Closed(); err != nil {
			return nil, fmt.Errorf("failed to check sandbox network namespace %q closed: %w", nsPath, err)
		} else if !closed {
			return nil, fmt.Errorf("sandbox network namespace %q is not fully closed", nsPath)
		}
	}

	// Remove all containers inside the sandbox.
	// NOTE(random-liu): container could still be created after this point, Kubelet should
	// not rely on this behavior.
	// TODO(random-liu): Introduce an intermediate state to avoid container creation after
	// this point.
	cntrs := c.containerStore.List()
	for _, cntr := range cntrs {
		if cntr.SandboxID != id {
			continue
		}
		_, err = c.RemoveContainer(ctx, &runtime.RemoveContainerRequest{ContainerId: cntr.ID})
		if err != nil {
			return nil, fmt.Errorf("failed to remove container %q: %w", cntr.ID, err)
		}
	}

	// Use sandbox controller to delete sandbox
	controller, err := c.getSandboxController(sandbox.Config, sandbox.RuntimeHandler)
	if err != nil {
		return nil, fmt.Errorf("failed to get sandbox controller: %w", err)
	}
	if _, err := controller.Delete(ctx, id); err != nil {
		return nil, fmt.Errorf("failed to delete sandbox %q: %w", id, err)
	}

	// Remove sandbox from sandbox store. Note that once the sandbox is successfully
	// deleted:
	// 1) ListPodSandbox will not include this sandbox.
	// 2) PodSandboxStatus and StopPodSandbox will return error.
	// 3) On-going operations which have held the reference will not be affected.
	c.sandboxStore.Delete(id)

	if err := c.client.SandboxStore().Delete(ctx, id); err != nil {
		return nil, fmt.Errorf("failed to remove sandbox metadata from store: %w", err)
	}

	// Release the sandbox name reserved for the sandbox.
	c.sandboxNameIndex.ReleaseByKey(id)

	sandboxRemoveTimer.WithValues(sandbox.RuntimeHandler).UpdateSince(start)

	return &runtime.RemovePodSandboxResponse{}, nil
}


text:
Configuration
=============

The only mandatory configuration is adding ``import_export`` to your
``INSTALLED_APPS``. This isn't necessary, if admin integration is not
used.


text:
from p5 import *

from walker import Walker

def setup():
    global walker
    size(800, 200)
    background(255)
    walker = Walker()

def draw():
    walker.step()
    walker.render()

run()


text:
package org.apache.camel.dataformat.csv;

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

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

import static org.hamcrest.core.StringStartsWith.startsWith;

public class CsvMarshalCharsetTest extends CamelTestSupport {

    @Test
    public void testMarshal() throws Exception {
        MockEndpoint endpoint = getMockEndpoint("mock:daltons");
        endpoint.expectedMessageCount(1);

        List<List<String>> data = new ArrayList<List<String>>();
        data.add(0, new ArrayList<String>());
        data.get(0).add(0, "L\u00fccky Luke");
        Exchange in = createExchangeWithBody(data);
        in.setProperty(Exchange.CHARSET_NAME, "ISO-8859-1");
        template.send("direct:start", in);

        endpoint.assertIsSatisfied();

        Exchange exchange = endpoint.getExchanges().get(0);
        String body = exchange.getIn().getBody(String.class);
        assertThat(body, startsWith("L\u00fccky Luke"));
    }

    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() {
                from("direct:start").marshal().csv().to("mock:daltons");
            }
        };
    }
}


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

<title>NaturalIdRegion (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.hibernate.cache.spi

Interface NaturalIdRegion

All Superinterfaces:

Region, TransactionalDataRegion

All Known Implementing Classes:

EhcacheNaturalIdRegion, NaturalIdRegionImpl

public interface NaturalIdRegion
extends TransactionalDataRegion

Defines the contract for a cache region which will specifically be used to
store naturalId data.

Method Summary

Methods

Modifier and Type
Method and Description

NaturalIdRegionAccessStrategy
buildAccessStrategy(AccessType accessType)

Methods inherited from interface org.hibernate.cache.spi.TransactionalDataRegion

getCacheDataDescription, isTransactionAware

Methods inherited from interface org.hibernate.cache.spi.Region

contains, destroy, getElementCountInMemory, getElementCountOnDisk, getName, getSizeInMemory, getTimeout, nextTimestamp, toMap

Method Detail

buildAccessStrategy

NaturalIdRegionAccessStrategy buildAccessStrategy(AccessType accessType)
                                                  throws CacheException

Build an access strategy for the requested access type.

Parameters:

accessType - The type of access strategy to build; never null.

Returns:

The appropriate strategy contract for accessing this region
for the requested type of access.

Throws:

CacheException - Usually indicates mis-configuration.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2001-2014 Red Hat, Inc.  All Rights Reserved.


text:
<?php
require(dirname(__FILE__).'/_autoload.class.php');

use CWG\Moip\MoipPagamento;

$token =  'J27IIMSM0MWSQJIXT1MDUTHZFBWMV4W2';
$key = 'IEVEAUWW0E4GX6FPYIEUHC7YTJEGOFNYXCEPKAER';
$sandbox = true;

$moipPag = new MoipPagamento($token, $key, $sandbox);

$urlPagamento = $moipPag->setID(uniqid())   //ID unico para identificar a compra
                        ->setPreco(50.00)   //Preço da compra
                        ->setVendedor('carloswgama@gmail.com') //Adiciona quem deverá receber o apagamento ao invés da conta vinculada a API
                        //->addComissao('carloswgama@gmail.com', 10) //Adiciona outro vendedor que irá receber 10 reais de comissão  do vendedor principal dessa venda
                        //->addComissao('carloswgama3@gmail.com', 10, TRUE) //Adiciona outro vendedor que irá receber 10% (5 reais) de comissão  do vendedor principal dessa venda
                        ->addFormaPagamento(MoipPagamento::CHECKOUT_BOLETO) //Libera forma de pagamento Boleto
                        ->configurarBoleto('2017-03-01', 'http://site.com.br/logo.png', array('Linha 1', 'Linha 2')) //Informações do boleto
                        ->addFormaPagamento(MoipPagamento::CHECKOUT_CARTAO) //Libera forma de pagamento por cartão
                        ->setDescricao('Descrição da Compra')
                        ->pagar();

if (!$urlPagamento) die ($moipPag->getErro());

echo "URL para o checkout do moip: " . $urlPagamento;


text:
package com.gor.sellphotos;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

/**
 * see https://github.com/bijukunjummen/spring-websocket-chat-sample/blob/master/src/main/java/bk/chat/SampleWebApplicationInitializer.java
 */
public class SellPhotosWebApplicationInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        application.sources(SellPhotos.class);
        return super.configure(application);
    }

}


text:
set -e
export CC=$DRAKE_CC
export CXX=$DRAKE_CXX
$CC -v
mkdir -p $TRAVIS_BUILD_DIR/build
if [ "$TRAVIS_OS_NAME" = "linux" ]; then
    export DEBIAN_FRONTEND=noninteractive
    sudo -E apt-get update -qq
    export CMAKE_FLAGS="-DWITH_AVL:BOOL=ON -DWITH_DIRECTOR:BOOL=ON -DWITH_IRIS:BOOL=ON -DWITH_LIBBOT:BOOL=ON -DWITH_MOSEK:BOOL=ON -DWITH_OCTOMAP:BOOL=ON -DWITH_SPOTLESS:BOOL=OFF -DWITH_SWIG_MATLAB=ON -DWITH_XFOIL:BOOL=ON"
    make download-all
    sudo -E ./install_prereqs.sh ubuntu
elif [ "$TRAVIS_OS_NAME" = "osx" ]; then
    brew update > brew_update.log
    export CMAKE_FLAGS="-DWITH_AVL:BOOL=ON -DWITH_DIRECTOR:BOOL=OFF -DWITH_IRIS:BOOL=ON -DWITH_LIBBOT:BOOL=ON -DWITH_MOSEK:BOOL=ON -DWITH_OCTOMAP:BOOL=ON -DWITH_SPOTLESS:BOOL=OFF -DWITH_XFOIL:BOOL=ON"
    make download-all > download.log || (cat download.log && exit 1)
    ./install_prereqs.sh homebrew
else
    exit 1
fi
make


text:
"""
Script to help deploy a Fluo or Accumulo cluster (optionally to AWS EC2)
"""

import os
import sys
from sys import exit
import shutil
from botocore.exceptions import ClientError
from config import DeployConfig, HOST_VAR_DEFAULTS, PLAY_VAR_DEFAULTS
from util import parse_args, AMI_HELP_MSG, get_block_device_map
from os.path import isfile, join
import time
import subprocess
import boto3

class MuchosCluster:

    def __init__(self, config):
        self.config = config

    def launch_node(self, hostname, services, sg_id):

        associate_public_ip = True
        if self.config.has_option('ec2', 'associate_public_ip'):
            associate_public_ip = self.config.get('ec2', 'associate_public_ip').strip().lower() == 'true'

        request = {'MinCount': 1, 'MaxCount': 1,
                   'NetworkInterfaces': [{'DeviceIndex': 0, 'AssociatePublicIpAddress': associate_public_ip,
                                          'Groups': [sg_id]}]}

        if self.config.has_option('ec2', 'subnet_id'):
            request['NetworkInterfaces'][0]['SubnetId'] = self.config.get('ec2', 'subnet_id')

        if 'worker' in services:
            instance_type = self.config.get('ec2', 'worker_instance_type')
        else:
            instance_type = self.config.get('ec2', 'default_instance_type')
        request['InstanceType'] = instance_type
        request['InstanceInitiatedShutdownBehavior'] = self.config.get('ec2', 'shutdown_behavior')

        if not self.config.has_option('ec2', 'aws_ami'):
            exit('aws_ami property must be set!')
        image_id = self.config.get('ec2', 'aws_ami')
        if not image_id:
            exit('aws_ami property was not properly')

        request['ImageId'] = image_id
        request['BlockDeviceMappings'] = get_block_device_map(instance_type)

        if self.config.has_option('ec2', 'key_name'):
            request['KeyName'] = self.config.get('ec2', 'key_name')

        tags = [{'Key': 'Name', 'Value': self.config.cluster_name + '-' + hostname},
                {'Key': 'Muchos', 'Value': self.config.cluster_name}]
        for key, val in self.config.instance_tags().iteritems():
            tags.append({'Key': key, 'Value': val})
        request['TagSpecifications'] = [{'ResourceType': 'instance', 'Tags': tags}]

        if self.config.has_option('ec2', 'user_data_path'):
            user_data_path = self.config.get('ec2', 'user_data_path')
            with open(user_data_path, 'r') as user_data_file:
                user_data = user_data_file.read()
            request['UserData'] = user_data

        ec2 = boto3.client('ec2')
        response = None
        try:
            response = ec2.run_instances(**request)
        except ClientError as e:
            exit("ERROR - Failed to launch EC2 instance due to exception:\n\n{0}\n\n{1}".format(e, AMI_HELP_MSG))

        if response is None or len(response['Instances']) != 1:
            exit('ERROR - Failed to start {0} node'.format(hostname))

        print 'Launching {0} node using {1}'.format(hostname, image_id)
        return response['Instances'][0]

    def create_security_group(self):
        ec2 = boto3.client('ec2')
        sg = self.config.sg_name
        create_group = True
        group_id = None
        try:
            response = ec2.describe_security_groups(Filters=[{'Name': 'group-name', 'Values': [sg]}])
            if len(response['SecurityGroups']) > 0:
                group_id = response['SecurityGroups'][0]['GroupId']
                create_group = False
        except ClientError:
            pass

        if create_group:
            print "Creating security group " + sg
            request = {'Description': "Security group created by Muchos", 'GroupName': sg}
            if self.config.has_option('ec2', 'vpc_id'):
                request['VpcId'] = self.config.get('ec2', 'vpc_id')
            response = ec2.create_security_group(**request)
            group_id = response['GroupId']
            ec2.authorize_security_group_ingress(GroupName=sg, SourceSecurityGroupName=sg)
            ec2.authorize_security_group_ingress(GroupName=sg, IpProtocol='tcp', FromPort=22, ToPort=22,
                                                 CidrIp='0.0.0.0/0')
        return group_id

    def delete_security_group(self):
        sg_id = None
        ec2 = boto3.client('ec2')
        try:
            response = ec2.describe_security_groups(Filters=[{'Name': 'group-name', 'Values': [self.config.sg_name]}])
            if len(response['SecurityGroups']) > 0:
                sg_id = response['SecurityGroups'][0]['GroupId']
        except ClientError:
            pass

        if not sg_id:
            print "Could not find security group '{0}'".format(self.config.sg_name)
            return

        print "Attempting to delete security group '{0}' with id '{1}'...".format(self.config.sg_name, sg_id)
        sg_exists = True
        while sg_exists:
            try:
                request = {'GroupId': sg_id}
                ec2.delete_security_group(**request)
                sg_exists = False
            except ClientError as e:
                print "Failed to delete security group '{0}' due exception below:\n{1}\nRetrying in 10 sec..."\
                    .format(self.config.sg_name, e)
                time.sleep(10)
        print "Deleted security group"

    def launch(self):
        if self.active_nodes():
            exit('ERROR - There are already instances running for {0} cluster'.format(self.config.cluster_name))

        if isfile(self.config.hosts_path):
            exit("ERROR - A hosts file already exists at {0}.  Please delete before running launch again"
                 .format(self.config.hosts_path))

        self.config.verify_launch()

        print "Launching {0} cluster".format(self.config.cluster_name)

        if self.config.has_option('ec2', 'security_group_id'):
            sg_id = self.config.get('ec2', 'security_group_id')
        else:
            sg_id = self.create_security_group()

        instance_d = {}
        for (hostname, services) in self.config.nodes().items():
            instance = self.launch_node(hostname, services, sg_id)
            instance_d[instance['InstanceId']] = hostname

        num_running = len(self.status(['running']))
        num_expected = len(self.config.nodes())
        while num_running != num_expected:
            print "{0} of {1} nodes have started.  Waiting another 5 sec..".format(num_running, num_expected)
            time.sleep(5)
            num_running = len(self.status(['running']))

        with open(self.config.hosts_path, 'w') as hosts_file:
            for instance in self.status(['running']):
                public_ip = ''
                if 'PublicIpAddress' in instance:
                    public_ip = instance['PublicIpAddress']
                private_ip = instance['PrivateIpAddress']
                hostname = instance_d[instance['InstanceId']]
                print >>hosts_file, hostname, private_ip, public_ip

        print "All {0} nodes have started. Created hosts file at {1}".format(num_expected, self.config.hosts_path)

    def sync(self):
        config = self.config
        print 'Syncing ansible directory on {0} cluster proxy node'.format(config.cluster_name)

        host_vars = HOST_VAR_DEFAULTS
        play_vars = PLAY_VAR_DEFAULTS

        for section in ("general", "ansible-vars", config.get('performance', 'profile')):
            for (name, value) in config.items(section):
                if name not in ('proxy_hostname', 'proxy_socks_port'):
                    if name in host_vars:
                        host_vars[name] = value
                    if name in play_vars:
                        play_vars[name] = value

        play_vars['accumulo_sha256'] = config.checksum('accumulo')
        play_vars['fluo_sha256'] = config.checksum('fluo')
        play_vars['fluo_yarn_sha256'] = config.checksum('fluo_yarn')
        play_vars['hadoop_sha256'] = config.checksum('hadoop')
        play_vars['spark_sha256'] = config.checksum('spark')
        play_vars['zookeeper_sha256'] = config.checksum('zookeeper')

        cloud_provider = host_vars.get('cloud_provider', 'ec2')
        node_type_map = {}
        if cloud_provider == 'ec2':
            node_type_map = config.node_type_map()
            play_vars["mount_root"] = config.mount_root
            play_vars["metrics_drive_ids"] = config.metrics_drive_ids()
            play_vars["fstype"] = config.fstype()
            play_vars["force_format"] = config.force_format()
            play_vars["shutdown_delay_minutes"] = config.get("ec2", "shutdown_delay_minutes")
        if cloud_provider == 'baremetal':
            play_vars["mount_root"] = config.get("baremetal", "mount_root")
            play_vars["metrics_drive_ids"] = config.get("baremetal", "metrics_drives_ids").split(",")
            mounts = config.get("baremetal", "mounts").split(",")
            devices = config.get("baremetal", "devices").split(",")
            for node_type in 'default', 'worker':
                node_type_map[node_type] = {'mounts': mounts, 'devices': devices}

        play_vars["node_type_map"] = node_type_map
        host_vars['worker_data_dirs'] = str(node_type_map['worker']['mounts'])
        host_vars['default_data_dirs'] = str(node_type_map['default']['mounts'])

        with open(join(config.deploy_path, "ansible/site.yml"), 'w') as site_file:
            print >>site_file, "- import_playbook: common.yml"
            if config.has_service("spark"):
                print >>site_file, "- import_playbook: spark.yml"
            print >>site_file, "- import_playbook: hadoop.yml"
            print >>site_file, "- import_playbook: zookeeper.yml"
            if config.has_service("metrics"):
                print >>site_file, "- import_playbook: metrics.yml"
            print >>site_file, "- import_playbook: accumulo.yml"
            if config.has_service('fluo'):
                print >>site_file, "- import_playbook: fluo.yml"
            if config.has_service('fluo_yarn'):
                print >>site_file, "- import_playbook: fluo_yarn.yml"
            if config.has_service("mesosmaster"):
                print >>site_file, "- import_playbook: mesos.yml"

        ansible_conf = join(config.deploy_path, "ansible/conf")
        with open(join(ansible_conf, "hosts"), 'w') as hosts_file:
            print >>hosts_file, "[proxy]\n{0}".format(config.proxy_hostname())
            print >>hosts_file, "\n[accumulomaster]\n{0}".format(config.get_service_hostnames("accumulomaster")[0])
            print >>hosts_file, "\n[namenode]\n{0}".format(config.get_service_hostnames("namenode")[0])
            print >>hosts_file, "\n[resourcemanager]\n{0}".format(config.get_service_hostnames("resourcemanager")[0])
            if config.has_service("spark"):
                print >>hosts_file, "\n[spark]\n{0}".format(config.get_service_hostnames("spark")[0])
            if config.has_service("mesosmaster"):
                print >>hosts_file, "\n[mesosmaster]\n{0}".format(config.get_service_hostnames("mesosmaster")[0])
            if config.has_service("metrics"):
                print >>hosts_file, "\n[metrics]\n{0}".format(config.get_service_hostnames("metrics")[0])

            print >>hosts_file, "\n[zookeepers]"
            for (index, zk_host) in enumerate(config.get_service_hostnames("zookeeper"), start=1):
                print >>hosts_file, "{0} id={1}".format(zk_host, index)

            if config.has_service('fluo'):
                print >>hosts_file, "\n[fluo]"
                for host in config.get_service_hostnames("fluo"):
                    print >>hosts_file, host

            if config.has_service('fluo_yarn'):
                print >>hosts_file, "\n[fluo_yarn]"
                for host in config.get_service_hostnames("fluo_yarn"):
                    print >>hosts_file, host

            print >>hosts_file, "\n[workers]"
            for worker_host in config.get_service_hostnames("worker"):
                print >>hosts_file, worker_host

            print >>hosts_file, "\n[accumulo:children]\naccumulomaster\nworkers"
            print >>hosts_file, "\n[hadoop:children]\nnamenode\nresourcemanager\nworkers"

            print >>hosts_file, "\n[nodes]"
            for (private_ip, hostname) in config.get_private_ip_hostnames():
                print >>hosts_file, "{0} ansible_ssh_host={1} node_type={2}".format(hostname, private_ip,
                                                                                config.node_type(hostname))

            print >>hosts_file, "\n[all:vars]"
            for (name, value) in sorted(host_vars.items()):
                print >>hosts_file, "{0} = {1}".format(name, value)

        with open(join(config.deploy_path, "ansible/group_vars/all"), 'w') as play_vars_file:
            for (name, value) in sorted(play_vars.items()):
                print >>play_vars_file, "{0}: {1}".format(name, value)

        # copy keys file to ansible/conf (if it exists)
        conf_keys = join(config.deploy_path, "conf/keys")
        ansible_keys = join(ansible_conf, "keys")
        if isfile(conf_keys):
            shutil.copyfile(conf_keys, ansible_keys)
        else:
            open(ansible_keys, 'w').close()

        basedir = config.get('general', 'cluster_basedir')
        cmd = "rsync -az --delete -e \"ssh -o 'StrictHostKeyChecking no'\""
        subprocess.call("{cmd} {src} {usr}@{ldr}:{tdir}".format(cmd=cmd, src=join(config.deploy_path, "ansible"),
                        usr=config.get('general', 'cluster_user'), ldr=config.get_proxy_ip(), tdir=basedir),
                        shell=True)

        self.exec_on_proxy_verified("{0}/ansible/scripts/install_ansible.sh".format(basedir), opts='-t')

    def setup(self):
        config = self.config
        print 'Setting up {0} cluster'.format(config.cluster_name)

        self.sync()

        conf_upload = join(config.deploy_path, "conf/upload")
        accumulo_tarball = join(conf_upload, "accumulo-{0}-bin.tar.gz".format(config.version("accumulo")))
        fluo_tarball = join(conf_upload, "fluo-{0}-bin.tar.gz".format(config.version("fluo")))
        fluo_yarn_tarball = join(conf_upload, "fluo-yarn-{0}-bin.tar.gz".format(config.version("fluo_yarn")))
        basedir = config.get('general', 'cluster_basedir')
        cluster_tarballs = "{0}/tarballs".format(basedir)
        self.exec_on_proxy_verified("mkdir -p {0}".format(cluster_tarballs))
        if isfile(accumulo_tarball):
            self.send_to_proxy(accumulo_tarball, cluster_tarballs)
        if isfile(fluo_tarball) and config.has_service('fluo'):
            self.send_to_proxy(fluo_tarball, cluster_tarballs)
        if isfile(fluo_yarn_tarball) and config.has_service('fluo_yarn'):
            self.send_to_proxy(fluo_yarn_tarball, cluster_tarballs)

        self.execute_playbook("site.yml")

    def status(self, states):
        ec2 = boto3.client('ec2')
        response = ec2.describe_instances(Filters=[{'Name': 'tag:Muchos', 'Values': [self.config.cluster_name]}])
        nodes = []
        for res in response['Reservations']:
            for inst in res['Instances']:
                if inst['State']['Name'] in states:
                    nodes.append(inst)
        return nodes

    def active_nodes(self):
        return self.status(['pending', 'running', 'stopping', 'stopped'])

    @staticmethod
    def print_nodes(nodes):
        for node in nodes:
            name = 'Unknown'
            for tag in node['Tags']:
                if tag['Key'] == 'Name':
                    name = tag['Value']
            print "  ", name, node['InstanceId'], node['PrivateIpAddress'], node.get('PublicIpAddress', '')

    def terminate(self, hosts_path):
        nodes = self.active_nodes()
        print "The following {0} nodes in {1} cluster will be terminated:".format(len(nodes), self.config.cluster_name)
        self.print_nodes(nodes)

        response = raw_input("Do you want to continue? (y/n) ")
        if response == "y":
            ec2 = boto3.client('ec2')
            for node in nodes:
                ec2.terminate_instances(InstanceIds=[node['InstanceId']])

            print "Terminated nodes."
            if not self.config.has_option('ec2', 'security_group_id'):
                self.delete_security_group()

            if isfile(hosts_path):
                os.remove(hosts_path)
                print "Removed hosts file at ", hosts_path
        else:
            print "Aborted termination"

    def ssh(self):
        self.wait_until_proxy_ready()
        fwd = ''
        if self.config.has_option('general', 'proxy_socks_port'):
            fwd = "-D " + self.config.get('general', 'proxy_socks_port')
        ssh_command = "ssh -C -A -o 'StrictHostKeyChecking no' {fwd} {usr}@{ldr}".format(
            usr=self.config.get('general', 'cluster_user'), ldr=self.config.get_proxy_ip(), fwd=fwd)
        print "Logging into proxy using: {0}".format(ssh_command)
        retcode = subprocess.call(ssh_command, shell=True)
        if retcode != 0:
            exit("ERROR - Command failed with return code of {0}: {1}".format(retcode, ssh_command))

    def exec_on_proxy(self, command, opts=''):
        ssh_command = "ssh -A -o 'StrictHostKeyChecking no' {opts} {usr}@{ldr} '{cmd}'".format(
                usr=self.config.get('general', 'cluster_user'),
                ldr=self.config.get_proxy_ip(), cmd=command, opts=opts)
        return subprocess.call(ssh_command, shell=True), ssh_command

    def exec_on_proxy_verified(self, command, opts=''):
        (retcode, ssh_command) = self.exec_on_proxy(command, opts)
        if retcode != 0:
            exit("ERROR - Command failed with return code of {0}: {1}".format(retcode, ssh_command))

    def wait_until_proxy_ready(self):
        cluster_user = self.config.get('general', 'cluster_user')
        print "Checking if '{0}' proxy can be reached using: ssh {1}@{2}"\
            .format(self.config.proxy_hostname(), cluster_user, self.config.get_proxy_ip())
        while True:
            (retcode, ssh_command) = self.exec_on_proxy('pwd > /dev/null')
            if retcode == 0:
                print "Connected to proxy using SSH!"
                time.sleep(1)
                break
            print "Proxy could not be accessed using SSH.  Will retry in 5 sec..."
            time.sleep(5)

    def execute_playbook(self, playbook):
        print "Executing '{0}' playbook".format(playbook)
        basedir = self.config.get('general', 'cluster_basedir')
        self.exec_on_proxy_verified("time -p ansible-playbook {base}/ansible/{playbook}"
                                    .format(base=basedir, playbook=playbook), opts='-t')

    def send_to_proxy(self, path, target, skip_if_exists=True):
        print "Copying to proxy: ", path
        cmd = "scp -o 'StrictHostKeyChecking no'"
        if skip_if_exists:
            cmd = "rsync --update --progress -e \"ssh -o 'StrictHostKeyChecking no'\""
        subprocess.call("{cmd} {src} {usr}@{ldr}:{tdir}".format(
            cmd=cmd, src=path, usr=self.config.get('general', 'cluster_user'), ldr=self.config.get_proxy_ip(),
            tdir=target), shell=True)

def main():
    deploy_path = os.environ.get('MUCHOS_HOME')
    if not deploy_path:
        exit('ERROR - MUCHOS_HOME env variable must be set!')
    if not os.path.isdir(deploy_path):
        exit('ERROR - Directory set by MUCHOS_HOME does not exist: '+deploy_path)

    config_path = join(deploy_path, "conf/muchos.props")
    if not isfile(config_path):
        exit('ERROR - A config file does not exist at '+config_path)
    checksums_path = join(deploy_path, "conf/checksums")
    if not isfile(checksums_path):
        exit('ERROR - A checksums file does not exist at '+checksums_path)

    hosts_dir = join(deploy_path, "conf/hosts/")

    # parse command line args
    retval = parse_args(hosts_dir)
    if not retval:
        print "Invalid command line arguments. For help, use 'muchos -h'"
        sys.exit(1)
    (opts, action, args) = retval

    hosts_path = join(hosts_dir, opts.cluster)

    config = DeployConfig(deploy_path, config_path, hosts_path, checksums_path, opts.cluster)
    config.verify_config(action)

    cluster = MuchosCluster(config)

    if action == 'launch':
        cluster.launch()
    elif action == 'status':
        nodes = cluster.status(['running'])
        print "Found {0} nodes in {1} cluster".format(len(nodes), config.cluster_name)
        cluster.print_nodes(nodes)
    elif action == 'sync':
        cluster.sync()
    elif action == 'setup':
        cluster.setup()
    elif action == 'config':
        if opts.property == 'all':
            config.print_all()
        else:
            config.print_property(opts.property)
    elif action == 'ssh':
        cluster.ssh()
    elif action in ('wipe', 'kill', 'cancel_shutdown'):
        if not isfile(hosts_path):
            exit("Hosts file does not exist for cluster: "+hosts_path)
        if action == 'wipe':
            print "Killing all processes started by Muchos and wiping Muchos data from {0} cluster"\
                .format(config.cluster_name)
        elif action == 'kill':
            print "Killing all processes started by Muchos on {0} cluster".format(config.cluster_name)
        elif action == 'cancel_shutdown':
            print "Cancelling automatic shutdown of {0} cluster".format(config.cluster_name)
        cluster.execute_playbook(action + ".yml")
    elif action == 'terminate':
        cluster.terminate(hosts_path)
    else:
        print 'ERROR - Unknown action:', action

main()


text:
function JacobiGaussian
  setup;

  gaussian = ProbabilityDistribution.Gaussian( ...
    'mu', 0, 'sigma', 1);
  beta = ProbabilityDistribution.Beta( ...
    'alpha', 2, 'beta', 2, 'a', -1, 'b', 1);

  assess(@(x) gaussian.icdf(beta.cdf(x)), ...
    'basis', 'Jacobi', 'order', 10, ...
    'distribution', beta, ...
    'exact', gaussian);
end


text:
package org.motechproject.config.service;

import org.motechproject.config.domain.ModulePropertiesRecord;
import org.motechproject.mds.annotations.Lookup;
import org.motechproject.mds.annotations.LookupField;
import org.motechproject.mds.service.MotechDataService;

import java.util.List;

/**
 * This service provides data access for {@link org.motechproject.config.domain.ModulePropertiesRecord}.
 * The implementation is generated by Motech Data Services and published as an OSGi service.
 */
public interface BundlePropertiesService extends MotechDataService<ModulePropertiesRecord> {

    /**
     * Returns a list of {@code ModulePropertiesRecord}s matching given bundle symbolic name and file name.
     *
     * @param bundle  the bundle symbolic name
     * @param filename  the name of the file
     * @return list of {@code ModulePropertiesRecord}s
     */
    @Lookup(name = "By bundle and file name")
    List<ModulePropertiesRecord> findByBundleAndFileName(@LookupField(name = "bundle") String bundle,
                                                         @LookupField(name = "filename") String filename);
    /**
     * Returns list of {@code ModulePropertiesRecord}s matching given bundle symbolic name.
     *
     * @param bundle  the bundle symbolic name
     * @return list of {@code ModulePropertiesRecord}s
     */
    @Lookup(name = "By bundle")
    List<ModulePropertiesRecord> findByBundle(@LookupField(name = "bundle") String bundle);

}


text:
<?php

use DDelrio1986\Superheroes\Superheroes;

// Setup autoloading.
if (file_exists(__DIR__ . '/../vendor/autoload.php')) {

    // Local installation.
    require __DIR__ . '/../vendor/autoload.php';
} elseif (file_exists(getcwd() . '/vendor/autoload.php')) {

    // Root project is current working directory.
    require getcwd() . '/vendor/autoload.php';
} elseif (file_exists(__DIR__ . '/../../../autoload.php')) {

    // Relative to composer install.
    require __DIR__ . '/../../../autoload.php';
} else {
    fwrite(STDERR, "Unable to setup autoloading; aborting\n");
    exit(2);
}

$options = getopt('a', ['all']);

$superheroes = new Superheroes;

// Print all superheroes.
if (count($options)) {
    array_walk($superheroes->all, function ($superhero) {
        echo $superhero . "\n";
    });

// Print one random superhero.
} else {
    echo $superheroes->random() . "\n";
}


text:
package oic.simulator.serviceprovider.view;

import java.util.List;

import oic.simulator.serviceprovider.Activator;
import oic.simulator.serviceprovider.manager.ResourceManager;
import oic.simulator.serviceprovider.resource.AutomationSettingHelper;
import oic.simulator.serviceprovider.resource.LocalResourceAttribute;
import oic.simulator.serviceprovider.resource.SimulatorResource;
import oic.simulator.serviceprovider.utils.Utility;
import oic.simulator.serviceprovider.view.dialogs.AutomationSettingDialog;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.oic.simulator.serviceprovider.AutomationType;

/**
 * This class provides editing support to the resources attributes table in the
 * attributes view.
 */
public class AttributeEditingSupport {

    private AttributeValueEditor attValueEditor;
    private AutomationEditor     automationEditor;

    public AttributeValueEditor createAttributeValueEditor(TableViewer viewer) {
        attValueEditor = new AttributeValueEditor(viewer);
        return attValueEditor;
    }

    public AutomationEditor createAutomationEditor(TableViewer viewer) {
        automationEditor = new AutomationEditor(viewer);
        return automationEditor;
    }

    class AttributeValueEditor extends EditingSupport {

        private final TableViewer      viewer;
        private LocalResourceAttribute attributeInSelection;
        private CCombo                 comboBox;

        public AttributeValueEditor(TableViewer viewer) {
            super(viewer);
            this.viewer = viewer;
        }

        @Override
        protected boolean canEdit(Object arg0) {
            return true;
        }

        @Override
        protected CellEditor getCellEditor(Object element) {
            attributeInSelection = (LocalResourceAttribute) element;

            // CellEditor is not required as the automation is in progress.
            if (attributeInSelection.isAutomationInProgress()) {
                return null;
            }

            String values[] = null;
            List<String> valueSet = attributeInSelection.getAttValues();
            values = convertListToStringArray(valueSet);

            ComboBoxCellEditor comboEditor = new ComboBoxCellEditor(
                    viewer.getTable(), values, SWT.READ_ONLY);
            comboBox = (CCombo) comboEditor.getControl();
            comboBox.addModifyListener(new ModifyListener() {

                @Override
                public void modifyText(ModifyEvent event) {
                    String oldValue = String.valueOf(attributeInSelection
                            .getAttributeValue());
                    String newValue = comboBox.getText();
                    if (!oldValue.equals(newValue)) {
                        attributeInSelection.setAttributeValue(newValue);
                        MessageBox dialog = new MessageBox(viewer.getTable()
                                .getShell(), SWT.ICON_QUESTION | SWT.OK
                                | SWT.CANCEL);
                        dialog.setText("Confirm action");
                        dialog.setMessage("Do you want to modify the value?");
                        int retval = dialog.open();
                        if (retval != SWT.OK) {
                            attributeInSelection.setAttributeValue(oldValue);
                        } else {
                            ResourceManager resourceManager;
                            resourceManager = Activator.getDefault()
                                    .getResourceManager();
                            SimulatorResource resource = resourceManager
                                    .getCurrentResourceInSelection();
                            resourceManager.attributeValueUpdated(resource,
                                    attributeInSelection.getAttributeName(),
                                    newValue);
                        }
                        viewer.update(attributeInSelection, null);
                        comboBox.setVisible(false);
                    }
                }
            });
            return comboEditor;
        }

        @Override
        protected Object getValue(Object element) {
            int indexOfItem = 0;
            LocalResourceAttribute att = (LocalResourceAttribute) element;
            String valueString = String.valueOf(att.getAttributeValue());
            List<String> valueSet = att.getAttValues();
            if (null != valueSet) {
                indexOfItem = valueSet.indexOf(valueString);
            }
            if (indexOfItem == -1) {
                indexOfItem = 0;
            }
            return indexOfItem;
        }

        @Override
        protected void setValue(Object element, Object value) {
            Object valueObj = attributeInSelection.getAttributeValue();
            if (null == valueObj)
                return;
            String attValue = String.valueOf(valueObj);
            ((LocalResourceAttribute) element).setAttributeValue(attValue);
            viewer.update(element, null);
        }

        public String[] convertListToStringArray(List<String> valueList) {
            String[] strArr;
            if (null != valueList && valueList.size() > 0) {
                strArr = valueList.toArray(new String[1]);
            } else {
                strArr = new String[1];
            }
            return strArr;
        }
    }

    class AutomationEditor extends EditingSupport {

        private final TableViewer viewer;

        public AutomationEditor(TableViewer viewer) {
            super(viewer);
            this.viewer = viewer;
        }

        @Override
        protected boolean canEdit(Object arg0) {
            return true;
        }

        @Override
        protected CellEditor getCellEditor(Object element) {
            // CellEditor is not required as the automation is in progress.
            ResourceManager resourceManager = Activator.getDefault()
                    .getResourceManager();
            SimulatorResource resource = resourceManager
                    .getCurrentResourceInSelection();
            if (null != resource && resource.isResourceAutomationInProgress()) {
                return null;
            }
            return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
        }

        @Override
        protected Object getValue(Object element) {
            LocalResourceAttribute att = (LocalResourceAttribute) element;
            return att.isAutomationInProgress();
        }

        @Override
        protected void setValue(Object element, Object value) {
            ResourceManager resourceManager = Activator.getDefault()
                    .getResourceManager();
            // As automation depends on the current resource in selection, its
            // presence is being checked.
            SimulatorResource resource = resourceManager
                    .getCurrentResourceInSelection();
            if (null == resource) {
                return;
            }

            LocalResourceAttribute att = (LocalResourceAttribute) element;
            boolean checked = (Boolean) value;
            if (checked) {
                // Start the automation
                // Fetch the settings data
                List<AutomationSettingHelper> automationSettings;
                automationSettings = AutomationSettingHelper
                        .getAutomationSettings(att);

                // Open the settings dialog
                AutomationSettingDialog dialog = new AutomationSettingDialog(
                        viewer.getTable().getShell(), automationSettings);
                dialog.create();
                if (dialog.open() == Window.OK) {
                    String automationType = dialog.getAutomationType();
                    String updateFreq = dialog.getUpdateFrequency();

                    AutomationType autoType = AutomationType
                            .valueOf(automationType);
                    int updFreq = Utility
                            .getUpdateIntervalFromString(updateFreq);
                    int autoId = resourceManager.startAutomation(resource, att,
                            autoType, updFreq);
                    if (autoId == -1) {
                        MessageDialog.openInformation(Display.getDefault()
                                .getActiveShell(), "Automation Status",
                                "Automation start failed!!");
                    } else {
                        viewer.update(element, null);
                    }
                }
            } else {
                // Stop the automation
                resourceManager.stopAutomation(resource, att,
                        att.getAutomationId());
                MessageDialog.openInformation(Display.getDefault()
                        .getActiveShell(), "Automation Status",
                        "Automation stopped.");
                viewer.update(element, null);
            }
        }
    }
}


text:
var express = require('express');
var io = require('../common/io');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {

  res.render('index', { title: 'Express' });

});

module.exports = router;

/**

 var onlineUsers = {};

 io.on("create",function(socketio){

    socketio.on('connection', function(socket){
      console.log('a user connected');

      //监听新用户加入
      socket.on('login', function(obj){
        //将新加入用户的唯一标识当作socket的名称,后面退出的时候会用到
        socket.name = obj.userid;

        //检查在线列表,如果不在里面就加入
        if(!onlineUsers.hasOwnProperty(obj.userid)) {
          onlineUsers[obj.userid] = obj.username;
          //在线人数+1
          onlineCount++;
        }

        //向所有客户端广播用户加入
        socketio.emit('login', {onlineUsers:onlineUsers, onlineCount:onlineCount, user:obj});
        console.log(obj.username+'加入了聊天室');
      });

      //监听用户退出
      socket.on('disconnect', function(){
        //将退出的用户从在线列表中删除
        if(onlineUsers.hasOwnProperty(socket.name)) {
          //退出用户的信息
          var obj = {userid:socket.name, username:onlineUsers[socket.name]};

          //删除
          delete onlineUsers[socket.name];
          //在线人数-1
          onlineCount--;

          //向所有客户端广播用户退出
          socketio.emit('logout', {onlineUsers:onlineUsers, onlineCount:onlineCount, user:obj});
          console.log(obj.username+'退出了聊天室');
        }
      });

      //监听用户发布聊天内容
      socket.on('message', function(obj){
        //向所有客户端广播发布的消息
        socketio.emit('message', obj);
        console.log(obj.username+'说:'+obj.content);
      });

    });

  });

 */


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

{% block title %}Domain Details{% endblock %}

{% block css_includes %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/diffview.css"/>
{% endblock %}

{% block content %}

Details

    {% if DomainACL.SERVICES_READ|has_access_to:user %}

Analysis ({{ service_results|length }})

    {% include 'services_tab_list_widget.html' %}
    {% endif %}

    Details for {{ domain.domain }}

                ID
                {{domain.id}}

                Created
                {{domain.created}}

            {% if DomainACL.DESCRIPTION_READ|has_access_to:user %}

                {% with description=domain.description %}
                    {% include 'description_widget.html' %}
                {% endwith %}

            {% endif %}

                DNSMon Enabled
                {{domain.watchlistEnabled|default:"False"}}

            {% if DomainACL.STATUS_READ|has_access_to:user %}

                Status

                    {{domain.status}}

            {% endif %}
            {% with tlp=domain.tlp %}
                        {% include "tlp_widget.html" %}
            {% endwith %}
            {% if DomainACL.SECTORS_READ|has_access_to:user %}
            {% with sectors=domain.sectors %}
                {% include "sector_widget.html" %}
            {% endwith %}
            {% endif %}
            {% if DomainACL.SOURCES_READ|has_access_to:user %}

                {% with sources=domain.source obj_id=domain.id obj_type=subscription.type %}
                    {% include "sources_listing_widget.html" %}
                {% endwith %}

            {% endif %}
            {% if DomainACL.RELEASABILITY_READ|has_access_to:user %}

                {% with releasability=domain.releasability %}
                    {% include "releasability_list_widget.html" %}
                {% endwith %}

            {% endif %}

        {% include 'details_options_widget.html' %}
        {% if DomainACL.BUCKETLIST_READ|has_access_to:user %}
        {% with bucket_list=domain.bucket_list %}
            {% include 'bucket_list_widget.html' %}
        {% endwith %}
        {% endif %}
        {% include 'add_related_widget.html' %}

    {% if DomainACL.ACTIONS_READ|has_access_to:user %}

        {% with obj=domain obj_type="Domain" %}
            {% include 'action_listing_widget.html' %}
        {% endwith %}

    {% endif %}
    {% if DomainACL.TICKETS_READ|has_access_to:user %}

      {% with obj=domain obj_type=subscription.type %}
         {% include 'tickets_listing_widget.html' %}
      {% endwith %}

    {% endif %}
    {% if DomainACL.CAMPAIGNS_READ|has_access_to:user and DomainACL.CAMPAIGN_READ|has_access_to:user %}

        {% with hit=domain col=COL_DOMAINS %}
            {% include "campaigns_display_widget.html" %}
        {% endwith %}

    {% endif %}
    {% if DomainACL.LOCATIONS_READ|has_access_to:user %}

        {% with hit=domain col=COL_DOMAINS %}
            {% include "locations_display_widget.html" %}
        {% endwith %}

    {% endif %}
    {% if DomainACL.RELATIONSHIPS_READ|has_access_to:user %}

       {% include 'relationships_listing_widget.html' %}

    {% endif %}
    {% if DomainACL.OBJECTS_READ|has_access_to:user %}

       {% include 'objects_listing_widget.html' %}

    {% endif %}
    {% if DomainACL.SCREENSHOTS_READ|has_access_to:user %}

    {% include 'screenshot_widget.html' %}

    {% endif %}
    {% if DomainACL.COMMENTS_READ|has_access_to:user %}

       {% include "comments_listing_widget.html" %}

    {% endif %}

    {% if DomainACL.SERVICES_READ|has_access_to:user %}
    {% with item=domain %}
        {% include "services_analysis_section.html" with crits_type="Domain" identifier=domain.id %}
    {% endwith %}

    {% include 'services_tab_tabs_widget.html' %}
    {% endif %}

{% endblock %}

{% block javascript_includes %}

{% endblock %}


text:
package com.timehop.droidcon2014retrofitsample.data.foursquare.api;

public class FoursquareException extends Exception {
  public FoursquareException(String detailMessage, Throwable throwable) {
    super(detailMessage, throwable);
  }
}


text:
{{--
    List of the accepted parameters
    $method          Required       The form method
    $action          Required       The form action when submitting
    [$autocomplete]  Default: False The Autocomplete value
    [$class]         Default: n/a   The field classes to be added
    [$error_bag]     Default: 'default' The error bag
--}}

@php($error_bag = (isset($error_bag))?$error_bag:'default')

<form
    method="{{ $method }}"
    action="{{ $action }}"
    autocomplete="@if (isset($autocomplete) && $autocomplete == 'on'){{'on'}}@else{{'off'}}@endif"
    class="@if (isset($class)) {{$class}} @endif"
>
    {{ csrf_field() }}
    {{ $slot }}

    @if (count($errors->$error_bag) > 0)
    @component('layout.components.view')
        @slot('class') mt-5 @endslot
        @lang('livror.labels.forms.errors')

            @foreach($errors->$error_bag->all() as $error)
                {{ $error }}
            @endforeach

    @endcomponent
    @endif
</form>


text:
//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2014, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE

package tripleplay.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import playn.core.Graphics;
import playn.core.QuadBatch;
import playn.core.Surface;
import playn.core.TextureSurface;
import playn.core.Tile;

import react.Slot;

/**
 * A runtime texture packer.
 */
public class TexturePacker
{
    public interface Renderer {
        void render (Surface surface, float x, float y, float width, float height);
    }

    /** Add an image to the packer. */
    public TexturePacker add (String id, Tile tile) {
        return addItem(new TileItem(id, tile));
    }

    /** Add a lazily rendered region to the packer.
      * The renderer will be used to draw the region each time pack() is called. */
    public TexturePacker add (String id, float width, float height, Renderer renderer) {
        return addItem(new RenderedItem(id, width, height, renderer));
    }

    /**
     * Pack all images into as few atlases as possible.
     * @return A map containing the new images, keyed by the id they were added with.
     */
    public Map<String,Tile> pack (Graphics gfx, QuadBatch batch) {
        List<Item> unpacked = new ArrayList<Item>(_items.values());
        // TODO(bruno): Experiment with different heuristics. Brute force calculate using multiple
        // different heuristics and use the best one?
        Collections.sort(unpacked, new Comparator<Item>() {
            public int compare (Item o1, Item o2) {
                // Sort by perimeter (instead of area). It can be harder to fit long skinny
                // textures after the large square ones
                return (int)(o2.width+o2.height) - (int)(o1.width+o1.height);
            }
        });

        List<Atlas> atlases = new ArrayList<Atlas>();
        while (!unpacked.isEmpty()) {
            atlases.add(createAtlas());

            // Try to pack each item into any atlas
            for (Iterator<Item> it = unpacked.iterator(); it.hasNext(); ) {
                Item item = it.next();

                for (Atlas atlas : atlases) {
                    if (atlas.place(item)) {
                        it.remove();
                    }
                }
            }
        }

        final Map<String,Tile> packed = new HashMap<String,Tile>();
        for (Atlas atlas : atlases) {
            Node root = atlas.root;
            final TextureSurface atlasTex = new TextureSurface(gfx, batch, root.width, root.height);
            atlasTex.begin();
            root.visitItems(new Slot<Node>() { @Override public void onEmit (Node n) {
                // Draw the item to the atlas
                n.item.draw(atlasTex, n.x, n.y);
                // Record its region
                packed.put(n.item.id, atlasTex.texture.tile(n.x, n.y, n.width, n.height));
            }});
            atlasTex.end();
        }
        return packed;
    }

    protected Atlas createAtlas () {
        // TODO(bruno): Be smarter about sizing
        return new Atlas(MAX_SIZE, MAX_SIZE);
    }

    protected TexturePacker addItem (Item item) {
        if (item.width+PADDING > MAX_SIZE || item.height+PADDING > MAX_SIZE) {
            throw new RuntimeException("Item is too big to pack " + item);
        }
        _items.put(item.id, item);
        return this;
    }

    protected static abstract class Item {
        public final String id;
        public final float width, height;

        public Item (String id, float width, float height) {
            this.id = id;
            this.width = width;
            this.height = height;
        }

        public abstract void draw (Surface surface, float x, float y);

        @Override public String toString () {
            return "[id=" + id + ", size=" + width + "x" + height + "]";
        }
    }

    protected static class TileItem extends Item {
        public final Tile tile;

        public TileItem (String id, Tile tile) {
            super(id, tile.width(), tile.height());
            this.tile = tile;
        }

        @Override public void draw (Surface surface, float x, float y) {
            surface.draw(tile, x, y);
        }
    }

    protected static class RenderedItem extends Item {
        public final Renderer renderer;

        public RenderedItem (String id, float width, float height, Renderer renderer) {
            super(id, width, height);
            this.renderer = renderer;
        }

        @Override public void draw (Surface surface, float x, float y) {
            renderer.render(surface, x, y, width, height);
        }
    }

    protected static class Atlas {
        public final Node root;

        public Atlas (int width, int height) {
            root = new Node(0, 0, width, height);
        }

        public boolean place (Item item) {
            Node node = root.search(item.width + PADDING, item.height + PADDING);
            if (node == null) return false;
            node.item = item;
            return true;
        }
    }

    protected static class Node {
        /** The bounds of this node (and its children). */
        public final float x, y, width, height;

        /** This node's two children, if any. */
        public Node left, right;

        /** The texture that is placed here, if any. Implies that this is a leaf node. */
        public Item item;

        public Node (float x, float y, float width, float height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }

        /** Find a free node in this tree big enough to fit an area, or null. */
        public Node search (float w, float h) {
            // There's already an item here, terminate
            if (item != null) return null;

            // That'll never fit, terminate
            if (width < w || height < h) return null;

            if (left != null) {
                Node descendent = left.search(w, h);
                if (descendent == null) descendent = right.search(w, h);
                return descendent;

            } else {
                // This node is a perfect size, no need to subdivide
                if (width == w && height == h) return this;

                // Split into two children
                float dw = width-w, dh = height-h;
                if (dw > dh) {
                    left = new Node(x, y, w, height);
                    right = new Node(x + w, y, dw, height);
                } else {
                    left = new Node(x, y, width, h);
                    right = new Node(x, y + h, width, dh);
                }

                return left.search(w, h);
            }
        }

        /** Iterate over all nodes with items in this tree. */
        public void visitItems (Slot<Node> slot) {
            if (item != null) slot.onEmit(this);
            if (left != null) {
                left.visitItems(slot);
                right.visitItems(slot);
            }
        }
    }

    protected static final int PADDING = 1;
    protected static final int MAX_SIZE = 2048;

    protected Map<String,Item> _items = new HashMap<String,Item>();
}


text:
<?php

declare(strict_types=1);

namespace OpenTelemetry\Tests\Unit\SDK\Trace\SpanProcessor;

use LogicException;
use Mockery;
use Mockery\Adapter\Phpunit\MockeryTestCase;
use Mockery\MockInterface;
use OpenTelemetry\API\Trace\SpanContext;
use OpenTelemetry\API\Trace\SpanContextInterface;
use OpenTelemetry\API\Trace\SpanContextValidator;
use OpenTelemetry\Context\Context;
use OpenTelemetry\SDK\Common\Future\CompletedFuture;
use OpenTelemetry\SDK\Common\Log\LoggerHolder;
use OpenTelemetry\SDK\Trace\ReadableSpanInterface;
use OpenTelemetry\SDK\Trace\ReadWriteSpanInterface;
use OpenTelemetry\SDK\Trace\SpanExporterInterface;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\Tests\Unit\SDK\Util\SpanData;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

/**
 * @covers OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor
 */
class SimpleSpanProcessorTest extends MockeryTestCase
{
    private SimpleSpanProcessor $simpleSpanProcessor;

    /** @var MockInterface&SpanExporterInterface */
    private $spanExporter;

    /** @var MockInterface&ReadWriteSpanInterface */
    private $readWriteSpan;

    /** @var MockInterface&ReadableSpanInterface */
    private $readableSpan;

    private SpanContextInterface $sampledSpanContext;
    private SpanContextInterface $nonSampledSpanContext;

    protected function setUp(): void
    {
        $this->readWriteSpan = Mockery::mock(ReadWriteSpanInterface::class);
        $this->readableSpan = Mockery::mock(ReadableSpanInterface::class);

        $this->sampledSpanContext = SpanContext::create(
            SpanContextValidator::INVALID_TRACE,
            SpanContextValidator::INVALID_SPAN,
            SpanContextInterface::TRACE_FLAG_SAMPLED
        );

        $this->nonSampledSpanContext = SpanContext::getInvalid();

        $this->spanExporter = Mockery::mock(SpanExporterInterface::class);
        $this->simpleSpanProcessor = new SimpleSpanProcessor($this->spanExporter);
    }

    public function test_on_start(): void
    {
        $this->simpleSpanProcessor->onStart($this->readWriteSpan, Context::getRoot());
        $this->spanExporter->shouldNotReceive('export');
    }

    public function test_on_end_after_shutdown(): void
    {
        $this->spanExporter->shouldReceive('shutdown');
        $this->spanExporter->shouldNotReceive('export');
        $this->simpleSpanProcessor->shutdown();
        $this->simpleSpanProcessor->onEnd($this->readableSpan);
    }

    public function test_on_end_sampled_span(): void
    {
        $spanData = new SpanData();
        $this->readableSpan->expects('getContext')->andReturn($this->sampledSpanContext);
        $this->readableSpan->expects('toSpanData')->andReturn($spanData);
        $this->spanExporter->expects('export')->with([$spanData])->andReturn(new CompletedFuture(0));
        $this->simpleSpanProcessor->onEnd($this->readableSpan);
    }

    public function test_on_end_non_sampled_span(): void
    {
        $this->readableSpan->expects('getContext')->andReturn($this->nonSampledSpanContext);
        $this->spanExporter->shouldNotReceive('export');
        $this->readableSpan->shouldReceive('toSpanData');
        $this->simpleSpanProcessor->onEnd($this->readableSpan);
    }

    public function test_does_not_trigger_concurrent_export(): void
    {
        $spanData = new SpanData();
        $count = 3;
        $this->readableSpan->expects('getContext')->times($count)->andReturn($this->sampledSpanContext);
        $this->readableSpan->expects('toSpanData')->times($count)->andReturn($spanData);

        $this->spanExporter->expects('export')->times($count)->andReturnUsing(function () use (&$running, &$count) {
            $this->assertNotTrue($running);
            $running = true;
            if (--$count) {
                $this->simpleSpanProcessor->onEnd($this->readableSpan);
            }
            $running = false;

            return 0;
        });

        $this->simpleSpanProcessor->onEnd($this->readableSpan);
    }

    // TODO: Add test to ensure exporter is retried on failure.

    public function test_force_flush(): void
    {
        $this->spanExporter->expects('forceFlush')->andReturn(true);
        $this->assertTrue($this->simpleSpanProcessor->forceFlush());
    }

    public function test_force_flush_after_shutdown(): void
    {
        $this->spanExporter->expects('shutdown')->andReturn(true);
        $this->spanExporter->shouldNotReceive('forceFlush');
        $this->simpleSpanProcessor->shutdown();
        $this->simpleSpanProcessor->forceFlush();
    }

    public function test_shutdown(): void
    {
        $this->spanExporter->expects('shutdown')->andReturnTrue();

        $this->assertTrue($this->simpleSpanProcessor->shutdown());
        $this->assertFalse($this->simpleSpanProcessor->shutdown());
    }

    public function test_throwing_exporter_export(): void
    {
        $exporter = $this->createMock(SpanExporterInterface::class);
        $exporter->method('forceFlush')->willReturn(true);
        $exporter->method('export')->willThrowException(new LogicException());

        $logger = $this->createMock(LoggerInterface::class);
        $logger->expects($this->once())->method('log')->with(LogLevel::ERROR);

        $processor = new SimpleSpanProcessor($exporter);

        $this->readableSpan->expects('getContext')->andReturn($this->sampledSpanContext);
        $this->readableSpan->expects('toSpanData')->andReturn(new SpanData());

        $previousLogger = LoggerHolder::get();
        LoggerHolder::set($logger);

        try {
            $processor->onStart($this->readWriteSpan, Context::getCurrent());
            $processor->onEnd($this->readableSpan);
        } finally {
            LoggerHolder::set($previousLogger);
        }
    }

    public function test_throwing_exporter_flush(): void
    {
        $exporter = $this->createMock(SpanExporterInterface::class);
        $exporter->method('forceFlush')->willThrowException(new LogicException());

        $this->expectException(LogicException::class);

        $processor = new SimpleSpanProcessor($exporter);

        $processor->forceFlush();
    }
}


text:
package com.github.arteam.jdit.domain.entity;

import com.google.common.base.MoreObjects;

import java.util.Date;
import java.util.Optional;

/**
 * Date: 2/7/15
 * Time: 5:00 PM
 *
 * @author Artem Prigoda
 */
public class Player {

    public final Optional<Long> id;
    public final String firstName;
    public final String lastName;
    public final Date birthDate;
    public final Optional<Integer> height;
    public final Optional<Integer> weight;

    public Player(Optional<Long> id, String firstName, String lastName, Date birthDate,
                  Optional<Integer> height, Optional<Integer> weight) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.birthDate = birthDate;
        this.height = height;
        this.weight = weight;
    }

    public Player(String firstName, String lastName, Date birthDate, int height, int weight) {
        this(Optional.<Long>empty(), firstName, lastName, birthDate, Optional.of(height), Optional.of(weight));
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .omitNullValues()
                .add("id", id.orElse(null))
                .add("firstName", firstName)
                .add("lastName", lastName)
                .add("birthDate", birthDate)
                .add("height", height.orElse(null))
                .add("weight", weight.orElse(null))
                .toString();
    }
}


text:
namespace media {

// Cap the frame rate command line input to reasonable values.
static const float kFakeCaptureMinFrameRate = 5.0f;
static const float kFakeCaptureMaxFrameRate = 60.0f;
// Default rate if none is specified as part of the command line.
static const float kFakeCaptureDefaultFrameRate = 20.0f;

FakeVideoCaptureDeviceFactory::FakeVideoCaptureDeviceFactory()
    : number_of_devices_(1),
      fake_vcd_ownership_(FakeVideoCaptureDevice::BufferOwnership::OWN_BUFFERS),
      frame_rate_(kFakeCaptureDefaultFrameRate) {}

scoped_ptr<VideoCaptureDevice> FakeVideoCaptureDeviceFactory::Create(
    const VideoCaptureDevice::Name& device_name) {
  DCHECK(thread_checker_.CalledOnValidThread());

  parse_command_line();

  for (int n = 0; n < number_of_devices_; ++n) {
    std::string possible_id = base::StringPrintf("/dev/video%d", n);
    if (device_name.id().compare(possible_id) == 0) {
      return scoped_ptr<VideoCaptureDevice>(
          new FakeVideoCaptureDevice(fake_vcd_ownership_, frame_rate_));
    }
  }
  return scoped_ptr<VideoCaptureDevice>();
}

void FakeVideoCaptureDeviceFactory::GetDeviceNames(
    VideoCaptureDevice::Names* const device_names) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(device_names->empty());
  for (int n = 0; n < number_of_devices_; ++n) {
    VideoCaptureDevice::Name name(base::StringPrintf("fake_device_%d", n),
                                  base::StringPrintf("/dev/video%d", n)
#if defined(OS_LINUX)
                                      ,
                                  VideoCaptureDevice::Name::V4L2_SINGLE_PLANE
#elif defined(OS_MACOSX)
                                      ,
                                  VideoCaptureDevice::Name::AVFOUNDATION
#elif defined(OS_WIN)
                                      ,
                                  VideoCaptureDevice::Name::DIRECT_SHOW
#elif defined(OS_ANDROID)
                                      ,
                                  VideoCaptureDevice::Name::API2_LEGACY
#endif
                                  );
    device_names->push_back(name);
  }
}

void FakeVideoCaptureDeviceFactory::GetDeviceSupportedFormats(
    const VideoCaptureDevice::Name& device,
    VideoCaptureFormats* supported_formats) {
  DCHECK(thread_checker_.CalledOnValidThread());
  const gfx::Size supported_sizes[] = {gfx::Size(320, 240),
                                       gfx::Size(640, 480),
                                       gfx::Size(1280, 720),
                                       gfx::Size(1920, 1080)};
  supported_formats->clear();
  for (const auto& size : supported_sizes) {
    supported_formats->push_back(
        VideoCaptureFormat(size, frame_rate_, media::PIXEL_FORMAT_I420));
  }
}

// Optional comma delimited parameters to the command line can specify buffer
// ownership, buffer planarity, and the fake video device FPS.
// Examples: "ownership=client, planarity=triplanar, fps=60" "fps=30"
void FakeVideoCaptureDeviceFactory::parse_command_line() {
  const std::string option =
      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kUseFakeDeviceForMediaStream);
  base::StringTokenizer option_tokenizer(option, ", ");
  option_tokenizer.set_quote_chars("\"");

  while (option_tokenizer.GetNext()) {
    std::vector<std::string> param =
        base::SplitString(option_tokenizer.token(), "=", base::TRIM_WHITESPACE,
                          base::SPLIT_WANT_NONEMPTY);

    if (param.size() != 2u) {
      LOG(WARNING) << "Forget a value '" << option << "'? Use name=value for "
                   << switches::kUseFakeDeviceForMediaStream << ".";
      return;
    }

    if (base::EqualsCaseInsensitiveASCII(param.front(), "ownership") &&
        base::EqualsCaseInsensitiveASCII(param.back(), "client")) {
      fake_vcd_ownership_ =
          FakeVideoCaptureDevice::BufferOwnership::CLIENT_BUFFERS;
    } else if (base::EqualsCaseInsensitiveASCII(param.front(), "fps")) {
      double fps = 0;
      if (base::StringToDouble(param.back(), &fps)) {
        frame_rate_ =
            std::max(kFakeCaptureMinFrameRate, static_cast<float>(fps));
        frame_rate_ = std::min(kFakeCaptureMaxFrameRate, frame_rate_);
      }
    }
  }
}

}  // namespace media


text:
package dockerface

import (
	"fmt"
	"net/http"

	log "github.com/Sirupsen/logrus"
	"github.com/ant0ine/go-json-rest/rest"
	"github.com/fsouza/go-dockerclient"
)

const CONTAINER_STOP_TIMEOUT = 10 // seconds

var (
	daemonPort    int = 2375
	daemonTLSPort int = 2376
	dockerClient  *docker.Client
)

func init() {
	var (
		daemonHost string
		client     *docker.Client
		err        error
	)

	// See https://docs.docker.com/reference/commandline/cli/
	tlsVerify := GetEnv("DOCKER_TLS_VERIFY", "")
	if tlsVerify == "" {
		daemonHost = fmt.Sprintf("tcp://%s:%d", getDaemonHostIp(), daemonPort)
		client, err = docker.NewClient(daemonHost)
	} else {
		certPath := GetEnv("DOCKER_CERT_PATH", "")
		if certPath == "" {
			log.Fatal("Using TLS verify but DOCKER_CERT_PATH is empty")
		}

		log.Infof("Docker cert path: %s", certPath)
		ca := GetEnv("TLS_CA", fmt.Sprintf("%s/ca.pem", certPath))
		cert := GetEnv("TLS_CERT", fmt.Sprintf("%s/cert.pem", certPath))
		key := GetEnv("TLS_KEY", fmt.Sprintf("%s/key.pem", certPath))

		daemonHost = fmt.Sprintf("tcp://%s:%d", getDaemonHostIp(), daemonTLSPort)
		client, err = docker.NewTLSClient(daemonHost, cert, key, ca)
	}

	log.Infof("Docker daemon host: %s", daemonHost)
	if err != nil {
		log.Fatalf("Error initializing docker client: %v", err)
	}
	dockerClient = client
}

type ContainerEndpoint struct{}

func (ce *ContainerEndpoint) Filter(w rest.ResponseWriter, req *rest.Request) {
	containers, err := dockerClient.ListContainers(docker.ListContainersOptions{
		All: req.URL.Query().Get("all") == "true",
	})
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteJson(containers)
}

func (ce *ContainerEndpoint) Start(w rest.ResponseWriter, req *rest.Request) {
	cid := req.PathParam("id")
	if err := dockerClient.StartContainer(cid, nil); err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	container, err := dockerClient.InspectContainer(cid)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteJson(container.State)
}

func (ce *ContainerEndpoint) Stop(w rest.ResponseWriter, req *rest.Request) {
	cid := req.PathParam("id")
	if err := dockerClient.StopContainer(cid, CONTAINER_STOP_TIMEOUT); err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	container, err := dockerClient.InspectContainer(cid)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteJson(container.State)
}

func (ce *ContainerEndpoint) Inspect(w rest.ResponseWriter, req *rest.Request) {
	cid := req.PathParam("id")
	container, err := dockerClient.InspectContainer(cid)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteJson(container)
}


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 *@ORM\Entity
 *@ORM\Table(name="param_value")
 */
class ParamValue
{
    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="User")
     * @ORM\JoinColumn(name="ID_User", referencedColumnName="ID_User")
     */
    private $ID_User;

    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="GroupParam")
     * @ORM\JoinColumn(name="ID_GroupParam", referencedColumnName="ID_GroupParam")
     */
    private $ID_GroupParam;

    /**
     * @ORM\Column(type="string", length=30)
     */
    private $value;

    public function __construct(User $user, GroupParam $groupParam, $value = "")
    {
        $this->setUser($user);
        $this->setGroupParam($groupParam);
        $this->setValue($value);
    }

    /**
     * Set value
     *
     * @param string $value
     *
     * @return ParamValue
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

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

    /**
     * Set User
     *
     * @param \AppBundle\Entity\User $User
     *
     * @return ParamValue
     */
    public function setUser(User $User)
    {
        $this->ID_User = $User;

        return $this;
    }

    /**
     * Get User
     *
     * @return \AppBundle\Entity\User
     */
    public function getUser()
    {
        return $this->ID_User;
    }

    /**
     * Set iDGroupParam
     *
     * @param \AppBundle\Entity\GroupParam $GroupParam
     *
     * @return ParamValue
     */
    public function setGroupParam(GroupParam $GroupParam)
    {
        $this->ID_GroupParam = $GroupParam;

        return $this;
    }

    /**
     * Get iDGroupParam
     *
     * @return \AppBundle\Entity\GroupParam
     */
    public function getGroupParam()
    {
        return $this->ID_GroupParam;
    }

    /**
     * Set iDUser
     *
     * @param \AppBundle\Entity\User $iDUser
     *
     * @return ParamValue
     */
    public function setIDUser(\AppBundle\Entity\User $iDUser)
    {
        $this->ID_User = $iDUser;

        return $this;
    }

    /**
     * Get iDUser
     *
     * @return \AppBundle\Entity\User
     */
    public function getIDUser()
    {
        return $this->ID_User;
    }

    /**
     * Set iDGroupParam
     *
     * @param \AppBundle\Entity\GroupParam $iDGroupParam
     *
     * @return ParamValue
     */
    public function setIDGroupParam(\AppBundle\Entity\GroupParam $iDGroupParam)
    {
        $this->ID_GroupParam = $iDGroupParam;

        return $this;
    }

    /**
     * Get iDGroupParam
     *
     * @return \AppBundle\Entity\GroupParam
     */
    public function getIDGroupParam()
    {
        return $this->ID_GroupParam;
    }
}


text:
/*
 * decaffeinate suggestions:
 * DS102: Remove unnecessary code created because of implicit returns
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
 */
const _ = require("underscore")
const sd = require("sharify").data
const benv = require("benv")
const Backbone = require("backbone")
const sinon = require("sinon")
const moment = require("moment")
const { resolve } = require("path")
const { fabricate } = require("@artsy/antigravity")
const Fair = require("../../../../models/fair.coffee")

xdescribe("ForYouView", function () {
  before(function (done) {
    return benv.setup(() => {
      sd.API_URL = "localhost:3003"

      sd.CURRENT_PATH = ""
      sd.CURRENT_USER = "hello"
      sd.NODE_ENV = "test"
      benv.expose({ $: benv.require("jquery") })
      sinon.stub(Backbone, "sync")
      this.OverviewView = require("../../client/overview.coffee")
      Backbone.$ = $

      this.fair = new Fair(fabricate("fair"))
      return done()
    })
  })

  after(function () {
    benv.teardown()
    Backbone.sync.restore()
    return (sd.CURRENT_USER = undefined)
  })

  return describe("#initialize", () =>
    it("renders personalized artist list", function () {
      const view = new this.OverviewView({
        el: $(`

`),
        fair: this.fair,
        model: this.model,
      })

      Backbone.sync.args[0][2].success({
        time: moment().subtract("minutes", 2).format("YYYY-MM-DD HH:mm:ss ZZ"),
      })
      Backbone.sync.args[1][2].success([{ artist: fabricate("artist") }])
      Backbone.sync.args[2][2].success([])

      view.$el.html().should.not.containEql("undefined")
      view.$el.html().should.not.containEql("#{")
      view.$el.html().should.not.containEql("NaN")

      view.$(".container-left .large-section-subheading").length.should.equal(1)
      return view
        .$(".container-left .large-section-subheading")
        .text()
        .should.containEql("Pablo Picasso")
    }))
})


text:
namespace quark {

class RuntimeError: public std::exception {
public:

	RuntimeError(json::Value v):v(v) {}

	const char *what() const throw() {
		if (s.empty()) {
			s = v.toString();
		}
		return s.c_str();
	}

	json::Value getData() const {
		return v;
	}

protected:
	json::Value v;
	mutable json::String s;

};

}


text:
function appstart(){
	console.log('app start!');
}


text:
import {assert} from '../../platform/chai-web.js';
import {manifestTestSetup} from '../../runtime/testing/manifest-integration-test-setup.js';
import {Speculator} from '../speculator.js';

describe('planning manifest integration', () => {
  it('can produce a recipe that can be speculated', async () => {
    const {runtime, arc, recipe} = await manifestTestSetup();
    const hash = ((hash) => hash.substring(hash.length - 4))(await recipe.digest());
    const {speculativeArc, relevance} = await new Speculator(runtime).speculate(arc, recipe, hash);
    assert.strictEqual(relevance.calcRelevanceScore(), 1);
    assert.lengthOf(speculativeArc.recipeDeltas, 1);
  });
});