text:
package org.apereo.cas.configuration.model.support.x509;

import org.apereo.cas.configuration.support.RequiresModule;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

/**
 * This is {@link SerialNoPrincipalResolverProperties}.
 * @since 6.0.0
 */
@RequiresModule(name = "cas-server-support-x509-webflow")
@Getter
@Setter
public class SerialNoPrincipalResolverProperties implements Serializable {

    /**
     * Radix used when {@link X509Properties.PrincipalTypes} is {@link X509Properties.PrincipalTypes#SERIAL_NO}.
     */
    private int principalSNRadix;
    /**
     * If radix hex padding should be used when {@link X509Properties.PrincipalTypes} is {@link X509Properties.PrincipalTypes#SERIAL_NO}.
     */
    private boolean principalHexSNZeroPadding;

}


text:
package org.ohmage.lifestreams.stores;

import org.joda.time.DateTime;
import org.ohmage.lifestreams.models.StreamRecord;
import org.ohmage.models.OhmageStream;
import org.ohmage.models.OhmageUser;
import org.ohmage.sdk.OhmageStreamIterator;

import java.io.Serializable;
import java.util.List;

public interface IStreamStore extends Serializable {
	void upload(OhmageStream stream, StreamRecord rec);
	List<StreamRecord> query(OhmageStream stream, OhmageUser user, DateTime start,
                                    DateTime end, OhmageStreamIterator.SortOrder order, int maxRows);
}

redpajama_set_name: RedPajamaGithub


text:
module.exports = {
    episode1: require('./episode1')
};


text:
<?php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\Models */
/* @var $form yii\bootstrap\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?php echo $form->errorSummary($model); ?>

    <?php echo $form->field($model, 'id_category')->dropDownList($category, ['prompt' => 'Выберите категорию',
    'onchange'=>'
                $.post( "/models/lists?id='.'"+$(this).val(), function( data ) {
                  $("select#models-id_brands").html( data );
                  $("select#models-id_brands").attr("disabled", false);
                });'
    ]) ?>

    <?php echo $form->field($model, 'id_brands')->dropDownList($brands, ['prompt' => 'Выберите бренд', 'disabled' => true]) ?>

    <?php echo $form->field($model, 'tovar')->hint(Yii::t('backend', 'Enter the list of models by pressing the "Enter"'),['class'=>'text-danger'])->textarea()->label(Yii::t('backend', 'Tovar')) ?>

        <?php echo Html::submitButton($model->isNewRecord ? Yii::t('backend', 'Create') : Yii::t('backend', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
function [params, names] = rbfwhiteKernExtractParam(kern)

% RBFWHITEKERNEXTRACTPARAM Extract parameters from the RBF-WHITE kernel
%
%	Description:
%	structure.
%
%	PARAM = RBFWHITEKERNEXTRACTPARAM(KERN) extracts parameters from the
%	RBF-WHITE kernel structure into a vector of parameters for
%	optimisation.
%	 Returns:
%	  PARAM - vector of parameters extracted from the kernel. If the
%	   field 'transforms' is not empty in the kernel structure, the
%	   parameters will be transformed before optimisation (for example
%	   positive only parameters could be logged before being returned).
%	 Arguments:
%	  KERN - the kernel structure containing the parameters to be
%	   extracted.
%
%	[PARAM, NAMES] = RBFWHITEKERNEXTRACTPARAM(KERN) extracts parameters
%	and parameter names from the RBF-WHITE kernel structure.
%	 Returns:
%	  PARAM - vector of parameters extracted from the kernel. If the
%	   field 'transforms' is not empty in the kernel structure, the
%	   parameters will be transformed before optimisation (for example
%	   positive only parameters could be logged before being returned).
%	  NAMES - cell array of strings containing names for each parameter.
%	 Arguments:
%	  KERN - the kernel structure containing the parameters to be
%	   extracted.
%	scg, conjgrad
%
%
%
%	See also
%	% SEEALSO RBFWHITEKERNPARAMINIT, RBFWHITEKERNEXPANDPARAM, KERNEXTRACTPARAM,

%	Copyright (c) 2009 David Luengo

params = [kern.inverseWidth kern.variance];
if nargout > 1
  names = {'inverse width', 'variance'};
end


text:
package org.eknet.publet.webdav

import com.google.inject.AbstractModule
import org.eknet.publet.web.guice.{AbstractPubletModule, PubletModule, PubletBinding}
import org.eknet.guice.squire.SquireModule
import org.eknet.publet.vfs.Resource
import org.eknet.publet.web.util.AppSignature

/**
 *
 * @author Eike Kettner
 * @since 16.10.12 19:18
 *
 */
class WebdavModule extends AbstractPubletModule with PubletBinding with PubletModule {

  def configure() {
    bindRequestHandler.add[WebdavHandlerFactory]
    bindDocumentation(docResource("_webdav.md"))
  }

  private[this] def docResource(names: String*) = names.map("org/eknet/publet/webdav/doc/"+ _).map(Resource.classpath(_)).toList

  val name = "WebDAV"
}


text:
function Greet(){
    this.greeting = "Hello world 3";
    this.greet = function(){
        console.log(this.greeting);
    }
}

module.exports = new Greet(); // Creates a new object from the constructor


text:
<?php

namespace Magento\Sales\Setup;

use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

/**
 * @codeCoverageIgnore
 */
class UpgradeSchema implements UpgradeSchemaInterface
{
    /**
     * @var string
     */
    private static $connectionName = 'sales';

    /**
     * {@inheritdoc}
     */
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        if (version_compare($context->getVersion(), '2.0.2', '<')) {
            $connection = $installer->getConnection(self::$connectionName);
            //sales_bestsellers_aggregated_daily
            $connection->dropForeignKey(
                $installer->getTable('sales_bestsellers_aggregated_daily', self::$connectionName),
                $installer->getFkName(
                    'sales_bestsellers_aggregated_daily',
                    'product_id',
                    'catalog_product_entity',
                    'entity_id',
                    self::$connectionName
                )
            );
            //sales_bestsellers_aggregated_monthly
            $connection->dropForeignKey(
                $installer->getTable('sales_bestsellers_aggregated_monthly', self::$connectionName),
                $installer->getFkName(
                    'sales_bestsellers_aggregated_monthly',
                    'product_id',
                    'catalog_product_entity',
                    'entity_id',
                    self::$connectionName
                )
            );

            //sales_bestsellers_aggregated_yearly
            $connection->dropForeignKey(
                $installer->getTable('sales_bestsellers_aggregated_yearly', self::$connectionName),
                $installer->getFkName(
                    'sales_bestsellers_aggregated_yearly',
                    'product_id',
                    'catalog_product_entity',
                    'entity_id',
                    self::$connectionName
                )
            );

            $installer->endSetup();
        }
        if (version_compare($context->getVersion(), '2.0.3', '<')) {
            $this->addColumnBaseGrandTotal($installer);
            $this->addIndexBaseGrandTotal($installer);
        }
    }

    /**
     * @param SchemaSetupInterface $installer
     * @return void
     */
    private function addColumnBaseGrandTotal(SchemaSetupInterface $installer)
    {
        $connection = $installer->getConnection(self::$connectionName);
        $connection->addColumn(
            $installer->getTable('sales_invoice_grid', self::$connectionName),
            'base_grand_total',
            [
                'type' => \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
                'nullable' => true,
                'length' => '12,4',
                'comment' => 'Base Grand Total',
                'after' => 'grand_total'
            ]
        );
    }

    /**
     * @param SchemaSetupInterface $installer
     * @return void
     */
    private function addIndexBaseGrandTotal(SchemaSetupInterface $installer)
    {
        $connection = $installer->getConnection(self::$connectionName);
        $connection->addIndex(
            $installer->getTable('sales_invoice_grid', self::$connectionName),
            $installer->getIdxName('sales_invoice_grid', ['base_grand_total'], '', self::$connectionName),
            ['base_grand_total']
        );
    }
}


text:
using SocialGoal.Data.Infrastructure;
using SocialGoal.Model.Models;
namespace SocialGoal.Data.Repository
{
    public class FocusRepository: RepositoryBase<Focus>, IFocusRepository
        {
        public FocusRepository(IDatabaseFactory databaseFactory)
            : base(databaseFactory)
            {
            }
        }
    public interface IFocusRepository : IRepository<Focus>
    {
    }
}


text:
package com.sequenceiq.cloudbreak.api.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sequenceiq.cloudbreak.doc.ModelDescriptions;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel
@JsonIgnoreProperties(ignoreUnknown = true)
public class NetworkResponse extends NetworkBase {
    @ApiModelProperty(value = ModelDescriptions.ID)
    private Long id;

    @ApiModelProperty(value = ModelDescriptions.PUBLIC_IN_ACCOUNT)
    private boolean publicInAccount;

    @JsonProperty("publicInAccount")
    public boolean isPublicInAccount() {
        return publicInAccount;
    }

    @JsonIgnore
    public void setPublicInAccount(boolean publicInAccount) {
        this.publicInAccount = publicInAccount;
    }

    @JsonProperty("id")
    public Long getId() {
        return id;
    }

