text:
from __future__ import unicode_literals
import frappe, unittest, json
from frappe.test_runner import make_test_records_for_doctype
from frappe.core.doctype.doctype.doctype import InvalidFieldNameError

test_dependencies = ["Custom Field", "Property Setter"]
class TestCustomizeForm(unittest.TestCase):
	def insert_custom_field(self):
		frappe.delete_doc_if_exists("Custom Field", "User-test_custom_field")
		frappe.get_doc({
			"doctype": "Custom Field",
			"dt": "User",
			"label": "Test Custom Field",
			"description": "A Custom Field for Testing",
			"fieldtype": "Select",
			"in_list_view": 1,
			"options": "\nCustom 1\nCustom 2\nCustom 3",
			"default": "Custom 3",
			"insert_after": frappe.get_meta('User').fields[-1].fieldname
		}).insert()

	def setUp(self):
		self.insert_custom_field()
		frappe.db.commit()
		frappe.clear_cache(doctype="User")

	def tearDown(self):
		frappe.delete_doc("Custom Field", "User-test_custom_field")
		frappe.db.commit()
		frappe.clear_cache(doctype="User")

	def get_customize_form(self, doctype=None):
		d = frappe.get_doc("Customize Form")
		if doctype:
			d.doc_type = doctype
		d.run_method("fetch_to_customize")
		return d

	def test_fetch_to_customize(self):
		d = self.get_customize_form()
		self.assertEquals(d.doc_type, None)
		self.assertEquals(len(d.get("fields")), 0)

		d = self.get_customize_form("Event")
		self.assertEquals(d.doc_type, "Event")
		self.assertEquals(len(d.get("fields")), 28)

		d = self.get_customize_form("User")
		self.assertEquals(d.doc_type, "User")

		self.assertEquals(len(d.get("fields")), len(frappe.get_doc("DocType", d.doc_type).fields) + 1)
		self.assertEquals(d.get("fields")[-1].fieldname, "test_custom_field")
		self.assertEquals(d.get("fields", {"fieldname": "location"})[0].in_list_view, 1)

		return d

	def test_save_customization_property(self):
		d = self.get_customize_form("User")
		self.assertEquals(frappe.db.get_value("Property Setter",
			{"doc_type": "User", "property": "allow_copy"}, "value"), None)

		d.allow_copy = 1
		d.run_method("save_customization")
		self.assertEquals(frappe.db.get_value("Property Setter",
			{"doc_type": "User", "property": "allow_copy"}, "value"), '1')

		d.allow_copy = 0
		d.run_method("save_customization")
		self.assertEquals(frappe.db.get_value("Property Setter",
			{"doc_type": "User", "property": "allow_copy"}, "value"), None)

	def test_save_customization_field_property(self):
		d = self.get_customize_form("User")
		self.assertEquals(frappe.db.get_value("Property Setter",
			{"doc_type": "User", "property": "reqd", "field_name": "location"}, "value"), None)

		location_field = d.get("fields", {"fieldname": "location"})[0]
		location_field.reqd = 1
		d.run_method("save_customization")
		self.assertEquals(frappe.db.get_value("Property Setter",
			{"doc_type": "User", "property": "reqd", "field_name": "location"}, "value"), '1')

		location_field = d.get("fields", {"fieldname": "location"})[0]
		location_field.reqd = 0
		d.run_method("save_customization")
		self.assertEquals(frappe.db.get_value("Property Setter",
			{"doc_type": "User", "property": "reqd", "field_name": "location"}, "value"), None)

	def test_save_customization_custom_field_property(self):
		d = self.get_customize_form("User")
		self.assertEquals(frappe.db.get_value("Custom Field", "User-test_custom_field", "reqd"), 0)

		custom_field = d.get("fields", {"fieldname": "test_custom_field"})[0]
		custom_field.reqd = 1
		d.run_method("save_customization")
		self.assertEquals(frappe.db.get_value("Custom Field", "User-test_custom_field", "reqd"), 1)

		custom_field = d.get("fields", {"is_custom_field": True})[0]
		custom_field.reqd = 0
		d.run_method("save_customization")
		self.assertEquals(frappe.db.get_value("Custom Field", "User-test_custom_field", "reqd"), 0)

	def test_save_customization_new_field(self):
		d = self.get_customize_form("User")
		last_fieldname = d.fields[-1].fieldname
		d.append("fields", {
			"label": "Test Add Custom Field Via Customize Form",
			"fieldtype": "Data",
			"is_custom_field": 1
		})
		d.run_method("save_customization")
		self.assertEquals(frappe.db.get_value("Custom Field",
			"User-test_add_custom_field_via_customize_form", "fieldtype"), "Data")

		self.assertEquals(frappe.db.get_value("Custom Field",
			"User-test_add_custom_field_via_customize_form", 'insert_after'), last_fieldname)

		frappe.delete_doc("Custom Field", "User-test_add_custom_field_via_customize_form")
		self.assertEquals(frappe.db.get_value("Custom Field",
			"User-test_add_custom_field_via_customize_form"), None)

	def test_save_customization_remove_field(self):
		d = self.get_customize_form("User")
		custom_field = d.get("fields", {"fieldname": "test_custom_field"})[0]
		d.get("fields").remove(custom_field)
		d.run_method("save_customization")

		self.assertEquals(frappe.db.get_value("Custom Field", custom_field.name), None)

		frappe.local.test_objects["Custom Field"] = []
		make_test_records_for_doctype("Custom Field")

	def test_reset_to_defaults(self):
		d = frappe.get_doc("Customize Form")
		d.doc_type = "User"
		d.run_method('reset_to_defaults')

		self.assertEquals(d.get("fields", {"fieldname": "location"})[0].in_list_view, 0)

		frappe.local.test_objects["Property Setter"] = []
		make_test_records_for_doctype("Property Setter")

	def test_set_allow_on_submit(self):
		d = self.get_customize_form("User")
		d.get("fields", {"fieldname": "first_name"})[0].allow_on_submit = 1
		d.get("fields", {"fieldname": "test_custom_field"})[0].allow_on_submit = 1
		d.run_method("save_customization")

		d = self.get_customize_form("User")

		# don't allow for standard fields
		self.assertEquals(d.get("fields", {"fieldname": "first_name"})[0].allow_on_submit or 0, 0)

		# allow for custom field
		self.assertEquals(d.get("fields", {"fieldname": "test_custom_field"})[0].allow_on_submit, 1)

	def test_title_field_pattern(self):
		d = self.get_customize_form("Web Form")

		df = d.get("fields", {"fieldname": "title"})[0]

		# invalid fieldname
		df.options = """{doc_type} - {introduction_test}"""
		self.assertRaises(InvalidFieldNameError, d.run_method, "save_customization")

		# space in formatter
		df.options = """{doc_type} - {introduction text}"""
		self.assertRaises(InvalidFieldNameError, d.run_method, "save_customization")

		# valid fieldname
		df.options = """{doc_type} - {introduction_text}"""
		d.run_method("save_customization")

		# valid fieldname with escaped curlies
		df.options = """{{ {doc_type} }} - {introduction_text}"""
		d.run_method("save_customization")

		# undo
		df.options = None
		d.run_method("save_customization")


text:
layout: page
title: Hero Ruby Enterprises Show
date: 2016-05-24
author: Jeffrey Campos
tags: weekly links, java
status: published
summary: Donec porttitor interdum nisi cursus vehicula.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 06/17/2018
  endDate: 06/20/2018
  ctyhocn: CNWARHX
  groupCode: HRES
published: true
---
Vestibulum vitae accumsan felis. Suspendisse scelerisque porta imperdiet. Suspendisse dolor nibh, iaculis non mi id, vehicula vestibulum sem. Ut tempor quam lectus, id interdum quam rutrum nec. Vestibulum ut consectetur urna, non dignissim metus. Duis rutrum a lacus id feugiat. Praesent cursus nibh ut cursus pulvinar. Pellentesque non leo quis velit sollicitudin volutpat. Duis sagittis gravida nisi, nec cursus lorem scelerisque vel.

* Aliquam in libero sed mauris congue accumsan
* Ut ornare leo at libero feugiat, sit amet commodo quam efficitur.

Ut eu purus eu libero placerat scelerisque. Donec ex massa, iaculis a massa id, tristique ultrices ex. Proin eget nibh in libero accumsan imperdiet in ac ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec semper ex eget viverra finibus. Maecenas euismod augue nec tempor malesuada. Sed commodo, urna ut venenatis convallis, odio velit tempus turpis, non euismod nibh eros quis elit. Nullam sagittis lectus at velit vestibulum, id vulputate ligula cursus. Nam luctus pellentesque risus pulvinar efficitur.
Sed consequat dui vitae lorem sodales, in fermentum lorem pharetra. Sed nec aliquet lacus, a commodo eros. Aliquam suscipit eros nec aliquet elementum. In sed nisl facilisis, sodales nulla nec, pretium metus. Donec sed hendrerit tortor. Etiam quis odio nisi. Duis id dictum arcu. Nunc elementum lacus justo, at hendrerit quam feugiat id. Phasellus venenatis dui at volutpat vestibulum. Integer commodo sem eu consequat sollicitudin. Fusce facilisis elementum ultricies. Nullam interdum interdum sem in tincidunt. Proin sed dolor in sem suscipit euismod. Fusce ullamcorper erat ante, id pretium lacus iaculis id.

redpajama_set_name: RedPajamaGithub


text:
import os
import sys
import time
import itertools
from flask import Flask, Response, redirect, request, url_for
from linkedin import linkedin
from config import *
from pprint import pprint as pp
from pprint import pformat
from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper

PATH = os.path.dirname(os.path.realpath(__file__))
reload(sys)
sys.setdefaultencoding('utf-8')

app = Flask(__name__, static_url_path='')

def crossdomain(origin=None, methods=None, headers=None,
                max_age=21600, attach_to_all=True,
                automatic_options=True):
    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, basestring):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        if methods is not None:
            return methods

        options_resp = current_app.make_default_options_response()
        return options_resp.headers['allow']

    def decorator(f):
        def wrapped_function(*args, **kwargs):
            if automatic_options and request.method == 'OPTIONS':
                resp = current_app.make_default_options_response()
            else:
                resp = make_response(f(*args, **kwargs))
            if not attach_to_all and request.method != 'OPTIONS':
                return resp

            h = resp.headers

            h['Access-Control-Allow-Origin'] = origin
            h['Access-Control-Allow-Methods'] = get_methods()
            h['Access-Control-Max-Age'] = str(max_age)
            if headers is not None:
                h['Access-Control-Allow-Headers'] = headers
            return resp

        f.provide_automatic_options = False
        return update_wrapper(wrapped_function, f)
    return decorator

