text:
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using NUnit.Framework;

namespace MongoDB.Driver.Tests.Builders
{
    [TestFixture]
    public class FieldsBuilderTypedTests
    {
        public class TestClass
        {
            public int _id;
            public int[] a;
            public SubClass[] a2;
            public int x;
            public string textfield;
            [BsonIgnoreIfDefault]
            public double relevance;
        }

        public class SubClass
        {
            public int b;
        }

        [Test]
        public void TestElemMatch()
        {
            var fields = Fields<TestClass>.ElemMatch(tc => tc.a2, qb => qb.EQ(tc => tc.b, 10));
            string expected = "{ \"a2\" : { \"$elemMatch\" : { \"b\" : 10 } } }";
            Assert.AreEqual(expected, fields.ToJson());
        }

        [Test]
        public void TestIncludeElemMatch()
        {
            var fields = Fields<TestClass>.Include(tc => tc.x).ElemMatch(tc => tc.a2, qb => qb.EQ(tc => tc.b, 10));
            string expected = "{ \"x\" : 1, \"a2\" : { \"$elemMatch\" : { \"b\" : 10 } } }";
            Assert.AreEqual(expected, fields.ToJson());
        }

        [Test]
        public void TestInclude()
        {
            var fields = Fields<TestClass>.Include(tc => tc.a);
            string expected = "{ \"a\" : 1 }";
            Assert.AreEqual(expected, fields.ToJson());
        }

        [Test]
        public void TestExclude()
        {
            var fields = Fields<TestClass>.Exclude(tc => tc.a);
            string expected = "{ \"a\" : 0 }";
            Assert.AreEqual(expected, fields.ToJson());
        }

        [Test]
        public void TestSliceNameSize()
        {
            var fields = Fields<TestClass>.Slice(tc => tc.a, 10);
            string expected = "{ \"a\" : { \"$slice\" : 10 } }";
            Assert.AreEqual(expected, fields.ToJson());
        }

        [Test]
        public void TestSliceNameSkipLimit()
        {
            var fields = Fields<TestClass>.Slice(tc => tc.a, 10, 20);
            string expected = "{ \"a\" : { \"$slice\" : [10, 20] } }";
            Assert.AreEqual(expected, fields.ToJson());
        }
        [Test]
        public void TestIncludeInclude()
        {
            var fields = Fields<TestClass>.Include(tc => tc.x).Include(tc => tc.a);
            string expected = "{ \"x\" : 1, \"a\" : 1 }";
            Assert.AreEqual(expected, fields.ToJson());
        }

        [Test]
        public void TestIncludeExclude()
        {
            var fields = Fields<TestClass>.Include(tc => tc.x).Exclude(tc => tc.a);
            string expected = "{ \"x\" : 1, \"a\" : 0 }";
            Assert.AreEqual(expected, fields.ToJson());
        }

        [Test]
        public void TestIncludeSliceNameSize()
        {
            var fields = Fields<TestClass>.Include(tc => tc.x).Slice(tc => tc.a, 10);
            string expected = "{ \"x\" : 1, \"a\" : { \"$slice\" : 10 } }";
            Assert.AreEqual(expected, fields.ToJson());
        }

        [Test]
        public void TestIncludeSliceNameSkipLimit()
        {
            var fields = Fields<TestClass>.Include(tc => tc.x).Slice(tc => tc.a, 10, 20);
            string expected = "{ \"x\" : 1, \"a\" : { \"$slice\" : [10, 20] } }";
            Assert.AreEqual(expected, fields.ToJson());
        }

        [Test]
        public void TestMetaText()
        {
            var server = Configuration.TestServer;
            var primary = server.Primary;
            if (primary.Supports(FeatureId.TextSearchQuery))
            {
                using (server.RequestStart(null, primary))
                {
                    var collection = Configuration.TestDatabase.GetCollection<TestClass>("test_meta_text");
                    collection.Drop();
                    collection.CreateIndex(IndexKeys<TestClass>.Text(x => x.textfield));
                    collection.Insert(new TestClass
                    {
                        _id = 1,
                        textfield = "The quick brown fox jumped",
                        x = 1
                    });
                    collection.Insert(new TestClass
                    {
                        _id = 2,
                        textfield = "over the lazy brown dog",
                        x = 1
                    });

                    var query = Query.Text("fox");
                    var result = collection.FindOneAs<BsonDocument>(query);
                    Assert.AreEqual(1, result["_id"].AsInt32);
                    Assert.IsFalse(result.Contains("relevance"));
                    Assert.IsTrue(result.Contains("x"));

                    var fields = Fields<TestClass>.MetaTextScore(y => y.relevance).Exclude(y => y.x);
                    result = collection.FindOneAs<BsonDocument>(new FindOneArgs() { Query = query, Fields = fields });
                    Assert.AreEqual(1, result["_id"].AsInt32);
                    Assert.IsTrue(result.Contains("relevance"));
                    Assert.IsFalse(result.Contains("x"));
                }
            }
        }

        [Test]
        public void TestMetaTextGenerate()
        {
            var fields = Fields<TestClass>.MetaTextScore(y => y.relevance);
            string expected = "{ \"relevance\" : { \"$meta\" : \"textScore\" } }";
            Assert.AreEqual(expected, fields.ToJson());
        }