    @JsonIgnore
    public void setId(Long id) {
        this.id = id;
    }

}


text:
class A
{
};
class B
{
public:
	B(int i, A* a) : i(i), a(a) {}

	A* getA() {return a;}
	A* getA() const {return a;}

public:
	int i;
	A* a;
};

bool predicate0(B* b);
bool predicate0(B* b)
{
	return b->getA() == nullptr;
}

struct Functor
{
	Functor(A* a) : a(a) {}

	bool operator()(B* b) const
	{
		return b->getA() == a;
	}

public:
	A* a;
};

struct FunctorWrapper
{
	FunctorWrapper(std::function<bool(A*, A*)> functor, A* a) : functor(functor), a(a) {}

	bool operator()(B* b) const
	{
		return functor(a, b->getA());
	}

public:
	std::function<bool(A*, A*)> functor;
	A* a;
};

struct MethodWrapper
{
	MethodWrapper(A*(B::*method)()) : method(method) {}

	A* operator()(B* instance) const
	{
		return (instance->*method)();
	}

	A*(B::*method)();
};

struct ComposingWrapper
{
	ComposingWrapper(std::function<bool(A*)> f, std::function<A*(B*)> g) : f(f), g(g) {}

	bool operator()(B* b)
	{
		return f(g(b));
	}

public:
	std::function<bool(A*)> f;
	std::function<A*(B*)> g;
};

template<typename R, typename F, typename ... ArgTypes>
auto factory(R* r, F f, ArgTypes... args)
{
	return std::bind(std::equal_to<R*>(), std::bind(f, std::placeholders::_1, args...), r);
}

void printResults(const char* label, std::vector<B*>& result)
{
	std::cout << label << " : {";
	if (result.size() > 0) {
		std::vector<B*>::const_iterator it = result.begin();
		if (result.size() > 1) {
			std::ostream_iterator<int> out(std::cout, ", ");
			for (std::vector<B*>::const_iterator itEnd = std::prev(result.end()); it != itEnd; ++it) {
				*out = (*it)->i;
			}
		}
		std::cout << (*it)->i;
	}
	std::cout << "}" << std::endl;
	result.clear();
}

int main(int argc, const char * argv[])
{
	A* a1 = new A();
	A* a2 = new A();
	std::vector<B*> objects = {
		new B(1, a1),
		new B(2, a2),
		new B(3, a1),
		new B(4, a2),
		new B(5, a1),
		new B(6, nullptr)
	};
	std::vector<B*> result;

	// predicate0
	std::copy_if(objects.begin(), objects.end(), std::back_inserter(result), predicate0);
	printResults("predicate0", result);

	// Functor
	std::copy_if(objects.begin(), objects.end(), std::back_inserter(result), Functor(a1));
	printResults("Functor(a1)", result);
	std::copy_if(objects.begin(), objects.end(), std::back_inserter(result), Functor(a2));
	printResults("Functor(a2)", result);

	// predicate1
	auto predicate1 = [a2](B* b) -> bool {return b->getA() == a2;};
	std::copy_if(objects.begin(), objects.end(), std::back_inserter(result), predicate1);
	printResults("predicate1", result);

	// predicate2
	auto predicate2 = [a1](B* b) -> bool {
		return std::equal_to<A*>()(b->getA(), a1);
	};
	std::copy_if(objects.begin(), objects.end(), std::back_inserter(result), predicate2);
	printResults("predicate2", result);

	// FunctorWrapper
	std::copy_if(objects.begin(), objects.end(), std::back_inserter(result), FunctorWrapper(std::equal_to<A*>(), a2));
	printResults("FunctorWrapper", result);

	// predicate3
	auto equalToA1 = std::bind(std::equal_to<A*>(), std::placeholders::_1, a1);
	auto predicate3 = [equalToA1](B* b) -> bool {
		return equalToA1(b->getA());
	};
	std::copy_if(objects.begin(), objects.end(), std::back_inserter(result), predicate3);
	printResults("predicate3", result);

	// ComposingWrapper + MethodWrapper
	std::copy_if(objects.begin(), objects.end(), std::back_inserter(result), ComposingWrapper(equalToA1, MethodWrapper(static_cast<A*(B::*)()>(&B::getA))));
	printResults("ComposingWrapper + MethodWrapper", result);

	// predicate4
	auto predicate4 = std::bind(std::equal_to<A*>(), std::bind(static_cast<A*(B::*)() const>(&B::getA), std::placeholders::_1), a2);
	std::copy_if(objects.begin(), objects.end(), std::back_inserter(result), predicate4);
	printResults("predicate4", result);
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>lxml.builder.ElementMaker</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

lxml API

        Package lxml ::
        Module builder ::
        Class ElementMaker

[hide private]

[frames] | no frames]

Class ElementMaker

source code

object --+
         |
        ElementMaker

Element generator factory.

Unlike the ordinary Element factory, the E factory allows you to pass in
more than just a tag and some optional attributes; you can also pass in
text and other elements.  The text is added as either text or tail
attributes, and elements are inserted at the right spot.  Some small
examples:

>>> from lxml import etree as ET
>>> from lxml.builder import E

>>> ET.tostring(E("tag"))
'<tag/>'
>>> ET.tostring(E("tag", "text"))
'<tag>text</tag>'
>>> ET.tostring(E("tag", "text", key="value"))
'<tag key="value">text</tag>'
>>> ET.tostring(E("tag", E("subtag", "text"), "tail"))
'<tag><subtag>text</subtag>tail</tag>'

For simple tags, the factory also allows you to write <tt class="rst-docutils literal">E.tag(...)</tt> instead
of <tt class="rst-docutils literal">E('tag', ...)</tt>:

>>> ET.tostring(E.tag())
'<tag/>'
>>> ET.tostring(E.tag("text"))
'<tag>text</tag>'
>>> ET.tostring(E.tag(E.subtag("text"), "tail"))
'<tag><subtag>text</subtag>tail</tag>'

Here's a somewhat larger example; this shows how to generate HTML
documents, using a mix of prepared factory functions for inline elements,
nested <tt class="rst-docutils literal">E.tag</tt> calls, and embedded XHTML fragments:

# some common inline elements
A = E.a
I = E.i
B = E.b

def CLASS(v):
    # helper function, 'class' is a reserved word
    return {'class': v}

page = (
    E.html(
        E.head(
            E.title("This is a sample document")
        ),
        E.body(
            E.h1("Hello!", CLASS("title")),
            E.p("This is a paragraph with ", B("bold"), " text in it!"),
            E.p("This is another paragraph, with a ",
                A("link", href="http://www.python.org"), "."),
            E.p("Here are some reservered characters: <spam&egg>."),
            ET.XML("<p>And finally, here is an embedded XHTML fragment.</p>"),
        )
    )
)

print ET.tostring(page)

Here's a prettyprinted version of the output from the above script:

<html>
  <head>
    <title>This is a sample document</title>
  </head>
  <body>
    <h1 class="title">Hello!</h1>
    <p>This is a paragraph with <b>bold</b> text in it!</p>
    <p>This is another paragraph, with <a href="http://www.python.org">link</a>.</p>
    <p>Here are some reservered characters: &lt;spam&amp;egg&gt;.</p>
    <p>And finally, here is an embedded XHTML fragment.</p>
  </body>
</html>

For namespace support, you can pass a namespace map (<tt class="rst-docutils literal">nsmap</tt>)
and/or a specific target <tt class="rst-docutils literal">namespace</tt> to the ElementMaker class:

>>> E = ElementMaker(namespace="http://my.ns/")
>>> print(ET.tostring( E.test ))
<test xmlns="http://my.ns/"/>

>>> E = ElementMaker(namespace="http://my.ns/", nsmap={'p':'http://my.ns/'})
>>> print(ET.tostring( E.test ))
<p:test xmlns:p="http://my.ns/"/>

        Instance Methods
        [hide private]

          __init__(self,
        typemap=None,
        namespace=None,
        nsmap=None,
        makeelement=None)

      x.__init__(...) initializes x; see help(type(x)) for signature

            source code

          __call__(self,
        tag,
        *children,
        **attrib)

            source code

          __getattr__(self,
        tag)

            source code

Inherited from object:
      __delattr__,
      __format__,
      __getattribute__,
      __hash__,
      __new__,
      __reduce__,
      __reduce_ex__,
      __repr__,
      __setattr__,
      __sizeof__,
      __str__,
      __subclasshook__

        Properties
        [hide private]

Inherited from object:
      __class__

        Method Details
        [hide private]

__init__(self,
        typemap=None,
        namespace=None,
        nsmap=None,
        makeelement=None)

(Constructor)

  	source code

  x.__init__(...) initializes x; see help(type(x)) for signature

Overrides:
        object.__init__

(inherited documentation)

         Home

         Trees

         Indices

         Help

lxml API

    Generated by Epydoc 3.0.1 on Sat Apr 25 16:24:35 2015

      http://epydoc.sourceforge.net


text:
<?php
//Comment this two lines if you are in production
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Consider that the main website is www.mydomaine.ci

// required libs
require_once __DIR__ . '/../src/cinetpay.php';
require_once __DIR__ . '/commande.php';