@app.route('/header')
def headers():
    print "-------------------------------------"
    pp(request.headers)
    return pformat(request.headers).replace("\n", "
").replace("  ","  ")

# simple template
def html(func):
    def wrapper(func):
        def wrapped(*args, **kwds):
            body = func(*args, **kwds)
            return """
            <!DOCTYPE html>

                <meta charset="UTF-8">
                <title>Titulek stranky</title>

            %s
        """ % body
        return wrapped
    return wrapper

def format_pprint (data):
    return pformat(data).replace("\n", "
").replace("  ","  ")

@app.route('/js/<path:path>')
def get_js(path):
    return open(PATH+'/js/'+path,'r').read()

@app.route('/css/<path:path>')
def get_css(path):
    return open(PATH+'/css/'+path,'r').read()

@app.route('/ctverecek')
@crossdomain(origin='*')
def ctverec():
    return open(PATH+"/index.html","r").read()

if __name__ == "__main__":
    app.run(host='0.0.0.0',debug=True, port=7000)


text:
package com.nordnetab.chcp.events;

import com.nordnetab.chcp.model.ChcpError;

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

/**
 * Created by Nikolay Demyankov on 25.08.15.
 * <p/>
 * Implementation of the IPluginEvent interface.
 * Also, base class for all plugin specific events.
 * All events are dispatched and captured through EventBus.
 *
 * @see de.greenrobot.event.EventBus
 */
class PluginEventImpl implements IPluginEvent {

    private final ChcpError error;
    private final String eventName;
    private final Map<String, Object>data;

    /**
     * Class constructor
     *
     * @param eventName string identifier of the event
     * @param error     error information
     *
     * @see ChcpError
     */
    protected PluginEventImpl(String eventName, ChcpError error) {
        this.eventName = eventName;
        this.error = error;
        this.data = new HashMap<String, Object>();
    }

    @Override
    public String name() {
        return eventName;
    }

    @Override
    public ChcpError error() {
        return error;
    }

    @Override
    public Map<String, Object> data() {
        return data;
    }
}


text:
namespace SoundClouder.Data
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Threading.Tasks;
    using Newtonsoft.Json;

    public class HttpRequester
    {
        public static async Task<T> GetAsync<T>(string resourceUrl, IDictionary<string, string> headers = null)
        {
            var request = WebRequest.Create(resourceUrl) as HttpWebRequest;
            request.ContentType = "application/json";
            request.Method = "GET";

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }

            var response = await request.GetResponseAsync();
            string responseString;

            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                responseString = reader.ReadToEnd();
            }

            var responseData = JsonConvert.DeserializeObject<T>(responseString);

            return responseData;
        }

        public static void Get(string resourceUrl)
        {
            var request = WebRequest.Create(resourceUrl) as HttpWebRequest;
            request.ContentType = "application/json";
            request.Method = "GET";
            request.GetResponse();
        }

        public static void Post(string resourceUrl, object data)
        {
            var request = WebRequest.Create(resourceUrl) as HttpWebRequest;
            request.ContentType = "application/json";
            request.Method = "POST";

            var jsonData = JsonConvert.SerializeObject(data);

            using (StreamWriter writer =
                new StreamWriter(request.GetRequestStream()))
            {
                writer.Write(jsonData);
            }

            request.GetResponse();
        }

        public static T Post<T>(string resourceUrl,
            object data,
            IDictionary<string, string> headers = null)
        {
            var request = WebRequest.Create(resourceUrl) as HttpWebRequest;
            request.ContentType = "application/json";
            request.Method = "POST";
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }

            var jsonData = JsonConvert.SerializeObject(data);

            using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
            {
                writer.Write(jsonData);
            }

            var response = request.GetResponse();
            string responseString;
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                responseString = reader.ReadToEnd();
            }
            var responseData = JsonConvert.DeserializeObject<T>(responseString);
            return responseData;
        }

        public static void Delete(string resourceUrl)
        {
            var request = WebRequest.Create(resourceUrl) as HttpWebRequest;
            request.ContentType = "application/json";
            request.Method = "DELETE";
            request.GetResponse();
        }

        internal static bool Put(string resourceUrl,
            IDictionary<string, string> headers = null)
        {
            var request = WebRequest.Create(resourceUrl) as HttpWebRequest;
            request.ContentType = "application/json";
            request.Method = "PUT";

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }

            //var jsonData = JsonConvert.SerializeObject(data);

            using (StreamWriter writer =
                new StreamWriter(request.GetRequestStream()))
            {
                writer.Write("");
            }

            try
            {
                var response = request.GetResponse();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}


text:
<?php

class PbPassword {

	public static function weakPassword($passwd) {
		if (strlen($passwd) < 6) {
			return true;
		}
		return false;
	}

	public static function hash($passwd) {
		if (version_compare(phpversion(), "5.5.0") < 0) {
			require_once APPPATH . "third_party/powerbase/libraries/password.php";
		}
		return password_hash($passwd, PASSWORD_DEFAULT);
	}

	public static function verify($passwd, $hash) {
		if (version_compare(phpversion(), "5.5.0") < 0) {
			require_once APPPATH . "third_party/powerbase/libraries/password.php";
		}
		return password_verify($passwd, $hash);

	}
}


text:
require 'rails_helper'

RSpec.describe Duty, type: :model do
  it 'saves when everything is fine' do
    duty = build(:duty)
    expect(duty.save).to be true
  end

  it 'does not save when date is null' do
    duty = build(:duty, date: nil)
    expect(duty.save).to be false
  end

  it 'does not save when timeslot_id is null' do
    duty = build(:duty, timeslot_id: nil)
    expect(duty.save).to be false
  end

  it 'saves when user_id is null' do
    duty = build(:duty, user_id: nil)
    expect(duty.save).to be true
  end

  it 'should belongs_to :user' do
    expect(Duty.reflect_on_association(:user).macro).to eq :belongs_to
  end

  it 'should belongs_to :timeslot' do
    expect(Duty.reflect_on_association(:timeslot).macro).to eq :belongs_to
  end
end


text:
class Seth

  class Provider

    class Log

      # Seth log provider, allows logging to seth's logs from recipes
      class SethLog < seth::Provider

        # ordered array of the log levels
        @@levels = [ :debug, :info, :warn, :error, :fatal ]

        # No concept of a 'current' resource for logs, this is a no-op
        #
        # === Return
        # true:: Always return true
        def load_current_resource
          true
        end

        # Write the log to Seth's log
        #
        # === Return
        # true:: Always return true
        def action_write
          Seth::Log.send(@new_resource.level, @new_resource.message)

          # resolve the integers for the current log levels
          global_level = Mixlib::Log::LEVELS.fetch(Seth::Log.level)
          resource_level = Mixlib::Log::LEVELS.fetch(@new_resource.level)

          # If the resource level is greater than or the same os the global
          # level, then it should have been written to the log.  Mark the
          # resource as updated.
          if resource_level >= global_level
            @new_resource.updated_by_last_action(true)
          end

        end

      end

    end

  end

end


text:
package org.radargun.stages.cache.background;

import java.util.List;
import java.util.Random;

import org.radargun.Operation;
import org.radargun.stages.cache.generators.ValueGenerator;
import org.radargun.stages.helpers.Range;
import org.radargun.stats.Request;
import org.radargun.stats.RequestSet;
import org.radargun.traits.BasicOperations;
import org.radargun.traits.ConditionalOperations;
import org.radargun.traits.Transactional;
import org.radargun.utils.Utils;

/**
 * Original background stressors logic which loads all entries into cache and then overwrites them.
 *
 * @author Radim Vansa <rvansa@redhat.com>
 * @author Michal Linhard <mlinhard@redhat.com>
 */
class BackgroundStressorLogic extends AbstractLogic {
   // these two caches can be transactional internally (with autocommit)
   // but must not be used between begin() and commit() | rollback()
   private final BasicOperations.Cache nonTxBasicCache;
   private final ConditionalOperations.Cache nonTxConditionalCache;
   private final long keyRangeStart;
   private final long keyRangeEnd;
   private final List<Range> deadWorkersRanges;
   private final boolean loadOnly;
   private final boolean putWithReplace;
   private final Random rand = new Random();
   private BasicOperations.Cache basicCache;
   private ConditionalOperations.Cache conditionalCache;
   private volatile long currentKey;
   private int remainingTxOps;
   private boolean loaded;
   private RequestSet transactionalRequests;
   private ValueGenerator valueGenerator;

   BackgroundStressorLogic(BackgroundOpsManager manager, Range range, List<Range> deadWorkersRanges, boolean loaded) {
      super(manager);
      this.manager = manager;
      this.nonTxBasicCache = manager.getBasicCache();
      this.nonTxConditionalCache = manager.getConditionalCache();
      if (transactionSize <= 0) {
         basicCache = nonTxBasicCache;
         conditionalCache = nonTxConditionalCache;
      }
      this.keyRangeStart = range.getStart();
      this.keyRangeEnd = range.getEnd();
      this.deadWorkersRanges = deadWorkersRanges;
      this.loadOnly = manager.getBackgroundStressorLogicConfiguration().isLoadOnly();
      this.putWithReplace = manager.getBackgroundStressorLogicConfiguration().isPutWithReplace();
      this.valueGenerator = manager.getBackgroundStressorLogicConfiguration().getValueGenerator();
      this.loaded = loaded;
      this.currentKey = range.getStart();
      this.remainingTxOps = transactionSize;
   }

   public void loadData() {
      log.trace("Loading key range [" + keyRangeStart + ", " + keyRangeEnd + "]");
      loadKeyRange(keyRangeStart, keyRangeEnd);
      if (deadWorkersRanges != null) {
         for (Range range : deadWorkersRanges) {
            log.trace("Loading key range for dead worker: [" + range.getStart() + ", " + range.getEnd() + "]");
            loadKeyRange(range.getStart(), range.getEnd());
         }
      }
   }