        [Test]
        public void TestMetaTextIncludeExcludeGenerate()
        {
            var fields = Fields<TestClass>.MetaTextScore(y => y.relevance).Include(y => y.x).Exclude(y => y._id);
            string expected = "{ \"relevance\" : { \"$meta\" : \"textScore\" }, \"x\" : 1, \"_id\" : 0 }";
            Assert.AreEqual(expected, fields.ToJson());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: "Private Sphinx docs with heroku and GitHub"
description: "Using a heroku buildpack and flask app to have private Sphinx docs online"
category:
tags: ['heroku', 'sphinx', 'github', 'flask', 'oauth', 'private', 'free']
---

Wouldn't it be great if you could push your sphinx docs to GitHub and in moments Heroku would have deployed them. Not only that but they are private: You need to be a member of a GitHub org to access them.

Last year I made [heroku-buildpack-sphinx](https://github.com/Jc2k/heroku-buildpack-sphinx).

At its core is a [single file flask app](https://github.com/Jc2k/heroku-buildpack-sphinx/blob/master/vendor/protect_and_serve.py) that serves static files via [send_from_directory](http://flask.pocoo.org/docs/0.11/api/#flask.send_from_directory) - but only if a user is logged in via GitHub. The build pack deploys a virtualenv and installs sphinx, builds your sphinx package and then copies in the flask app. Your docs are then served via gunicorn.


text:
class CommentsController < ApplicationController
  before_action :set_comment, only: [:show, :edit, :update, :destroy]

  def create
    @link = Link.find(params[:link_id])
    @comment = @link.comments.new(comment_params)
    @comment.user = current_user

    respond_to do |format|
      if @comment.save
        format.html { redirect_to @link, notice: 'Comment was successfully created.' }
        format.json { render :show, status: :created, location: @comment }
      else
        format.html { render :new }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @comment.destroy
    respond_to do |format|
      format.html { redirect_to comments_url, notice: 'Comment was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_comment
      @comment = Comment.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def comment_params
      params.require(:comment).permit(:link_id, :body, :user_id)
    end
end


text:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int countUnivalSubtrees(TreeNode* root) {
        if(root==NULL){
            return 0;
        }

        int count=0;

        helper(root,count);

        return count;
    }
    bool helper(TreeNode* root, int &count){
        if(root==NULL){
            return true;
        }

        bool lres=helper(root->left,count);
        bool rres=helper(root->right,count);

        if(lres && rres){
            //left substree and right subtree is unival
            if((root->left==NULL || root->left->val==root->val) && (root->right==NULL || root->right->val==root->val)){
                //check the root and left subtree and right subtree
                count++;
                return true;
            }
        }

        return false;
    }
};


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Ionize, creative CMS
 * Module Controller
 *
 * @package		Ionize
 * @author		Ionize Dev Team
 * @license		http://doc.ionizecms.com/en/basic-infos/license-agreement
 * @link		http://ionizecms.com
 * @since		Version 0.9.0
 */

class Module extends MY_admin
{

	public $modules_folder = 'modules';

	/**
	 * Constructor
	 *
	 */
	public function __construct()
	{
		parent::__construct();
	}

	// ------------------------------------------------------------------------

	/**
	 * Loads a module controller
	 * Receives the module name and proccess the URI
	 *
	 *
	 *
	 */
	function _remap($module_name)
	{
		// Delete the segments before the module name
		$mod_uri = array_slice($this->uri->segments, 3);

		// Get the controller, the called func name and the args
		$module_controller = $mod_uri[0];

		$module_func = 'index';
		if (isset($mod_uri[1]))
			$module_func = $mod_uri[1];

		$module_args = array_slice($mod_uri, 2);

		// Module path
		$module_path = MODPATH.ucfirst($module_name).'/';

		// Add the module path to the finder
		array_unshift(Finder::$paths, $module_path);

		// Includes the module Class file
		if ( ! class_exists($module_controller) && file_exists($module_path.'controllers/admin/'.$module_controller.EXT))
		{
			include($module_path.'controllers/admin/'.$module_controller.EXT);
		}
		else
		{
			echo('Class ' . ucfirst($module_controller) . ' not found in :
'. $module_path.'controllers/admin/');
			die();
		}

		// Create an instance of the module controller
		$obj = new $module_controller($this);

		// Loads module language file, if exists
//		if (is_file($module_path.'language/'.$this->config->item('default_lang_code').'/'.$module_name.'_lang.php'))
//		{
			$this->lang->load($module_name, $this->config->item('default_lang_code'));
//		}
//		else
//		{
//			trace('warning: no language file for this module in : '. $module_path.'language/'.$this->config->item('default_lang_code').'/');
//		}

		call_user_func_array(array($obj, $module_func), $module_args);
	}
}


text:
<!DOCTYPE HTML>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<title>Calendar - sap.ui.unified</title>
		<link rel="shortcut icon" type="image/x-icon" href="../images/controls/sap.ui.unified.Calendar.gif">

		<link rel="stylesheet" href="../../../../../resources/sap/ui/thirdparty/qunit.css" type="text/css" media="screen">

QUnit tests: sap.ui.unified.Calendar (Islamic)


text:
/*!
	\file
	\version \$Id: KaxVersion.h,v 1.13 2004/04/23 16:46:07 mosu Exp $
	\author Steve Lhomme     <robux4 @ users.sf.net>
*/
#ifndef LIBMATROSKA_VERSION_H
#define LIBMATROSKA_VERSION_H

#include <string>

#include "ebml/EbmlConfig.h"
#include "matroska/KaxConfig.h"

START_LIBMATROSKA_NAMESPACE

#define LIBMATROSKA_VERSION 0x010100

static const std::string KaxCodeVersion = "1.1.0";
static const std::string KaxCodeDate    = __TIMESTAMP__;

/*!
	\todo Improve the CRC/ECC system (backward and forward possible ?) to fit streaming/live writing/simple reading
*/

END_LIBMATROSKA_NAMESPACE

#endif // LIBMATROSKA_VERSION_H


text:
class ParallelBatch < ActiveRecord::Base

  #####################
  ### Class methods ###
  #####################

  def self.find_or_create!
    first || create!
  # When starting many batches at the same time we are pretty sure to get a MySQL
  # error reporting a duplicated entry. That's why we are retrying one time only.
  rescue ActiveRecord::StatementInvalid
    first || create!
  end

  def self.start(concurrency = 1)
    concurrency.times { Process.detach(fork { start_fork }) }
  end

  def self.start_fork
    puts "#{self} has started with pid #{Process.pid}"
    ActiveRecord::Base.connection.reconnect!
    Process.daemon(false)
    find_or_create!.run
  end

  def self.reset
    find_or_create!.update_attributes!(offset: nil)
  end

  ########################
  ### Instance methods ###
  ########################

  def find_records
    offset ? scope.where('id > ?', offset).order(:id).limit(batch_size) : scope.order(:id).limit(batch_size)
  end

  def next_batch
    transaction do
      reload(lock: true)
      next unless (records = find_records).last
      update_attributes!(offset: records.last.id)
      records
    end
  end

  def run
    while records = next_batch
      records.each { |record| perform(record) rescue nil }
    end
  end

  def perfom(record)
    raise NotImplementedError, 'You must override this method to perform your batch.'
  end

  def scope
    raise NotImplementedError, 'You must override this method to scope your records.'
  end

  def batch_size
    100
  end

end


text:
class DatabaseCall < ApplicationRecord
  belongs_to :application, optional: true
  belongs_to :host, optional: true
  belongs_to :database_type, optional: true

  belongs_to :span, :primary_key => :uuid, optional: true
end


text:
package gov.nih.nci.ncicb.cadsr.common.jsp.tag.handler;
import gov.nih.nci.ncicb.cadsr.common.CaDSRConstants;
import gov.nih.nci.ncicb.cadsr.common.resource.DataElement;
import gov.nih.nci.ncicb.cadsr.common.resource.Module;
import gov.nih.nci.ncicb.cadsr.common.resource.Question;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.ListIterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
import gov.nih.nci.ncicb.cadsr.common.formbuilder.struts.common.FormConstants;
import org.apache.commons.beanutils.PropertyUtils;
import gov.nih.nci.ncicb.cadsr.common.util.*;

/**
 * This Handler is used to display Alternate Question text from a Dataelement property
 * The text is displayed as hyper link if it not equal to Questions longName.
 * Example Usage
 *   <cde:questionAltText questionBeanId= "question"
 *                 htmlObjectRef="questionInputText"
 *                 deProperty = "longName"
 *                 questionProperty="longName"
 *                 formIndex="0"
 *                 questionIndex="2" />
 *  deProperty and questionPropery are options if both are set question property is used
 *  the property value for the question is from the orgQuestionBeanId bean in session. When
 *  questionProperty is specified orgModuleBeanId,questionBeanId also need to be defined
 *
 */
public class AltQuestionText extends TagSupport implements CaDSRConstants,FormConstants
{
  private String questionBeanId;
  private String deProperty;
  private String htmlObjectRef;
  private String formIndex;
  private String questionIndex;
  private String questionProperty;
  private String orgModuleBeanId;

  public AltQuestionText()
  {
  }

  public int doStartTag() throws javax.servlet.jsp.JspException {
    HttpServletRequest  req;
    JspWriter out;
     try {
        req = ( HttpServletRequest )pageContext.getRequest();
        out = pageContext.getOut();
        Question currQuestion = (Question)pageContext.getAttribute(questionBeanId);
        String longName = currQuestion.getLongName();
        DataElement de = currQuestion.getDataElement();
        if(questionProperty!=null&&orgModuleBeanId!=null)
        {
          // Get the property from the Question in the orgModule
          // If its a new Question the get the property value from
          // the DataElement for deProperty if deProperty is defined
          Module orgModule = (Module)pageContext.getSession().getAttribute(orgModuleBeanId);
          if(orgModule==null)
            throw new JspException( "No Bean by name "+orgModuleBeanId+"in session");
          List orgQuestions = orgModule.getQuestions();
          String propValue =null;
          if(orgQuestions.contains(currQuestion))
          {
            Question orgQuestion = getQuestionFromList(currQuestion.getQuesIdseq(),orgQuestions);
            propValue = (String)PropertyUtils.getProperty(orgQuestion,questionProperty);
          }
          else// get the value from the de
          {
            if(deProperty!=null)
            {
            if(de!=null)
              propValue = (String)PropertyUtils.getProperty(de,deProperty);
            }
          }

          /*if(propValue==null)
              return Tag.SKIP_BODY;
            */
        /* for saved question, use the default question text when CDE does not have preferred question text
            This is a temporary fix for GF1437 - to keep saved question behavior consistent for CDE
            with/without Preferred Question Text
        */
          if (  (propValue==null || propValue.length()==0)
                && "longCDEName".equals(deProperty) && "longName".equals(questionProperty)) {
                propValue = "Data Element " + de.getLongName() + " does not have Preferred Question Text";
          }
          String script  = generateJavaScript("question",formIndex,questionIndex,questionProperty,propValue);
          StringBuffer linkStr = new StringBuffer("");
          linkStr.append(propValue);
          linkStr.append("");
          out.print(script);
          out.print(linkStr.toString());
        }
        else if(de!=null)
          {
            String propValue = (String)PropertyUtils.getProperty(de,deProperty);
            /*if(propValue==null)
              return Tag.SKIP_BODY;
             */
             /* for saved question, use the default question text when CDE does not have preferred question text
                  This is a temporary fix for GF1437 - to keep saved question behavior consistent for CDE
                  with/without Preferred Question Text
              */
            if (propValue==null && "longCDEName".equals(deProperty) && "longName".equals(questionProperty)) {
                propValue = "Data Element " + de.getLongName() + " does not have Preferred Question Text";
            }
            if(propValue.equals(longName))
            {
              out.print(propValue);
            }
            else
            {
              String script  = generateJavaScript("questionde",formIndex,questionIndex,deProperty,propValue);
              StringBuffer linkStr = new StringBuffer("");
              linkStr.append(propValue);
              linkStr.append("");
              out.print(script);
              out.print(linkStr.toString());
            }
          }
       //out.print(getTableFooter());
      } catch(Exception ioe ) {
          throw new JspException( "I/O Error : " + ioe.getMessage() );
      }//end try/catch
      return Tag.SKIP_BODY;

    }//end doStartTag()

  private String generateJavaScript(String methodPrefix, String formIndex,String questionIndex
                                    , String property, String propValue)
  {

    StringBuffer script = new StringBuffer("\n\n");

    return script.toString();
  }

  private Question getQuestionFromList(
    String questionIdSeq,
    List questions) {
    ListIterator iterate = questions.listIterator();

    while (iterate.hasNext()) {
      Question question = (Question) iterate.next();

      if (question.getQuesIdseq().equals(questionIdSeq)) {
        return question;
      }
    }
    return null;
    }
  public String getQuestionBeanId()
  {
    return questionBeanId;
  }

  public void setQuestionBeanId(String newQuestionBeanId)
  {
    questionBeanId = newQuestionBeanId;
  }

  public String getDeProperty()
  {
    return deProperty;
  }

  public void setDeProperty(String newDeProperty)
  {
    deProperty = newDeProperty;
  }

  public String getHtmlObjectRef()
  {
    return htmlObjectRef;
  }

  public void setHtmlObjectRef(String newHtmlObjectRef)
  {
    htmlObjectRef = newHtmlObjectRef;
  }

  public void setFormIndex(String formIndex)
  {
    this.formIndex = formIndex;
  }

  public String getFormIndex()
  {
    return formIndex;
  }

  public void setQuestionIndex(String questionIndex)
  {
    this.questionIndex = questionIndex;
  }

  public String getQuestionIndex()
  {
    return questionIndex;
  }

  public String getQuestionProperty()
  {
    return questionProperty;
  }

  public void setQuestionProperty(String newQuestionProperty)
  {
    questionProperty = newQuestionProperty;
  }

  public String getOrgModuleBeanId()
  {
    return orgModuleBeanId;
  }

  public void setOrgModuleBeanId(String newOrgModuleBeanId)
  {
    orgModuleBeanId = newOrgModuleBeanId;
  }

}


text:
"""
    Bot functions to generate and post a comments.

    Instructions to file with comments:
        one line - one comment.

    Example:
        lol
        kek

"""
from tqdm import tqdm

from . import limits, delay

def comment(self, media_id, comment_text):
    if self.is_commented(media_id):
        return True
    if limits.check_if_bot_can_comment(self):
        delay.comment_delay(self)
        if super(self.__class__, self).comment(media_id, comment_text):
            self.total_commented += 1
            return True
    else:
        self.logger.info("Out of comments for today.")
    return False

def comment_medias(self, medias):
    broken_items = []
    self.logger.info("Going to comment %d medias." % (len(medias)))
    for media in tqdm(medias, disable = not self.progress_bar):
        if not self.is_commented(media):
            text = self.get_comment()
            self.logger.info("Commented with text: %s" % text)
            if not self.comment(media, text):
                delay.comment_delay(self)
                broken_items = medias[medias.index(media):]
                break
    self.logger.info("DONE: Total commented on %d medias. " %
                     self.total_commented)
    return broken_items

def comment_hashtag(self, hashtag, amount=None):
    self.logger.info("Going to comment medias by %s hashtag" % hashtag)
    medias = self.get_hashtag_medias(hashtag)
    return self.comment_medias(medias[:amount])

def comment_users(self, user_ids):
    # user_id = self.convert_to_user_id(user_id)
    # TODO: Put a comment to last media of every user from list
    pass

def comment_geotag(self, geotag):
    # TODO: comment every media from geotag
    pass

def is_commented(self, media_id):
    return self.user_id in self.get_media_commenters(media_id)


text:
package Model.Database;

import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionFactory {

    public Connection getConnection() {
        try {
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            return (Connection) DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/s2aeij_beta", "root", "");

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}


text:
import base64
import json
import os
import pickle

from Crypto import Random
from Crypto.Cipher import AES

from cumulusci.core.config import BaseConfig
from cumulusci.core.config import ConnectedAppOAuthConfig
from cumulusci.core.config import OrgConfig
from cumulusci.core.config import ScratchOrgConfig
from cumulusci.core.config import ServiceConfig
from cumulusci.core.exceptions import OrgNotFound
from cumulusci.core.exceptions import ServiceNotConfigured
from cumulusci.core.exceptions import ServiceNotValid
from cumulusci.core.exceptions import KeychainConnectedAppNotFound

class BaseProjectKeychain(BaseConfig):
    encrypted = False

    def __init__(self, project_config, key):
        super(BaseProjectKeychain, self).__init__()
        self.config = {
            'orgs': {},
            'app': None,
            'services': {},
        }
        self.project_config = project_config
        self.key = key
        self._load_keychain()

    def _load_keychain(self):
        """ Subclasses can override to implement logic to load the keychain """
        pass

    def change_key(self, key):
        """ re-encrypt stored services, orgs, and the connected_app
        with the new key """

        connected_app = self.get_connected_app()

        services = {}
        for service_name in self.list_services():
            services[service_name] = self.get_service(service_name)

        orgs = {}
        for org_name in self.list_orgs():
            orgs[org_name] = self.get_org(org_name)

        self.key = key
        if connected_app:
            self.set_connected_app(connected_app)

        if orgs:
            for org_name, org_config in orgs.items():
                self.set_org(org_name, org_config)

        if services:
            for service_name, service_config in services.items():
                self.set_service(service_name, service_config)

    def set_connected_app(self, app_config, project=False):
        """ store a connected_app configuration """

        self._set_connected_app(app_config, project)
        self._load_keychain()

    def _set_connected_app(self, app_config, project):
        self.app = app_config

    def get_connected_app(self):
        """ retrieve the connected app configuration """

        return self._get_connected_app()

    def _get_connected_app(self):
        return self.app

    def set_org(self, name, org_config, global_org=False):
        if isinstance(org_config, ScratchOrgConfig):
            org_config.config['scratch'] = True
        self._set_org(name, org_config, global_org)
        self._load_keychain()

    def _set_org(self, name, org_config, global_org):
        self.orgs[name] = org_config

    def get_default_org(self):
        """ retrieve the name and configuration of the default org """
        for org in self.list_orgs():
            org_config = self.get_org(org)
            if org_config.default:
                return org, org_config
        return None, None

    def set_default_org(self, name):
        """ set the default org for tasks by name key """
        org = self.get_org(name)
        self.unset_default_org()
        org.config['default'] = True
        self.set_org(name, org)

    def unset_default_org(self):
        """ unset the default orgs for tasks """
        for org in self.list_orgs():
            org_config = self.get_org(org)
            if org_config.default:
                del org_config.config['default']
                self.set_org(org, org_config)

    def get_org(self, name):
        """ retrieve an org configuration by name key """
        if name not in self.orgs:
            self._raise_org_not_found(name)
        return self._get_org(name)

    def _get_org(self, name):
        return self.orgs.get(name)

    def _raise_org_not_found(self, name):
        raise OrgNotFound('Org named {} was not found in keychain'.format(name))

    def list_orgs(self):
        """ list the orgs configured in the keychain """
        orgs = self.orgs.keys()
        orgs.sort()
        return orgs

    def set_service(self, name, service_config, project=False):
        """ Store a ServiceConfig in the keychain """
        if name not in self.project_config.services:
            self._raise_service_not_valid(name)
        self._validate_service(name, service_config)
        self._set_service(name, service_config, project)
        self._load_keychain()

    def _set_service(self, name, service_config, project):
        self.services[name] = service_config

    def get_service(self, name):
        """ Retrieve a stored ServiceConfig from the keychain or exception

        :param name: the service name to retrieve
        :type name: str

        :rtype ServiceConfig
        :return the configured Service
        """
        if name not in self.project_config.services:
            self._raise_service_not_valid(name)
        if name not in self.services:
            self._raise_service_not_configured(name)

        return self._get_service(name)

    def _get_service(self, name):
        return self.services.get(name)

    def _validate_service(self, name, service_config):
        missing_required = []
        attr_key = 'services__{0}__attributes'.format(name)
        for atr, config in getattr(self.project_config, attr_key).iteritems():
            if config.get('required') is True and not getattr(service_config, atr):
                missing_required.append(atr)

        if missing_required:
            self._raise_service_not_valid(name)

    def _raise_service_not_configured(self, name):
        raise ServiceNotConfigured(
            'Service named {} is not configured for this project'.format(name)
        )

    def _raise_service_not_valid(self, name):
        raise ServiceNotValid('Service named {} is not valid for this project'.format(name))

    def list_services(self):
        """ list the services configured in the keychain """
        services = self.services.keys()
        services.sort()
        return services

class EnvironmentProjectKeychain(BaseProjectKeychain):
    """ A project keychain that stores org credentials in environment variables """
    encrypted = False
    org_var_prefix = 'CUMULUSCI_ORG_'
    app_var = 'CUMULUSCI_CONNECTED_APP'
    service_var_prefix = 'CUMULUSCI_SERVICE_'

    def _load_keychain(self):
        self._load_keychain_app()
        self._load_keychain_orgs()
        self._load_keychain_services()

    def _load_keychain_app(self):
        app = os.environ.get(self.app_var)
        if app:
            self.app = ConnectedAppOAuthConfig(json.loads(app))

    def _load_keychain_orgs(self):
        for key, value in os.environ.items():
            if key.startswith(self.org_var_prefix):
                org_config = json.loads(value)
                if org_config.get('scratch'):
                    self.orgs[key[len(self.org_var_prefix):]] = ScratchOrgConfig(json.loads(value))
                else:
                    self.orgs[key[len(self.org_var_prefix):]] = OrgConfig(json.loads(value))

    def _load_keychain_services(self):
        for key, value in os.environ.items():
            if key.startswith(self.service_var_prefix):
                self.services[key[len(self.service_var_prefix):]] = ServiceConfig(json.loads(value))

BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]

class BaseEncryptedProjectKeychain(BaseProjectKeychain):
    """ Base class for building project keychains that use AES encryption for securing stored org credentials """
    encrypted = True

    def _set_connected_app(self, app_config, project):
        encrypted = self._encrypt_config(app_config)
        self._set_encrypted_connected_app(encrypted, project)

    def _set_encrypted_connected_app(self, encrypted, project):
        self.app = encrypted

    def _get_connected_app(self):
        if self.app:
            return self._decrypt_config(ConnectedAppOAuthConfig, self.app)

    def _get_service(self, name):
        return self._decrypt_config(ServiceConfig, self.services[name])

    def _set_service(self, service, service_config, project):
        encrypted = self._encrypt_config(service_config)
        self._set_encrypted_service(service, encrypted, project)

    def _set_encrypted_service(self, service, encrypted, project):
        self.services[service] = encrypted

    def _set_org(self, name, org_config, global_org):
        encrypted = self._encrypt_config(org_config)
        self._set_encrypted_org(name, encrypted, global_org)

    def _set_encrypted_org(self, name, encrypted, global_org):
        self.orgs[name] = encrypted

    def _get_org(self, name):
        return self._decrypt_config(OrgConfig, self.orgs[name])

    def _get_cipher(self, iv=None):
        if iv is None:
            iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return cipher, iv

    def _encrypt_config(self, config):
        pickled = pickle.dumps(config.config)
        pickled = pad(pickled)
        #pickled = base64.b64encode(pickled)
        cipher, iv = self._get_cipher()
        encrypted = base64.b64encode(iv + cipher.encrypt(pickled))
        return encrypted

    def _decrypt_config(self, config_class, encrypted_config):
        if not encrypted_config:
            return config_class()
        encrypted_config = base64.b64decode(encrypted_config)
        iv = encrypted_config[:16]
        cipher, iv = self._get_cipher(iv)
        pickled = cipher.decrypt(encrypted_config[16:])
        config_dict = pickle.loads(pickled)
        if config_dict.get('scratch'):
            config_class = ScratchOrgConfig
        return config_class(pickle.loads(pickled))

class EncryptedFileProjectKeychain(BaseEncryptedProjectKeychain):
    """ An encrypted project keychain that stores in the project's local directory """

    @property
    def config_local_dir(self):
        return os.path.join(
            os.path.expanduser('~'),
            self.project_config.global_config_obj.config_local_dir,
        )

    @property
    def project_local_dir(self):
        return self.project_config.project_local_dir

    def _load_keychain(self):

        def load_files(dirname):
            for item in os.listdir(dirname):
                if item.endswith('.org'):
                    with open(os.path.join(dirname, item), 'r') as f_item:
                        org_config = f_item.read()
                    org_name = item.replace('.org', '')
                    self.config['orgs'][org_name] = org_config
                elif item.endswith('.service'):
                    with open(os.path.join(dirname, item), 'r') as f_item:
                        service_config = f_item.read()
                    service_name = item.replace('.service', '')
                    self.config['services'][service_name] = service_config
                elif item == 'connected.app':
                    with open(os.path.join(dirname, item), 'r') as f_item:
                        app_config = f_item.read()
                    self.config['app'] = app_config

        load_files(self.config_local_dir)
        if not self.project_local_dir:
            return
        load_files(self.project_local_dir)

    def _set_encrypted_connected_app(self, encrypted, project):
        if project:
            filename = os.path.join(self.project_local_dir, 'connected.app')
        else:
            filename = os.path.join(self.config_local_dir, 'connected.app')
        with open(filename, 'w') as f_org:
            f_org.write(encrypted)
        self.app = encrypted

    def _set_encrypted_org(self, name, encrypted, global_org):
        if global_org:
            filename = os.path.join(self.config_local_dir, '{}.org'.format(name))
        else:
            filename = os.path.join(self.project_local_dir, '{}.org'.format(name))
        with open(filename, 'w') as f_org:
            f_org.write(encrypted)

    def _set_encrypted_service(self, name, encrypted, project):
        if project:
            filename = os.path.join(self.project_local_dir, '{}.service'.format(name))
        else:
            filename = os.path.join(self.config_local_dir, '{}.service'.format(name))
        with open(filename, 'w') as f_service:
            f_service.write(encrypted)

    def _raise_org_not_found(self, name):
        raise OrgNotFound(
            'Org information could not be found.  Expected to find encrypted file at {}/{}.org'.format(
                self.project_local_dir,
                name
            )
        )

    def _raise_service_not_configured(self, name):
        raise ServiceNotConfigured(
            'Service configuration could not be found.  Expected to find encrypted file at {}/{}.org'.format(
                self.project_local_dir,
                name
            )
        )


text:
#ifndef CPPKAFKA_COMPACTED_TOPIC_PROCESSOR_H
#define CPPKAFKA_COMPACTED_TOPIC_PROCESSOR_H

#include <functional>
#include <string>
#include <map>
#include <set>
#include <boost/optional.hpp>
#include "../buffer.h"
#include "../consumer.h"
#include "../macros.h"

namespace cppkafka {
/**
 * \brief Events generated by a CompactedTopicProcessor
 */
template <typename Key, typename Value>
class CompactedTopicEvent {
public:
    /**
     * \brief Event type enum
     */
    enum EventType {
        SET_ELEMENT,
        DELETE_ELEMENT,
        CLEAR_ELEMENTS,
        REACHED_EOF
    };

    /**
     * Constructs an instance providing only a type
     */
    CompactedTopicEvent(EventType type, std::string topic, int partition);

    /**
     * Constructs an instance providing a type and a key
     */
    CompactedTopicEvent(EventType type, std::string topic, int partition, Key key);

    /**
     * Constructs an instance providing a type, a key and a value
     */
    CompactedTopicEvent(EventType type, std::string topic, int partition, Key key, Value value);

    /**
     * Gets the event type
     */
    EventType get_type() const;

    /**
     * Gets the topic that generated this event
     */
    const std::string& get_topic() const;

    /**
     * Gets the partition that generated this event
     */
    int get_partition() const;

    /**
     * \brief Gets the event key
     *
     * Note that it's only valid to call this method if the event type is either:
     *
     * * SET_ELEMENT
     * * DELETE_ELEMENT
     */
    const Key& get_key() const;

    /**
     * \brief Gets the event value
     *
     * Note that it's only valid to call this method if the event type is SET_ELEMENT
     */
    const Value& get_value() const;
private:
    EventType type_;
    std::string topic_;
    int partition_;
    boost::optional<Key> key_;
    boost::optional<Value> value_;
};

template <typename Key, typename Value>
class CompactedTopicProcessor {
public:
    /**
     * The type of events generated by this processor
     */
    using Event = CompactedTopicEvent<Key, Value>;

    /**
     * Callback used for decoding key objects
     */
    using KeyDecoder = std::function<boost::optional<Key>(const Buffer&)>;

    /**
     * Callback used for decoding value objects
     */
    using ValueDecoder = std::function<boost::optional<Value>(const Key& key, const Buffer&)>;

    /**
     * Callback used for event handling
     */
    using EventHandler = std::function<void(Event)>;

    /**
     * Callback used for error handling
     */
    using ErrorHandler = std::function<void(Message)>;

    /**
     * \brief Constructs an instance
     */
    CompactedTopicProcessor(Consumer& consumer);
    ~CompactedTopicProcessor();

    CompactedTopicProcessor(const CompactedTopicProcessor&) = delete;
    CompactedTopicProcessor(CompactedTopicProcessor&&) = delete;
    CompactedTopicProcessor& operator=(const CompactedTopicProcessor&) = delete;
    CompactedTopicProcessor& operator=(CompactedTopicProcessor&&) = delete;

    /**
     * \brief Sets the key decoder callback
     */
    void set_key_decoder(KeyDecoder callback);

    /**
     * \brief Sets the value decoder callback
     */
    void set_value_decoder(ValueDecoder callback);

    /**
     * \brief Sets the event handler callback
     */
    void set_event_handler(EventHandler callback);

    /**
     * \brief Sets the error handler callback
     */
    void set_error_handler(ErrorHandler callback);

    /**
     * \brief Processes the next event
     */
    void process_event();
private:
    void on_assignment(TopicPartitionList& topic_partitions);

    Consumer& consumer_;
    KeyDecoder key_decoder_;
    ValueDecoder value_decoder_;
    EventHandler event_handler_;
    ErrorHandler error_handler_;
    std::map<TopicPartition, int64_t> partition_offsets_;
    Consumer::AssignmentCallback original_assignment_callback_;
};

// CompactedTopicEvent

template <typename K, typename V>
CompactedTopicEvent<K, V>::CompactedTopicEvent(EventType type, std::string topic, int partition)
: type_(type), topic_(std::move(topic)), partition_(partition) {

}

template <typename K, typename V>
CompactedTopicEvent<K, V>::CompactedTopicEvent(EventType type, std::string topic, int partition,
                                               K key)
: type_(type), topic_(std::move(topic)), partition_(partition), key_(std::move(key)) {

}

template <typename K, typename V>
CompactedTopicEvent<K, V>::CompactedTopicEvent(EventType type, std::string topic, int partition,
                                               K key, V value)
: type_(type), topic_(std::move(topic)), partition_(partition), key_(std::move(key)),
  value_(std::move(value)) {

}

template <typename K, typename V>
typename CompactedTopicEvent<K, V>::EventType CompactedTopicEvent<K, V>::get_type() const {
    return type_;
}

template <typename K, typename V>
const std::string& CompactedTopicEvent<K, V>::get_topic() const {
    return topic_;
}

template <typename K, typename V>
int CompactedTopicEvent<K, V>::get_partition() const {
    return partition_;
}

template <typename K, typename V>
const K& CompactedTopicEvent<K, V>::get_key() const {
    return *key_;
}

template <typename K, typename V>
const V& CompactedTopicEvent<K, V>::get_value() const {
    return *value_;
}

// CompactedTopicProcessor

template <typename K, typename V>
CompactedTopicProcessor<K, V>::CompactedTopicProcessor(Consumer& consumer)
: consumer_(consumer) {
    // Save the current assignment callback and assign ours
    original_assignment_callback_ = consumer_.get_assignment_callback();
    consumer_.set_assignment_callback([&](TopicPartitionList& topic_partitions) {
        on_assignment(topic_partitions);
    });
}

template <typename K, typename V>
CompactedTopicProcessor<K, V>::~CompactedTopicProcessor() {
    // Restore previous assignment callback
    consumer_.set_assignment_callback(original_assignment_callback_);
}

template <typename K, typename V>
void CompactedTopicProcessor<K, V>::set_key_decoder(KeyDecoder callback) {
    key_decoder_ = std::move(callback);
}

template <typename K, typename V>
void CompactedTopicProcessor<K, V>::set_value_decoder(ValueDecoder callback) {
    value_decoder_ = std::move(callback);
}

template <typename K, typename V>
void CompactedTopicProcessor<K, V>::set_event_handler(EventHandler callback) {
    event_handler_ = std::move(callback);
}

template <typename K, typename V>
void CompactedTopicProcessor<K, V>::set_error_handler(ErrorHandler callback) {
    error_handler_ = std::move(callback);
}

template <typename Key, typename Value>
void CompactedTopicProcessor<Key, Value>::process_event() {
    Message message = consumer_.poll();
    if (message) {
        if (!message.get_error()) {
            boost::optional<Key> key = key_decoder_(message.get_key());
            if (key) {
                if (message.get_payload()) {
                    boost::optional<Value> value = value_decoder_(*key, message.get_payload());
                    if (value) {
                        // If there's a payload and we managed to parse the value, generate a
                        // SET_ELEMENT event
                        event_handler_({ Event::SET_ELEMENT, message.get_topic(),
                                         message.get_partition(), *key, std::move(*value) });
                    }
                }
                else {
                    // No payload, generate a DELETE_ELEMENT event
                    event_handler_({ Event::DELETE_ELEMENT, message.get_topic(),
                                     message.get_partition(), *key });
                }
            }
            // Store the offset for this topic/partition
            TopicPartition topic_partition(message.get_topic(), message.get_partition());
            partition_offsets_[topic_partition] = message.get_offset();
        }
        else {
            if (message.is_eof()) {
                event_handler_({ Event::REACHED_EOF, message.get_topic(),
                                 message.get_partition() });
            }
            else if (error_handler_) {
                error_handler_(std::move(message));
            }
        }
    }
}

template <typename K, typename V>
void CompactedTopicProcessor<K, V>::on_assignment(TopicPartitionList& topic_partitions) {
    if (original_assignment_callback_) {
        original_assignment_callback_(topic_partitions);
    }
    std::set<TopicPartition> partitions_found;
    // See if we already had an assignment for any of these topic/partitions. If we do,
    // then restore the offset following the last one we saw
    for (TopicPartition& topic_partition : topic_partitions) {
        auto iter = partition_offsets_.find(topic_partition);
        if (iter != partition_offsets_.end()) {
            topic_partition.set_offset(iter->second);
        }
        // Populate this set
        partitions_found.insert(topic_partition);
    }
    // Clear our cache: remove any entries for topic/partitions that aren't assigned to us now.
    // Emit a CLEAR_ELEMENTS event for each topic/partition that is gone
    auto iter = partition_offsets_.begin();
    while (iter != partition_offsets_.end()) {
        const TopicPartition& topic_partition = iter->first;
        if (partitions_found.count(topic_partition) == 0) {
            event_handler_({ Event::CLEAR_ELEMENTS, topic_partition.get_topic(),
                             topic_partition.get_partition() });
            iter = partition_offsets_.erase(iter);
        }
        else {
            ++iter;
        }
    }
}

} // cppkafka

#endif // CPPKAFKA_COMPACTED_TOPIC_PROCESSOR_H


text:
var parseBits = function(data, bits, offset, invert, callback) {
  offset = offset || 0;
  invert = invert || false;
  callback = callback || function(lastValue, newValue, bits) { return (lastValue * Math.pow(2, bits)) + newValue; };
  var offsetBytes = offset >> 3;

  var inv = function(value) {
    if (invert) {
      return ~value & 0xff;
    }

    return value;
  };

  // read first (maybe partial) byte
  var mask = 0xff;
  var firstBits = 8 - (offset % 8);
  if (bits < firstBits) {
    mask = (0xff << (8 - bits)) & 0xff;
    firstBits = bits;
  }

  if (offset) {
    mask = mask >> (offset % 8);
  }

  var result = 0;
  if ((offset % 8) + bits >= 8) {
    result = callback(0, inv(data[offsetBytes]) & mask, firstBits);
  }

  // read bytes
  var bytes = (bits + offset) >> 3;
  for (var i = offsetBytes + 1; i < bytes; i++) {
    result = callback(result, inv(data[i]), 8);
  }

  // bits to read, that are not a complete byte
  var lastBits = (bits + offset) % 8;
  if (lastBits > 0) {
    result = callback(result, inv(data[bytes]) >> (8 - lastBits), lastBits);
  }

  return result;
};

var parseFloatFromBits = function(data, precisionBits, exponentBits) {
  var bias = Math.pow(2, exponentBits - 1) - 1;
  var sign = parseBits(data, 1);
  var exponent = parseBits(data, exponentBits, 1);

  if (exponent === 0) {
    return 0;
  }

  // parse mantissa
  var precisionBitsCounter = 1;
  var parsePrecisionBits = function(lastValue, newValue, bits) {
    if (lastValue === 0) {
      lastValue = 1;
    }

    for (var i = 1; i <= bits; i++) {
      precisionBitsCounter /= 2;
      if ((newValue & (0x1 << (bits - i))) > 0) {
        lastValue += precisionBitsCounter;
      }
    }

    return lastValue;
  };

  var mantissa = parseBits(data, precisionBits, exponentBits + 1, false, parsePrecisionBits);

  // special cases
  if (exponent == (Math.pow(2, exponentBits + 1) - 1)) {
    if (mantissa === 0) {
      return (sign === 0) ? Infinity : -Infinity;
    }

    return NaN;
  }

  // normale number
  return ((sign === 0) ? 1 : -1) * Math.pow(2, exponent - bias) * mantissa;
};

var parseBool = function(value) {
  return (parseBits(value, 8) == 1);
};

var parseInt16 = function(value) {
  if (parseBits(value, 1) == 1) {
    return -1 * (parseBits(value, 15, 1, true) + 1);
  }

  return parseBits(value, 15, 1);
};

var parseInt32 = function(value) {
  if (parseBits(value, 1) == 1) {
    return -1 * (parseBits(value, 31, 1, true) + 1);
  }

  return parseBits(value, 31, 1);
};

var parseFloat32 = function(value) {
  return parseFloatFromBits(value, 23, 8);
};

var parseFloat64 = function(value) {
  return parseFloatFromBits(value, 52, 11);
};

var parseNumeric = function(value) {
  var sign = parseBits(value, 16, 32);
  if (sign == 0xc000) {
    return NaN;
  }

  var weight = Math.pow(10000, parseBits(value, 16, 16));
  var result = 0;

  var digits = [];
  var ndigits = parseBits(value, 16);
  for (var i = 0; i < ndigits; i++) {
    result += parseBits(value, 16, 64 + (16 * i)) * weight;
    weight /= 10000;
  }

  var scale = Math.pow(10, parseBits(value, 16, 48));
  return ((sign === 0) ? 1 : -1) * Math.round(result * scale) / scale;
};

var parseDate = function(isUTC, value) {
  var sign = parseBits(value, 1);
  var rawValue = parseBits(value, 63, 1);

  // discard usecs and shift from 2000 to 1970
  var result = new Date((((sign === 0) ? 1 : -1) * rawValue / 1000) + 946684800000);

  if (!isUTC) {
    result.setTime(result.getTime() + result.getTimezoneOffset() * 60000);
  }

  // add microseconds to the date
  result.usec = rawValue % 1000;
  result.getMicroSeconds = function() {
    return this.usec;
  };
  result.setMicroSeconds = function(value) {
    this.usec = value;
  };
  result.getUTCMicroSeconds = function() {
    return this.usec;
  };

  return result;
};

var parseArray = function(value) {
  var dim = parseBits(value, 32);

  var flags = parseBits(value, 32, 32);
  var elementType = parseBits(value, 32, 64);

  var offset = 96;
  var dims = [];
  for (var i = 0; i < dim; i++) {
    // parse dimension
    dims[i] = parseBits(value, 32, offset);
    offset += 32;

    // ignore lower bounds
    offset += 32;
  }

  var parseElement = function(elementType) {
    // parse content length
    var length = parseBits(value, 32, offset);
    offset += 32;

    // parse null values
    if (length == 0xffffffff) {
      return null;
    }

    var result;
    if ((elementType == 0x17) || (elementType == 0x14)) {
      // int/bigint
      result = parseBits(value, length * 8, offset);
      offset += length * 8;
      return result;
    }
    else if (elementType == 0x19) {
      // string
      result = value.toString(this.encoding, offset >> 3, (offset += (length << 3)) >> 3);
      return result;
    }
    else {
      console.log("ERROR: ElementType not implemented: " + elementType);
    }
  };

  var parse = function(dimension, elementType) {
    var array = [];
    var i;

    if (dimension.length > 1) {
      var count = dimension.shift();
      for (i = 0; i < count; i++) {
        array[i] = parse(dimension, elementType);
      }
      dimension.unshift(count);
    }
    else {
      for (i = 0; i < dimension[0]; i++) {
        array[i] = parseElement(elementType);
      }
    }

    return array;
  };

  return parse(dims, elementType);
};

var parseText = function(value) {
  return value.toString('utf8');
};

var parseBool = function(value) {
  return (parseBits(value, 8) > 0);
};

var init = function(register) {
  register(21, parseInt16);
  register(23, parseInt32);
  register(26, parseInt32);
  register(1700, parseNumeric);
  register(700, parseFloat32);
  register(701, parseFloat64);
  register(16, parseBool);
  register(1114, parseDate.bind(null, false));
  register(1184, parseDate.bind(null, true));
  register(1007, parseArray);
  register(1016, parseArray);
  register(1008, parseArray);
  register(1009, parseArray);
  register(25, parseText);
};

module.exports = {
  init: init
};


text:
<!DOCTYPE html>
<title>CSS aspect-ratio: select elements with min-width</title>
<link rel="author" title="Mozilla" href="https://www.mozilla.org/">
<link rel="help" href="https://drafts.csswg.org/css-sizing-4/#aspect-ratio">
<link rel="match" href="select-element-001-ref.html">

<select style="height: 50px; aspect-ratio: 1/1; background: green;">
  <option value=""></option>
</select>

<select style="height: 50px; aspect-ratio: 1/1; background: green; min-width: 0px;">
  <option value="">The long text is selected</option>
</select>

<select style="height: 50px; aspect-ratio: 1/1; background: green;">
  <option value="">The long text is selected</option>
</select>


text:
package org.squbs.stream

import akka.actor.ActorSystem
import akka.testkit.TestKit
import org.scalatest.flatspec.AnyFlatSpecLike
import org.scalatest.matchers.should.Matchers

import scala.language.postfixOps

class TriggerMergeJSpec extends TestKit(ActorSystem.create("TriggerMergeJSpec")) with AnyFlatSpecLike with Matchers {

  // expose probe port(s)
  val mat = new TriggerMergeJ(system).runnableGraph()
  val (pub, sub) = mat.toScala
  val (pubIn, pubTrigger) = pub.toScala

  "TriggerMergeJ" should "start the flow" in {
    // send 2 elements to in
    pubIn.sendNext("1")
    pubIn.sendNext("2")
    sub.request(2)

    // does not trigger flow
    pubTrigger.sendNext(3)
    sub.expectNoMessage(remainingOrDefault)

    // does not trigger flow
    pubTrigger.sendNext(0)
    sub.expectNoMessage(remainingOrDefault)

    // trigger flow
    pubTrigger.sendNext(1)
    sub.expectNext("1", "2")
  }

  "TriggerMergeJ" should "pause the flow" in {
    // does not pause flow
    pubTrigger.sendNext(3)
    pubIn.sendNext("3")
    sub.request(1)
    sub.expectNext("3")

    // does not pause flow
    pubTrigger.sendNext(1)
    pubIn.sendNext("4")
    sub.request(1)
    sub.expectNext("4")

    // pause flow allowing previous pull to go through
    pubTrigger.sendNext(0)
    pubIn.sendNext("5")
    sub.request(1)
    sub.expectNext("5")
    // pause flow
    pubIn.sendNext("6")
    sub.request(1)
    sub.expectNoMessage(remainingOrDefault)
  }

  "TriggerMergeJ" should "re-start the flow" in {
    // does not re-start flow
    pubTrigger.sendNext(3)
    sub.expectNoMessage(remainingOrDefault)

    // does not re-start flow
    pubTrigger.sendNext(0)
    sub.expectNoMessage(remainingOrDefault)

    // re-start flow
    pubTrigger.sendNext(1)
    sub.expectNext("6")
  }

  "TriggerMergeJ" should "handle complete" in {
    // trigger complete will not complete the flow
    pubTrigger.sendComplete()
    pubIn.sendNext("7")
    pubIn.sendNext("8")
    sub.request(2)
    sub.expectNext("7", "8")

    // input complete will complete the flow
    pubIn.sendComplete()
    sub.request(1)
    sub.expectComplete()

    pubIn.sendNext("9")
    sub.request(1)
    sub.expectNoMessage(remainingOrDefault)
  }

  "TriggerMergeJ" should "match stage name" in {
    new TriggerMerge[String].toString shouldBe "TriggerMerge"
  }
}


text:
@implementation PSMAnyTabContentViewController

@synthesize progressIndicatorCheckbox;
@synthesize markDirtyCheckbox;

- (id)initWithTabViewItem:(NSTabViewItem *)tabViewItem {
    self = [super initWithNibName:@"TabContentView" bundle:[NSBundle mainBundle] tabViewItem:tabViewItem];
    if (self) {
        self.tabViewItem = tabViewItem;
    }

    return self;
}

- (IBAction)setTabLabel:(id)sender {
    NSString *tabLabelText = self.tabLabelTextField.stringValue;
    if (tabLabelText && tabLabelText.length > 0) {
        [self.tabViewItem setLabel:tabLabelText];
    } else {
        [self.tabViewItem setLabel:@"Untitled"];
    }
}

- (IBAction)setBadgeCount:(id)sender {
    NSString *badgeCountText = self.badgeCountTextField.stringValue;
    if (badgeCountText && badgeCountText.length > 0) {
        self.objectCount = badgeCountText.integerValue;
    } else {
        self.objectCount = 0;
    }
}

- (IBAction)showProgressIndicator:(id)sender {
    if (self.progressIndicatorCheckbox.state == NSOnState) {
        self.isProcessing = YES;
    } else {
        self.isProcessing = NO;
    }
}

- (IBAction)markAsDirty:(id)sender {
    if (self.markDirtyCheckbox.state = NSOnState) {
        self.isEdited = YES;
    } else {
        self.isEdited = NO;
    }
}
@end


text:
import Component from '@ember/component';
import { assert } from '@ember/debug';
import { assign } from '@ember/polyfills';
import { get, observer, set } from '@ember/object';
import { next } from '@ember/runloop';
import { inject as service } from '@ember/service';

export default Component.extend({

  gaEmbed: service(),

  classNames: ['ga-embed-authorize'],
  classNameBindings: ['gaEmbed.isAuthorized:ga-embed-is-authorized'],

  clientId: null,

  didInsertElement() {
    this._super(...arguments);
    get(this, 'gaEmbed')._onApiReady(() => {
      this.authorize();
    });

  },

  authorize() {

    if (get(this, 'accessToken')) { return this.authorizeWithAccessToken(); }

    const clientid = get(this, 'clientId') || get(this, 'gaEmbed.config.clientId');

    assert('[ember-google-analytics-embed] No Google Analytics clientId set in config/environment.js', clientid);

    let params = {
      container: this.elementId,
      clientid
    };

    const apiKey = get(this, 'apiKey') || get(this, 'gaEmbed.config.apiKey');

    if (apiKey) { assign(params, { apiKey }); }

    this._authorize(params);

  },

  onSignIn() {},
  onSignOut() {},
  onError() {},

  authorizeWithAccessToken() {

    this._authorize({
      'serverAuth': {
        'access_token': get(this, 'accessToken')
      }
    });

    set(this, 'gaEmbed.isAuthorized', true);
    get(this, 'onSignIn')();
    get(this, 'onSignOut')();

  },

  _authorize(params) {
    let authorize = window.gapi.analytics.auth.authorize(params);

    authorize.on('signIn', () => {
      set(this, 'gaEmbed.isAuthorized', true);
      get(this, 'onSignIn')();

    });

    authorize.on('signOut', () => {
      set(this, 'gaEmbed.isAuthorized', false);
      get(this, 'onSignOut')();

    });

    authorize.on('error', (err) => {
      get(this, 'onError')(err);
    });

  },

  // eslint-disable-next-line ember/no-observers
  hideOnAuthorize: observer('gaEmbed.isAuthorized', function() {
    const isAuthorized = get(this, 'gaEmbed.isAuthorized');
    let display = isAuthorized ? 'none' : 'block';

    next(() => {
      this.$().css({ display });
    });

  })

});


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('card-picker', 'Integration | Component | card picker', {
  integration: true
});

test('it renders', function(assert) {
  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{card-picker}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:
  this.render(hbs`
    {{#card-picker}}
      template block text
    {{/card-picker}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});


text:
public class Verifier
{
    public static final String EXAMPLE1_FILE = "example1.txt";
    public static final int EXAMPLE1_TOTAL_NUMBER_OF_BAGS = 32;

    public static final String EXAMPLE2_FILE = "example2.txt";
    public static final int EXAMPLE2_TOTAL_NUMBER_OF_BAGS = 126;

    public Verifier (boolean debug)
    {
        _debug = debug;
    }

    public final boolean verify ()
    {
        Rules theRules = new Rules(_debug);
        Inventory inv = theRules.parse(EXAMPLE1_FILE);

        if (_debug)
            System.out.println("\nLoaded rules:\n\n"+inv);

        int count = inv.totalBagCount(LuggageProcessing.BAG_TYPE);

        if (count == EXAMPLE1_TOTAL_NUMBER_OF_BAGS)
        {
            inv = theRules.parse(EXAMPLE2_FILE);

            if (_debug)
                System.out.println("\nLoaded rules:\n\n"+inv);

            count = inv.totalBagCount(LuggageProcessing.BAG_TYPE);

            if (count == EXAMPLE2_TOTAL_NUMBER_OF_BAGS)
                return true;
            else
                System.out.println("Invalid number of total bags: "+count+" for "+EXAMPLE2_FILE);
        }
        else
            System.out.println("Invalid number of total bags: "+count+" for "+EXAMPLE1_FILE);

        return false;
    }

    private boolean _debug;
}


text:
@implementation Speak

- (void)speakString:(NSString *)text {
	SpeechChannel fCurSpeechChannel;
	OSErr theErr = noErr;

	// create
	// TODO: use a ghostly voice
	NewSpeechChannel(NULL, &fCurSpeechChannel);

	SetSpeechProperty(fCurSpeechChannel, kSpeechVolumeProperty, (__bridge CFTypeRef)(@(0.1)));

	SetSpeechProperty(fCurSpeechChannel, kSpeechOutputToAudioDeviceProperty, (__bridge CFTypeRef)(@(0))); // takes AudioDeviceID

	theErr = SpeakCFString(fCurSpeechChannel, (__bridge CFStringRef)text, NULL);
	if (noErr != theErr) {
		NSString *fErrorFormatString = NSLocalizedString(@"Error #%d (0x%0X) returned.", @"Error #%d (0x%0X) returned.");
		NSLog(fErrorFormatString, theErr, theErr);
	}
}

@end


text:
//
//  BCVideoFilter.h
//  BCVideoFilterDemo
//
//  Created by 陈明标 on 9/2/16.
//  Copyright © 2016 陈明标. All rights reserved.
//

#import <Foundation/Foundation.h>

#import "BCGLKView.h"

@class BCFilter;

@interface BCVideoFilter : NSObject

// OpenGL ES2 视图
@property (nonatomic, strong) BCGLKView *view;

// 当前的滤镜
@property (nonatomic, copy, readonly) NSString *currentFilter;

typedef void(^BCVideoFilterStatus)(float progress, BOOL isFinish, NSError *error);

/**
 *  初始化
 *
 *  @param frame          框架
 *  @param videoInputPath 视频输入地址
 */
- (instancetype)initWithFrame:(CGRect)frame
                videoInputUrl:(NSURL *)videoInputUrl;

/**
 *  初始化
 *
 *  @param frame          框架
 *  @param videoInputPath 视频输入地址
 *  @param filter         滤镜
 */
- (instancetype)initWithFrame:(CGRect)frame
                videoInputUrl:(NSURL *)videoInputUrl
                       filter:(BCFilter *)filter;

/**
 *  初始化
 *
 *  @param frame              框架
 *  @param videoInputPath     视频输入地址
 *  @param watermarkInputPath 水印输入地址
 */
- (instancetype)initWithFrame:(CGRect)frame
                videoInputUrl:(NSURL *)videoInputUrl
            watermarkInputUrl:(NSURL *)watermarkInputUrl;

/**
 *  初始化
 *
 *  @param frame              框架
 *  @param videoInputPath     视频输入地址
 *  @param filter             滤镜
 *  @param watermarkInputPath 水印输入地址
 */
- (instancetype)initWithFrame:(CGRect)frame
                videoInputUrl:(NSURL *)videoInputUrl
                       filter:(BCFilter *)filter
            watermarkInputUrl:(NSURL *)watermarkInputUrl;

/**
 *  添加滤镜
 *
 *  @param filter 滤镜
 */
- (void)addFilter:(BCFilter *)filter;

/**
 *  添加滤镜
 *
 *  @param filter     滤镜
 *  @param parameters 参数
 */
- (void)addFilter:(BCFilter *)filter parameter:(NSArray *)parameters;

/**
 *  更换滤镜
 *
 *  @param filter 滤镜
 */
- (void)changeFilter:(BCFilter *)filter;

/**
 *  更换滤镜
 *
 *  @param filter     滤镜
 *  @param parameters 参数
 */
- (void)changeFilter:(BCFilter *)filter parameter:(NSArray *)parameters;

/**
 *  开始加载视频
 */
- (void)processVideoWithBlockCompletionHandler:(BCVideoFilterStatus)status;

/**
 *  导出视频
 */
- (void)exportVideoWithVideoOuputPath:(NSString *)videooutputPath;

@end


text:
FROM biocontainers/biocontainers:debian-stretch-backports
MAINTAINER biocontainers <biodocker@gmail.com>
LABEL    software="bioconductor-makecdfenv" \
    container="bioconductor-makecdfenv" \
    about.summary="BioConductor CDF Environment Maker" \
    about.home="https://bioconductor.org/packages/makecdfenv/" \
    software.version="1.50.0-1-deb" \
    version="1" \
    about.copyright=" 2006-2016 Rafael A. Irizarry <rafa@jhu.edu>," \
    about.license="Artistic-2.0" \
    about.license_file="/usr/share/doc/bioconductor-makecdfenv/copyright" \
    about.tags=""

ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && apt-get install -y r-bioc-makecdfenv && apt-get clean && apt-get purge && rm -rf /var/lib/apt/lists/* /tmp/*
USER biodocker


text:
This template creates an Interconnect resource.

## Prerequisites

- Install [gcloud](https://cloud.google.com/sdk)
- Create a [GCP project, set up billing, enable requisite APIs](../project/README.md)
- Create a [network](../network/README.md)
- Create a [interconnect] (../interconnect/README.md)
- Create a [cloud_router] (../cloud_router/README.md)
- Grant the [compute.networkAdmin](https://cloud.google.com/compute/docs/access/iam)
  IAM role to the project service account

## Deployment

### Resources

- [compute.v1.interconnects](https://cloud.google.com/compute/docs/reference/rest/v1/interconnects)

### Properties

See the `properties` section in the schema file(s):

- [Interconnect](interconnect.py.schema)

### Usage

1. Clone the [Deployment Manager Samples repository](https://github.com/GoogleCloudPlatform/deploymentmanager-samples):

```shell
    git clone https://github.com/GoogleCloudPlatform/deploymentmanager-samples
```

2. Go to the [community/cloud-foundation](../../) directory:

```shell
    cd community/cloud-foundation
```

3. Copy the example DM config to be used as a model for the deployment; in this case,
   [examples/interconnect_dedicated.yaml](examples/interconnect_dedicated.yaml):

```shell
    cp templates/interconnect/examples/interconnect_dedicated.yaml my_interconnect_dedicated.yaml
```

4. Change the values in the config file to match your specific GCP setup (for
   properties, refer to the schema files listed above):

```shell
    vim my_interconnect_dedicated.yaml  # <== change values to match your GCP setup
```

5. Create your deployment (replace \<YOUR\_DEPLOYMENT\_NAME\> with the relevant
   deployment name):

```shell
    gcloud deployment-manager deployments create <YOUR_DEPLOYMENT_NAME> \
    --config my_interconnect_dedicated.yaml
```

6. In case you need to delete your deployment:

```shell
    gcloud deployment-manager deployments delete <YOUR_DEPLOYMENT_NAME>
```

## Examples

- [Dedicated Interconnect](examples/interconnect_dedicated.yaml)


text:
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.IO;
using System.Xml.Serialization;
using CslaGenerator.Attributes;
using CslaGenerator.Design;

namespace CslaGenerator.Metadata
{
    public delegate void ChildPropertyNameChanged(ChildProperty sender, PropertyNameChangedEventArgs e);

    /// <summary>
    /// Summary description for ChildProperty.
    /// </summary>
    [Serializable]
    public class ChildProperty : Property, IHaveBusinessRules, IComparable
    {
        #region Private Fields

        private string _friendlyName = String.Empty;
        private LoadingScheme _loadingScheme = LoadingScheme.ParentLoad;
        private PropertyDeclaration _declarationMode;
        private string _interfaces = string.Empty;
        private readonly BusinessRuleCollection _businessRules;
        private string[] _attributes = {};
        private AuthorizationProvider _authzProvider;
        private readonly AuthorizationRuleCollection _authzRules;
        private string _readRoles = string.Empty;
        private string _writeRoles = string.Empty;
        private bool _lazyLoad;
        private string _typeName = String.Empty;
        private bool _undoable = true;
        private PropertyCollection _parentLoadProperties = new PropertyCollection();
        private ParameterCollection _loadParameters = new ParameterCollection();
        private PropertyAccess _access = PropertyAccess.IsPublic;
        private int _childUpdateOrder;
        private bool _isCollection;

        #endregion

        #region Constructor

        public ChildProperty()
        {
            _businessRules = new BusinessRuleCollection();
            NameChanged += _businessRules.OnParentChanged;
            _authzRules = new AuthorizationRuleCollection();
            _authzRules.Add(new AuthorizationRule());
            _authzRules.Add(new AuthorizationRule());
            NameChanged += _authzRules.OnParentChanged;
        }

        #endregion

        #region 01. Definition

        [Category("01. Definition")]
        [Description("The property name.")]
        public override string Name
        {
            get { return base.Name; }
            set
            {
                value = PropertyHelper.Tidy(value);
                var e = new PropertyNameChangedEventArgs(base.Name, value);
                base.Name = value;
                if (NameChanged != null)
                    NameChanged(this, e);
            }
        }

        [Category("01. Definition")]
        [Description("Human readable friendly display name of the property.")]
        [UserFriendlyName("Friendly Name")]
        public string FriendlyName
        {
            get
            {
                if (string.IsNullOrEmpty(_friendlyName))
                    return PropertyHelper.SplitOnCaps(base.Name);
                return _friendlyName;
            }
            set
            {
                if (value != null && !value.Equals(PropertyHelper.SplitOnCaps(base.Name)))
                    _friendlyName = value;
                else
                    _friendlyName = string.Empty;
            }
        }

        [Category("01. Definition")]
        [Description("This is a description.")]
        [Editor(typeof(ChildTypeEditor), typeof(UITypeEditor))]
        [UserFriendlyName("Type Name")]
        public string TypeName
        {
            get { return _typeName; }
            set { _typeName = value; }
        }

        [Category("01. Definition")]
        [Description("Property Declaration Mode. For child collections this must be \"ClassicProperty\", \"AutoProperty\" or \"Managed\".\r\n" +
            "For lazy loaded child collections this must be \"ClassicProperty\" or \"Managed\".")]
        [UserFriendlyName("Declaration Mode")]
        public PropertyDeclaration DeclarationMode
        {
            get { return _declarationMode; }
            set
            {
                if (LoadingScheme == LoadingScheme.SelfLoad && LazyLoad)
                {
                    if (value == PropertyDeclaration.ClassicProperty ||
                        value == PropertyDeclaration.Managed)
                        _declarationMode = value;
                }
                else if (value == PropertyDeclaration.ClassicProperty ||
                         value == PropertyDeclaration.AutoProperty ||
                         value == PropertyDeclaration.Managed)
                    _declarationMode = value;
            }
        }

        [Category("01. Definition")]
        [Description("Whether this property can be changed by other classes.")]
        public override bool ReadOnly
        {
            get { return base.ReadOnly; }
            set { base.ReadOnly = value; }
        }

        [Category("01. Definition")]
        [Description("Specify the order in which the child updates occur. Set to 0 on all chilren to ignore it.")]
        [UserFriendlyName("Child Update Order")]
        public int ChildUpdateOrder
        {
            get { return _childUpdateOrder; }
            set { _childUpdateOrder = value; }
        }

        #endregion

        #region 02. Advanced

        [Category("02. Advanced")]
        [Description("The attributes you want to add to this property.")]
        public virtual string[] Attributes
        {
            get { return _attributes; }
            set { _attributes = PropertyHelper.TidyAllowSpaces(value); }
        }

        [Category("02. Advanced")]
        [Description("The interface this property explicitly implements.")]
        public virtual string Interfaces
        {
            get { return _interfaces; }
            set
            {
                value = PropertyHelper.Tidy(value);
                if (!string.IsNullOrEmpty(value))
                {
                    var namePostfix = '.' + Name;
                    if (value.LastIndexOf(namePostfix, StringComparison.Ordinal) != value.Length - namePostfix.Length)
                    {
                        if (GeneratorController.Current.CurrentUnit != null)
                        {
                            if (GeneratorController.Current.CurrentUnit.GenerationParams.OutputLanguage ==
                                CodeLanguage.CSharp ||
                                _interfaces == string.Empty)
                                value = value + namePostfix;
                        }
                    }
                }
                _interfaces = value;
            }
        }

        #endregion

        #region 03. Business Rules & Authorization

        [Category("03. Business Rules & Authorization")]
        [Description("Collection of business rules (transformation, validation, etc).")]
        [Editor(typeof(PropertyCollectionForm), typeof(UITypeEditor))]
        [UserFriendlyName("Business Rules Collection")]
        public virtual BusinessRuleCollection BusinessRules
        {
            get { return _businessRules; }
        }

        [Category("03. Business Rules & Authorization")]
        [Description("The Authorization Provider for this property.")]
        [UserFriendlyName("Authorization Provider")]
        public virtual AuthorizationProvider AuthzProvider
        {
            get { return _authzProvider; }
            set { _authzProvider = value; }
        }

        [Category("03. Business Rules & Authorization")]
        [Description("Roles allowed to read the property. Use a comma to separate multiple roles.")]
        [UserFriendlyName("Read Roles")]
        public virtual string ReadRoles
        {
            get { return _readRoles; }
            set { _readRoles = PropertyHelper.TidyAllowSpaces(value).Replace(';', ',').Trim(new[] {','}); }
        }

        [Category("03. Business Rules & Authorization")]
        [Description("Roles allowed to write to the property. Use a comma to separate multiple roles.")]
        [UserFriendlyName("Write Roles")]
        public virtual string WriteRoles
        {
            get { return _writeRoles; }
            set { _writeRoles = PropertyHelper.TidyAllowSpaces(value).Replace(';', ',').Trim(new[] {','}); }
        }

        [Category("03. Business Rules & Authorization")]
        [Description("The Authorization Type that controls read action. You can either select an object defined in the current project or an object defined in another assembly.")]
        [Editor(typeof(ObjectEditor), typeof(UITypeEditor))]
        [TypeConverter(typeof(AuthorizationRuleTypeConverter))]
        [UserFriendlyName("Read Authorization Type")]
        public virtual AuthorizationRule ReadAuthzRuleType
        {
            get { return _authzRules[0]; }
            set
            {
                if (!ReferenceEquals(value, _authzRules[0]))
                {
                    if (_authzRules[0] != null)
                    {
                        _authzRules[0] = value;
                        _authzRules[0].Parent = Name;
                    }
                }
            }
        }

        [Category("03. Business Rules & Authorization")]
        [Description("The Authorization Type that controls write action. You can either select an object defined in the current project or an object defined in another assembly.")]
        [Editor(typeof(ObjectEditor), typeof(UITypeEditor))]
        [TypeConverter(typeof(AuthorizationRuleTypeConverter))]
        [UserFriendlyName("Write Authorization Type")]
        public virtual AuthorizationRule WriteAuthzRuleType
        {
            get { return _authzRules[1]; }
            set
            {
                if (!ReferenceEquals(value, _authzRules[1]))
                {
                    if (_authzRules[1] != null)
                    {
                        _authzRules[1] = value;
                        _authzRules[1].Parent = Name;
                    }
                }
            }
        }

        #endregion

        #region 05. Options

        [Category("05. Options")]
        [Description("The Loading Scheme for the child." +
        "If set to ParentLoad, data for both the parent and the child will be fetched at the same time. " +
        "If set to SelfLoad, the child will fetch its own data. " +
         "None option is discontinued and the setting will be reset to ParentLoad.")]
        [UserFriendlyName("Loading Scheme")]
        public LoadingScheme LoadingScheme
        {
            get
            {
                if (_loadingScheme == LoadingScheme.None)
                    return LoadingScheme.ParentLoad;

                return _loadingScheme;
            }
            set { _loadingScheme = value; }
        }

        [Category("05. Options")]
        [Description("Whether or not this object should be lazy loaded.\r\n" +
            "If Loading Scheme is set to ParentLoad, Lazy Load is forced to False.\r\n" +
            "If set to True, loading of child data is defered until the child object is referenced.\r\n" +
            "If set to False, the child data is loaded when the parent is instantiated.")]
        [UserFriendlyName("Lazy Load")]
        public bool LazyLoad
        {
            get
            {
                if (_loadingScheme == LoadingScheme.SelfLoad)
                    return _lazyLoad;

                return false;
            }
            set { _lazyLoad = value; }
        }

        [Category("05. Options")]
        [Description("The parent properties that are used to load the child object.")]
        [Editor(typeof(PropertyCollectionEditor), typeof(UITypeEditor))]
        [TypeConverter(typeof(PropertyCollectionConverter))]
        [UserFriendlyName("Parent Properties")]
        public PropertyCollection ParentLoadProperties
        {
            get { return _parentLoadProperties; }
            set { _parentLoadProperties = value; }
        }

        [Category("05. Options")]
        [Editor(typeof(ParameterCollectionEditor), typeof(UITypeEditor))]
        [TypeConverter(typeof(ParameterCollectionConverter))]
        [Description("The parent get criteria parameters that are used to load the child object.")]
        [UserFriendlyName("Parent Criteria Parameters")]
        public ParameterCollection LoadParameters
        {
            get { return _loadParameters; }
            set { _loadParameters = value; }
        }

        [Category("05. Options")]
        [Description("Accessibility for the property as a whole.\r\nDefaults to IsPublic.")]
        [UserFriendlyName("Property Accessibility")]
        public PropertyAccess Access
        {
            get { return _access; }
            set { _access = value; }
        }

        [Category("05. Options")]
        [Description("Setting to false will cause the n-level undo process to ignore that property's value.")]
        public bool Undoable
        {
            get { return _undoable; }
            set { _undoable = value; }
        }

        #endregion

        #region Hidden Properties

        [Browsable(false)]
        [XmlIgnore]
        public bool IsCollection
        {
            get { return _isCollection; }
            internal set { _isCollection = value; }
        }

        [Browsable(false)]
        public override TypeCodeEx PropertyType
        {
            get { return TypeCodeEx.Empty; }
        }

        [Browsable(false)]
        public override bool Nullable
        {
            get { return base.Nullable; }
        }

        #endregion

        [field: NonSerialized]
        public event ChildPropertyNameChanged NameChanged;

        public override object Clone()
        {
            using (var buffer = new MemoryStream())
            {
                var ser = new XmlSerializer(typeof(ChildProperty));
                ser.Serialize(buffer, this);
                buffer.Position = 0;
                return ser.Deserialize(buffer);
            }
        }

        public int CompareTo(object other)
        {
            return ChildUpdateOrder.CompareTo(((ChildProperty) other).ChildUpdateOrder);
        }
    }
}


text:
<?php

namespace luya\traits;

use yii\web\NotFoundHttpException;

trait ErrorHandler
{
    public $api = 'http://luya.io/errorapi';

    public $transferException = false;

    public function renderException($exception)
    {
        if ($exception instanceof NotFoundHttpException || !$this->transferException) {
            return parent::renderException($exception);
        }

        $data = json_encode($this->getExceptionArray($exception));

        $curl = new \Curl\Curl();
        $rsp = $curl->post(\luya\helpers\Url::trailing($this->api).'create', [
            'error_json' => $data,
        ]);

        if (!YII_DEBUG) {
            return '<title>Fehler</title>
Seiten Fehler

Es ist ein unerwartet Fehler passiert, wir bitten um Entschuldigung. Bitte versuchen Sie es später erneut.
';
        }

        return parent::renderException($exception);
    }

    /**
     * @todo: catch getPrevious() exception
     *
     * @param object $exception Exception
     *
     * @return multitype:multitype:Ambigous <NULL, unknown>
     */
    public function getExceptionArray($exception)
    {
        $_trace = [];
        foreach ($exception->getTrace() as $key => $item) {
            $_trace[$key] = [
                'file' => isset($item['file']) ? $item['file'] : null,
                'line' => isset($item['line']) ? $item['line'] : null,
                'function' => isset($item['function']) ? $item['function'] : null,
                'class' => isset($item['class']) ? $item['class'] : null,
            ];
        }

        return [
            'message' => $exception->getMessage(),
            'serverName' => (isset($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : null,
            'request_uri' => (isset($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : null,
            'date' => date('d.m.Y H:i'),
            'line' => $exception->getLine(),
            'file' => $exception->getFile(),
            'trace' => $_trace,
            'ip' => (isset($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : null,
            'get' => $_GET,
            'post' => $_POST,
            'server' => $_SERVER,
            'session' => (isset($_SESSION)) ? $_SESSION : null,
        ];
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- EN-Revision: 20807 -->
<!-- Reviewed: no -->
<sect2 id="zend.test.phpunit.db.adapter">
    <title>Utiliser l'adaptateur de tests</title>

    <para>
        Il peut être nécessaire quelques fois de vouloir tester l'application, mais sans base de données
        réelle physique. <classname>Zend_Test_DbAdapter</classname> offre des possibilités d'utiliser
        une implémentation de <classname>Zend_Db_Adapter_Abstract</classname> sans avoir à ouvrir une
        connexion vers une base physique. En plus, cet adaptateur est très facilement déguisable car
        aucun paramètre de constructeur n'est nécessaire.
    </para>

    <para>
        L'adaptateur de tests agit comme une pile pour des résultats de base. L'ordre des résultats
        doit être implémenté manuellement ce qui peut devenir assez complexe, mais cet adaptateur
        est très pratique dans le cas où un ensemble logique de requêtes est éxecuté et que vous
        connaissez l'ordre précis dans lequel les résultats doivent être retournés.
    </para>

    <programlisting language="php"><![CDATA[
$adapter   = new Zend_Test_DbAdapter();
$stmt1Rows = array(array('foo' => 'bar'), array('foo' => 'baz'));
$stmt1     = Zend_Test_DbStatement::createSelectStatement($stmt1Rows);
$adapter->appendStatementToStack($stmt1);

$stmt2Rows = array(array('foo' => 'bar'), array('foo' => 'baz'));
$stmt2     = Zend_Test_DbStatement::createSelectStatement($stmt2Rows);
$adapter->appendStatementToStack($stmt2);

$rs = $adapter->query('SELECT ...'); // Retourne Statement 2
while ($row = $rs->fetch()) {
    echo $rs['foo']; // Prints "Bar", "Baz"
}
$rs = $adapter->query('SELECT ...'); // Retourne Statement 1
]]></programlisting>

    <para>
        Le comportement des adaptateurs réels est simulé afin que des méthodes telles que
        <methodname>fetchAll()</methodname>, <methodname>fetchObject()</methodname>,
        <methodname>fetchColumn()</methodname> puissent fonctionner avec l'adaptateur de tests.
    </para>

    <para>
        Bien sûr, INSERT, UPDATE et DELETE peuvent être empilés aussi, mais vous ne pourrez alors tester
        que <methodname>$stmt->rowCount()</methodname> car ces types de requêtes ne retournent pas de
        résultats.
    </para>

    <programlisting language="php"><![CDATA[
$adapter = new Zend_Test_DbAdapter();
$adapter->appendStatementToStack(
    Zend_Test_DbStatement::createInsertStatement(1)
);
$adapter->appendStatementToStack(
    Zend_Test_DbStatement::createUpdateStatement(2)
);
$adapter->appendStatementToStack(
    Zend_Test_DbStatement::createDeleteStatement(10
));
]]></programlisting>

    <para>
        Par défaut, le profiler est activé pour que vous puissiez récupérer la requête éxecutée de manière
        textuelle, avec ses paramètres donc.
    </para>

    <programlisting language="php"><![CDATA[
$adapter = new Zend_Test_DbAdapter();
$stmt = $adapter->query("SELECT * FROM bugs");

$qp = $adapter->getProfiler()->getLastQueryProfile();

echo $qp->getQuerY(); // SELECT * FROM bugs
]]></programlisting>

    <para>
        L'adaptateur de test ne vérifie jamais si la requête spécifiée est réellement de type SELECT, DELETE,
        INSERT ou UPDATE. L'ordre exact de retour des données doit être spécifié manuellement dans l'adaptateur
        de tests.
    </para>

    <para>
        L'adaptateur de tests définit aussi les méthodes
        <methodname>listTables()</methodname>, <methodname>describeTables()</methodname> et
        <methodname>lastInsertId()</methodname>. De plus en utilisant
        <methodname>setQuoteIdentifierSymbol()</methodname> vous pouvez spécifier quel symbole
        utilisé pour l'échappement, par défaut aucun n'est utilisé.
    </para>
</sect2>


text:
<?php
/*
Plugin Name:        Rankz
Plugin URI:         https://github.com/hellosensoul/rankz
Description:        A WordPress plugin which contains a bunch of customizations for Sage WordPress theme.
Version:            3.0.0
Author:             Ensoul
Author URI:         https://ensoul.it

License:            MIT License
License URI:        http://opensource.org/licenses/MIT
*/

namespace Ensoul\Rankz;

class Options {
  protected static $modules = [];
  protected $options = [];

  public static function init($module, $options = []) {
    if (!isset(self::$modules[$module])) {
      self::$modules[$module] = new static((array) $options);
    }
    return self::$modules[$module];
  }

  public static function getByFile($file) {
    if (file_exists($file) || file_exists(__DIR__ . '/modules/' . $file)) {
      return self::get('rankz-' . basename($file, '.php'));
    }
    return [];
  }

  public static function get($module) {
    if (isset(self::$modules[$module])) {
      return self::$modules[$module]->options;
    }
    if (substr($module, 0, 5) !== 'rankz-') {
      return self::get('rankz-' . $module);
    }
    return [];
  }

  protected function __construct($options) {
    $this->set($options);
  }

  public function set($options) {
    $this->options = $options;
  }
}

require_once __DIR__ . '/lib/utils.php';

function load_modules() {
  global $_wp_theme_features;
  foreach (glob(__DIR__ . '/modules/*.php') as $file) {
    $feature = 'rankz-' . basename($file, '.php');
    if (isset($_wp_theme_features[$feature])) {
      Options::init($feature, $_wp_theme_features[$feature]);
      require_once $file;
    }
  }
}
add_action('after_setup_theme', __NAMESPACE__ . '\\load_modules', 100);


text:
package gwen.web.eval.lambda.unit

import gwen.web.eval.WebContext

import gwen.core.behavior.BehaviorType
import gwen.core.eval.lambda.UnitStep
import gwen.core.node.GwenNode
import gwen.core.node.gherkin.Step

import scala.util.chaining._

class BindUrl(url: String, targetScope: Option[String]) extends UnitStep[WebContext] {

  override def apply(parent: GwenNode, step: Step, ctx: WebContext): Step = {
    step tap { _ =>
      checkStepRules(step, BehaviorType.Context, ctx)
      targetScope.foreach { scope =>
        ctx.scopes.addScope(scope)
      }
      ctx.scopes.set("url", url)
    }
  }

}


text:
package net.acomputerdog.ircbot.core.command;

import com.sorcix.sirc.structure.Channel;
import com.sorcix.sirc.structure.User;
import com.sorcix.sirc.util.Chattable;
import net.acomputerdog.ircbot.command.Command;
import net.acomputerdog.ircbot.command.util.CommandLine;
import net.acomputerdog.ircbot.config.Config;
import net.acomputerdog.ircbot.main.IrcBot;

public class CommandBlacklist extends Command {
    public CommandBlacklist(IrcBot bot) {
        super(bot, "Blacklist", "blacklist", "addblacklist", "add_blacklist", "add-blacklist");
    }

    @Override
    public String getHelpString() {
        return Config.COMMAND_PREFIX + "blacklist <user>";
    }

    @Override
    public int getMinArgs() {
        return 1;
    }

    @Override
    public boolean requiresAdmin() {
        return true;
    }

    @Override
    public String getDescription() {
        return "Changes a player's blacklist status.";
    }

    @Override
    public boolean processCommand(Channel channel, User sender, Chattable target, CommandLine command) {
        User user = bot.getConnection().createUser(command.args);
        if (bot.getBlacklist().isBlacklisted(user)) {
            bot.getBlacklist().removeBlacklisted(user);
            target.send("User " + user.getNick() + " has been un-blacklisted.");
        } else {
            bot.getBlacklist().addBlacklisted(user);
            target.send("User " + user.getNick() + " has been blacklisted.");
        }
        return true;
    }
}


text:
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""

import re

from lib.core.enums import HTTP_HEADER
from lib.core.settings import WAF_ATTACK_VECTORS

__product__ = "Teros/Citrix Application Firewall Enterprise (Teros/Citrix Systems)"

def detect(get_page):
    retval = False

    for vector in WAF_ATTACK_VECTORS:
        page, headers, code = get_page(get=vector)
        retval = re.search(r"\Ast8(id|_wat|_wlf)", headers.get(HTTP_HEADER.SET_COOKIE, ""), re.I) is not None
        if retval:
            break

    return retval


text:
<!DOCTYPE html>

	<title>
		Jon and Tim's Berkshire site
	</title>

		BERKSHIRE HATHAWAY INC.
		3555 Farnam Street
		Omaha, NE 68131
		Official Home Page

		A Message From Warren E. Buffett

		News Releases  Updated August 10, 2015

	Annual & Interim Reports Updated August 7, 2015

		Warren Buffett's Letters to Berkshire Shareholders Updated February 28, 2015

		A Message From Warren E. Buffett

Special Letters From Warren & Charlie RE:Past, Present and Future

Charlie Munger's Letters to Wesco Shareholders

Link to SEC Filings

Annual Meeting Information

Links to Berkshire Subsidiary Companies

Celebrating 50 Years of a Profitable Partnership (A commemorative book first sold at the 2015 Annual Meeting and now for sale on eBay.)

Corporate Governance

Comparative Rights and Relative Prices of Class A and B Stock

Owner's Manual

Berkshire Activewear

Letters from Warren E. Buffett Regarding Pledges to Make Gifts of Berkshire Stock

	FOR A FREE CAR INSURANCE RATE QUOTE THAT COULD SAVE YOU SUBSTANTIAL MONEY

	WWW.GEICO.COM OR CALL 1-888-395-6349, 24 HOURS A DAY

	If you have any comments about our WEB page, you can either write us at the address shown above or e-mail us at berkshire@berkshirehathaway.com. However, due to the limited number of personnel in our corporate office, we are unable to provide a direct response.

	Legal Disclaimer
	Copyright © 1978-2015 Berkshire Hathaway Inc.


text:
"""
Test extracting the QUERY_STRING into tiddlyweb.query.
Not much yet as it is just a directly mappen.
"""

import urllib

from tiddlyweb.web.query import Query

def setup_module(module):
    module.environ = {'QUERY_STRING': 'hello=goodbye&barney=ugly&special=nice', 'REQUEST_METHOD': 'GET'}

def test_interpret_query():
    def app(environ, start_response):
        pass
    query = Query(app)
    query(environ, lambda x: x)

    assert environ['tiddlyweb.query']['hello'][0] == 'goodbye'
    assert environ['tiddlyweb.query']['barney'][0] == 'ugly'
    assert environ['tiddlyweb.query']['special'][0] == 'nice'
    assert environ['tiddlyweb.query'].get('flip', [None])[0] == None


text:
JS memory management

https://blog.sessionstack.com/how-javascript-works-memory-management-how-to-handle-4-common-memory-leaks-3f28b94cfbec


text:
package sagan;

import javax.sql.DataSource;

import org.springframework.cloud.Cloud;
import org.springframework.cloud.CloudFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.util.Assert;

public abstract class DatabaseConfig {

    @Bean
    public abstract DataSource dataSource();

    protected void configureDataSource(org.apache.tomcat.jdbc.pool.DataSource dataSource) {
        dataSource.setMaxActive(20);
        dataSource.setMaxIdle(8);
        dataSource.setMinIdle(8);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
    }
}

@Configuration
@Profile(SaganProfiles.STANDALONE)
class StandaloneDatabaseConfig extends DatabaseConfig {

    @Bean
    public DataSource dataSource() {
        org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource();

        dataSource.setDriverClassName("org.h2.Driver");
        dataSource.setUrl("jdbc:h2:mem:sagan;MODE=PostgreSQL");
        dataSource.setUsername("sa");
        dataSource.setPassword("");
        dataSource.setValidationQuery("SELECT 1");

        configureDataSource(dataSource);

        return dataSource;
    }
}

@Configuration
@Profile(SaganProfiles.CLOUDFOUNDRY)
class CloudFoundryDatabaseConfig extends DatabaseConfig {

    @Bean
    public Cloud cloud() {
        return new CloudFactory().getCloud();
    }

    @Bean
    public DataSource dataSource() {
        DataSource dataSource = cloud().getServiceConnector("sagan-db", DataSource.class, null);
        Assert.isInstanceOf(org.apache.tomcat.jdbc.pool.DataSource.class, dataSource);
        configureDataSource((org.apache.tomcat.jdbc.pool.DataSource) dataSource);
        return dataSource;
    }
}


text:
package flags_test

import (
	. "github.com/cloudfoundry/cli/flags"
	"github.com/cloudfoundry/cli/flags/flag"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Flags", func() {

	Describe("FlagContext", func() {

		Describe("Parsing and retriving values", func() {

			var (
				fCtx       FlagContext
				cmdFlagMap map[string]FlagSet
			)

			BeforeEach(func() {
				cmdFlagMap = make(map[string]FlagSet)
				cmdFlagMap["name"] = &cliFlags.StringFlag{Name: "name", Value: "", Usage: "test string flag"}
				cmdFlagMap["skip"] = &cliFlags.BoolFlag{Name: "skip", Value: false, Usage: "test bool flag"}
				cmdFlagMap["instance"] = &cliFlags.IntFlag{Name: "instance", Value: 0, Usage: "test int flag"}
				cmdFlagMap["skip2"] = &cliFlags.BoolFlag{Name: "skip2", Value: false, Usage: "test bool flag"}

				fCtx = NewFlagContext(cmdFlagMap)
			})

			It("accepts flags with either single '-' or double '-' ", func() {
				err := fCtx.Parse("--name", "blue")
				Ω(err).ToNot(HaveOccurred())

				err = fCtx.Parse("-name", "")
				Ω(err).ToNot(HaveOccurred())
			})

			It("checks if a flag is defined in the FlagContext", func() {
				err := fCtx.Parse("-not_defined", "")
				Ω(err).To(HaveOccurred())

				err = fCtx.Parse("-name", "blue")
				Ω(err).ToNot(HaveOccurred())

				err = fCtx.Parse("--skip", "")
				Ω(err).ToNot(HaveOccurred())
			})

			It("sets Bool(<flag>) to return value if bool flag is provided with value true/false", func() {
				err := fCtx.Parse("--skip=false", "-skip2", "true", "-name", "johndoe")
				Ω(err).ToNot(HaveOccurred())

				Ω(fCtx.Bool("skip")).To(Equal(false), "skip should be false")
				Ω(fCtx.Bool("skip2")).To(Equal(true), "skip2 should be true")
				Ω(fCtx.Bool("name")).To(Equal(false), "name should be false")
				Ω(fCtx.Bool("non-exisit-flag")).To(Equal(false))
			})

			It("sets Bool(<flag>) to return true if bool flag is provided with invalid value", func() {
				err := fCtx.Parse("--skip=Not_Valid", "skip2", "FALSE", "-name", "johndoe")
				Ω(err).ToNot(HaveOccurred())

				Ω(fCtx.Bool("skip")).To(Equal(true), "skip should be true")
				Ω(fCtx.Bool("skip2")).To(Equal(false), "skip2 should be false")
			})

			It("sets Bool(<flag>) to return true when a bool flag is provided without value", func() {
				err := fCtx.Parse("--skip", "-name", "johndoe")
				Ω(err).ToNot(HaveOccurred())

				Ω(fCtx.Bool("skip")).To(Equal(true), "skip should be true")
				Ω(fCtx.Bool("name")).To(Equal(false), "name should be false")
				Ω(fCtx.Bool("non-exisit-flag")).To(Equal(false))
			})

			It("sets String(<flag>) to return provided value when a string flag is provided", func() {
				err := fCtx.Parse("--skip", "-name", "doe")
				Ω(err).ToNot(HaveOccurred())

				Ω(fCtx.String("name")).To(Equal("doe"))
				Ω(fCtx.Bool("skip")).To(Equal(true), "skip should be true")
			})

			It("errors when a non-boolean flag is provided without a value", func() {
				err := fCtx.Parse("-name")
				Ω(err).To(HaveOccurred())
				Ω(err.Error()).To(ContainSubstring("No value provided for flag"))
				Ω(fCtx.String("name")).To(Equal(""))
			})

			It("sets Int(<flag>) to return provided value when a int flag is provided", func() {
				err := fCtx.Parse("--instance", "10")
				Ω(err).ToNot(HaveOccurred())

				Ω(fCtx.Int("instance")).To(Equal(10))
				Ω(fCtx.IsSet("instance")).To(Equal(true))

				Ω(fCtx.Int("non-exist-flag")).To(Equal(0))
				Ω(fCtx.IsSet("non-exist-flag")).To(Equal(false))
			})

			It("returns any non-flag arguments in Args()", func() {
				err := fCtx.Parse("Arg-1", "--instance", "10", "--skip", "Arg-2")
				Ω(err).ToNot(HaveOccurred())

				Ω(len(fCtx.Args())).To(Equal(2))
				Ω(fCtx.Args()[0]).To(Equal("Arg-1"))
				Ω(fCtx.Args()[1]).To(Equal("Arg-2"))
			})

			It("accepts flag/value in the forms of '-flag=value' and '-flag value'", func() {
				err := fCtx.Parse("-instance", "10", "--name=foo", "--skip", "Arg-1")
				Ω(err).ToNot(HaveOccurred())

				Ω(fCtx.IsSet("instance")).To(Equal(true))
				Ω(fCtx.Int("instance")).To(Equal(10))

				Ω(fCtx.IsSet("name")).To(Equal(true))
				Ω(fCtx.String("name")).To(Equal("foo"))

				Ω(fCtx.IsSet("skip")).To(Equal(true))

				Ω(len(fCtx.Args())).To(Equal(1))
				Ω(fCtx.Args()[0]).To(Equal("Arg-1"))
			})

		})

	})
})