// This class manage "Commande" table in DB
$commande = new Commande();
try {
    //transaction id
    $id_transaction = date("YmdHis"); // or $id_transaction = Cinetpay::generateTransId()
    // Payment description
    $description_du_paiement = "Mon produit de ref: $id_transaction";
    // Payment Date must be on date format
    $date_transaction = date("Y-m-d H:i:s");
    // Amount
    $montant_a_payer = mt_rand(5, 100);

    // put a value that you can use to identify the buyer in your system
    $identifiant_du_payeur = 'payeur@domaine.ci';

    //Veuillez entrer votre apiKey
    $apiKey = "39955468c7a8c0cef1.68322505";
    //Veuillez entrer votre siteId
    $site_id = "124598";

    //platform ,  utiliser PROD si vous avez créé votre compte sur www.cinetpay.com  ou TEST si vous avez créé votre compte sur www.sandbox.cinetpay.com
    $plateform = "TEST";

    //la version ,  utilisé V1 si vous voulez utiliser la version 1 de l'api
    $version = "V2";

    // nom du formulaire CinetPay
    $formName = "goCinetPay";
    // notify url
    $notify_url = 'www.mydomaine.ci/notify/';
    // return url
    $return_url = 'www.mydomaine.ci/return/';
    // cancel url
    $cancel_url = 'www.mydomaine.ci';

    // cinetpay button type, must be 1, 2, 3, 4 or 5
    $btnType = 2;
    // button size, can be 'small' , 'large' or 'larger'
    $btnSize = 'large';
    // fill command class
    $commande->setTransId($id_transaction);
    $commande->setMontant($montant_a_payer);

    // save transaction in db
    $commande->create();

    // create html form for your basket
    $CinetPay = new CinetPay($site_id, $apiKey, $plateform, $version);
    $CinetPay->setTransId($id_transaction)
        ->setDesignation($description_du_paiement)
        ->setTransDate($date_transaction)
        ->setAmount($montant_a_payer)
        ->setDebug(false)// put it on true, if you want to activate debug
        ->setCustom($identifiant_du_payeur)// optional
        ->setNotifyUrl($notify_url)// optional
        ->setReturnUrl($return_url)// optional
        ->setCancelUrl($cancel_url)// optional
        ->displayPayButton($formName, $btnType, $btnSize);
} catch (Exception $e) {
    echo $e->getMessage();
}


text:
package com.ppmessage.ppcomlib.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.GridView;

import com.ppmessage.ppcomlib.PPComSDK;
import com.ppmessage.ppcomlib.R;
import com.ppmessage.ppcomlib.model.ConversationMemberModel;
import com.ppmessage.ppcomlib.model.ConversationsModel;
import com.ppmessage.ppcomlib.ui.adapter.ConversationMembersAdapter;
import com.ppmessage.ppcomlib.utils.PPComUtils;
import com.ppmessage.sdk.core.L;
import com.ppmessage.sdk.core.bean.common.Conversation;
import com.ppmessage.sdk.core.bean.common.User;
import com.ppmessage.sdk.core.utils.Utils;

import java.util.Iterator;
import java.util.List;

/**
 * Created by ppmessage on 5/13/16.
 */
public class ConversationMemberActivity extends AppCompatActivity {

    public static final String EXTRA_CONVERSATION_UUID = "com.ppmessage.ppcomlib.ui.ConversationMemberActivity.conversation_uuid";

    private static final String TAG = ConversationMemberActivity.class.getSimpleName();
    private static final String LOG_LOST_COM_USER = "[" + TAG + "], can not find ppcom user";
    private static final String LOG_LOST_CONVERSATION = "[" + TAG + "], can not find avaliable conversation";

    private PPComSDK sdk;

    private GridView gridView;
    private ProgressDialog loadingDialog;