   private void loadKeyRange(long from, long to) {
      int loadedKeys = 0;
      boolean loadWithPutIfAbsent = manager.getBackgroundStressorLogicConfiguration().isLoadWithPutIfAbsent();
      int entrySize = manager.getBackgroundStressorLogicConfiguration().getEntrySize();
      for (long keyId = from; keyId < to && !stressor.isTerminated(); keyId++, loadedKeys++) {
         while (!stressor.isTerminated()) {
            try {
               Object key = keyGenerator.generateKey(keyId);
               Object value = valueGenerator.generateValue(keyId, entrySize, rand);
               if (loadWithPutIfAbsent) {
                  nonTxConditionalCache.putIfAbsent(key, value);
               } else {
                  nonTxBasicCache.put(key, value);
               }
               if (loadedKeys % 1000 == 0) {
                  log.debug("Loaded " + loadedKeys + " out of " + (to - from));
               }
               // if we get an exception, it's OK - we can retry.
               break;
            } catch (Exception e) {
               log.error("Error while loading data", e);
            }
         }
      }
      log.debug("Loaded all " + (to - from) + " keys");
   }

   @Override
   public void init() {
      // TODO: maybe loadData should go here?
   }

   public void invoke() throws InterruptedException {
      if (!loaded) {
         loadData();
         loaded = true;
      }
      if (loadOnly) {
         log.info("Data have been loaded, terminating.");
         return;
      }
      long startTime = 0;
      Operation operation = getOperation(rand);
      try {
         Object key = keyGenerator.generateKey(currentKey++);
         if (currentKey == keyRangeEnd) {
            currentKey = keyRangeStart;
         }
         if (transactionSize > 0 && remainingTxOps == transactionSize) {
            ongoingTx = manager.newTransaction();
            basicCache = ongoingTx.wrap(nonTxBasicCache);
            conditionalCache = ongoingTx.wrap(nonTxConditionalCache);
            Request beginRequest = stressor.stats.startRequest();
            beginRequest.exec(Transactional.BEGIN, () -> ongoingTx.begin());
            transactionalRequests = stressor.stats.requestSet();
            transactionalRequests.add(beginRequest);
         }
         Request request = stressor.stats.startRequest();
         try {
            Object result;
            if (operation == BasicOperations.GET) {
               result = basicCache.get(key);
               if (result == null) operation = GET_NULL;
            } else if (operation == BasicOperations.PUT) {
               int entrySize = manager.getBackgroundStressorLogicConfiguration().getEntrySize();
               Object value = valueGenerator.generateValue(key, entrySize, rand);
               if (putWithReplace) {
                  conditionalCache.replace(key, value);
               } else {
                  basicCache.put(key, value);
               }
            } else if (operation == BasicOperations.REMOVE) {
               basicCache.remove(key);
            } else {
               throw new IllegalArgumentException();
            }
            request.succeeded(operation);
         } catch (Exception e) {
            request.failed(operation);
            throw e;
         } finally {
            if (transactionalRequests != null) {
               transactionalRequests.add(request);
            }
         }
         if (transactionSize > 0) {
            remainingTxOps--;
            if (remainingTxOps == 0) {
               Request commitRequest = stressor.stats.startRequest();
               try {
                  ongoingTx.commit();
                  commitRequest.succeeded(Transactional.COMMIT);
               } catch (Exception e) {
                  commitRequest.succeeded(Transactional.COMMIT);
                  throw e;
               } finally {
                  if (transactionalRequests != null) {
                     transactionalRequests.add(commitRequest);
                     transactionalRequests.finished(commitRequest.isSuccessful(), Transactional.DURATION);
                  }
                  txCleanup();
               }
               remainingTxOps = transactionSize;
            }
         }
      } catch (Exception e) {
         InterruptedException ie = Utils.findThrowableCauseByClass(e, InterruptedException.class);
         if (ie != null) {
            throw ie;
         } else if (e.getClass().getName().contains("SuspectException")) {
            log.error("Request failed due to SuspectException: " + e.getMessage());
         } else {
            log.error("Cache operation error", e);
         }
         if (transactionSize > 0) {
            try {
               ongoingTx.rollback();
            } catch (Exception e1) {
               log.error("Error while ending transaction", e);
            } finally {
               txCleanup();
            }
            remainingTxOps = transactionSize;
         }
      }
   }

   private void txCleanup() {
      ongoingTx = null;
      basicCache = null;
      conditionalCache = null;
   }

   @Override
   public String getStatus() {
      return String.format("currentKey=%s, remainingTxOps=%d", keyGenerator.generateKey(currentKey), remainingTxOps);
   }

   public boolean isLoaded() {
      return loaded;
   }
}


text:
package com.amazonaws.services.sns.model;

import javax.annotation.Generated;

/**
 * <p>
 * Indicates an internal service error.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InternalErrorException extends com.amazonaws.services.sns.model.AmazonSNSException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new InternalErrorException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public InternalErrorException(String message) {
        super(message);
    }

}


text:
/**
 * Allows text config to be resolved from an external source.
 */
package com.adaptris.interlok.resolver;


text:
package azkaban.webapp;

import static azkaban.Constants.LogConstants.NEARLINE_LOGS;

import azkaban.Constants.ConfigurationKeys;
import azkaban.logs.ExecutionLogsLoader;
import azkaban.utils.Props;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
@SuppressWarnings("FutureReturnValueIgnored")
public class ExecutionLogsCleaner {

   private static final Logger logger = LoggerFactory.getLogger(ExecutionLogsCleaner.class);
   private final ScheduledExecutorService scheduler;
   private final ExecutionLogsLoader executionLogsLoader;
   private final Props azkProps;
   private long executionLogsRetentionMs;
   // 30 days
   private static final long DEFAULT_EXECUTION_LOGS_RETENTION_MS = 30 * 24 * 60 * 60 * 1000L;

   // 1 hour
   private static final long DEFAULT_LOG_CLEANUP_INTERVAL_SECONDS = 60 * 60;
   private long cleanupIntervalInSeconds;

   private static final int DEFAULT_LOG_CLEANUP_RECORD_LIMIT = 1000;
   private int executionLogCleanupRecordLimit;

   // Only applicable to nearline/jdbc logs.
   // We expect offline logs to be managed by another platform where retention is handled well.
   @Inject
   public ExecutionLogsCleaner(final Props azkProps,
       final @Named(NEARLINE_LOGS) ExecutionLogsLoader executionLogsLoader) {
      this.azkProps = azkProps;
      this.executionLogsLoader = executionLogsLoader;
      this.scheduler =
          Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setNameFormat(
              "azk-execlog-cleaner").build());
      this.executionLogsRetentionMs = this.azkProps.getLong(
          ConfigurationKeys.EXECUTION_LOGS_RETENTION_MS,
          DEFAULT_EXECUTION_LOGS_RETENTION_MS);
      this.cleanupIntervalInSeconds = this.azkProps.getLong(
          ConfigurationKeys.EXECUTION_LOGS_CLEANUP_INTERVAL_SECONDS,
          DEFAULT_LOG_CLEANUP_INTERVAL_SECONDS);
      this.executionLogCleanupRecordLimit =
          this.azkProps.getInt(ConfigurationKeys.EXECUTION_LOGS_CLEANUP_RECORD_LIMIT,
              DEFAULT_LOG_CLEANUP_RECORD_LIMIT);
   }

   public void start() {
      logger.info("Starting execution logs clean up thread");
      this.scheduler.scheduleAtFixedRate(() -> cleanExecutionLogs(), 0L, cleanupIntervalInSeconds,
          TimeUnit.SECONDS);
   }

   private void cleanExecutionLogs() {
      logger.info("Cleaning old logs from execution_logs");
      final long cutoff = System.currentTimeMillis() - this.executionLogsRetentionMs;
      logger.info("Cleaning old log files before "
          + new DateTime(cutoff).toString());
      cleanOldExecutionLogs(cutoff);
   }

   private void cleanOldExecutionLogs(final long millis) {
      final long beforeDeleteLogsTimestamp = System.currentTimeMillis();
      try {
         final int count = this.executionLogsLoader.removeExecutionLogsByTime(millis,
             this.executionLogCleanupRecordLimit);
         logger.info("Cleaned up " + count + " log entries.");
      } catch (final Exception e) {
         logger.error("log clean up failed. ", e);
      }
      logger.info(
          "log clean up time: " + (System.currentTimeMillis() - beforeDeleteLogsTimestamp)
              + " ms.");
   }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace SharpYaml.Serialization.Descriptors
{
	/// <summary>
	/// A descriptor for an array.
	/// </summary>
	public class ArrayDescriptor : ObjectDescriptor
	{
		private readonly Type elementType;
		private readonly Type listType;
		private readonly MethodInfo toArrayMethod;

		/// <summary>
		/// Initializes a new instance of the <see cref="ObjectDescriptor" /> class.
		/// </summary>
		/// <param name="attributeRegistry">The attribute registry.</param>
		/// <param name="type">The type.</param>
		/// <exception cref="System.ArgumentException">Expecting arrat type;type</exception>
		public ArrayDescriptor(IAttributeRegistry attributeRegistry, Type type)
			: base(attributeRegistry, type, false)
		{
			if (!type.IsArray) throw new ArgumentException("Expecting array type", "type");

			if (type.GetArrayRank() != 1)
			{
				throw new ArgumentException("Cannot support dimension [{0}] for type [{1}]. Only supporting dimension of 1".DoFormat(type.GetArrayRank(), type.FullName));
			}

			elementType = type.GetElementType();
			listType = typeof(List<>).MakeGenericType(ElementType);
			toArrayMethod = listType.GetMethod("ToArray");
		}

		/// <summary>
		/// Gets the type of the array element.
		/// </summary>
		/// <value>The type of the element.</value>
		public Type ElementType { get { return elementType; } }

		/// <summary>
		/// Creates the equivalent of list type for this array.
		/// </summary>
		/// <returns>A list type with same element type than this array.</returns>
		public Array CreateArray(int dimension)
		{
			return Array.CreateInstance(ElementType, dimension);
		}
	}
}


text:
'use strict';

const { config } = require('../../config');

module.exports = config.isEnvironment('production') ? [] : [
    require('./freight')
];


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

<title>Uses of Interface org.apache.river.discovery.ClientSubjectChecker (River-Internet vtrunk API Documentation)</title>
<meta name="date" content="2016-03-28">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.apache.river.discovery.ClientSubjectChecker

Packages that use ClientSubjectChecker

Package
Description

org.apache.river.discovery

Provides a set of constraints, low-level utility classes, and provider
interfaces for participating in versions 1 and 2 of the multicast request,
multicast announcement, and unicast discovery protocols.

org.apache.river.discovery.plaintext

Provides an implementation of the net.jini.discovery.plaintext
discovery format, specified in the Jini Discovery and Join
Specification.

Uses of ClientSubjectChecker in org.apache.river.discovery

Classes in org.apache.river.discovery that implement ClientSubjectChecker

Modifier and Type
Class and Description

class
ClientPermissionChecker

Implementation of ClientSubjectChecker that approves or rejects
 client subjects based on whether or not they have been granted a particular
 permission.

Methods in org.apache.river.discovery with parameters of type ClientSubjectChecker

Modifier and Type
Method and Description

MulticastRequest
MulticastRequestDecoder.decodeMulticastRequest(ByteBuffer buf,
                      InvocationConstraints constraints,
                      ClientSubjectChecker checker)

Decodes the multicast request data contained in the given buffer in a
 manner that satisfies the specified absolute constraints and client
 subject checker (if any), returning a MulticastRequest instance
 that contains the decoded data.

MulticastRequest
DelayedMulticastRequestDecoder.decodeMulticastRequest(ByteBuffer buf,
                      InvocationConstraints constraints,
                      ClientSubjectChecker checker,
                      boolean delayConstraintCheck)

Decodes the multicast request data contained in the given buffer in a
 manner that satisfies the specified absolute constraints and client
 subject checker (if any), returning a MulticastRequest instance
 that contains the decoded data, with constraint checking optionally
 delayed.

abstract MulticastRequest
Discovery.decodeMulticastRequest(DatagramPacket packet,
                      InvocationConstraints constraints,
                      ClientSubjectChecker checker)

Decodes the multicast request data contained in the given datagram in a
 manner that satisfies the specified constraints and client subject
 checker (if any), returning a MulticastRequest instance that
 contains the decoded data.

MulticastRequest
Discovery.decodeMulticastRequest(DatagramPacket packet,
                      InvocationConstraints constraints,
                      ClientSubjectChecker checker,
                      boolean delayConstraintCheck)

Decodes the multicast request data contained in the given datagram in a
 manner that satisfies the specified constraints and client subject
 checker (if any), returning a MulticastRequest instance that
 contains the decoded data, with constraint checking optionally
 delayed.

abstract void
Discovery.handleUnicastDiscovery(UnicastResponse response,
                      Socket socket,
                      InvocationConstraints constraints,
                      ClientSubjectChecker checker,
                      Collection context)

Handles the server side of unicast discovery, transmitting the given
 response data over the provided socket using the given collection of
 object stream context objects in a manner that satisfies the specified
 constraints and client subject checker (if any).

void
UnicastDiscoveryServer.handleUnicastDiscovery(UnicastResponse response,
                      Socket socket,
                      InvocationConstraints constraints,
                      ClientSubjectChecker checker,
                      Collection context,
                      ByteBuffer received,
                      ByteBuffer sent)

Handles the server side of unicast discovery, transmitting the given
 response data over the provided socket using the given collection of
 object stream context objects in a manner that satisfies the specified
 absolute constraints and client subject checker (if any).

Uses of ClientSubjectChecker in org.apache.river.discovery.plaintext

Methods in org.apache.river.discovery.plaintext with parameters of type ClientSubjectChecker

Modifier and Type
Method and Description

MulticastRequest
Server.decodeMulticastRequest(ByteBuffer buf,
                      InvocationConstraints constraints,
                      ClientSubjectChecker checker)

void
Server.handleUnicastDiscovery(UnicastResponse response,
                      Socket socket,
                      InvocationConstraints constraints,
                      ClientSubjectChecker checker,
                      Collection context,
                      ByteBuffer received,
                      ByteBuffer sent)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright 2007-2013, multiple authors.
Licensed under the Apache License, Version 2.0, see the NOTICE file for attributions.


text:
package org.lennartb.gtlaptimer.Helpers;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaScannerConnection;
import android.os.Environment;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class DBExport {
    public static final String EXPORT_FILENAME = "GTLapTimer_Export.csv";

    private DBExport() {
    }

    /**
     * Exports all saved times including tuning, parts and times to a CSV file.
     *
     * @param outFileName Name of the CSV file.
     * @param context     Application context.
     * @return True if succeeded, false if not.
     */

    public static Boolean backupDatabaseCSV(String outFileName, Activity context) {

        Boolean returnCode;
        String csvValues;
        SQLiteDatabase database = DBHelper.getInstance(context).getDatabase();
        File outFile;

        // Notification to display failure or success to the user.
        Toast notification = new Toast(context);
        notification.setView(context.findViewById(org.lennartb.gtlaptimer.R.id.centered_toast_text));

        try {
            outFile = new File(Environment.getExternalStorageDirectory(), outFileName);
            FileWriter fileWriter = new FileWriter(outFile);
            BufferedWriter out = new BufferedWriter(fileWriter);

            // Super complicated SQL query. Basically gathers all information from all timesets across all tables.
            Cursor cursor = database.rawQuery("SELECT Cars.manufacturer || ' ' || Cars.model AS car," +
                                                      "Game.gamename, " +
                                                      "Group_Concat(DISTINCT Tuning.tunepart || ': ' || TimeSet_Tuning.progress) AS tuning, " +
                                                      "Group_Concat(DISTINCT CASE WHEN Parts.levelname IS NULL THEN Parts.name ELSE Parts.name || ': ' || Parts.levelname END) AS fullpartname, " +
                                                      "TimeSet.time, " +
                                                      "TimeSet.date, " +
                                                      "Track.trackname || CASE (TimeSet.reverse) WHEN \"0\" THEN '' WHEN \"1\" THEN ' (Reverse)' END, " +
                                                      "TimeSet.timesetid " +
                                                      "FROM Cars " +
                                                      "INNER JOIN Parts ON Game.gameid = Parts.gameid " +
                                                      "INNER JOIN Game ON Game.gameid = TimeSet.gameid " +
                                                      "INNER JOIN TimeSet ON Cars.carid = TimeSet.carid " +
                                                      "INNER JOIN TimeSet_Parts ON Parts.partid = TimeSet_Parts.partid AND TimeSet.timesetid = TimeSet_Parts.timesetid " +
                                                      "LEFT OUTER JOIN TimeSet_Tuning ON TimeSet.timesetid = TimeSet_Tuning.timesetid " +
                                                      "INNER JOIN Track ON Track.trackid = TimeSet.trackid " +
                                                      "LEFT OUTER JOIN Tuning ON Tuning.tuneid = TimeSet_Tuning.tuneid " +
                                                      "GROUP BY TimeSet.date", null);

            // Add commas to make a CSV file.
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    csvValues = cursor.getString(0) + ",";
                    csvValues += cursor.getString(1) + ",";
                    csvValues += cursor.getString(2) + ",";
                    csvValues += cursor.getString(3) + ",";
                    csvValues += cursor.getString(4) + ",";
                    csvValues += cursor.getString(5) + ",";
                    csvValues += cursor.getString(6);
                    csvValues += "\n";
                    out.write(csvValues);
                }
                cursor.close();
            }
            out.close();

            // Scan file, so it is immediately visible to other Android applications.
            MediaScannerConnection.scanFile(context, new String[]{outFile.getAbsolutePath()}, null, null);
            returnCode = true;
            notification.makeText(context, "Exported Database successfully to " + outFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            returnCode = false;
            L.e(e.getMessage());
            notification.makeText(context, "Exporting Database failed. Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }

        return returnCode;
    }
}


text:
module rl.utilities.services.array {
	'use strict';

	export var moduleName: string = 'rl.utilities.services.array';
	export var serviceName: string = 'arrayUtility';

	export interface IArrayUtility {
		findIndexOf<TDataType>(array: TDataType[], predicate: { (item: TDataType): boolean }): number;
		remove<TDataType>(array: TDataType[], item: { (obj: TDataType): boolean }): TDataType;
		remove<TDataType>(array: TDataType[], item: TDataType): TDataType;
		replace<TDataType>(array: TDataType[], oldItem: TDataType, newItem: TDataType): void;
		sum<TDataType>(array: TDataType[], transform: { (item: TDataType): number }): number;
		sum(array: number[]): number;
		toDictionary<TDataType>(array: TDataType[], keySelector: {(item: TDataType): string}): TDataType[];
		toDictionary<TDataType>(array: TDataType[], keySelector: {(item: TDataType): number}): TDataType[];
	}

	class ArrayUtility implements IArrayUtility {
		findIndexOf<TDataType>(array: TDataType[], predicate: { (item: TDataType): boolean }): number {
			var targetIndex: number;

			_.each(array, (item: TDataType, index: number): boolean => {
				if (predicate(item)) {
					targetIndex = index;
					return false;
				}
			});

			return targetIndex != null ? targetIndex : -1;
		}

		remove<TDataType>(array: TDataType[], item: TDataType | { (obj: TDataType): boolean }): TDataType {
			var index: number;

			if (_.isFunction(item)) {
				index = this.findIndexOf(array, <{(obj: TDataType): boolean}>item);
			} else {
				index = _.indexOf(array, <TDataType>item);
			}

			if (index >= 0) {
				return array.splice(index, 1)[0];
			} else {
				return null;
			}
		}

		replace<TDataType>(array: TDataType[], oldItem: TDataType, newItem: TDataType): void {
			var index: number = _.indexOf(array, oldItem);

			if (index >= 0) {
				array.splice(index, 1, newItem);
			}
		}

		sum<TDataType>(array: TDataType[], transform?: { (item: TDataType): number }): number {
			var list: number[];

			if (transform != null) {
				list = _.map(array, (item: TDataType): number => { return transform(item); });
			} else {
				list = <any[]>array;
			}

			return _.reduce(list, (sum: number, num: number): number => { return sum + num; }, 0);
		}

		toDictionary<TDataType>(array: TDataType[], keySelector: { (item: TDataType): string | number }): TDataType[] {
			return _.reduce(array, (dictionary: TDataType[], item: TDataType): TDataType[] => {
				dictionary[<any>keySelector(item)] = item;
				return dictionary;
			}, []);
		}
	}

	angular.module(moduleName, [])
		.service(serviceName, ArrayUtility);
}


text:
using System;
#if WPF
using System.Windows;
using System.Windows.Media.Animation;
#elif METRO
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Animation;
#endif
using GraphX.Controls.Models;

namespace GraphX.Controls.Animations
{
    public sealed class DeleteFadeAnimation : IOneWayControlAnimation
    {
        public double Duration { get; set; }

        public DeleteFadeAnimation(double duration = .3)
        {
            Duration = duration;
        }

        private void RunAnimation(IGraphControl target)
        {
            //create and run animation
            var story = new Storyboard();
            var fadeAnimation = new DoubleAnimation {Duration = new Duration(TimeSpan.FromSeconds(Duration)), FillBehavior = FillBehavior.Stop, From = 1, To = 0};
            fadeAnimation.Completed += (sender, e) => OnCompleted(target);
            story.Children.Add(fadeAnimation);
            Storyboard.SetTarget(fadeAnimation, target as FrameworkElement);
#if WPF
            Storyboard.SetTargetProperty(fadeAnimation, new PropertyPath(UIElement.OpacityProperty));
            story.Begin(target as FrameworkElement);
#elif METRO
            Storyboard.SetTargetProperty(fadeAnimation, "Opacity");
            story.Begin();
#else
            throw new NotImplementedException();
#endif
        }

        public void AnimateVertex(VertexControl target)
        {
            RunAnimation(target);
        }

        public void AnimateEdge(EdgeControl target)
        {
            RunAnimation(target);
        }

        public event RemoveControlEventHandler Completed;

        public void OnCompleted(IGraphControl target)
        {
            if (Completed != null)
                Completed(this, new ControlEventArgs(target));
        }
    }
}


text:
package com.hazelcast.sql.impl.exec.scan.index;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.map.impl.MapContainer;
import com.hazelcast.map.impl.MapService;
import com.hazelcast.query.impl.InternalIndex;
import com.hazelcast.query.impl.QueryableEntry;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import org.junit.After;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;

@SuppressWarnings({"rawtypes", "unchecked"})
public class IndexFilterIteratorTestSupport extends IndexFilterTestSupport {

    protected static final String MAP_NAME = "map";
    protected static final String INDEX_NAME = "index";

    protected final TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1);

    @After
    public void after() {
        factory.shutdownAll();
    }

    protected static InternalIndex getIndex(HazelcastInstance instance) {
        MapService mapService = nodeEngine(instance).getService(MapService.SERVICE_NAME);

        MapContainer mapContainer = mapService.getMapServiceContext().getMapContainer(MAP_NAME);

        return mapContainer.getIndexes().getIndex(INDEX_NAME);
    }

    protected static <T> void checkIterator(Iterator<QueryableEntry> iterator, T... expectedKeys) {
        Set<T> expected;

        if (expectedKeys != null) {
            expected = new HashSet<>(Arrays.asList(expectedKeys));

            assertEquals("Key passed to this method must be unique!", expected.size(), expectedKeys.length);
        } else {
            expected = Collections.emptySet();
        }

        Set<T> actual = new HashSet<>();

        while (iterator.hasNext()) {
            Object key = iterator.next().getKey();

            if (key instanceof Data) {
                key = getSerializationService().toObject(key);
            }

            assertTrue("Duplicate key: " + key, actual.add((T) key));
        }

        assertEquals("Expected: " + expected + ", actual: " + actual, expected.size(), actual.size());
        assertTrue("Expected: " + expected + ", actual: " + actual, expected.containsAll(actual));
    }

    public static class Value implements Serializable {
        public Integer value1;
        public Integer value2;

        public Value(Integer value) {
            this(value, value);
        }

        public Value(Integer value1, Integer value2) {
            this.value1 = value1;
            this.value2 = value2;
        }
    }
}