    private String conversationUUID;
    /** 会员成员数量:包括自己 **/
    private int conversationMembersCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ppcomlib_conversation_member_activity);

        setTitle(R.string.ppcom_sdk_conversation_members_activity_name);
        PPComUtils.setActivityActionBarStyle(this);

        gridView = (GridView) findViewById(R.id.gridView);

        sdk = PPComSDK.getInstance();
        conversationUUID = (String) getIntent().getStringExtra(EXTRA_CONVERSATION_UUID);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (conversationUUID != null && checkRequirements()) {
            startLoading();

            ConversationMemberModel conversationMemberModel = sdk.getMessageService().getConversationMemberModel();
            conversationMemberModel.getMembers(conversationUUID, new ConversationMemberModel.OnGetConversationMembersEvent() {
                @Override
                public void onCompleted(List<User> userList) {
                    ConversationMemberActivity.this.conversationMembersCount =
                            userList != null ? userList.size() : 0;
                    stopLoading();
                    updateGridView(userList);
                }
            });
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void updateGridView(List<User> userList) {
        User comUser = sdk.getStartupHelper().getComUser().getUser();
        for (Iterator<User> iter = userList.listIterator(); iter.hasNext(); ) {
            User u = iter.next();
            if (u.getUuid().equals(comUser.getUuid())) {
                iter.remove();
            }
        }

        final ConversationMembersAdapter conversationMembersAdapter = new ConversationMembersAdapter(sdk, userList);
        conversationMembersAdapter.setListener(new ConversationMembersAdapter.OnConversationMembersItemClickListener() {
            @Override
            public void onClicked(User user, int position, View convertView) {
                if (user.getUuid() == null) return;

                User comUser = sdk.getStartupHelper().getComUser().getUser();
                if (comUser == null) return;

                if (user.getUuid().equals(comUser.getUuid())) return;

                chattingWithUser(user);
            }
        });
        gridView.setAdapter(conversationMembersAdapter);
    }

    private void chattingWithUser(final User user) {
        // 当前会话只有两个成员,说明当前这个会话就是我们要找的会话
        if (conversationMembersCount == 2) {
            Conversation conversation = sdk.getMessageService().getConversationsModel().get(conversationUUID);
            if (conversation != null) {
                enterMessageActivity(conversation);
                return;
            }
            L.w(LOG_LOST_CONVERSATION);
        }

        // 从服务器拿取
        startLoading();
        ConversationsModel conversationsModel = sdk.getMessageService().getConversationsModel();
        conversationsModel.asyncGetUserConversation(user.getUuid(), new ConversationsModel.OnGetConversationEvent() {
            @Override
            public void onCompleted(Conversation conversation) {
                stopLoading();

                if (conversation != null) {
                    enterMessageActivity(conversation);
                }
            }
        });
    }

    private void enterMessageActivity(Conversation conversation) {
        Intent intent = new Intent(ConversationMemberActivity.this, PPComMessageActivity.class);
        intent.putExtra(PPComMessageActivity.EXTRA_KEY_CONVERSATION_NAME, conversation.getConversationName());
        intent.putExtra(PPComMessageActivity.EXTRA_KEY_CONVERSATION_UUID, conversation.getConversationUUID());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private void startLoading() {
        if (loadingDialog == null) {
            loadingDialog = new ProgressDialog(this);
            loadingDialog.setTitle(R.string.pp_com_sdk_loading_dialog_content);
        }
        if (loadingDialog != null) {
            loadingDialog.show();
        }
    }

    private void stopLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    private boolean checkRequirements() {
        if (sdk == null ||
                sdk.getStartupHelper() == null ||
                sdk.getStartupHelper().getComUser() == null ||
                sdk.getStartupHelper().getComUser().getUser() == null) {
            L.w(LOG_LOST_COM_USER);
            Utils.makeToast(this, R.string.pp_configuration_not_valid);
            return false;
        }
        return true;
    }

}


text:
package com.sulaco.fuse.akka.actor.annotated;

import com.sulaco.fuse.akka.actor.FuseEndpointActor;
import com.sulaco.fuse.config.annotation.FuseEndpoint;
import org.springframework.context.ApplicationContext;

@FuseEndpoint( path ="/test", method = "GET")
public class TestEndpointActor extends FuseEndpointActor {

}


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'Language'
        db.create_table(u'people_language', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=64)),
        ))
        db.send_create_signal(u'people', ['Language'])

        # Adding field 'Commit.files'
        db.add_column(u'people_commit', 'files',
                      self.gf('jsonfield.fields.JSONField')(null=True, blank=True),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting model 'Language'
        db.delete_table(u'people_language')

        # Deleting field 'Commit.files'
        db.delete_column(u'people_commit', 'files')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'july.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'location_members'", 'null': 'True', 'to': u"orm['people.Location']"}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'picture_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
            'projects': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['people.Project']", 'null': 'True', 'blank': 'True'}),
            'team': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'team_members'", 'null': 'True', 'to': u"orm['people.Team']"}),
            'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'people.achievedbadge': {
            'Meta': {'object_name': 'AchievedBadge'},
            'achieved_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'badge': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['people.Badge']", 'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['july.User']", 'null': 'True', 'blank': 'True'})
        },
        u'people.badge': {
            'Meta': {'object_name': 'Badge'},
            'description': ('django.db.models.fields.CharField', [], {'max_length': '2024', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'text': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
        },
        u'people.commit': {
            'Meta': {'ordering': "['-timestamp']", 'object_name': 'Commit'},
            'author': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'created_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'email': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'files': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}),
            'hash': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'message': ('django.db.models.fields.CharField', [], {'max_length': '2024', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['people.Project']", 'null': 'True', 'blank': 'True'}),
            'timestamp': ('django.db.models.fields.DateTimeField', [], {}),
            'url': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['july.User']", 'null': 'True', 'blank': 'True'})
        },
        u'people.language': {
            'Meta': {'object_name': 'Language'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '64'})
        },
        u'people.location': {
            'Meta': {'object_name': 'Location'},
            'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'primary_key': 'True'}),
            'total': ('django.db.models.fields.IntegerField', [], {'default': '0'})
        },
        u'people.project': {
            'Meta': {'object_name': 'Project'},
            'created_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'forked': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'forks': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'parent_url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'repo_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'service': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '30', 'blank': 'True'}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
            'url': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'watchers': ('django.db.models.fields.IntegerField', [], {'default': '0'})
        },
        u'people.team': {
            'Meta': {'object_name': 'Team'},
            'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'primary_key': 'True'}),
            'total': ('django.db.models.fields.IntegerField', [], {'default': '0'})
        }
    }

    complete_apps = ['people']


text:
<?php

namespace Magento\Framework\View\Design\Theme;

/**
 * Class Validator
 */
class Validator
{
    /**
     * Validators list by data key
     * array('dataKey' => array('validator_name' => [validators], ...), ...)
     *
     * @var array
     */
    protected $_dataValidators = [];

    /**
     * List of errors after validation process
     * array('dataKey' => 'Error message')
     *
     * @var array
     */
    protected $_errorMessages;

    /**
     * Initialize validators
     */
    public function __construct()
    {
        $this->_setTypeValidators();
        $this->_setTitleValidators();
    }

    /**
     * Set title validators
     *
     * @return $this
     */
    protected function _setTitleValidators()
    {
        $titleValidators = [
            [
                'name' => 'not_empty',
                'class' => 'Zend_Validate_NotEmpty',
                'break' => true,
                'options' => [],
                'message' => (string)new \Magento\Framework\Phrase('Field title can\'t be empty'),
            ],
        ];

        $this->addDataValidators('theme_title', $titleValidators);
        return $this;
    }

    /**
     * Set theme type validators
     *
     * @return $this
     */
    protected function _setTypeValidators()
    {
        $typeValidators = [
            [
                'name' => 'not_empty',
                'class' => 'Zend_Validate_NotEmpty',
                'break' => true,
                'options' => [],
                'message' => (string)new \Magento\Framework\Phrase('Theme type can\'t be empty'),
            ],
            [
                'name' => 'available',
                'class' => 'Zend_Validate_InArray',
                'break' => true,
                'options' => [
                    'haystack' => [
                        \Magento\Framework\View\Design\ThemeInterface::TYPE_PHYSICAL,
                        \Magento\Framework\View\Design\ThemeInterface::TYPE_VIRTUAL,
                        \Magento\Framework\View\Design\ThemeInterface::TYPE_STAGING,
                    ],
                ],
                'message' => (string)new \Magento\Framework\Phrase('Theme type is invalid')
            ],
        ];

        $this->addDataValidators('type', $typeValidators);

        return $this;
    }

    /**
     * Add validators
     *
     * @param string $dataKey
     * @param array $validators
     * @return $this
     */
    public function addDataValidators($dataKey, $validators)
    {
        if (!isset($this->_dataValidators[$dataKey])) {
            $this->_dataValidators[$dataKey] = [];
        }
        foreach ($validators as $validator) {
            $this->_dataValidators[$dataKey][$validator['name']] = $validator;
        }
        return $this;
    }

    /**
     * Return error messages for items
     *
     * @param string|null $dataKey
     * @return array
     */
    public function getErrorMessages($dataKey = null)
    {
        if ($dataKey) {
            return isset($this->_errorMessages[$dataKey]) ? $this->_errorMessages[$dataKey] : [];
        }
        return $this->_errorMessages;
    }

    /**
     * Instantiate class validator
     *
     * @param array &$validators
     * @return $this
     */
    protected function _instantiateValidators(array &$validators)
    {
        foreach ($validators as &$validator) {
            if (is_string($validator['class'])) {
                $validator['class'] = new $validator['class']($validator['options']);
                $validator['class']->setDisableTranslator(true);
            }
        }
        return $this;
    }

    /**
     * Validate one data item
     *
     * @param array $validator
     * @param string $dataKey
     * @param mixed $dataValue
     * @return bool
     */
    protected function _validateDataItem($validator, $dataKey, $dataValue)
    {
        if ($validator['class'] instanceof \Zend_Validate_NotEmpty && !$validator['class']->isValid(
            $dataValue
        ) || !empty($dataValue) && !$validator['class']->isValid(
            $dataValue
        )
        ) {
            $this->_errorMessages[$dataKey][] = $validator['message'];
            if ($validator['break']) {
                return false;
            }
        }
        return true;
    }

    /**
     * Validate all data items
     *
     * @param \Magento\Framework\DataObject $data
     * @return bool
     */
    public function validate(\Magento\Framework\DataObject $data)
    {
        $this->_errorMessages = [];
        foreach ($this->_dataValidators as $dataKey => $validators) {
            if (!isset($data[$dataKey])) {
                continue;
            }

            $this->_instantiateValidators($validators);
            foreach ($validators as $validator) {
                if (!$this->_validateDataItem($validator, $dataKey, $data[$dataKey])) {
                    break;
                }
            }
        }
        return empty($this->_errorMessages);
    }
}


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

    用户名
    {{current_user.email}}

    <form action="{{ url_for('user_update') }}" method=post>

            昵称
            <input type=text name=nickname id=nickname value={{current_user.nickname}}>

            新密码
            <input type=password name=password id=password>

        <input type=submit value=更新>
    </form>

    {% if live_info %}

        <form action="{{ url_for('live_update') }}" method=post>
            <input type="hidden" name="activity_id" value="{{ live_info['activityId'] }}">

                创建时间:{{ live_info['createTime'] }}

                结束时间:{{ live_info['endTime']}}

                直播名称:
                <input type=text name=activity_name id=activity_name value="{{ live_info['activityName'] }}">

                直播简介:
                <textarea name=description rows="4" cols="40" id=description>{{ live_info['description'] }}</textarea>

            清晰度:
            <input type="checkbox" name=code_rate_types value="16">高清
            <input type="checkbox" name=code_rate_types value="19">超清
            <input type="checkbox" name=code_rate_types value="22">720P
            <input type="checkbox" name=code_rate_types value="25">1080P
            <input type="checkbox" name=code_rate_types value="99">原画

                延长直播时间:
                <input type="radio" name='add_live_time' id='add_live_time' >

            <input type="submit" value="更新直播信息">
        </form>

        <button id="get-live-stream">获取直播推流信息</button>

直播推流软件下载:OBS Studio

        FMS URL<input type="text" name='fmsurl' id='fmsurl'>
        播放路径<input type="text" name='fmspath' id='fmspath'>

        <form action="{{ url_for('live_cancel') }}" method=post>
            <input type="hidden" name="live_id" value="{{ live_info['liveId'] }}">
            <input type="hidden" name="activity_id" value="{{ live_info['activityId'] }}">
            <input type="submit" name=cancel_live value="删除直播">
        </form>

    {% else %} {% if current_user.is_passed() %}
    <form action="{{ url_for('live_create') }}" method=post>

            直播名称:
            <input type=text name=activity_name id=activity_name required>

            直播简介:
            <textarea name=description rows="4" cols="40" id=description required></textarea>

        清晰度:
        <input type="checkbox" name=code_rate_types value="16">高清
        <input type="checkbox" name=code_rate_types value="19">超清
        <input type="checkbox" name=code_rate_types value="22">720P
        <input type="checkbox" name=code_rate_types value="25">1080P
        <input type="checkbox" name=code_rate_types value="99">原画
        <input type="submit" name=create_live value="开始直播!">
    </form>
    {% else %}

你的账户还没审核

请联系WayJam

    {% endif %} {% endif %}

{% endblock %}


text:
package org.leibnizcenter.rechtspraak.markup.docs;

import org.leibnizcenter.rechtspraak.TrainWithMallet;

import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.util.List;

/**
 * Created by maarten on 22-3-16.
 */
public class RandomDocs {
    private static final int INT = 20;

    public static void main(String[] args) throws ParserConfigurationException {
        List<File> xmlFiles = RechtspraakCorpus.listXmlFiles(TrainWithMallet.xmlFiles, 500, true);
        for (File f : xmlFiles) {
            System.out.println(
                    "file://" +
                            f.getAbsolutePath());
        }
        for (LabeledTokenList doc : new LabeledTokenList.FileIterable(new LabeledTokenList.FileIteratorFromXmlStructure(xmlFiles))) {
            for (LabeledToken token : doc) {
                String text = token.getToken().normalizedText;
            }
        }
    }
}


text:
package de.otto.wickettester;

import org.apache.wicket.Component;

public class NegatingComponentMatcher<T extends Component> implements ComponentMatcher<T, T> {

    private final ComponentMatcher<T, T> matcher;

    public NegatingComponentMatcher(final ComponentMatcher<T, T> matcher) {
        this.matcher = matcher;
    }

    @Override
    public T match(final T component) {
        return matcher.match(component) != null ? null : component;
    }

    @Override
    public String criterionAsString() {
        return "not " + matcher.criterionAsString();
    }
}


text:
package com.github.games647.tabchannels.listener;

import com.github.games647.tabchannels.Channel;
import com.github.games647.tabchannels.Subscriber;
import com.github.games647.tabchannels.TabChannels;

import java.util.UUID;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;

public class ChatListener implements Listener {

    private final TabChannels plugin;

    public ChatListener(TabChannels plugin) {
        this.plugin = plugin;
    }

    //listen to the highest priority in order to let other plugins interpret it as successfull event
    @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
    public void onPlayerChat(AsyncPlayerChatEvent playerChatEvent) {
        Player sender = playerChatEvent.getPlayer();
        String message = playerChatEvent.getMessage();
        String format = playerChatEvent.getFormat();
        String chatMessage = String.format(format, sender.getDisplayName(), message);

        Subscriber subscriber = plugin.getSubscribers().get(sender.getUniqueId());
        Channel messageChannel = subscriber.getCurrentChannel();
        messageChannel.addMessage(chatMessage);

        notifyChanges(messageChannel);

        //remove the recipients from normal chats without hiding log messages
        playerChatEvent.getRecipients().clear();
    }

    @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
    public void onJoin(PlayerJoinEvent joinEvent) {
        Player player = joinEvent.getPlayer();
        String joinMessage = joinEvent.getJoinMessage();

        if (joinMessage != null && !joinMessage.isEmpty()) {
            Subscriber subscriber = plugin.getSubscribers().get(player.getUniqueId());
            for (Channel messageChannel : subscriber.getSubscriptions()) {
                messageChannel.addMessage(joinMessage);

                notifyChanges(messageChannel);
            }

            joinEvent.setJoinMessage("");
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onQuit(PlayerQuitEvent quitEvent) {
        Player player = quitEvent.getPlayer();
        String quitMessage = quitEvent.getQuitMessage();

        if (quitMessage != null && !quitMessage.isEmpty()) {
            Subscriber subscriber = plugin.getSubscribers().get(player.getUniqueId());
            for (Channel messageChannel : subscriber.getSubscriptions()) {
                messageChannel.addMessage(quitMessage);

                notifyChanges(messageChannel);
            }

            quitEvent.setQuitMessage("");
        }
    }

    private void notifyChanges(Channel messageChannel) {
        for (UUID recipient : messageChannel.getRecipients()) {
            Subscriber receiver = plugin.getSubscribers().get(recipient);
            if (receiver != null) {
                onNewMessage(recipient, receiver, messageChannel);
            }
        }
    }

    private void onNewMessage(UUID recipient, Subscriber receiver, Channel messageChannel) {
        Player recipientPlayer = Bukkit.getPlayer(recipient);

        receiver.notifyNewMessage(messageChannel);
        Channel subscriberUsedChannel = receiver.getCurrentChannel();

        recipientPlayer.spigot().sendMessage(messageChannel.getHeader(messageChannel.getName(recipient)));
        recipientPlayer.spigot().sendMessage(subscriberUsedChannel.getContent());
        recipientPlayer.spigot().sendMessage(receiver.getChannelSelection());
    }
}


text:
"""
Page elements for basic form widgets.

Author: pnovotny
"""

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

from webstr.selenium.ui import forms
from webstr.core import PageElement, BaseWebElementHelper

class Checkbox(PageElement):
    """
    Page element for a checkbox widget.
    """
    _helper = forms.Checkbox

class BaseRadio(BaseWebElementHelper):
    """
    Web element wrapper for a radio widget
    """

    @property
    def value(self):
        """
        Getter method returns if radio button is selected
        """
        return self.is_selected()

    @value.setter
    def value(self, value):
        """
        Setter method for handling the widget when using value assignment.

        Parameters:
            value:
                value used in assignment
                options: True expression - select radio; otherwise do nothing
        """
        if value == True:
            self.click()

class Radio(PageElement):
    """
    Page element for a radio widget.
    """
    _helper = BaseRadio

class Button(PageElement):
    """
    Page element for a GWT button widget.
    """

class Select(PageElement):
    """
    Page element for a select box widget.
    """
    _helper = forms.Select

class BaseTextInput(BaseWebElementHelper):
    """
    Web element wrapper for a text input widget.
    """
    @property
    def value(self):
        """
        Getter method returns current text of the element
        """
        return self.get_attribute("value")

    @value.setter
    def value(self, value):
        """
        Setter method for handling the widget when using value assignment.

        Parameters:
            element: Selenium <WebElement> instance
            value: value used in assignment
        """
        self.clear()
        self.send_keys(value)

class TextInput(PageElement):
    """
    Page element for a text input widget.
    """
    _helper = BaseTextInput

PasswordInput = TextInput

TextArea = TextInput

class BaseComboBox(BaseWebElementHelper):
    """
    Web element wrapper for a combo-box widget.

    Class attributes:
        _KEY_ENTER (unicode):
            Enter key representation
            The Selenium's `Keys.ENTER` could not be used because the widget
            didn't react to it, so the classic sequence CRLF was used.
    """
    _KEY_ENTER = u'\r\n'

    @property
    def value(self):
        """
        Getter method returns current text of the element
        """
        return self.text

    @value.setter
    def value(self, value):
        """
        Setter method for handling the widget when using value assignment.
        The value is actually assigned to the inner INPUT element.

        Parameters:
            value (str): value to be assigned
        """
        input_elem = self.find_element_by_tag_name('input')
        input_elem.clear()
        input_elem.send_keys(value)
        input_elem.send_keys(self._KEY_ENTER)

class ComboBox(PageElement):
    """
    Page element for a combo-box widget.
    """
    _helper = BaseComboBox

class DynamicCheckbox(Checkbox):
    """
    Page element for a dynamic checkbox widget.
    """
    _is_dynamic = True

class DynamicRadio(Radio):
    """
    Page element for a dynamic radio widget.
    """
    _is_dynamic = True

class DynamicButton(Button):
    """
    Page element for a dynamic GWT button widget.
    """
    _is_dynamic = True

class DynamicSelect(Select):
    """
    Page element for a dynamic select box widget.
    """
    _is_dynamic = True

class DynamicTextInput(TextInput):
    """
    Page element for a dynamic text input widget.
    """
    _is_dynamic = True

DynamicPasswordInput = DynamicTextInput


text:
typedef struct
{
	unsigned int seg_length0_15	: 16;
	unsigned int base_addr0_15	: 16;
	unsigned int base_addr16_23	:  8;
	unsigned int flags			:  8;
	unsigned int type			:  8;
	unsigned int base_addr24_31	:  8;
} __attribute__ ((packed)) segment_descriptor;

#define GDT_SYSTEMCODE	8
#define GDT_SYSTEMDATA	16
#define GDT_USERCODE	24
#define GDT_USERDATA	32

#define MAX_GDT			256

#include <inttypes.h>

void init_gdt();
uint32_t gdt_get_offset( unsigned int cpu_id, unsigned int entry );
int gdt_new_segment( unsigned int id, uint32_t base,
					  uint32_t length,
					  uint8_t flags,
					  uint8_t type,
					  uint32_t access);

int load_gdt( unsigned int cpu_id );

#endif


text:
package com.kcwdev.downloader;

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

import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.kroll.common.TiMessenger;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.util.Log;
import org.appcelerator.titanium.util.TiConfig;
import org.appcelerator.titanium.util.TiConvert;
import org.json.JSONArray;

import android.os.Handler;
import android.os.Message;

@Kroll.module(name="Downloader", id="com.kcwdev.downloader")
public class DownloaderModule extends KrollModule
{

	// Standard Debugging variables
	private static final String LCAT = "DownloaderModule";
	private static final boolean DBG = TiConfig.LOGD;

	private ProgressiveDownloader downloader;
	private DownloaderModule self;

	public static final String EVENT_PROGRESS = "progress";
	public static final String EVENT_PAUSED = "paused";
	public static final String EVENT_FAILED = "failed";
	public static final String EVENT_COMPLETED = "completed";
	public static final String EVENT_CANCELLED = "cancelled";
	public static final String EVENT_STARTED = "started";
	public static final String EVENT_BATCHPAUSED = "batchpaused";
	public static final String EVENT_BATCHFAILED = "batchfailed";
	public static final String EVENT_BATCHCOMPLETED = "batchcompleted";
	public static final String EVENT_BATCHCANCELLED = "batchcancelled";

	@Kroll.constant public static final int NETWORK_TYPE_WIFI = 0;
	@Kroll.constant public static final int NETWORK_TYPE_MOBILE = 1;
	@Kroll.constant public static final int NETWORK_TYPE_ANY = 2;

	@Kroll.constant public static final int DOWNLOAD_PRIORITY_LOW = 1;
	@Kroll.constant public static final int DOWNLOAD_PRIORITY_NORMAL = 2;
	@Kroll.constant public static final int DOWNLOAD_PRIORITY_HIGH = 3;

	// You can define constants with @Kroll.constant, for example:
	// @Kroll.constant public static final String EXTERNAL_NAME = value;

	public DownloaderModule() {
		super("Downloader");
		downloader = new ProgressiveDownloader(TiApplication.getAppRootOrCurrentActivity());
		downloader.setMaximumSimultaneousDownloads(2);
		downloader.DownloadProgress.addListener(new ProgressListener());
		downloader.DownloadPaused.addListener(new PausedListener());
		downloader.DownloadFailed.addListener(new FailedListener());
		downloader.DownloadCompleted.addListener(new CompletedListener());
		downloader.DownloadCancelled.addListener(new CancelledListener());
		downloader.DownloadStarted.addListener(new StartedListener());
		downloader.DownloadBatchPaused.addListener(new BatchPausedListener());
		downloader.DownloadBatchFailed.addListener(new BatchFailedListener());
		downloader.DownloadBatchCompleted.addListener(new BatchCompletedListener());
		downloader.DownloadBatchCancelled.addListener(new BatchCancelledListener());

		this.self = this;
	}

//	private static final int MSG_FIRE_PROGRESS = 70000;
//	private static final int MSG_FIRE_PAUSED = 70001;
//	private static final int MSG_FIRE_FAILED = 70002;
//	private static final int MSG_FIRE_COMPLETED = 70003;
//	private static final int MSG_FIRE_CANCELLED = 70004;
//	private final Handler handler = new Handler(TiApplication.getInstance().getMainLooper(), new Handler.Callback() {
//
//		@Override
//		public boolean handleMessage(Message msg) {
//			// TODO Auto-generated method stub
//
//			String eventToFire = "";
//			if (msg.what == MSG_FIRE_PROGRESS)
//			{
//				eventToFire = EVENT_PROGRESS;
//			}
//			else if (msg.what == MSG_FIRE_PAUSED)
//			{
//				eventToFire = EVENT_PAUSED;
//			}
//			else if (msg.what == MSG_FIRE_FAILED)
//			{
//				eventToFire = EVENT_FAILED;
//			}
//			else if (msg.what == MSG_FIRE_COMPLETED)
//			{
//				eventToFire = EVENT_COMPLETED;
//			}
//			else if (msg.what == MSG_FIRE_CANCELLED)
//			{
//				eventToFire = EVENT_CANCELLED;
//			}
//
//			if (eventToFire.length() > 0)
//			{
//				self.fireEvent(eventToFire, msg.obj);
//				return true;
//			}
//
//
//			return false;
//		}
//	});

	class ProgressListener implements IListener<DownloadEvent>
	{
		@Override
		public void handleEvent(DownloadEvent event) {
			// Log.d(LCAT, "Download Progress " + event.getDownloadInformation().getAvailableLength() + "/" + event.getDownloadInformation().getLength());
			KrollDict dict = createDict(event.getDownloadInformation());
			self.fireEvent(EVENT_PROGRESS, dict);
			//TiMessenger.sendBlockingMainMessage(handler.obtainMessage(MSG_FIRE_PROGRESS, dict));
		}
	}
	class PausedListener implements IListener<DownloadEvent>
	{
		@Override
		public void handleEvent(DownloadEvent event) {
			// TODO Auto-generated method stub
			Log.d(LCAT, "Download Paused ");
			KrollDict dict = createDict(event.getDownloadInformation());
			self.fireEvent(EVENT_PAUSED, dict);
			//TiMessenger.sendBlockingMainMessage(handler.obtainMessage(MSG_FIRE_PAUSED, dict));
		}
	}
	class FailedListener implements IListener<DownloadEvent>
	{
		@Override
		public void handleEvent(DownloadEvent event) {
			// TODO Auto-generated method stub
			Log.d(LCAT, "Download Failed ");
			KrollDict dict = createDict(event.getDownloadInformation());
			self.fireEvent(EVENT_FAILED, dict);
			//TiMessenger.sendBlockingMainMessage(handler.obtainMessage(MSG_FIRE_FAILED, dict));
		}
	}
	class CompletedListener implements IListener<DownloadEvent>
	{
		@Override
		public void handleEvent(DownloadEvent event) {
			// TODO Auto-generated method stub
			Log.d(LCAT, "Download Completed ");
			KrollDict dict = createDict(event.getDownloadInformation());
			self.fireEvent(EVENT_COMPLETED, dict);
			//TiMessenger.sendBlockingMainMessage(handler.obtainMessage(MSG_FIRE_COMPLETED, dict));
		}
	}
	class CancelledListener implements IListener<DownloadEvent>
	{
		@Override
		public void handleEvent(DownloadEvent event) {
			// TODO Auto-generated method stub
			Log.d(LCAT, "Download Cancelled ");
			KrollDict dict = createDict(event.getDownloadInformation());
			self.fireEvent(EVENT_CANCELLED, dict);
			//TiMessenger.sendBlockingMainMessage(handler.obtainMessage(MSG_FIRE_CANCELLED, dict));
		}
	}

	class StartedListener implements IListener<DownloadEvent>
	{
		@Override
		public void handleEvent(DownloadEvent event) {
			// TODO Auto-generated method stub
			Log.d(LCAT, "Download Started ");
			KrollDict dict = createDict(event.getDownloadInformation());
			dict.put("reason", event.getDownloadInformation().getMessage());
			self.fireEvent(EVENT_CANCELLED, dict);
			//TiMessenger.sendBlockingMainMessage(handler.obtainMessage(MSG_FIRE_CANCELLED, dict));
		}
	}

	class BatchPausedListener implements IListener<DownloadEvent>
	{
		@Override
		public void handleEvent(DownloadEvent event) {
			// TODO Auto-generated method stub
			//Log.d(LCAT, "Download Batch Paused ");
		}
	}
	class BatchFailedListener implements IListener<DownloadEvent>
	{
		@Override
		public void handleEvent(DownloadEvent event) {
			// TODO Auto-generated method stub
			//Log.d(LCAT, "Download Batch Failed ");
		}
	}
	class BatchCompletedListener implements IListener<DownloadEvent>
	{
		@Override
		public void handleEvent(DownloadEvent event) {
			// TODO Auto-generated method stub
			//Log.d(LCAT, "Download Batch Completed ");
		}
	}
	class BatchCancelledListener implements IListener<DownloadEvent>
	{
		@Override
		public void handleEvent(DownloadEvent event) {
			// TODO Auto-generated method stub
			//Log.d(LCAT, "Download Batch Cancelled ");
		}
	}

	@Kroll.getProperty
	public int getMaximumSimultaneousDownloads() {
		return downloader.getMaximumSimultaneousDownloads();
	}

	@Kroll.setProperty @Kroll.method
	public void setMaximumSimultaneousDownloads(int count) {
		downloader.setMaximumSimultaneousDownloads(count);
	}

	@Kroll.getProperty
	public int getPermittedNetworkTypes() {
		EnumSet<NetworkTypes> types = downloader.getPermittedNetworkTypes();
		if (types.containsAll(NetworkTypes.Any)) {
			return NETWORK_TYPE_ANY;
		} else if (types.containsAll(NetworkTypes.Mobile)) {
			return NETWORK_TYPE_MOBILE;
		} else if (types.contains(NetworkTypes.Wireless80211)) {
			return NETWORK_TYPE_WIFI;
		}

		return -1;
	}

	@Kroll.setProperty @Kroll.method
	public void setPermittedNetworkTypes(int type) {
		if (type == NETWORK_TYPE_ANY) {
			downloader.setPermittedNetworkTypes(NetworkTypes.Any);
		} else if (type == NETWORK_TYPE_WIFI) {
			downloader.setPermittedNetworkTypes(EnumSet.of(NetworkTypes.Wireless80211));
		} else if (type == NETWORK_TYPE_MOBILE) {
			downloader.setPermittedNetworkTypes(NetworkTypes.Mobile);
		}
	}
	// Methods
	@Kroll.method
	public void addDownload(KrollDict dict) {
		DownloadRequest request = new DownloadRequest();
		request.setUrl(TiConvert.toString(dict, "url"));
		request.setName(TiConvert.toString(dict, "name"));
		request.setLocale("eng");
		request.setFileName(TiConvert.toString(dict, "filePath"));

		int priority = 0;
		if (dict.containsKey("priority")) {
			priority = TiConvert.toInt(dict, "priority");
		}
		switch(priority) {
			case 1:  request.setDownloadPriority(DownloadPriority.Low); break;
			case 3:  request.setDownloadPriority(DownloadPriority.High); break;
			default: request.setDownloadPriority(DownloadPriority.Normal); break;
		}

		downloader.download(request);
	}

	@Kroll.method
	public void pauseAll() {
		downloader.pause();
	}

	@Kroll.method
	public void pauseItem(String url) {
		downloader.pause(url);
	}

	@Kroll.method
	public void resumeAll() {
		downloader.resume();
	}

	@Kroll.method
	public void resumeItem(String url) {
		downloader.resume(url);
	}

	@Kroll.method
	public void cancelItem(String url) {
		downloader.cancel(url);
	}

	@Kroll.method
	public void stopDownloader() {
		downloader.stop();
	}

	@Kroll.method
	public void restartDownloader() {
		downloader.start();
	}

	@Kroll.method
	public void deleteItem(String url) {
		downloader.delete(url);
	}

	@Kroll.method
	public KrollDict getDownloadInfo(String url) {

		DownloadInformation di = downloader.getDownloadInformation(url);
		if (di == null)
		{
			return null;
		}

		return createDict(di);
	}

	@Kroll.method
	public KrollDict[] getAllDownloadInfo() {
		ArrayList<KrollDict> list = new ArrayList<KrollDict>();
		for (DownloadInformation di : downloader.getDownloadInformation()) {
			list.add(createDict(di));
		}

		KrollDict[] array = new KrollDict[0];

		return list.toArray(array);
	}

	private KrollDict createDict(DownloadInformation di) {
		KrollDict dict = new KrollDict();
		dict.put("name", di.getName());
		dict.put("url", di.getUrl());
		dict.put("downloadedBytes", di.getAvailableLength());
		dict.put("totalBytes", di.getLength());
		dict.put("bps", di.getLastDownloadBitsPerSecond());
		dict.put("filePath", di.getFilePath());
		dict.put("createdDate", di.getCreationUtc());
		dict.put("priority", di.getDownloadPriority().getValue());
		return dict;
	}
}


text:
import Boom from 'boom';
module.exports = function handleESError(error) {
  if (!(error instanceof Error)) {
    throw new Error('Expected an instance of Error');
  }

  if (error.status) {
    return Boom.boomify(error, { statusCode: error.status });
  } else {
    return Boom.badImplementation(error.message || 'Internal Server Error');
  }
};


text:
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 * Card Description:
 * Soccer Goalie
 * Play in George Allen Field
 * Prerequisites:
 * 3 learning pts
 * 3 craft pts
 * Success:
 * Get 5 quality pts
 * Get 1 game card
 * Fail: Go to student parking
 * @author Hieu Tran
 *
 */

public class Card30 extends Card {

	public Card30() {
		name = "Soccer Goalie";
		//Required 3 learning pts, 3 craft pts
		checkReqPts = true;
		reqLearningPts = 3;
		reqCraftPts = 3;
		//Play in George Allen Field
		checkReqLoc = true;
		reqLocation.add(0);
		//initialize image
		try {
			img = ImageIO.read(new File("img/card30.png"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 *
	 */
	/*@Override
	public Player play(Player player) {
		//boolean flag identifying if the play successes or fail
		boolean result = false;
		//points and location validation: this determine if the play is successes
		//or fail
		if(checkReqPts) {
			result = validatePts(player);
		}
		if(checkReqLoc) {
			result = validateLoc(player);
		}
		//calling win() or fail() method base on "result"
		if(result) {
			return win(player);
		}
		else {
			return fail(player);
		}
	}*/

	@Override
	//Success: Get 5 quality pts, 1 game card
	public Player win(Player player) {
		player.updateQP(5);
		//player.updateGameCard(1);
		return player;
	}

	@Override
	//Fail: Go to student parking
	public Player fail(Player player) {
		player.setLoc(2);
		return player;
	}
}


text:
@protocol UIChannelPickerViewDelegate;
@protocol UIChannelPickerViewDataSource;

@interface UIChannelPickerView : UIView <UIScrollViewDelegate>

@property(strong, nonatomic) UIFont *itemFont;

@property(strong, nonatomic) UIFont *selectedItemFont;

@property(strong, nonatomic) UIColor *itemColor;

@property(strong, nonatomic) UIImage *splitImage;

@property(nonatomic) NSUInteger selectedIndex;

@property(nonatomic) UIEdgeInsets insets;

@property(weak, nonatomic) id <UIChannelPickerViewDelegate> delegate;

@property(weak, nonatomic) id <UIChannelPickerViewDataSource> dataSource;

- (void)setSelectedIndex:(NSUInteger)selectedIndex animated:(BOOL)animated;

- (void)reloadData;

@end

@protocol UIChannelPickerViewDelegate <NSObject>

- (void)pickerViewDidSelectItem:(NSUInteger) index;

@end

@protocol UIChannelPickerViewDataSource <NSObject>

- (NSUInteger)pickerViewNumberOfPickItems;

- (NSString *)pickerViewTitleForPickItem:(NSUInteger) index;

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cassandra.Data.Linq;
using Cassandra.IntegrationTests.Linq.Structures;
using Cassandra.IntegrationTests.TestBase;
using Cassandra.Mapping;
using NUnit.Framework;
#pragma warning disable 612

namespace Cassandra.IntegrationTests.Linq.LinqMethods
{
    [Category("short"), Category("realcluster")]
    public class OrderBy : SharedClusterTest
    {
        ISession _session = null;
        private List<Movie> _movieList = Movie.GetDefaultMovieList();
        string _uniqueKsName = TestUtils.GetUniqueKeyspaceName();
        private Table<Movie> _movieTable;

        public override void OneTimeSetUp()
        {
            base.OneTimeSetUp();
            _session = Session;
            _session.CreateKeyspace(_uniqueKsName);
            _session.ChangeKeyspace(_uniqueKsName);

            // drop table if exists, re-create
            MappingConfiguration movieMappingConfig = new MappingConfiguration();
            movieMappingConfig.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(Movie),
                 () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(Movie)));
            _movieTable = new Table<Movie>(_session, movieMappingConfig);
            _movieTable.Create();

            //Insert some data
            foreach (var movie in _movieList)
                _movieTable.Insert(movie).Execute();
        }

        [Test]
        public void LinqOrderBy()
        {
            List<Movie> moreMovies = new List<Movie>();
            string sameTitle = "sameTitle";
            string sameMovieMaker = "sameMovieMaker";
            for (int i = 0; i < 10; i++)
            {
                Movie movie = Movie.GetRandomMovie();
                movie.Title = sameTitle;
                movie.MovieMaker = sameMovieMaker;
                moreMovies.Add(movie);
                _movieTable.Insert(movie).Execute();
            }

            var movieQuery = _movieTable.Where(m => m.Title == sameTitle && m.MovieMaker == sameMovieMaker);

            List<Movie> actualOrderedMovieList = movieQuery.Execute().ToList();
            List<Movie> expectedOrderedMovieList = moreMovies.OrderBy(m => m.Director).ToList();
            Assert.AreEqual(expectedOrderedMovieList.Count, actualOrderedMovieList.Count);
            for (int i = 0; i < expectedOrderedMovieList.Count; i++)
            {
                Assert.AreEqual(expectedOrderedMovieList[i].Director, actualOrderedMovieList[i].Director);
                Assert.AreEqual(expectedOrderedMovieList[i].MainActor, actualOrderedMovieList[i].MainActor);
                Assert.AreEqual(expectedOrderedMovieList[i].MovieMaker, actualOrderedMovieList[i].MovieMaker);
            }
        }

        [Test]
        public void LinqOrderBy_Unrestricted_Sync()
        {
            try
            {
                _movieTable.OrderBy(m => m.MainActor).Execute();
                Assert.Fail("Expected Exception was not thrown!");
            }
            catch (InvalidQueryException e)
            {
                Assert.AreEqual("ORDER BY is only supported when the partition key is restricted by an EQ or an IN.", e.Message);
            }
        }

        [Test]
        public void LinqOrderBy_Unrestricted_Async()
        {
            var ex = Assert.ThrowsAsync<InvalidQueryException>(
                async () => await _movieTable.OrderBy(m => m.MainActor).ExecuteAsync().ConfigureAwait(false));
            const string expectedException = "ORDER BY is only supported when the partition key is restricted by an EQ or an IN.";
            Assert.AreEqual(expectedException, ex.Message);
        }

    }
}


text:
'''
PMInfo Python implementation
'''

#
# Copyright (C) 2014 Red Hat.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#

# Our buildbot does not have the pcp libraries installed and most likely
# will never have them since this runs in a container.
# pylint: disable=import-error
from pcp import pmapi
import re
import os
import time
import multiprocessing

class PMInfo(object):
    """ Looks up values from pcp through the pmapi.
    """

    def __init__(self):
        """ Construct object - prepare for command line handling """
        self.context = None
        self.metrics = []

    def extract_value(self, valfmt, vlist, typ):
        '''
        Perform the extract and return an atom
        '''
        atom = self.context.pmExtractValue(valfmt, vlist, typ, typ)
        return atom.dref(typ)

    def get_value(self, metrics):
        '''Receive a list of metrics and query pcp
           libs for descriptions and values
        '''
        rval = {}
        pmids = self.context.pmLookupName(metrics)
        descs = self.context.pmLookupDescs(pmids)
        results = self.context.pmFetch(pmids)

        for i in range(results.contents.numpmid):
            num_vals = results.contents.get_numval(i)
            m_name = None
            # if num_vals is > 1 we have multiple instances returned
            # query for the names so we can generate the keys
            if num_vals > 1:
                m_name = metrics[i] + '.'
                text_descs = self.context.pmGetInDom(descs[i])
            else:
                m_name = metrics[i]
            for j in range(num_vals):
                desc = ''
                try:
                    m_value = self.extract_value(results.contents.get_valfmt(i),
                                                 results.contents.get_vlist(i, j),
                                                 descs[i].contents.type)
                except pmapi.pmErr:
                    #Impossible value or scale conversion
                    rval[m_name] = m_value
                    continue

                if num_vals > 1:
                    desc = re.sub(' ', '_', text_descs[1][j])

                rval[m_name + desc] = m_value
        return rval

    def get_children(self, root_string=''):
        ''' Return all metrics
        '''
        status = self.context.pmGetChildrenStatus(root_string)

        # Status on leaf nodes is (None,None)
        if not status[0]:
            self.metrics.append(root_string)
            return

        zipped_status = zip(status[0], status[1])
        for child in zipped_status:
            if root_string != '':
                child_name = root_string + "." + child[0]
            else:
                child_name = child[0]

            if child[1] == 0:
                self.metrics.append(child_name)
            else:
                self.get_children(child_name)

    def register_derived_metric(self, derived_metrics):
        """ This function registers the derived function name and expression """

        for dmetric, dexpression in derived_metrics.iteritems():
            self.context.pmRegisterDerived(dmetric, dexpression)

    def execute(self, metrics=None):
        """ Using a PMAPI context (could be either host or archive),
            fetch and show all of the values
        """
        if not metrics:
            self.get_children()
        else:
            for metric in metrics:
                self.get_children(metric)
        return self.get_value(self.metrics)

    def connect(self):
        """ Establish a PMAPI context to archive, host or local, via args """
        self.context = pmapi.pmContext()

def calculate_percent_cpu(start, end, interval):
    ''' Calculate the percent of cpu utilization from sample1 and sample2.
        Requires:
          start
          end
          interval
    '''
    num_cpu = multiprocessing.cpu_count()
    jiffy = os.sysconf(os.sysconf_names['SC_CLK_TCK'])
    return ((end - start) * 100 / (float(jiffy) * interval)) / (num_cpu * 10)

def get_sampled_data(metrics, interval, count=1):
    '''Recieve a list of metrics, a time interval, and a count.
       Sample the metrics based on an interval for count number of times.
    '''
    if not metrics:
        return {}

    sampled_results = []
    for i in range(count):
        sampled_results.append(get_metrics(metrics))
        if i == count - 1:
            break
        time.sleep(interval)

    results = {}
    for m_key in sampled_results[0]:
        results[m_key] = [sample[m_key] for sample in sampled_results]

    return results

def get_metrics(metrics=None, derived_metrics=None):
    '''Get a list of metrics and query pcp for their values
    '''
    try:
        pcp = PMInfo()
        pcp.connect()

        if derived_metrics:
            pcp.register_derived_metric(derived_metrics)

            if not metrics:
                metrics = derived_metrics.keys()
            else:
                metrics += derived_metrics.keys()

        return pcp.execute(metrics)

    except pmapi.pmErr as error:
        print error.message()
    except pmapi.pmUsageErr as usage:
        usage.message()
    except KeyboardInterrupt:
        pass


text:
from setuptools import setup, Extension
import npmln

ext=Extension(
	'rc_semver',
	sources=['rc_semver.c'],
	extra_compile_args=['-O3','-std=c99','-Ofast','-Wall','-g0'],
	extra_link_args=['-s', '-g0'],
	language='c'
)

setup(
	name='npmln',
	author='S-YOU',
	author_email='S-YOU@users.noreply.github.com',
	version=npmln.__version__,
	description='Symlink NPM Modules',
	url='https://github.com/S-YOU/npmln',
	download_url='https://github.com/S-YOU/npmln/tarball/master',
	ext_modules=[ext],
	install_requires=['python-cjson'],
	py_modules=['npmln'],
	entry_points={
		"console_scripts": [
			"npmln=npmln:main"
		]
	}
)


text:
namespace {

content::WebUIDataSource* CreateInstantHTMLSource() {
  content::WebUIDataSource* source =
      content::WebUIDataSource::Create(chrome::kChromeUIInstantHost);
  source->SetJsonPath("strings.js");
  source->AddResourcePath("instant.js", IDR_INSTANT_JS);
  source->AddResourcePath("instant.css", IDR_INSTANT_CSS);
  source->SetDefaultResource(IDR_INSTANT_HTML);
  return source;
}

#if !defined(OS_ANDROID)
std::string FormatTime(int64_t time) {
  base::Time::Exploded exploded;
  base::Time::FromInternalValue(time).UTCExplode(&exploded);
  return base::StringPrintf("%04d-%02d-%02d %02d:%02d:%02d.%03d",
      exploded.year, exploded.month, exploded.day_of_month,
      exploded.hour, exploded.minute, exploded.second, exploded.millisecond);
}
#endif  // !defined(OS_ANDROID)

// This class receives JavaScript messages from the renderer.
// Note that the WebUI infrastructure runs on the UI thread, therefore all of
// this class's methods are expected to run on the UI thread.
class InstantUIMessageHandler
    : public content::WebUIMessageHandler,
      public base::SupportsWeakPtr<InstantUIMessageHandler> {
 public:
  InstantUIMessageHandler();
  ~InstantUIMessageHandler() override;

  // WebUIMessageHandler implementation.
  void RegisterMessages() override;

 private:
  void GetPreferenceValue(const base::ListValue* args);
  void SetPreferenceValue(const base::ListValue* args);
  void GetDebugInfo(const base::ListValue* value);
  void ClearDebugInfo(const base::ListValue* value);

  DISALLOW_COPY_AND_ASSIGN(InstantUIMessageHandler);
};

InstantUIMessageHandler::InstantUIMessageHandler() {}

InstantUIMessageHandler::~InstantUIMessageHandler() {}

void InstantUIMessageHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback(
      "getPreferenceValue",
      base::Bind(&InstantUIMessageHandler::GetPreferenceValue,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "setPreferenceValue",
      base::Bind(&InstantUIMessageHandler::SetPreferenceValue,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "getDebugInfo",
      base::Bind(&InstantUIMessageHandler::GetDebugInfo,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "clearDebugInfo",
      base::Bind(&InstantUIMessageHandler::ClearDebugInfo,
                 base::Unretained(this)));
}

void InstantUIMessageHandler::GetPreferenceValue(const base::ListValue* args) {
  std::string pref_name;
  if (!args->GetString(0, &pref_name)) return;

  base::StringValue pref_name_value(pref_name);
  if (pref_name == prefs::kInstantUIZeroSuggestUrlPrefix) {
    PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs();
    base::StringValue arg(prefs->GetString(pref_name.c_str()));
    web_ui()->CallJavascriptFunctionUnsafe(
        "instantConfig.getPreferenceValueResult", pref_name_value, arg);
  }
}

void InstantUIMessageHandler::SetPreferenceValue(const base::ListValue* args) {
  std::string pref_name;
  if (!args->GetString(0, &pref_name)) return;

  if (pref_name == prefs::kInstantUIZeroSuggestUrlPrefix) {
    std::string value;
    if (!args->GetString(1, &value))
      return;
    PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs();
    prefs->SetString(pref_name.c_str(), value);
  }
}

void InstantUIMessageHandler::GetDebugInfo(const base::ListValue* args) {
#if !defined(OS_ANDROID)
  typedef std::pair<int64_t, std::string> DebugEvent;

  if (!web_ui()->GetWebContents())
    return;
  Browser* browser = chrome::FindBrowserWithWebContents(
      web_ui()->GetWebContents());
  if (!browser || !browser->instant_controller())
    return;

  InstantController* instant = browser->instant_controller()->instant();
  const std::list<DebugEvent>& events = instant->debug_events();

  base::DictionaryValue data;
  base::ListValue* entries = new base::ListValue();
  for (std::list<DebugEvent>::const_iterator it = events.begin();
       it != events.end(); ++it) {
    std::unique_ptr<base::DictionaryValue> entry(new base::DictionaryValue());
    entry->SetString("time", FormatTime(it->first));
    entry->SetString("text", it->second);
    entries->Append(std::move(entry));
  }
  data.Set("entries", entries);

  web_ui()->CallJavascriptFunctionUnsafe("instantConfig.getDebugInfoResult",
                                         data);
#endif
}

void InstantUIMessageHandler::ClearDebugInfo(const base::ListValue* args) {
#if !defined(OS_ANDROID)
  if (!web_ui()->GetWebContents())
    return;
  Browser* browser = chrome::FindBrowserWithWebContents(
      web_ui()->GetWebContents());
  if (!browser || !browser->instant_controller())
    return;

  browser->instant_controller()->instant()->ClearDebugEvents();
#endif
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// InstantUI

InstantUI::InstantUI(content::WebUI* web_ui) : WebUIController(web_ui) {
  web_ui->AddMessageHandler(base::MakeUnique<InstantUIMessageHandler>());

  // Set up the chrome://instant/ source.
  Profile* profile = Profile::FromWebUI(web_ui);
  content::WebUIDataSource::Add(profile, CreateInstantHTMLSource());
}

// static
void InstantUI::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterStringPref(prefs::kInstantUIZeroSuggestUrlPrefix,
                               std::string());
}


text: """Experiments configuration."""