text:
declare module "vinyl-source-stream" {
    function vinylSourceStream(filename: string): NodeJS.ReadWriteStream;
    export = vinylSourceStream;
}


text:
#include <aws/mediaconvert/model/Ac3MetadataControl.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace MediaConvert
  {
    namespace Model
    {
      namespace Ac3MetadataControlMapper
      {

        static const int FOLLOW_INPUT_HASH = HashingUtils::HashString("FOLLOW_INPUT");
        static const int USE_CONFIGURED_HASH = HashingUtils::HashString("USE_CONFIGURED");

        Ac3MetadataControl GetAc3MetadataControlForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == FOLLOW_INPUT_HASH)
          {
            return Ac3MetadataControl::FOLLOW_INPUT;
          }
          else if (hashCode == USE_CONFIGURED_HASH)
          {
            return Ac3MetadataControl::USE_CONFIGURED;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<Ac3MetadataControl>(hashCode);
          }

          return Ac3MetadataControl::NOT_SET;
        }

        Aws::String GetNameForAc3MetadataControl(Ac3MetadataControl enumValue)
        {
          switch(enumValue)
          {
          case Ac3MetadataControl::FOLLOW_INPUT:
            return "FOLLOW_INPUT";
          case Ac3MetadataControl::USE_CONFIGURED:
            return "USE_CONFIGURED";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return "";
          }
        }

      } // namespace Ac3MetadataControlMapper
    } // namespace Model
  } // namespace MediaConvert
} // namespace Aws


text:
package com.navercorp.pinpoint.plugin.httpclient5.interceptor;

import com.navercorp.pinpoint.bootstrap.async.AsyncContextAccessor;
import com.navercorp.pinpoint.bootstrap.context.AsyncContext;
import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
import com.navercorp.pinpoint.bootstrap.context.TraceContext;
import com.navercorp.pinpoint.bootstrap.interceptor.SpanEventSimpleAroundInterceptorForPlugin;
import com.navercorp.pinpoint.common.util.ArrayArgumentUtils;
import com.navercorp.pinpoint.plugin.httpclient5.HttpClient5Constants;

public class MinimalHttpAsyncClientExecuteInterceptor extends SpanEventSimpleAroundInterceptorForPlugin {
    public MinimalHttpAsyncClientExecuteInterceptor(TraceContext traceContext, MethodDescriptor methodDescriptor) {
        super(traceContext, methodDescriptor);
    }

    @Override
    public void doInBeforeTrace(SpanEventRecorder recorder, Object target, Object[] args) throws Exception {
        final AsyncContextAccessor asyncContextAccessor = ArrayArgumentUtils.getArgument(args, 0, AsyncContextAccessor.class);
        if (asyncContextAccessor != null) {
            final AsyncContext asyncContext = recorder.recordNextAsyncContext();
            asyncContextAccessor._$PINPOINT$_setAsyncContext(asyncContext);
        }
    }

    @Override
    public void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) throws Exception {
        recorder.recordApi(methodDescriptor);
        recorder.recordException(throwable);
        recorder.recordServiceType(HttpClient5Constants.HTTP_CLIENT5_INTERNAL);
    }
}


text:
/// <amd-module name="@angular/compiler-cli/src/transformers/entry_points" />
export { createCompilerHost } from './compiler_host';
export { createProgram } from './program';


text:
@erase lang.inc
@echo lang fix en >lang.inc
@fasm -m 16384 @panel.asm @panel
@erase lang.inc
@kpack @panel
@pause


text:
package org.ftc.opmodes;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;

import com.google.common.collect.HashBiMap;
import com.google.common.io.Files;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.util.RobotLog;
import com.qualcomm.robotcore.util.RunShellCommand;

import org.ftccommunity.ftcxtensible.opmodes.Autonomous;
import org.ftccommunity.ftcxtensible.opmodes.Disabled;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

@Disabled
@Autonomous
public class NetworkAnalyzer extends OpMode {
    private WifiManager wifi;
    private String mostCommon = "None";
    private String secondMostCommon = "None";

    private HashBiMap<Integer, String> wifiChannelMap;
    private String operChannel;
    private String recChannel = "Not Ready";

    @Override
    public void init() {
        wifiChannelMap = HashBiMap.create();
        wifiChannelMap.put(2412, "2.4G Ch01");
        wifiChannelMap.put(2417, "2.4G Ch02");
        wifiChannelMap.put(2422, "2.4G Ch03");
        wifiChannelMap.put(2427, "2.4G Ch04");
        wifiChannelMap.put(2432, "2.4G Ch05");
        wifiChannelMap.put(2437, "2.4G Ch06");
        wifiChannelMap.put(2442, "2.4G Ch07");
        wifiChannelMap.put(2447, "2.4G Ch08");
        wifiChannelMap.put(2452, "2.4G Ch09");
        wifiChannelMap.put(2457, "2.4G Ch10");
        wifiChannelMap.put(2462, "2.4G Ch11");
        wifiChannelMap.put(2467, "2.4G Ch12");
        wifiChannelMap.put(2472, "2.4G Ch13");
        wifiChannelMap.put(2484, "2.4G Ch14");

        wifi = (WifiManager) hardwareMap.appContext.getSystemService(Context.WIFI_SERVICE);
        hardwareMap.appContext.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                LinkedList<ScanResult> results = new LinkedList<>(wifi.getScanResults());
                scanResults(results);
            }
        }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

        wifi.startScan();

        try {
            String absolutePath = hardwareMap.appContext.getFilesDir().getAbsolutePath() + "/";
            RunShellCommand cmd = new RunShellCommand();
            String output;
            if ((output = cmd.run(String.format("cp /data/misc/wifi/p2p_supplicant.conf %sp2p_supplicant.conf \n", absolutePath))).length() > 0) {
                RobotLog.e("Cannot copy p2p file" + output);
                operChannel = output;
            }

            String fileData = Files.toString(new File(absolutePath + "p2p_supplicant.conf"), Charset.defaultCharset());
            String[] datas = fileData.split("/n");
            for (String data : datas) {
                if (data.contains("p2p_oper_channel")) {
                    operChannel = data.substring(data.indexOf("="));
                }
            }
        } catch (IOException ex) {
            if (operChannel.equals("")) {
                operChannel = ex.getMessage();
            }
        }
    }

    @Override
    public void loop() {
        telemetry.addData("Most Common Freq: ", mostCommon);
        telemetry.addData("Second Most Common Freq: ", secondMostCommon);
        telemetry.addData("Recommended Channel", recChannel);
        telemetry.addData("Current Channel: ", operChannel);
    }

    private void scanResults(LinkedList<ScanResult> results) {
        @SuppressLint("UseSparseArrays")
        HashMap<Integer, Integer> frequencyCount = new HashMap<>();

        for (ScanResult result : results) {
            WifiManager.calculateSignalLevel(result.level, 100);

            if (frequencyCount.get(result.frequency) == 0) {
                int count = frequencyCount.get(result.frequency);
                frequencyCount.put(result.frequency, ++count);
            } else {
                frequencyCount.put(result.frequency, 1);
            }

            RobotLog.d("Network on: " + wifiChannelMap.get(result.frequency));
        }
        RobotLog.d("Done displaying networks!");

        LinkedList<Map.Entry<Integer, Integer>> frequencies = new LinkedList<>(frequencyCount.entrySet());
        Collections.sort(frequencies, new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> lhs, Map.Entry<Integer, Integer> rhs) {
                if (lhs.equals(rhs)) {
                    return 0;
                }

                if (lhs.getValue() > rhs.getValue()) {
                    return 1;
                } else if (lhs.getValue() < rhs.getValue()) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });

        if (frequencies.size() > 0) {
            int location = frequencies.size() - 1;
            mostCommon = wifiChannelMap.containsKey(frequencies.get(location).getKey()) ?
                    wifiChannelMap.get(frequencies.get(location).getKey()) : "5 GHz";
        }

        if (frequencies.size() > 1) {
            int location = frequencies.size() - 2;
            secondMostCommon = wifiChannelMap.containsKey(frequencies.get(location).getKey()) ?
                    wifiChannelMap.get(frequencies.get(location).getKey()) : "5 GHz";
        }

        recChannel = recommendedChannel();
    }

    private String recommendedChannel() {
        int mostCommonChannel = wifiChannelMap.inverse().get(mostCommon);
        int secondMostCommonChannel = wifiChannelMap.inverse().get(secondMostCommon);

        int[] recommendations = secondMostRecommended(secondMostCommonChannel);
        if (mostCommonChannel <= 2422) { // Most Common is Channel 1-3
            if (recommendations[0] > 2452) {
                return wifiChannelMap.get(recommendations[0]);
            } else {
                return wifiChannelMap.get(recommendations[1]);
            }
        } else if (mostCommonChannel < 2452) { // Channel 4-9
            if (recommendations[0] <= 2422) {
                return wifiChannelMap.get(recommendations[0]);
            } else {
                return wifiChannelMap.get(recommendations[1]);
            }
        } else { // Channel 9-14
            if (recommendations[0] < 2452) {
                return wifiChannelMap.get(recommendations[0]);
            } else {
                return wifiChannelMap.get(recommendations[1]);
            }
        }
    }

    private int[] secondMostRecommended(int secondChannel) {
        int[] results = new int[2];

        if (secondChannel <= 2422) { // Channel 1-3
            results[0] = 2462; // Channel 11
            results[1] = 2437; // Channel 6
        } else if (secondChannel < 2452) { // Channel 4-9
            results[0] = 2412; // Channel 1
            results[1] = 2462; // Channel 11
        } else { // Channel 9-14
            results[0] = 2412; // Channel 1
            results[1] = 2437; // Channel 6
        }

        return results;
    }
}


text:
SYNONYM

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

#### Published in
in Briton-Jones, Bulletin of the Minist. Agric. Egypt, Bot. Sect. 49: 65 (1925)

#### Original name
Sclerotium bataticola Taubenh., 1913

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:background="@drawable/touch_selector"
    android:orientation="horizontal"

    android:padding="16dp">

    <ImageView
        android:id="@+id/list_item_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_width="0dp"

        android:layout_weight="1"
        android:orientation="vertical"
        android:paddingLeft="16dp">

        <TextView
            android:id="@+id/list_item_date_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/list_item_forecast_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/list_item_high_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/list_item_low_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>


text:
from django.conf import settings
if settings.FILE_DB == settings.S3:
    from cripts.core.s3_tools import get_file_s3

import gridfs
import pymongo

import magic

class MongoError(Exception):
    """
    Generic MongoError exception.
    """
    pass

# TODO: mongo_connector() and gridfs_connector() can probably be combined into
# one function.

# Setup standard connector to the MongoDB instance for use in any functions
def mongo_connector(collection, preference=settings.MONGO_READ_PREFERENCE):
    """
    Connect to the mongo database if you need to use PyMongo directly and not
    use MongoEngine.

    :param collection: the collection to use.
    :type collection: str
    :param preference: PyMongo Read Preference for ReplicaSet/clustered DBs.
    :type preference: str.
    :returns: :class:`pymongo.MongoClient`,
              :class:`cripts.core.mongo_tools.MongoError`
    """

    try:
        connection = pymongo.MongoClient("%s" % settings.MONGO_HOST,
                                        settings.MONGO_PORT,
                                        read_preference=preference,
                                        ssl=settings.MONGO_SSL)
        db = connection[settings.MONGO_DATABASE]
        if settings.MONGO_USER:
            db.authenticate(settings.MONGO_USER, settings.MONGO_PASSWORD)
        return db[collection]
    except pymongo.errors.ConnectionFailure as e:
        raise MongoError("Error connecting to Mongo database: %s" % e)
    except KeyError as e:
        raise MongoError("Unknown database or collection: %s" % e)
    except:
        raise

def gridfs_connector(collection, preference=settings.MONGO_READ_PREFERENCE):
    """
    Connect to the mongo database if you need to use PyMongo directly and not
    use MongoEngine. Used specifically for accessing GridFS.

    :param collection: the collection to use.
    :type collection: str
    :param preference: PyMongo Read Preference for ReplicaSet/clustered DBs.
    :type preference: str.
    :returns: :class:`gridfs.GridFS`,
              :class:`cripts.core.mongo_tools.MongoError`
    """

    try:
        connection = pymongo.MongoClient("%s" % settings.MONGO_HOST,
                                        settings.MONGO_PORT,
                                        read_preference=preference,
                                        ssl=settings.MONGO_SSL)
        db = connection[settings.MONGO_DATABASE]
        if settings.MONGO_USER:
            db.authenticate(settings.MONGO_USER, settings.MONGO_PASSWORD)
        return gridfs.GridFS(db, collection)
    except pymongo.errors.ConnectionFailure as e:
        raise MongoError("Error connecting to Mongo database: %s" % e)
    except KeyError as e:
        raise MongoError("Unknown database: %s" % e)
    except:
        raise

def get_file(sample_md5, collection):
    """
    Get a file from GridFS (or S3 if that's what you've configured).

    :param sample_md5: The MD5 of the file to download.
    :type sample_md5: str
    :param collection: The collection to grab the file from.
    :type collection: str
    :returns: str
    """

    # Workaround until pcap download uses pcap object
    if settings.FILE_DB == settings.GRIDFS:
        return get_file_gridfs(sample_md5, collection)
    elif settings.FILE_DB == settings.S3:
        objs = mongo_connector(collection)
        obj = objs.find_one({"md5": sample_md5})
        oid = obj['filedata']
        return get_file_s3(oid,collection)

def put_file(m, data, collection):
    """
    Add a file to storage.

    :param m: The filename.
    :type m: str
    :param data: The data to add.
    :type data: str
    :param collection: The collection to grab the file from.
    :type collection: str
    :returns: str
    """

    return put_file_gridfs(m, data, collection)

def get_file_gridfs(sample_md5, collection):
    """
    Get a file from GridFS.

    :param sample_md5: The MD5 of the file to download.
    :type sample_md5: str
    :param collection: The collection to grab the file from.
    :type collection: str
    :returns: str
    """

    data = None
    try:
        fm = mongo_connector("%s.files" % collection)
        objectid = fm.find_one({'md5': sample_md5}, {'_id': 1})['_id']
        fs = gridfs_connector("%s" % collection)
        data = fs.get(objectid).read()
    except Exception:
        return None
    return data

def put_file_gridfs(m, data, collection):
    """
    Add a file to storage.

    :param m: The filename.
    :type m: str
    :param data: The data to add.
    :type data: str
    :param collection: The collection to grab the file from.
    :type collection: str
    :returns: str
    """

    mimetype = magic.from_buffer(data, mime=True)
    try:
        fs = gridfs_connector("%s" % collection)
        fs.put(data, content_type="%s" % mimetype, filename="%s" % m)
    except Exception:
        return None
    return m

def delete_file(sample_md5, collection):
    """
    delete_file allows you to delete a file from a gridfs collection specified
    in the collection parameter.
    this will only remove the file object, not metadata from assocatiated collections
    for full deletion of metadata and file use delete_sample

    :param sample_md5: The MD5 of the file to delete.
    :type sample_md5: str
    :param collection: The collection to delete the file from.
    :type collection: str
    :returns: True, False, None
    """
    fm = mongo_connector("%s.files" % collection)
    sample = fm.find_one({'md5': sample_md5}, {'_id': 1})
    success = None
    if sample:
        objectid = sample["_id"]
        fs = gridfs_connector("%s" % collection)
        try:
            fs.delete(objectid)
            return True
        except:
            return None
    return success

####################################################
# NOTE: The following wrappers are only here for   #
#       legacy code and rare instances where we    #
#       cannot use MongoEngine to achieve our      #
#       goal. Please use these as a last resort!   #
####################################################

# Wrapper for pymongo's find_one function
def mongo_find_one(collection, query, fields=None, skip=0, sort=None,
                   *args, **kwargs):
    """
    Find one document from a collection matching the parameters.

    :param collection: The collection to query.
    :type collection: str
    :param query: The query to find the document(s).
    :type query: dict
    :param fields: The fields to return for each document.
    :type fields: dict
    :param skip: How many documents to skip before returning.
    :type skip: int
    :param sort: How to sort the results.
    :type sort: dict
    :returns: PyMongo cursor.
    """

    col = mongo_connector(collection)
    return col.find_one(query, fields, skip=skip, sort=sort, *args, **kwargs)

# Wrapper for pymongo's find function
def mongo_find(collection, query, fields=None, skip=0, limit=0, sort=None,
               count=False, *args, **kwargs):
    """
    Find documents from a collection matching the parameters.

    :param collection: The collection to query.
    :type collection: str
    :param query: The query to find the document(s).
    :type query: dict
    :param fields: The fields to return for each document.
    :type fields: dict
    :param skip: How many documents to skip before returning.
    :type skip: int
    :param limit: How many documents to return.
    :type limit: int
    :param sort: How to sort the results.
    :type sort: dict
    :param count: Only return a count of the documents.
    :type count: boolean
    :returns: PyMongo cursor, int
    """

    col = mongo_connector(collection)
    results = col.find(query, fields, skip=skip, limit=limit, sort=sort,
                       *args, **kwargs)
    if not kwargs.get('timeout', True):
        col.close
    if count:
        return results.count()
    else:
        return results

# Wrapper for pymongo's insert function
def mongo_insert(collection, doc_or_docs, username=None, safe=True, *args,
                 **kwargs):
    """
    Insert documents into a collection.

    :param collection: The collection to query.
    :type collection: str
    :param doc_or_docs: A single document or list of documents to insert.
    :type doc_or_docs: dict or list
    :param username: The user inserting these documents.
    :type username: str
    :param safe: Whether or not to insert in safe mode.
    :type safe: boolean
    :returns: dict with keys:
              "success" (boolean),
              "message" (list),
              "object" (insertion response) if successful.
    """

    col = mongo_connector(collection)
    try:
        col.insert(doc_or_docs, safe=safe, check_keys=True, *args, **kwargs)
        return {'success':True, 'message':[], 'object':doc_or_docs}
    except Exception, e:
        # OperationFailure gets raised only if safe=True and there is some error
        return {'success':False, 'message':[format_error(e)]}

# Wrapper for pymongo's update function
def mongo_update(collection, query, alter, username=None,
                 multi=True, upsert=False, safe=True, *args, **kwargs):
    """
    Update documents in a collection.

    :param collection: The collection to query.
    :type collection: str
    :param query: The query to use to find the documents to update.
    :type query: dict
    :param alter: How to update the documents.
    :type alter: dict
    :param username: The user updating the documents.
    :type username: str
    :param multi: Whether or not to update multiple documents.
    :type multi: boolean
    :param upsert: Insert documents into the collection if they are not found.
    :type upsert: boolean
    :param safe: Use safe mode while performing the update.
    :type safe: boolean
    :returns: dict with keys "success" (boolean) and "message" (list)
    """

    col = mongo_connector(collection)
    try:
        r = col.update(query, alter, multi=multi, upsert=upsert,
                       check_keys=True, safe=safe, *args, **kwargs)
        return {'success':True, 'message':[r]}
    except Exception, e:
       return {'success':False, 'message':[format_error(e)]}

# Wrapper for pymongo's save function
def mongo_save(collection, to_save, username=None, safe=True, *args, **kwargs):
    """
    Save a document to a collection.

    :param collection: The collection to query.
    :type collection: str
    :param to_save: The document to save.
    :type to_save: dict
    :param username: The user saving the document.
    :type username: str
    :param safe: Use safe mode while performing the save.
    :type safe: boolean
    :returns: dict with keys "success" (boolean) and "message" (list)
    """

    col = mongo_connector(collection)
    try:
        r = col.save(to_save, check_keys=True, manipulate=True, safe=safe,
                     *args, **kwargs)
        return {'success':True, 'message':[r]}
    except Exception, e:
       return {'success':False, 'message':[format_error(e)]}

# Wrapper for pymongo's find_and_modify function
def mongo_find_and_modify(collection, query, alter, fields=None, username=None,
                          sort={}, remove=False, new=False, upsert=False, *args,
                          **kwargs):
    """
    Find documents from a collection matching the parameters, update them, and
    return them.

    :param collection: The collection to query.
    :type collection: str
    :param query: The query to use to find the documents to update.
    :type query: dict
    :param alter: How to update the documents.
    :type alter: dict
    :param fields: The fields to return for each document.
    :type fields: dict
    :param username: The user updating the documents.
    :type username: str
    :param sort: How to sort the results.
    :type sort: dict
    :param remove: Remove documents instead of update.
    :type remove: boolean
    :param new: Return the updated documents instead of the original ones.
    :param upsert: Insert documents into the collection if they are not found.
    :type upsert: boolean
    :returns: dict with keys:
              "success" (boolean),
              "message" (list),
              "object" (cursor) if successful.
    """
    try:
        col = mongo_connector(collection)
        result = col.find_and_modify(query, update=alter, fields=fields,
                                     remove=remove, new=new, upsert=upsert,
                                     sort=sort, *args, **kwargs)
    except Exception, e:
        return {'success':False, 'message':[format_error(e)]}
    try:
        return {'success':True, 'message':[], 'object': result}
    except Exception, e:
        return {'success':True, 'message':[format_error(e)], 'object': result}

# Wrapper for pymongo's remove function
def mongo_remove(collection, query=None, username=None, safe=True, verify=False,
                 *args, **kwargs):
    """
    Find documents from a collection matching the parameters.

    :param collection: The collection to query.
    :type collection: str
    :param query: The query to use to find the documents to remove.
    :type query: dict
    :param username: The user removing the documents.
    :type username: str
    :param safe: Use safe mode while removing the documents.
    :type safe: boolean
    :param verify: Verify the removal.
    :type verify: boolean
    :returns: dict with keys "success" (boolean) and "message" list.
    """

    if not query:
        return {'success': False, 'message':['No query supplied to remove']}
    else:
        try:
            col = mongo_connector(collection)
            col.remove(query, safe=safe, *args, **kwargs)
            if verify:
                if mongo_find(collection, query, count=True):
                    return {'success':False,
                            'message':['Unknown error; unable to remove item']}
            return {'success':True, 'message':[]}
        except Exception, e:
            return {'success':False, 'message':[format_error(e)]}

def format_error(e):
    """
    wrapper for core/handlers format_error function.
    Redefined here to avoid circular imports.

    :param e: The error.
    :type e: :class:`Exception`
    :returns: str
    """

    from cripts.core.handlers import format_error as fe
    return fe(e)


text:
"""
The script handler makes sure to check through all stored scripts to
make sure they are still relevant. A scripthandler is automatically
added to all game objects. You access it through the property
`scripts` on the game object.

"""
from builtins import object

from evennia.scripts.models import ScriptDB
from evennia.utils import create
from evennia.utils import logger

from django.utils.translation import ugettext as _

class ScriptHandler(object):
    """
    Implements the handler.  This sits on each game object.

    """
    def __init__(self, obj):
        """
        Set up internal state.

        Args:
            obj (Object): A reference to the object this handler is
                attached to.

        """
        self.obj = obj

    def __str__(self):
        """
        List the scripts tied to this object.

        """
        scripts = ScriptDB.objects.get_all_scripts_on_obj(self.obj)
        string = ""
        for script in scripts:
            interval = "inf"
            next_repeat = "inf"
            repeats = "inf"
            if script.interval > 0:
                interval = script.interval
                if script.repeats:
                    repeats = script.repeats
                try:
                    next_repeat = script.time_until_next_repeat()
                except Exception:
                    next_repeat = "?"
            string += _("\n '%(key)s' (%(next_repeat)s/%(interval)s, %(repeats)s repeats): %(desc)s") % \
              {"key": script.key, "next_repeat": next_repeat,
               "interval": interval, "repeats": repeats, "desc": script.desc}
        return string.strip()

    def add(self, scriptclass, key=None, autostart=True):
        """
        Add a script to this object.

        Args:
            scriptclass (Scriptclass, Script or str): Either a class
                object inheriting from DefaultScript, an instantiated
                script object or a python path to such a class object.
            key (str, optional): Identifier for the script (often set
                in script definition and listings)
            autostart (bool, optional): Start the script upon adding it.

        """
        if self.obj.__dbclass__.__name__ == "PlayerDB":
            # we add to a Player, not an Object
            script = create.create_script(scriptclass, key=key, player=self.obj,
                                          autostart=autostart)
        else:
            # the normal - adding to an Object
            script = create.create_script(scriptclass, key=key, obj=self.obj,
                                      autostart=autostart)
        if not script:
            logger.log_err("Script %s could not be created and/or started." % scriptclass)
            return False
        return True

    def start(self, key):
        """
        Find scripts and force-start them

        Args:
            key (str): The script's key or dbref.

        Returns:
            nr_started (int): The number of started scripts found.

        """
        scripts = ScriptDB.objects.get_all_scripts_on_obj(self.obj, key=key)
        num = 0
        for script in scripts:
            num += script.start()
        return num

    def get(self, key):
        """
        Search scripts on this object.

        Args:
            key (str): Search criterion, the script's key or dbref.

        Returns:
            scripts (list): The found scripts matching `key`.

        """
        return ScriptDB.objects.get_all_scripts_on_obj(self.obj, key=key)

    def delete(self, key=None):
        """
        Forcibly delete a script from this object.

        Args:
            key (str, optional): A script key or the path to a script (in the
                latter case all scripts with this path will be deleted!)
                If no key is given, delete *all* scripts on the object!

        """
        delscripts = ScriptDB.objects.get_all_scripts_on_obj(self.obj, key=key)
        if not delscripts:
            delscripts = [script for script in ScriptDB.objects.get_all_scripts_on_obj(self.obj) if script.path == key]
        num = 0
        for script in delscripts:
            num += script.stop()
        return num
    # alias to delete
    stop = delete

    def all(self):
        """
        Get all scripts stored in this handler.

        """
        return ScriptDB.objects.get_all_scripts_on_obj(self.obj)

    def validate(self, init_mode=False):
        """
        Runs a validation on this object's scripts only.  This should
        be called regularly to crank the wheels.

        Args:
            init_mode (str, optional): - This is used during server
                upstart and can have three values:
                - `False` (no init mode). Called during run.
                - `"reset"` - server reboot. Kill non-persistent scripts
                - `"reload"` - server reload. Keep non-persistent scripts.

        """
        ScriptDB.objects.validate(obj=self.obj, init_mode=init_mode)


text:
"use strict";

const qs = require("querystring");
const zlib = require("zlib");

const spidex = require("spidex");

require("sugar");

const device = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) ";
const kit = "AppleWebKit/537.36 (KHTML, like Gecko) ";
const core = "Chrome/40.0.2214.94 Safari/537.36";
const UA = `${device}${kit}${core}`;
const baseUri = "http://baidu.kuaidi100.com/query?";

spidex.setDefaultUserAgent(UA);

/**
 * query for express
 * @param {String} num post id
 * @param {String} company company type
 * @param {Function} callback the callback function
 * @returns {void}
 */
exports.query = function(num, company, callback) {
    const queryObject = {
        type: company,
        postid: num,
        id: 4,
        valicode: "",
        temp: Math.random(),
        sessionid: ""
    };

    const header = {
        accept: "*/*",
        "accept-encoding": "gzip, deflate, sdch",
        "accept-language": "zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4,sv;q=0.2,zh-TW;q=0.2",
        connection: "keep-alive",
        host: "www.kuaidi100.com"
    };

    const url = baseUri + qs.stringify(queryObject);

    spidex.get(url, {
        timeout: 60000,
        charset: "binary",
        header: header
    }, function(data, status) {
        if(status !== 200) {
            return callback(new Error(`Server returns a wrong status. ${status}`));
        }

        zlib.unzip(data, function(err, buff) {
            if(err) return callback(err);
            data = buff.toString("utf8");

            let json;
            try {
                json = JSON.parse(data);
            } catch(e) {
                return callback(e);
            }

            if(undefined === json.data ||
                null === json.data ||
                (Array.isArray(json.data) ? json.data.length : 0) === 0
            ) {
                let msg = json.message || "Unknown error.";
                if(msg.indexOf(":") !== -1) {
                    msg = msg.substr(msg.indexOf(":") + 1);
                }
                return callback(new Error(msg));
            }

            return callback(undefined, json);
        });
    }).on("error", callback);
};


text:
var jshint = require("jshint");
module.exports = "test";


text:
<link rel="stylesheet"
	href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

	<wicket:extend>
		<form wicket:id="form">

								<wicket:message key="item_form.summary" />
									*
								<input wicket:id="summary" style="width: 49.7em"
									type="text" maxlength="255" /> <input type="submit"
									wicket:id="delete" wicket:message="value:delete" />

								<wicket:message key="item_form.detail" />
									*
								<textarea id="itemFormDetail" wicket:id="detail"
										rows="10" style="width: 600px"></textarea>

								<wicket:message
										key="item_form.originator" /> *
								<input wicket:id="originator" type="text" />

								<wicket:message
										key="item_form.originatorContact" /> *
								<input wicket:id="originator_contact" type="text" />

								<wicket:message key="item_form.dateAdded" />
									*

									<input type="text" wicket:id="dateTextField" />

								<wicket:message key="item_form.severity" />
									*
								<select wicket:id="severities" />

								<wicket:message key="item_form.category" />
									*
								<select wicket:id="categories" />

								<wicket:message key="item_form.assignTo" />
									*

										<select wicket:id="assignedTo" />

								<wicket:message
										key="item_form.editReason" /> *
								<textarea id="itemFormReason" wicket:id="editReason"
										rows="5" cols="40" style="width: 600px"></textarea>

								<input type="checkbox" wicket:id="sendNotifications" />
									<wicket:message key="item_form.sendNotifications" />

								<input type="checkbox" wicket:id="smsNotifications" />
									<wicket:message key="item_form.smsNotifications" />

								<input type="submit" wicket:message="value:submit" />

								<wicket:message
										key="item_form.notifyByEmail" />

								<wicket:message
										key="item_form.notifyBySMS" />

								<wicket:message
										key="item_form.attachment" />

								<input wicket:id="file" size="15" type="file"
									multiple="multiple" />

								<wicket:message key="item_form.attachmentLimit" />

		</form>
	</wicket:extend>


text:
using System;
using System.Collections;
using UnityEngine;

namespace JAudio
{
	/**
	 * The AudioManager is a utility class that can be used to directly handle audio, please remember to change the camera object when the scene reloads
	 * */
	public class AudioManager
	{
		public static readonly AudioManager INSTANCE = new AudioManager (GameObject.FindGameObjectWithTag("MainCamera"));
		private readonly GameObject audioPref;
		private GameObject camera;

		public AudioManager (GameObject camera) {
			this.audioPref = Resources.Load ("Prefab/Functional/AudioSource") as GameObject;
			this.camera = camera;
		}

		public static void Init() {
		}

		public AudioSource PlayAudio(AudioClip clip, GameObject location, bool loop, float volume) {
			GameObject newAudioPref = UnityEngine.Object.Instantiate (audioPref) as GameObject;
			AudioSource audioSrc = newAudioPref.GetComponent<AudioSource> ();

			audioSrc.loop = loop; //If it should loop
			audioSrc.clip = clip;//Assigns the clip
			audioSrc.volume = volume;

			newAudioPref.name = "AudioSource";
			newAudioPref.transform.position = location.transform.position;//Changes the position to the location
			newAudioPref.transform.SetParent(location.transform);//Sets it as a parent

			audioSrc.Play();

			return audioSrc;
		}

		public AudioSource PlayAudio (AudioClip clip, GameObject location, bool loop){
			return this.PlayAudio (clip, location, loop, 1.0F);
		}

		public AudioSource PlayAudio (AudioClip clip, GameObject location) {
			return this.PlayAudio (clip, location, false);
		}

		public AudioSource PlayAudio (AudioClip clip) {
			return this.PlayAudio (clip, this.camera);
		}

		public AudioSource PlayAudio (AudioClip clip, bool loop) {
			return this.PlayAudio (clip, this.camera, loop);
		}

		public AudioSource PlayAudio (AudioClip clip, bool loop, float volume) {
			return this.PlayAudio (clip, this.camera, loop, volume);
		}

		public AudioSource PlayAudio (AudioClip clip, float volume) {
			return this.PlayAudio (clip, this.camera, false, volume);
		}

		public void SetCamera (GameObject camera) {
			this.camera = camera;
		}

	}
}


text:
"""The tests for the notify smtp platform."""
import unittest

from homeassistant.components.notify import smtp

from tests.common import get_test_home_assistant

class MockSMTP(smtp.MailNotificationService):
    """Test SMTP object that doesn't need a working server."""

    def connection_is_valid(self):
        """Pretend connection is always valid for testing."""
        return True

    def _send_email(self, msg):
        """Just return string for testing."""
        return msg.as_string()

class TestNotifySmtp(unittest.TestCase):
    """Test the smtp notify."""

    def setUp(self):  # pylint: disable=invalid-name
        """Setup things to be run when tests are started."""
        self.hass = get_test_home_assistant()
        self.mailer = MockSMTP('localhost', 25, 'test@test.com', 1, 'testuser',
                               'testpass', 'testrecip@test.com', 0)

    def tearDown(self):  # pylint: disable=invalid-name
        """"Stop down everything that was started."""
        self.hass.stop()

    def test_text_email(self):
        """Test build of default text email behavior."""
        msg = self.mailer.send_message('Test msg')
        expected = ('Content-Type: text/plain; charset="us-ascii"\n'
                    'MIME-Version: 1.0\n'
                    'Content-Transfer-Encoding: 7bit\n'
                    'Subject: Home Assistant\n'
                    'To: testrecip@test.com\n'
                    'From: test@test.com\n'
                    'X-Mailer: HomeAssistant\n'
                    '\n'
                    'Test msg')
        self.assertEqual(msg, expected)

    def test_mixed_email(self):
        """Test build of mixed text email behavior."""
        msg = self.mailer.send_message('Test msg',
                                       data={'images': ['test.jpg']})
        self.assertTrue('Content-Type: multipart/related' in msg)


text:
var Prompt = require( '../node_modules/prompt.js' ).Prompt;

var prompt  = new Prompt();
prompt.handleCommand = function ( c ) {
  console.log( c.trim() );
  prompt.show();
}
prompt.show();


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.djs.learn</groupId>
	<artifactId>WsTomcatSample3</artifactId>
	<version>1.0.0</version>
	<packaging>war</packaging>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<junit.version>4.12</junit.version>
		<javax.ws.rs.version>2.1</javax.ws.rs.version>
		<javax.json.version>1.1.2</javax.json.version>
		<jersey.version>2.26</jersey.version>
		<hk2.version>2.5.0-b60</hk2.version>
	</properties>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.7.0</version>
				<configuration>
					<source>${maven.compiler.source}</source>
					<target>${maven.compiler.target}</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.2.0</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
				</configuration>
			</plugin>
			<!-- To generate "target\dependencies" with needed jars. -->
			<plugin>
				<artifactId>maven-dependency-plugin</artifactId>
				<executions>
					<execution>
						<id>copy-dependencies</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<includeScope>runtime</includeScope>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
			<exclusions>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>javax.ws.rs</groupId>
			<artifactId>javax.ws.rs-api</artifactId>
			<version>${javax.ws.rs.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.hk2</groupId>
			<artifactId>hk2-locator</artifactId>
			<version>${hk2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.hk2.external</groupId>
			<artifactId>javax.inject</artifactId>
			<version>${hk2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet</artifactId>
			<version>${jersey.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-client</artifactId>
			<version>${jersey.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-common</artifactId>
			<version>${jersey.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-server</artifactId>
			<version>${jersey.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.inject</groupId>
			<artifactId>jersey-hk2</artifactId>
			<version>${jersey.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-jaxb</artifactId>
			<version>${jersey.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-json-binding</artifactId>
			<version>${jersey.version}</version>
		</dependency>
	</dependencies>
</project>


text:
<?php

// Check to ensure this file is within the rest of the framework
defined('JPATH_BASE') or die();

// Register legacy classes for autoloading
JLoader::register('JDispatcher' , JPATH_LIBRARIES.DS.'joomla'.DS.'event'.DS.'dispatcher.php');

/**
 * Legacy class, use {@link JDispatcher} instead
 *
 * @deprecated	As of version 1.5
 * @package	Joomla.Legacy
 * @subpackage	1.5
 */
class mosMambotHandler extends JDispatcher
{
	function __construct()
	{
		parent::__construct();
	}

	/**
	* Loads all the bot files for a particular group
	* @param string The group name, relates to the sub-directory in the plugins directory
	*/
	function loadBotGroup( $group )
	{
		return JPluginHelper::importPlugin($group, null, false);
	}
	/**
	 * Loads the bot file
	 * @param string The folder (group)
	 * @param string The elements (name of file without extension)
	 * @param int Published state
	 * @param string The params for the bot
	 */
	function loadBot( $folder, $element, $published, $params='' )
	{
		return JPluginHelper::_import($folder, $element, $published, $params='' );
	}

	/**
	* Registers a function to a particular event group
	*
	* @param string The event name
	* @param string The function name
	*/
	function registerFunction( $event, $function )
	{
		 JApplication::registerEvent( $event, $function );
	}

	/**
	* Deprecated, use {@link JDispatcher::trigger() JDispatcher->trigger()} instead and handle return values
	* in your code
	*
	* @param string The event name
	* @since 1.5
	* @deprecated As of 1.5
	*/
	function call($event)
	{
		$args = & func_get_args();
		array_shift($args);

		$retArray = $this->trigger( $event, $args );
		return $retArray[0];
	}
}