text:
package com.baidu.cc.web.action;

import com.baidu.bjf.web.struts2.annotation.FromJSON;
import com.baidu.bjf.web.struts2.annotation.ToJSON;
import com.baidu.cc.web.action.EnvironmentDeleteActionBase.DataResult;
import com.baidu.lego.web.spi.EJsonDataResult;

import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

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

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

/**
 * 功能:删除环境.
 *
 * @author BJF
 * @param <ReqParam>
 *            request param
 * @param <DataResult>
 *            data return result
 */
@Namespace("/env")
@Results({ @Result(name = "success", type = "json")

})
public abstract class EnvironmentDeleteActionBase<ReqParam, DataResult>
        extends
        com.baidu.lego.web.struts2.DirectServiceVisitAction<ReqParam, DataResult> {

    /** serial Version UID. */
    private static final long serialVersionUID = 1L;

    /** request param. */
    @FromJSON(validationVisitor = EnvironmentDeleteAction.class)
    protected EnvironmentDeleteActionBase.ReqParam reqParam;

    /**
     * get request param.
     *
     * @return ReqParam
     */
    public EnvironmentDeleteActionBase.ReqParam getReqParam() {
        if (reqParam == null) {
            reqParam = new EnvironmentDeleteActionBase.ReqParam();
        }
        return reqParam;
    }

    /**
     * set request param.
     *
     * @param reqParam
     *            ReqParam
     */
    public void setReqParam(EnvironmentDeleteActionBase.ReqParam reqParam) {
        this.reqParam = reqParam;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.baidu.lego.web.struts2.DirectVisitAction#getAsReqParam()
     */
    @Override
    public Object getAsReqParam() {
        return getReqParam();
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * com.baidu.lego.web.struts2.DirectVisitAction#setAsDataResult(java.lang
     * .Object)
     */
    @Override
    public void setAsDataResult(Object v) {
        if (v instanceof EnvironmentDeleteActionBase.DataResult) {
            setData((EnvironmentDeleteActionBase.DataResult) v);
        }
        setEJsonDataResult(v);
    }

    /** return data object. */
    protected EnvironmentDeleteActionBase.DataResult data;

    /**
     * get return data object.
     *
     * @return DataResult
     */
    public EnvironmentDeleteActionBase.DataResult getData() {
        if (data == null) {
            data = new EnvironmentDeleteActionBase.DataResult();
        }
        return data;
    }

    /**
     * set return data object.
     *
     * @param data
     *            DataResult
     */
    protected void setData(EnvironmentDeleteActionBase.DataResult data) {
        this.data = data;
    }

    /** return data object of e-json wrapped. */
    @ToJSON
    protected EJsonDataResult result;

    /**
     * get return data object wrapped by ejson.
     *
     * @return EJsonDataResult
     */
    public EJsonDataResult getResult() {
        if (result == null) {
            result = new EJsonDataResult();
        }
        return result;
    }

    /**
     * set ejson data object.
     *
     * @param result
     *            EJsonDataResult
     */
    public void setEJsonDataResult(EJsonDataResult result) {
        this.result = result;
    }

    /**
     * set ejson data object.
     *
     * @param data
     *            DataResult
     */
    public void setEJsonDataResult(Object data) {
        getResult().setData(data);
    }

    /**
     * set ejson data object.
     *
     * @param data
     *            DataResult
     * @param status
     *            状态码
     * @param statusInfo
     *            状态信息
     */
    public void setEJsonDataResult(DataResult data, int status,
            String statusInfo) {
        getResult().setData(data);
        getResult().setStatus(status);
        getResult().setStatusInfo(statusInfo);
    }

    // step1 main entry to define action name
    /**
     * do execute service.
     *
     * @return result name
     * @throws Exception
     *             throws all available exception
     */
    @Action("delEnv")
    public String doExecute() throws Exception {
        return execute();
    }

    /**
     * do interal validaotr. do not override it
     */
    @Validations(regexFields = { @RegexFieldValidator(fieldName = "reqParam.projectId",
        message = "字段\'projectId\'必须为整数类型", expression = "^(\\+|-)?[0-9]\\d*$") })
    public final void internalValidator() {
        throw new RuntimeException("invalid access.");
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * com.baidu.lego.web.struts2.DirectVisitAction#getValidationTarget(java
     * .lang.Object)
     */
    @Override
    protected Object getValidationTarget(Object target) {
        EnvironmentDeleteAction action = new EnvironmentDeleteAction();
        action.setReqParam((EnvironmentDeleteActionBase.ReqParam) target);
        return action;
    }

    /**
     * Request param class.
     *
     * @author BJF
     */
    protected static class ReqParam {

        /** 说明:environmentId. */
        private Long environmentId;

        /**
         * set environmentId.
         *
         * @param environmentId
         *            the new environment id
         */
        public void setEnvironmentId(Long environmentId) {
            this.environmentId = environmentId;
        }

        /**
         * get environmentId.
         *
         * @return Long
         */
        public Long getEnvironmentId() {
            return environmentId;
        }

        /**
         * get Map instance.
         *
         * @return Map
         */
        public Map<String, Object> toMap() {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("environmentId", environmentId);
            return map;
        }
    }

    /**
     * Data return class.
     *
     * @author BJF
     */
    public static class DataResult {

    }

}


text:
'use strict';

var request = require('request');

exports.save = function(req, res, gfs) {

    gfs.files.findOne({
        filename: 'theme.css'
    }, function(err, file) {

        if (err) return res.send(500, 'Error updating theme');

        // Id of the current theme file
        var _id = (file ? file._id : null);

        // Creating write stream
        var writestream = gfs.createWriteStream({
            filename: 'theme.css'
        });

        //Retrieving theme from source

        request(req.query.theme).pipe(writestream);

        // Remove old theme file

        writestream.on('close', function(file) {

            res.send('saved');

            if (_id && file.filename === 'theme.css') {
                gfs.files.remove({
                    _id: _id
                }, function(err) {
                    console.log(err);
                });
            }
        });

        writestream.on('error', function(file) {

            res.send(500, 'error updating theme');

        });

    });

};

exports.defaultTheme = function(req, res, gfs) {

    gfs.files.findOne({
        filename: 'theme.css'
    }, function(err, file) {

        if (err) return res.send(500, 'Error updating theme');

        // Id of the current theme file
        var _id = (file ? file._id : null);

        if (_id && file.filename === 'theme.css') {
            gfs.files.remove({
                _id: _id
            }, function(err) {
                res.send('saved');
                console.log(err);
            });
        }
    });
};

redpajama_set_name: RedPajamaGithub


text:
Sample application to show how to use the TransformOperator to transform the input POJO using given expressions.

Operators in sample application are as follows:
1) POJOGenerator which generates and emits the CustomerEvent POJO.
2) TransformOperator which transforms the input POJO using provided expressions and emits the transformed POJO.
3) ConsoleOutputOperator which writes transformed POJO to stdout.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Flora, Jena 56: 207 (1873)

#### Original name
Arthonia galactites var. depuncta Nyl.

### Remarks
null


text:
package mesosphere.marathon
package storage.migration

import akka.Done
import akka.stream.Materializer
import akka.stream.scaladsl.Flow
import com.typesafe.scalalogging.StrictLogging
import mesosphere.marathon.core.instance.Instance.{AgentInfo, Id, InstanceState}
import mesosphere.marathon.core.instance.Reservation
import mesosphere.marathon.core.storage.store.PersistenceStore
import mesosphere.marathon.core.storage.store.impl.zk.{ZkId, ZkSerialized}
import mesosphere.marathon.core.task.Task
import mesosphere.marathon.state._
import mesosphere.marathon.storage.repository.InstanceRepository
import play.api.libs.functional.syntax._
import play.api.libs.json.Reads._
import play.api.libs.json._

import scala.async.Async.{async, await}
import scala.concurrent.{ExecutionContext, Future}

class MigrationTo19200(
    defaultMesosRole: Role,
    instanceRepository: InstanceRepository,
    persistenceStore: PersistenceStore[ZkId, String, ZkSerialized]
) extends MigrationStep
    with StrictLogging {

  override def migrate()(implicit ctx: ExecutionContext, mat: Materializer): Future[Done] =
    async {
      logger.info("Starting migration to 1.9.200")
      await(InstanceMigration.migrateInstances(instanceRepository, persistenceStore, instanceMigrationFlow))
    }

  /**
    * Read format for old instance without reservation id.
    */
  val instanceJsonReads18200: Reads[Instance] = {
    import mesosphere.marathon.api.v2.json.Formats.TimestampFormat
    import mesosphere.marathon.core.instance.Instance.tasksMapFormat

    (
      (__ \ "instanceId").read[Id] ~
        (__ \ "agentInfo").readNullable[AgentInfo] ~
        (__ \ "tasksMap").read[Map[Task.Id, Task]] ~
        (__ \ "runSpecVersion").read[Timestamp] ~
        (__ \ "state").read[InstanceState] ~
        (__ \ "reservation").readNullable[Reservation] ~
        (__ \ "role").readNullable[String]
    ) { (instanceId, agentInfo, tasksMap, runSpecVersion, state, reservation, persistedRole) =>
      logger.info(s"Migrate $instanceId")

      val role = persistedRole.orElse(Some(defaultMesosRole))

      new Instance(instanceId, agentInfo, state, tasksMap, runSpecVersion, reservation, role)
    }
  }

  /**
    * Extract instance from old format
    *
    * @param jsValue The instance as JSON.
    * @return The parsed instance.
    */
  def extractInstanceFromJson(jsValue: JsValue): Instance = jsValue.as[Instance](instanceJsonReads18200)

  val instanceMigrationFlow = Flow[JsValue].filter { jsValue =>
    // Only migrate instances that don't have a role
    (jsValue \ "role").isEmpty
  }.map(extractInstanceFromJson)
}


text:
import PropTypes from 'prop-types';

import TextField from 'material-ui/TextField';

const FieldWrapper = (props) => {
  const { input, meta, fieldError, component: TextFieldComponent, ...otherProps } = props;
  let { error, helperText, ...other } = otherProps;

  if (fieldError) {
    error = true;
    helperText = fieldError.message;
  }

  if (meta.touched && (!fieldError || input.value != fieldError.value)) {
    error = typeof meta.error !== 'undefined';
    helperText = error ? meta.error : helperText;
  }

  return (<TextFieldComponent
    fullWidth
    InputProps={input}
    error={error}
    helperText={helperText}
    {...other}
    />);
};
FieldWrapper.propTypes = {
  input: PropTypes.object,
  meta: PropTypes.object,
  error: PropTypes.bool,
  helperText: PropTypes.string,
  fieldError: PropTypes.object,
  component: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired,
};

export default FieldWrapper;


text:
<?php

use vekqaam\models\QaaMainSearch;
use yii\helpers\Html;
use yii\web\View;
use yii\widgets\ActiveForm;

/**
 * @var $this  View
 * @var $model QaaMainSearch
 * @var $form  ActiveForm
 */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?php echo $form->field($model, 'id') ?>

    <?php echo $form->field($model, 'category_id') ?>

    <?php echo $form->field($model, 'title') ?>

    <?php echo $form->field($model, 'text') ?>

    <?php echo $form->field($model, 'isHidden')->checkbox() ?>

        <?php echo Html::submitButton(Yii::t('vekqaam', 'Search'), ['class' => 'btn btn-primary']) ?>
        <?php echo Html::resetButton(Yii::t('vekqaam', 'Reset'), ['class' => 'btn btn-default']) ?>

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


text:
package bnfc.abs.Absyn; // Java Package generated by the BNF Converter.

public class PUnderscore extends Pattern {
  public PUnderscore() { }

  public <R,A> R accept(bnfc.abs.Absyn.Pattern.Visitor<R,A> v, A arg) { return v.visit(this, arg); }

  public boolean equals(Object o) {
    if (this == o) return true;
    if (o instanceof bnfc.abs.Absyn.PUnderscore) {
      return true;
    }
    return false;
  }

  public int hashCode() {
    return 37;
  }

}


text:
"""
Dump the selected glyph to a Glif as a seperate, individual file.
This is not saved through a GlyphSet and any contents.plist in the
same directory will not be updated. If that's what you need use
DumpOneGlyphToUFO.py

"""

from robofab.glifLib import writeGlyphToString
from robofab.world import CurrentFont, CurrentGlyph
from robofab.interface.all.dialogs import PutFile
from robofab.tools.glyphNameSchemes import glyphNameToShortFileName
import os

f = CurrentFont()
g = CurrentGlyph()

if g is not None:
	todo = [g.name]
else:
	todo = f.selection

for c in todo:
	g = f[c]
	result = True
	data = writeGlyphToString(g.name, g, g.drawPoints)
	filename = glyphNameToShortFileName(g.name, None)
	file = PutFile("Save this glif as:")
	if file is not None:
		path = os.path.join(os.path.dirname(file), filename)
		print "saving to", path
		f = open(path, "w")
		f.write(data)
		f.close()

print 'done'


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="org.coenraets.ionicdirectory" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>StarterApp</name>
    <description>
        A sample Ionic Framework app using Cordova and AngularJS
    </description>
    <author email="ccoenraets@gmail.com" href="http://coenraets.org">
        Christophe Coenraets
    </author>
    <content src="index.html" />
    <access origin="*" />
    <preference name="fullscreen" value="true" />
    <preference name="webviewbounce" value="false" />
    <preference name="UIWebViewBounce" value="false" />
    <preference name="DisallowOverscroll" value="true" />
</widget>


text:
'use strict';

module TourabuEx.timer {
    export interface TimerTask {
        end: Date;
        type: string;
        callbackParam: any;
    }

    interface TimerTaskToSave {
        end: string;
        type: string;
        callbackParam: any;
    }

    var timers: TimerTask[] = [];
    var seconds: number = 0;

    export function set(p: TimerTask) {
        timers.push(p);
        saveTimers();
    }

    export function cancel(f: (t: TimerTask) => boolean) {
        timers.forEach((t, i, ts) => {
            if (f(t)) {
                TourabuEx.util.removeAt(ts, i);
                saveTimers();
                return;
            }
        });
    }

    function saveTimers() {
        var timersToSave: TimerTaskToSave[];

        timersToSave = timers.map((task) => {
            return {
                end: task.end.toString(),
                type: task.type,
                callbackParam: task.callbackParam
            }
        });

        console.log('timers/save', timersToSave);
        TourabuEx.storage.set({ 'timer_tasks': timersToSave });
    }

    function loadTimers() {
        TourabuEx.storage.get('timer_tasks').done(function (tasks: TimerTaskToSave[]) {
            tasks.forEach((task) => {
                var d = new Date(task.end);
                if (TourabuEx.util.isValid(d)) {
                    timers.push({
                        end: d,
                        type: task.type,
                        callbackParam: task.callbackParam
                    });
                }
            });
        })
    }

    function checkTimers() {
        var now = new Date(),
            anyTimersFinished = false;
        timers = timers.filter((task) => {
            var ended = task.end < now;
            if (ended) {
                TourabuEx.events.trigger('timer/' + task.type + '/end', task.callbackParam);
                anyTimersFinished = true;
                return false;
            } else {
                return true;
            }
        });
        if (anyTimersFinished) {
            saveTimers();
        }
    }

    function initialize() {
        var events = TourabuEx.events;

        timers  = [];
        seconds = 0;

        loadTimers();

        events.bind('second/change', function () {
            if ((seconds++) % 5 === 0) {
                checkTimers();
            }
        });
    }

    initialize();
}


text:
Bitcurex API

## Installation

Add this line to your application's Gemfile:

    gem 'bitcurex'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install bitcurex

## Usage

Use with caution!

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
from warnings import warn

import pandas as pd

from zipline.assets import Asset, Future
from zipline.utils.input_validation import expect_types
from .utils.enum import enum
from zipline._protocol import BarData  # noqa

# Datasource type should completely determine the other fields of a
# message with its type.
DATASOURCE_TYPE = enum(
    'AS_TRADED_EQUITY',
    'MERGER',
    'SPLIT',
    'DIVIDEND',
    'TRADE',
    'TRANSACTION',
    'ORDER',
    'EMPTY',
    'DONE',
    'CUSTOM',
    'BENCHMARK',
    'COMMISSION',
    'CLOSE_POSITION'
)

# Expected fields/index values for a dividend Series.
DIVIDEND_FIELDS = [
    'declared_date',
    'ex_date',
    'gross_amount',
    'net_amount',
    'pay_date',
    'payment_sid',
    'ratio',
    'sid',
]
# Expected fields/index values for a dividend payment Series.
DIVIDEND_PAYMENT_FIELDS = [
    'id',
    'payment_sid',
    'cash_amount',
    'share_count',
]

class Event(object):

    def __init__(self, initial_values=None):
        if initial_values:
            self.__dict__.update(initial_values)

    def keys(self):
        return self.__dict__.keys()

    def __eq__(self, other):
        return hasattr(other, '__dict__') and self.__dict__ == other.__dict__

    def __contains__(self, name):
        return name in self.__dict__

    def __repr__(self):
        return "Event({0})".format(self.__dict__)

    def to_series(self, index=None):
        return pd.Series(self.__dict__, index=index)

def _deprecated_getitem_method(name, attrs):
    """Create a deprecated ``__getitem__`` method that tells users to use
    getattr instead.

    Parameters
    ----------
    name : str
        The name of the object in the warning message.
    attrs : iterable[str]
        The set of allowed attributes.

    Returns
    -------
    __getitem__ : callable[any, str]
        The ``__getitem__`` method to put in the class dict.
    """
    attrs = frozenset(attrs)
    msg = (
        "'{name}[{attr!r}]' is deprecated, please use"
        " '{name}.{attr}' instead"
    )

    def __getitem__(self, key):
        """``__getitem__`` is deprecated, please use attribute access instead.
        """
        warn(msg.format(name=name, attr=key), DeprecationWarning, stacklevel=2)
        if key in attrs:
            return self.__dict__[key]
        raise KeyError(key)

    return __getitem__

class Order(Event):
    # If you are adding new attributes, don't update this set. This method
    # is deprecated to normal attribute access so we don't want to encourage
    # new usages.
    __getitem__ = _deprecated_getitem_method(
        'order', {
            'dt',
            'sid',
            'amount',
            'stop',
            'limit',
            'id',
            'filled',
            'commission',
            'stop_reached',
            'limit_reached',
            'created',
        },
    )

def asset_multiplier(asset):
    return asset.multiplier if isinstance(asset, Future) else 1

class Portfolio(object):

    def __init__(self):
        self.capital_used = 0.0
        self.starting_cash = 0.0
        self.portfolio_value = 0.0
        self.pnl = 0.0
        self.returns = 0.0
        self.cash = 0.0
        self.positions = Positions()
        self.start_date = None
        self.positions_value = 0.0

    def __repr__(self):
        return "Portfolio({0})".format(self.__dict__)

    # If you are adding new attributes, don't update this set. This method
    # is deprecated to normal attribute access so we don't want to encourage
    # new usages.
    __getitem__ = _deprecated_getitem_method(
        'portfolio', {
            'capital_used',
            'starting_cash',
            'portfolio_value',
            'pnl',
            'returns',
            'cash',
            'positions',
            'start_date',
            'positions_value',
        },
    )

    @property
    def current_portfolio_weights(self):
        """
        Compute each asset's weight in the portfolio by calculating its held
        value divided by the total value of all positions.

        Each equity's value is its price times the number of shares held. Each
        futures contract's value is its unit price times number of shares held
        times the multiplier.
        """
        position_values = pd.Series({
            asset: (
                position.last_sale_price *
                position.amount *
                asset_multiplier(asset)
            )
            for asset, position in self.positions.items()
        })
        return position_values / self.portfolio_value

class Account(object):
    '''
    The account object tracks information about the trading account. The
    values are updated as the algorithm runs and its keys remain unchanged.
    If connected to a broker, one can update these values with the trading
    account values as reported by the broker.
    '''

    def __init__(self):
        self.settled_cash = 0.0
        self.accrued_interest = 0.0
        self.buying_power = float('inf')
        self.equity_with_loan = 0.0
        self.total_positions_value = 0.0
        self.total_positions_exposure = 0.0
        self.regt_equity = 0.0
        self.regt_margin = float('inf')
        self.initial_margin_requirement = 0.0
        self.maintenance_margin_requirement = 0.0
        self.available_funds = 0.0
        self.excess_liquidity = 0.0
        self.cushion = 0.0
        self.day_trades_remaining = float('inf')
        self.leverage = 0.0
        self.net_leverage = 0.0
        self.net_liquidation = 0.0

    def __repr__(self):
        return "Account({0})".format(self.__dict__)

    # If you are adding new attributes, don't update this set. This method
    # is deprecated to normal attribute access so we don't want to encourage
    # new usages.
    __getitem__ = _deprecated_getitem_method(
        'account', {
            'settled_cash',
            'accrued_interest',
            'buying_power',
            'equity_with_loan',
            'total_positions_value',
            'total_positions_exposure',
            'regt_equity',
            'regt_margin',
            'initial_margin_requirement',
            'maintenance_margin_requirement',
            'available_funds',
            'excess_liquidity',
            'cushion',
            'day_trades_remaining',
            'leverage',
            'net_leverage',
            'net_liquidation',
        },
    )

class Position(object):
    @expect_types(asset=Asset)
    def __init__(self, asset):
        self.asset = asset
        self.amount = 0
        self.cost_basis = 0.0  # per share
        self.last_sale_price = 0.0
        self.last_sale_date = None

    @property
    def sid(self):
        # for backwards compatibility
        return self.asset

    def __repr__(self):
        return "Position({0})".format(self.__dict__)

    # If you are adding new attributes, don't update this set. This method
    # is deprecated to normal attribute access so we don't want to encourage
    # new usages.
    __getitem__ = _deprecated_getitem_method(
        'position', {
            'sid',
            'amount',
            'cost_basis',
            'last_sale_price',
            'last_sale_date',
        },
    )

# Copied from Position and renamed.  This is used to handle cases where a user
# does something like `context.portfolio.positions[100]` instead of
# `context.portfolio.positions[sid(100)]`.
class _DeprecatedSidLookupPosition(object):
    def __init__(self, sid):
        self.sid = sid
        self.amount = 0
        self.cost_basis = 0.0  # per share
        self.last_sale_price = 0.0
        self.last_sale_date = None

    def __repr__(self):
        return "_DeprecatedSidLookupPosition({0})".format(self.__dict__)

    # If you are adding new attributes, don't update this set. This method
    # is deprecated to normal attribute access so we don't want to encourage
    # new usages.
    __getitem__ = _deprecated_getitem_method(
        'position', {
            'sid',
            'amount',
            'cost_basis',
            'last_sale_price',
            'last_sale_date',
        },
    )

class Positions(dict):
    def __missing__(self, key):
        if isinstance(key, Asset):
            return Position(key)
        elif isinstance(key, int):
            warn("Referencing positions by integer is deprecated."
                 " Use an asset instead.")
        else:
            warn("Position lookup expected a value of type Asset but got {0}"
                 " instead.".format(type(key).__name__))

        return _DeprecatedSidLookupPosition(key)


text:
package com.atlassian.plugins.codegen.modules;

import java.util.Properties;

import com.atlassian.plugins.codegen.util.ClassnameUtil;

import org.apache.commons.lang.StringUtils;

/**
 * @since 3.6
 */
public abstract class AbstractNameBasedModuleProperties extends AbstractPluginModuleProperties implements NameBasedModuleProperties
{

    protected AbstractNameBasedModuleProperties()
    {
        super();
    }

    public void setModuleNameAndKey(String moduleName)
    {
        if (StringUtils.isNotBlank(moduleName))
        {
            setModuleName(moduleName);
            setModuleKey(ClassnameUtil.camelCaseOrSpaceToDashed(moduleName)
                    .toLowerCase());
            setDescription("The " + getProperty(MODULE_NAME) + " Plugin");
            setNameI18nKey(getProperty(MODULE_KEY) + ".name");
            setDescriptionI18nKey(getProperty(MODULE_KEY) + ".description");
        }
    }

    @Override
    public void setModuleName(String name)
    {
        setProperty(MODULE_NAME, name);
    }

    @Override
    public String getModuleName()
    {
        return getProperty(MODULE_NAME);
    }

    @Override
    public void setModuleKey(String name)
    {
        setProperty(MODULE_KEY, name);
    }

    @Override
    public String getModuleKey()
    {
        return getProperty(MODULE_KEY);
    }

    @Override
    public void setDescription(String desc)
    {
        setProperty(DESCRIPTION, desc);
    }

    @Override
    public String getDescription()
    {
        return getProperty(DESCRIPTION);
    }

    @Override
    public void setDescriptionI18nKey(String key)
    {
        setProperty(DESCRIPTION_I18N_KEY, key);
    }

    @Override
    public String getDescriptionI18nKey()
    {
        return getProperty(DESCRIPTION_I18N_KEY);
    }

    @Override
    public void setNameI18nKey(String key)
    {
        setProperty(NAME_I18N_KEY, key);
    }

    @Override
    public String getNameI18nKey()
    {
        return getProperty(NAME_I18N_KEY);
    }

    @Override
    public Properties getI18nProperties()
    {
        Properties props = super.getI18nProperties();
        props.setProperty(getProperty(NAME_I18N_KEY), getProperty(MODULE_NAME));
        props.setProperty(getProperty(DESCRIPTION_I18N_KEY), getProperty(DESCRIPTION));

        return props;
    }
}


text:
<?php

namespace Foggyline\SalesBundle\Repository;

/**
 * SalesOrderRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class SalesOrderRepository extends \Doctrine\ORM\EntityRepository
{
}


text:
@interface GLNearby_RecommendMerchatCollectionCell : UICollectionViewCell

@property (nonatomic, strong)LBRecomendShopModel *model;

@end


text:
<?php
namespace Zilack\Listeners;

use Zilack\Events\WebhookEvent;
use Zilack\ZilackWebhook;

class WebhookListener
{
    public function onWebhookReceived(WebhookEvent $event)
    {
        $webhook = $event->getWebhook();

        if (!is_null($webhook) && $this->validate($event->getPayload())) {
            $webhook->execute($event->getPayload(), $event->getContext());
        }
    }

    public function validate(array $payload)
    {
        return true;
    }
}


text:
import pyrfa

p = pyrfa.Pyrfa()
p.createConfigDb("./pyrfa.cfg")
p.setDebugMode(True)
p.acquireSession("Session3")
p.createOMMConsumer()
p.login()
p.directoryRequest()
p.dictionaryRequest()

p.marketByPriceRequest("ANZ.CHA");

end = False
while not end:
    try:
        updates = p.dispatchEventQueue(100)
    except KeyboardInterrupt:
        end = True
    if updates:
        print("")
        for u in updates:
            print(u['SERVICE'] + " - " + u['RIC'])
            for k,v in u.items():
                if type(v) is float:
                    print("%15s %g" % (k,v))
                else:
                    print("%15s %s" % (k,v))
            print("")
del p


text:
#ifndef vtkMultiBlockPLOT3DReaderInternals_h
#define vtkMultiBlockPLOT3DReaderInternals_h

#include "vtkByteSwap.h"
#include "vtkMultiBlockPLOT3DReader.h"
#include "vtkSmartPointer.h"
#include "vtkStructuredGrid.h"

#include <vector>

struct vtkMultiBlockPLOT3DReaderInternals
{
  std::vector<vtkSmartPointer<vtkStructuredGrid> > Blocks;
  int BinaryFile;
  int ByteOrder;
  int HasByteCount;
  int MultiGrid;
  int NumberOfDimensions;
  int Precision; // in bytes
  int IBlanking;

  bool NeedToCheckXYZFile;

  vtkMultiBlockPLOT3DReaderInternals() :
    BinaryFile(1),
    ByteOrder(vtkMultiBlockPLOT3DReader::FILE_BIG_ENDIAN),
    HasByteCount(1),
    MultiGrid(0),
    NumberOfDimensions(3),
    Precision(4),
    IBlanking(0),
    NeedToCheckXYZFile(true)
    {
    }

  int ReadInts(FILE* fp, int n, int* val);
  void CheckBinaryFile(FILE *fp);
  int CheckByteOrder(FILE* fp);
  int CheckByteCount(FILE* fp);
  int CheckMultiGrid(FILE* fp);
  int Check2DGeom(FILE* fp);
  int CheckBlankingAndPrecision(FILE* fp);
  int CheckCFile(FILE* fp, long fileSize);
  long CalculateFileSize(int mgrid,
                         int precision, // in bytes
                         int blanking,
                         int ndims,
                         int hasByteCount,
                         int nGrids,
                         int* gridDims);
  long CalculateFileSizeForBlock(int precision, // in bytes
                                 int blanking,
                                 int ndims,
                                 int hasByteCount,
                                 int* gridDims);
};
#endif
// VTK-HeaderTest-Exclude: vtkMultiBlockPLOT3DReaderInternals.h


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

         <meta property="rnews:description"
            content="The Cassini probe in orbit around Saturn is going to picture the ringed planet in a special photo that also includes a distant Earth."/>
         <meta property="rnews:datePublished" content="2013-06-19T04:08:23"/>
         <meta property="rnews:thumbnailUrl"
            content="http://news.bbcimg.co.uk/media/images/68250000/jpg/_68250795_68250640.jpg"/>
         <meta property="rnews:headline" content="Saturn probe to acquire Earth image"/>
         <meta name="CPS_SECTION_PATH" content="Science and Environment"/>
         <meta property="rnews:creator" content="http://www.bbc.co.uk#org"/>
         <link rel="copyright"
            href="http://www.bbc.co.uk/terms/"
            title="Terms of Use"/>
         <link rel="http://purl.org/dc/terms/source"
            href="http://www.bbc.co.uk/news/science-environment-22963237"/>
         <title>BBC News - Nasa's
Cassini probe to acquire distant Earth portrait</title>

               19 June 2013
               Last updated
at
               05:08

Nasa's Cassini probe to
acquire distant Earth portrait

               By Jonathan
Amos
               Science correspondent, BBC
News

               This favourite 2006 image of Saturn includes Earth
as a speck just inside the G-ring at upper-left. In the coming
picture, Earth will be lower-right. Dr Porco hopes it will look
even better

Nasa's Cassini probe
is going to try to take a special picture of Planet Earth.

The spacecraft will include our home world when it makes a giant
mosaic of Saturn and its ring system.

In the Friday 19 July portrait, Earth will be almost a
billion miles in the distance - a mere pixel in size.

Carolyn Porco, who leads Cassini's camera team, hopes the
picture will be reminiscent of the famous "Pale Blue Dot"
image captured by the Voyager-1 probe in 1990.

That was an image she helped
produce. A major difference on this occasion is that people
will know in advance that they are being photographed from the
outer Solar System. They could wave, said
the researcher from the Space Science Institute in Boulder,
Colorado.

"People can celebrate it and join in. This will be like an
interplanetary cosmic photo session," she told BBC News.

"People can enjoy the fact that we have a robot out there, a
billion miles away, taking our picture. How cool is that?"

Cassini has caught sight of Planet Earth before as it has
studied and photographed the ringed gas giant. But the set-up has
never been ideal.

This time Dr Porco has searched through the upcoming mission
plan for Cassini to find an occasion when she can properly frame
the shot, using the most appropriate filters to capture Earth in
natural colour.

Using the probe to look back towards the inner Solar System
needs great care and must only be done when the Sun is eclipsed by
Saturn. To do otherwise risks the full glare of our star falling on
the probe's instruments and damaging their sensitive detectors.

In 2006, Cassini managed to do this in a mosaic that is
routinely cited as the most popular picture ever taken by the
satellite. It shows Saturn as a translucent orb surrounded by its
rings, with Earth - a speck so small you could almost miss it -
sitting in the upper-left of the frame. It is visible just inside
the planet's faint G-ring.

               This simulation shows the face Earth will present to
Cassini

Dr Porco believes her Ciclops
team can improve on the 2006 picture, especially if they use
their high resolution camera to picture Earth during the 19 July
opportunity.

No science is being interrupted for the purpose of getting the
new mosaic. Researchers who will be working through the eclipse to
gather infrared data on Saturn have agreed to accommodate Dr Porco
in her quest to acquire what should be another spectacular
vista.

Opportunities like this are few and far between, particularly
given that Cassini is moving towards the end of its mission.

Nasa has determined that it will crash the probe into Saturn's
atmosphere in 2017, but may pull the plug even earlier if its
budget becomes severely constrained in the fiscal squeeze now
afflicting US federal agencies.

               Voyager pictured the Pale Blue Dot of Earth when it
had travelled beyond Neptune

Although Cassini has been at the ringed planet for nine years
now, scientists say there is still much to learn.

They plan to use the remaining time to make some manoeuvres that
might have been regarded as too risky in the mission's early
years.

This includes diving between Saturn and the inner C-ring.
"That's kind of a wildly crazy thing to do, but it will give us
very high resolution views of the rings," said Dr Porco. "And we
really want to measure how massive the rings are. We're puzzled by
that, and it's important because it plays into how long they've
been around."

Cassini's images of Earth to be included in the mosaic - both
wide angle and narrow angle - will be acquired between 21:27 and
21:42 GMT (17:27 and 17:42 EDT) on 19 July. During these times,
North America and part of the Atlantic Ocean will be in sunlight.
The illuminated parts of the Earth and the Moon will each be no
more than one pixel across in the final image.

You can follow Dr
Porco on Twitter as she builds up to 19 July. There is also an
event page
that provides more details. And watch
Carolyn Porco reflect on the original Pale Blue Dot image.

               Jonathan.Amos-INTERNET@bbc.co.uk
and follow me on Twitter: @BBCAmos

Related Stories

                  Viewpoint: A day to celebrate
the pale blue dot

                  Voyager: Taking a picture of
home Watch

                  Jupiter probe's 'goodbye for
now'

Saturn

Saturn is the sixth planet from the
Sun and has a prominent
icy ring system

Although it is the second largest planet in the Solar System,
it is the least dense and would float in water

It has 62 satellites - the largest,
Titan, is the only moon in the Solar System with a substantial
atmosphere

Launched in 1997,
Cassini-Huygens is a joint US-Europe mission to explore Saturn
and its moons

See Saturn's intricate rings up-close

Enter the Cassini probe's mission control


text:
using System;
using System.IO;
using Markdig.Helpers;
using Markdig.Parsers;
using Markdig.Parsers.Inlines;

namespace Markdig
{
    /// <summary>
    /// This class allows to modify the pipeline to parse and render a Markdown document.
    /// </summary>
    /// <remarks>NOTE: A pipeline is not thread-safe.</remarks>
    public class MarkdownPipelineBuilder
    {
        private MarkdownPipeline pipeline;

        /// <summary>
        /// Initializes a new instance of the <see cref="MarkdownPipeline" /> class.
        /// </summary>
        public MarkdownPipelineBuilder()
        {
            // Add all default parsers
            BlockParsers = new OrderedList<BlockParser>()
            {
                new ThematicBreakParser(),
                new HeadingBlockParser(),
                new QuoteBlockParser(),
                new ListBlockParser(),

                new HtmlBlockParser(),
                new FencedCodeBlockParser(),
                new IndentedCodeBlockParser(),
                new ParagraphBlockParser(),
            };

            InlineParsers = new OrderedList<InlineParser>()
            {
                new HtmlEntityParser(),
                new LinkInlineParser(),
                new EscapeInlineParser(),
                new EmphasisInlineParser(),
                new CodeInlineParser(),
                new AutolineInlineParser(),
                new LineBreakInlineParser(),
            };

            Extensions = new OrderedList<IMarkdownExtension>();
        }

        /// <summary>
        /// Gets the block parsers.
        /// </summary>
        public OrderedList<BlockParser> BlockParsers { get; private set; }

        /// <summary>
        /// Gets the inline parsers.
        /// </summary>
        public OrderedList<InlineParser> InlineParsers { get; private set; }

        /// <summary>
        /// Gets the register extensions.
        /// </summary>
        public OrderedList<IMarkdownExtension> Extensions { get; }

        /// <summary>
        /// Gets or sets a value indicating whether to enable precise source location (slower parsing but accurate position for block and inline elements)
        /// </summary>
        public bool PreciseSourceLocation { get; set; }

        /// <summary>
        /// Gets or sets the debug log.
        /// </summary>
        public TextWriter DebugLog { get; set; }

        /// <summary>
        /// Occurs when a document has been processed after the <see cref="MarkdownParser.Parse()"/> method.
        /// </summary>
        public event ProcessDocumentDelegate DocumentProcessed;

        internal ProcessDocumentDelegate GetDocumentProcessed => DocumentProcessed;

        /// <summary>
        /// Builds a pipeline from this instance. Once the pipeline is build, it cannot be modified.
        /// </summary>
        /// <exception cref="InvalidOperationException">An extension cannot be null</exception>
        public MarkdownPipeline Build()
        {
            if (pipeline != null)
            {
                return pipeline;
            }

            // TODO: Review the whole initialization process for extensions
            // - It does not prevent a user to modify the pipeline after it has been used
            // - a pipeline is not thread safe.
            // We should find a proper way to make the pipeline safely modifiable/freezable (PipelineBuilder -> Pipeline)

            // Allow extensions to modify existing BlockParsers, InlineParsers and Renderer
            foreach (var extension in Extensions)
            {
                if (extension == null)
                {
                    ThrowHelper.InvalidOperationException("An extension cannot be null");
                }
                extension.Setup(this);
            }

            pipeline = new MarkdownPipeline(
                new OrderedList<IMarkdownExtension>(Extensions),
                new BlockParserList(BlockParsers),
                new InlineParserList(InlineParsers),
                DebugLog,
                GetDocumentProcessed)
            {
                PreciseSourceLocation = PreciseSourceLocation
            };
            return pipeline;
        }
    }
}


text:
@interface PodsDummy_Pods_CocoapodLib_Tests : NSObject
@end
@implementation PodsDummy_Pods_CocoapodLib_Tests
@end


text:
package com.InfinityRaider.elemancy.init;

public class Blocks {
    public static void init() {

    }
}


text:
package org.sourcepit.b2.model.module.internal.util;

import java.util.List;

import org.sourcepit.b2.model.module.Project;

/**
 * @author Bernd
 */
public final class ProjectUtils {
   private ProjectUtils() {
      super();
   }

   public static <P extends Project> P getProjectById(List<P> projects, String id) {
      if (projects == null || id == null) {
         return null;
      }
      for (P project : projects) {
         if (id != null && id.equals(project.getId())) {
            return project;
         }
      }
      return null;
   }
}


text:
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [("members", "0010_auto_20180424_1452"), ("diary", "0001_initial")]

    operations = [
        migrations.AddField(
            model_name="booking",
            name="player_1",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="player_1",
                to="members.Person",
            ),
        ),
        migrations.AddField(
            model_name="booking",
            name="player_2",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="player_2",
                to="members.Person",
            ),
        ),
        migrations.AddField(
            model_name="booking",
            name="player_3",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="player_3",
                to="members.Person",
            ),
        ),
    ]


text:
<template name="comment">

    {{#if canEdit}}

    {{/if}}

      {{>_userIcon author}}
      {{author.name}}
      {{fromNow created_at}}

    {{body}}

</template>


text:
import { Grid } from '@rocket.chat/fuselage';
import React from 'react';

import Counter from './Counter';

function CounterSet({ counters = [] }) {
	return <Grid>
		{counters.map(({ count, variation, description }, i) => <Grid.Item key={i}>
			<Counter
				count={count}
				variation={variation}
				description={description}
			/>
		</Grid.Item>)}
	</Grid>;
}

export default CounterSet;


text:
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements

class AwayNotify(ModuleData):
	implements(IPlugin, IModuleData)

	name = "AwayNotify"

	def actions(self):
		return [ ("usermetadataupdate", 10, self.sendAwayNotice),
		         ("capabilitylist", 10, self.addCapability),
		         ("join", 10, self.tellChannelAway) ]

	def load(self):
		if "unloading-away-notify" in self.ircd.dataCache:
			del self.ircd.dataCache["unloading-away-notify"]
			return
		if "cap-add" in self.ircd.functionCache:
			self.ircd.functionCache["cap-add"]("away-notify")

	def unload(self):
		self.ircd.dataCache["unloading-away-notify"] = True

	def fullUnload(self):
		del self.ircd.dataCache["unloading-away-notify"]
		if "cap-del" in self.ircd.functionCache:
			self.ircd.functionCache["cap-del"]("away-notify")

	def addCapability(self, user, capList):
		capList.append("away-notify")

	def sendAwayNotice(self, user, key, oldValue, value, visibility, setByUser, fromServer):
		if key != "away":
			return
		noticeUsers = set()
		noticePrefix = user.hostmask()
		conditionalTags = {}
		self.ircd.runActionStandard("sendingusertags", user, conditionalTags)
		for channel in user.channels:
			for noticeUser in channel.users.iterkeys():
				if noticeUser.uuid[:3] == self.ircd.serverID and noticeUser != user and "capabilities" in noticeUser.cache and "away-notify" in noticeUser.cache["capabilities"]:
					noticeUsers.add(noticeUser)
		if value:
			for noticeUser in noticeUsers:
				tags = noticeUser.filterConditionalTags(conditionalTags)
				noticeUser.sendMessage("AWAY", value, to=None, prefix=noticePrefix, tags=tags)
		else:
			for noticeUser in noticeUsers:
				tags = noticeUser.filterConditionalTags(conditionalTags)
				noticeUser.sendMessage("AWAY", to=None, prefix=noticePrefix, tags=tags)

	def tellChannelAway(self, channel, user):
		if not user.metadataKeyExists("away"):
			return
		awayReason = user.metadataValue("away")
		noticePrefix=user.hostmask()
		conditionalTags = {}
		self.ircd.runActionStandard("sendingusertags", user, conditionalTags)
		for noticeUser in channel.users.iterkeys():
			if noticeUser.uuid[:3] == self.ircd.serverID and "capabilities" in noticeUser.cache and "away-notify" in noticeUser.cache["capabilities"]:
				tags = noticeUser.filterConditionalTags(conditionalTags)
				noticeUser.sendMessage("AWAY", awayReason, to=None, prefix=noticePrefix, tags=tags)

awayNotify = AwayNotify()


text:
#ifndef DatabaseManager_h
#define DatabaseManager_h

#include "modules/webdatabase/DatabaseBasicTypes.h"
#include "modules/webdatabase/DatabaseError.h"
#include "wtf/Assertions.h"
#include "wtf/HashMap.h"
#include "wtf/PassRefPtr.h"
#include "wtf/ThreadingPrimitives.h"
#include "wtf/text/WTFString.h"

namespace WebCore {

class AbstractDatabaseServer;
class Database;
class DatabaseBackendBase;
class DatabaseCallback;
class DatabaseContext;
class DatabaseSync;
class DatabaseTaskSynchronizer;
class ExceptionState;
class SecurityOrigin;
class ExecutionContext;

typedef int ExceptionCode;

class DatabaseManager {
    WTF_MAKE_NONCOPYABLE(DatabaseManager); WTF_MAKE_FAST_ALLOCATED;
public:
    static DatabaseManager& manager();

    // This gets a DatabaseContext for the specified ExecutionContext.
    // If one doesn't already exist, it will create a new one.
    PassRefPtr<DatabaseContext> databaseContextFor(ExecutionContext*);

    // These 2 methods are for DatabaseContext (un)registration, and should only
    // be called by the DatabaseContext constructor and destructor.
    void registerDatabaseContext(DatabaseContext*);
    void unregisterDatabaseContext(DatabaseContext*);

#if !ASSERT_DISABLED
    void didConstructDatabaseContext();
    void didDestructDatabaseContext();
#else
    void didConstructDatabaseContext() { }
    void didDestructDatabaseContext() { }
#endif

    static void throwExceptionForDatabaseError(DatabaseError, const String& errorMessage, ExceptionState&);

    PassRefPtr<Database> openDatabase(ExecutionContext*, const String& name, const String& expectedVersion, const String& displayName, unsigned long estimatedSize, PassOwnPtr<DatabaseCallback>, DatabaseError&, String& errorMessage);
    PassRefPtr<DatabaseSync> openDatabaseSync(ExecutionContext*, const String& name, const String& expectedVersion, const String& displayName, unsigned long estimatedSize, PassOwnPtr<DatabaseCallback>, DatabaseError&, String& errorMessage);

    bool hasOpenDatabases(ExecutionContext*);
    void stopDatabases(ExecutionContext*, DatabaseTaskSynchronizer*);

    String fullPathForDatabase(SecurityOrigin*, const String& name, bool createIfDoesNotExist = true);

    void closeDatabasesImmediately(const String& originIdentifier, const String& name);

    void interruptAllDatabasesForContext(ExecutionContext*);

private:
    DatabaseManager();
    ~DatabaseManager() { }

    // This gets a DatabaseContext for the specified ExecutionContext if
    // it already exist previously. Otherwise, it returns 0.
    PassRefPtr<DatabaseContext> existingDatabaseContextFor(ExecutionContext*);

    PassRefPtr<DatabaseBackendBase> openDatabaseBackend(ExecutionContext*,
        DatabaseType, const String& name, const String& expectedVersion, const String& displayName,
        unsigned long estimatedSize, bool setVersionInNewDatabase, DatabaseError&, String& errorMessage);

    static void logErrorMessage(ExecutionContext*, const String& message);

    AbstractDatabaseServer* m_server;

    // Access to the following fields require locking m_contextMapLock:
    typedef HashMap<ExecutionContext*, DatabaseContext*> ContextMap;
    ContextMap m_contextMap;
#if !ASSERT_DISABLED
    int m_databaseContextRegisteredCount;
    int m_databaseContextInstanceCount;
#endif
    Mutex m_contextMapLock;
};

} // namespace WebCore

#endif // DatabaseManager_h


text:
<?php

namespace Point\PointFinance\Http\Controllers\PaymentOrder;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Point\Core\Helpers\UserHelper;
use Point\Core\Models\User;
use Point\Core\Traits\ValidationTrait;
use Point\Framework\Helpers\FormulirHelper;
use Point\Framework\Models\Master\Allocation;
use Point\Framework\Models\Master\Coa;
use Point\Framework\Models\Master\CoaCategory;
use Point\Framework\Models\Master\CoaPosition;
use Point\Framework\Models\Master\Person;
use Point\PointFinance\Helpers\PaymentHelper;
use Point\PointFinance\Helpers\PaymentOrderHelper;
use Point\PointFinance\Http\Controllers\Controller;
use Point\PointFinance\Models\CashAdvance;
use Point\PointFinance\Models\PaymentOrder\PaymentOrder;

class PaymentOrderController extends Controller
{
    use ValidationTrait;

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        access_is_allowed('read.point.finance.payment.order');

        $view = view('point-finance::app.finance.point.payment-order.index');
        $list_payment_order = PaymentOrder::joinFormulir()->joinPerson()->notArchived()->selectOriginal();
        $view->list_payment_order = PaymentOrderHelper::searchList($list_payment_order, \Input::get('order_by'), \Input::get('order_type'), \Input::get('status'), \Input::get('date_from'), \Input::get('date_to'), \Input::get('search'));
        $view->list_payment_order = $list_payment_order->paginate(100);
        return $view;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function createStep1()
    {
        access_is_allowed('create.point.finance.payment.order');

        $view = view('point-finance::app.finance.point.payment-order.create-step-1');
        $view->list_person = Person::active()->get();
        return $view;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function createStep2()
    {
        access_is_allowed('create.point.finance.payment.order');

        $view = view('point-finance::app.finance.point.payment-order.create-step-2');
        if (app('request')->input('person_id') == null) {
            gritter_error('please choose who will receive this payment');
            return back();
        }
        $view->person = Person::find(app('request')->input('person_id'));
        $view->list_coa = Coa::getNonSubledgerAndNotInSettingJournal();
        $view->list_allocation = Allocation::active()->get();
        $view->list_user_approval = UserHelper::getAllUser();
        $view->list_cash_advance = CashAdvance::joinFormulir()->notArchived()->notCanceled()->selectOriginal()
            ->where('is_payed', true)
            ->where('remaining_amount', '>', 0)
            ->get();

        $view->coa_expense = CoaPosition::where("name", "Expense")->first();
        $view->list_coa_category_expense = CoaCategory::where('coa_position_id', $view->coa_expense->id)->get();

        return $view;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function createStep3()
    {
        access_is_allowed('create.point.finance.payment.order');

        if (app('request')->input('approval_to') == null) {
            gritter_error('please choose user approval');
            return redirect('finance/point/payment-order/create-step-1');
        }

        $view = view('point-finance::app.finance.point.payment-order.create-step-3');
        $view->payment_date = date_format_db(app('request')->input('payment_date'), app('request')->input('time'));
        $view->approval_to = User::find(app('request')->input('approval_to'));
        $view->person = Person::find(app('request')->input('person_id'));
        $view->coa_id = app('request')->input('coa_id');
        $view->payment_type = app('request')->input('payment_type');
        $view->cash_advance = CashAdvance::find(app('request')->input('cash_advance'));
        $view->notes = app('request')->input('notes');
        $view->amount = number_format_db(app('request')->input('amount'));
        $view->allocation_id = app('request')->input('allocation_id');
        $view->detail_notes = app('request')->input('detail_notes');
        return $view;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'payment_date' => 'required',
            'approval_to' => 'required',
            'person_id' => 'required',
            'payment_type' => 'required',
            'coa_id' => 'required',
            'coa_allocation_id' => 'required',
            'other_notes' => 'required',
            'coa_value' => 'required',
        ]);

        $request['form_date'] = date('Y-m-d', strtotime($request->input('payment_date')));

        DB::beginTransaction();

        formulir_is_allowed_to_create('create.point.finance.payment.order', date_format_db($request->input('form_date')), []);
        $formulir = FormulirHelper::create($request->input(), 'point-finance-payment-order');
        $payment_order = PaymentOrderHelper::create($request, $formulir);

        timeline_publish('create.point.finance.payment.order', 'create payment order "'. $formulir->form_number .'" success');
        DB::commit();

        gritter_success('create payment order "'. $formulir->form_number .'" success');
        return redirect('finance/point/payment-order/'.$payment_order->id);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        access_is_allowed('read.point.finance.payment.order');

        $view = view('point-finance::app.finance.point.payment-order.show');
        $view->payment_order = PaymentOrder::find($id);
        $view->cash_advance = $view->payment_order->cashAdvance;
        $view->list_payment_order_archived = PaymentOrder::joinFormulir()->archived($view->payment_order->formulir->form_number)->selectOriginal()->get();
        $view->revision = $view->list_payment_order_archived->count();
        return $view;
    }

    /**
     * Display archived resource
     *
     * @param $id
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function archived($id)
    {
        $view = view('point-finance::app.finance.point.payment-order.archived');
        $view->payment_order_archived = PaymentOrder::find($id);
        $view->payment_order = PaymentOrder::joinFormulir()->notArchived($view->payment_order_archived->formulir->archived)->selectOriginal()->first();
        return $view;
    }

    /**
     * Cancel a form
     *
     * @return array
     */
    public function cancel()
    {
        $permission_slug = app('request')->input('permission_slug');
        $formulir_id = app('request')->input('formulir_id');

        DB::beginTransaction();

        FormulirHelper::cancel($permission_slug, $formulir_id);
        PaymentHelper::cancelPaymentReference($formulir_id);

        DB::commit();

        return array('status' => 'success');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        access_is_allowed('update.point.finance.payment.order');

        $view = view('point-finance::app.finance.point.payment-order.edit');
        $view->payment_order = PaymentOrder::find($id);
        $view->list_coa = Coa::getNonSubledger();
        $view->list_allocation = Allocation::active()->get();
        $view->list_user_approval = UserHelper::getAllUser();
        $view->coa_expense = CoaPosition::where("name", "Expense")->first();
        $view->list_coa_category_expense = CoaCategory::where('coa_position_id', $view->coa_expense->id)->get();
        return $view;
    }

    /**
     * Display review edited form
     *
     * @param $id
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function editReview($id)
    {
        access_is_allowed('update.point.finance.payment.order');

        $view = view('point-finance::app.finance.point.payment-order.edit-review');
        $view->payment_order = PaymentOrder::find($id);
        $view->payment_date = date_format_db(app('request')->input('payment_date'), app('request')->input('time'));
        $view->approval_to = User::find(app('request')->input('approval_to'));
        $view->person = Person::find(app('request')->input('person_id'));
        $view->payment_type = app('request')->input('payment_type');
        $view->coa_id = app('request')->input('coa_id');
        $view->notes = app('request')->input('notes');
        $view->amount = number_format_db(app('request')->input('amount'));
        $view->allocation_id = app('request')->input('allocation_id');
        $view->detail_notes = app('request')->input('detail_notes');
        return $view;
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'payment_date' => 'required',
            'approval_to' => 'required',
            'person_id' => 'required',
            'payment_type' => 'required',
            'coa_id' => 'required',
            'coa_allocation_id' => 'required',
            'other_notes' => 'required',
            'coa_value' => 'required',
        ]);

        $request['form_date'] = date('Y-m-d', strtotime($request->input('payment_date')));
        formulir_is_allowed_to_update('update.point.finance.payment.order', $request['form_date'], PaymentOrder::find($id)->formulir);

        DB::beginTransaction();
        $payment_order = PaymentOrder::find($id);
        $formulir_old = FormulirHelper::archive($request->input(), $payment_order->formulir_id);
        $formulir = FormulirHelper::update($request->input(), $formulir_old->archived, $formulir_old->form_raw_number);
        $payment_order = PaymentOrderHelper::create($request, $formulir);
        PaymentHelper::cancelPaymentReference($formulir_old->id);
        timeline_publish('update.point.finance.payment.order', 'update payment order "'. $formulir->form_number .'" success');

        DB::commit();

        gritter_success('update payment order "'. $formulir->form_number .'" success');
        return redirect('finance/point/payment-order/'.$payment_order->id);
    }

    public function _createCoaExpense(Request $request)
    {
        access_is_allowed('create.coa');

        if (!$this->validateCSRF()) {
            return response()->json($this->restrictionAccessMessage());
        }

        $validator = \Validator::make($request->all(), [
            'name' => 'required|string',
            'coa_category'=>'required',
        ]);

        $response = array('status' =>'failed');
        if ($validator->fails()) {
            return response()->json($response);
        }

        $coa = new Coa;
        $coa->name = $_POST['name'];
        $coa->coa_category_id = $_POST['coa_category'];
        $coa->created_by = auth()->user()->id;
        $coa->updated_by = auth()->user()->id;

        $check = Coa::where('name', $_POST['name'])->first();

        if (count($check) < 1) {
            $coa->save();
            $response = array(
                'status' => 'success',
                'code'=> $coa->id,
                'name'=> $coa->name,
             );
        }
        return response()->json($response);
    }
}


text:
/*
 * inferenz.hpp
 *
 *  Created on: Mar 24, 2013
 *      Author: mdantone
 */

#ifndef INFERENZ_HPP_
#define INFERENZ_HPP_

#include "cpp/learning/pictorial_structure/model.hpp"

namespace learning
{
namespace ps
{

class Inferenz {
public:

  Inferenz(Model* m) : model(m), _inferenz_score(0),min_computed(false)  {
    int n_parts = model->get_num_parts();

    // scores with the message recieved from the child (parent_score + distance_transform(child_score))
    scores.resize(n_parts);
    // scores without the message that a child sends to its parent
    scores_without_dt.resize(n_parts);
    score_src_x.resize(n_parts);
    score_src_y.resize(n_parts);

  };

  float compute_min(int part_id = 0);

  void compute_arg_min( std::vector<cv::Point_<int> >& min_locations,
      int part_id = 0) const;

  void non_max_supression( std::vector<std::vector<cv::Point_<int> > >& locations,
      int n_locations);

  float get_score() const {
    return _inferenz_score;
  }

  bool min_is_computed() const{
    return min_computed;
  }

protected:
  Model* model;
  float _inferenz_score;
  std::vector<cv::Mat_<float> > scores;
  std::vector<cv::Mat_<float> > scores_without_dt;
  std::vector<cv::Mat_<int> > score_src_x;
  std::vector<cv::Mat_<int> > score_src_y;
  bool min_computed;
};

float inferenz_multiple(std::vector<Model> models,
    const std::vector<cv::Mat_<float> >& apperance_scores,
    std::vector<cv::Point_<int> >& min_locations, bool debug = false,
    const cv::Mat& img = cv::Mat(), float weight = 0.0, int num_threads = 0);

float inferenz_multiple(std::vector<Model> models,
    const std::vector<cv::Mat_<float> >& apperance_scores,
    std::vector<cv::Point_<int> >& min_locations, int& min_index, bool debug = false,
    const cv::Mat& img = cv::Mat(), float weight = 0.0, int num_threads = 0);

float inferenz_multiple_diff_votmap(std::vector<std::vector<Model> > models,
      const std::vector< std::vector<cv::Mat_<float> > >& apperance_scores,
      std::vector<int> indexes,
      std::vector<cv::Point_<int> >& min_locations, bool debug = false, const cv::Mat& img = cv::Mat(), float weight = 0.0, int num_threads = 0);

} /* namespace ps */
} /* namespace learning */

#endif /* INFERENZ_HPP_ */


text:
/* global describe, it, beforeEach*/
'use strict';

var sinon = require('sinon');
var expect = require('expect.js');
var FoxxRepository = require('@arangodb/foxx/legacy/repository').Repository;
var Model = require('@arangodb/foxx/legacy/model').Model;

describe('Model Events', function () {
  var collection, instance, repository;

  beforeEach(function () {
    collection = {
      update: function () {},
      save: function () {},
      type: sinon.stub().returns(2),
      remove: function () {}
    };
    instance = new Model({ random: '', beforeCalled: false, afterCalled: false });
    repository = new FoxxRepository(collection, {model: Model});
  });

  it('should be possible to subscribe and emit events', function () {
    expect(instance.on).to.be.a('function');
    expect(instance.emit).to.be.a('function');
  });

  it('should emit beforeCreate and afterCreate events when creating the model', function () {
    addHooks(instance, 'Create');
    expect(repository.save(instance)).to.eql(instance);
    expect(instance.get('beforeCalled')).to.be(true);
    expect(instance.get('afterCalled')).to.be(true);
  });

  it('should emit beforeSave and afterSave events when creating the model', function () {
    addHooks(instance, 'Save');
    expect(repository.save(instance)).to.eql(instance);
    expect(instance.get('beforeCalled')).to.be(true);
    expect(instance.get('afterCalled')).to.be(true);
  });

  it('should emit beforeUpdate and afterUpdate events when updating the model', function () {
    var newData = { newAttribute: 'test' };
    addHooks(instance, 'Update', newData);
    expect(repository.update(instance, newData)).to.eql(instance);
    expect(instance.get('beforeCalled')).to.be(true);
    expect(instance.get('afterCalled')).to.be(true);
  });

  it('should emit beforeSave and afterSave events when updating the model', function () {
    var newData = { newAttribute: 'test' };
    addHooks(instance, 'Save', newData);
    expect(repository.update(instance, newData)).to.eql(instance);
    expect(instance.get('beforeCalled')).to.be(true);
    expect(instance.get('afterCalled')).to.be(true);
  });

  it('should emit beforeRemove and afterRemove events when removing the model', function () {
    addHooks(instance, 'Remove');
    repository.remove(instance);
    expect(instance.get('beforeCalled')).to.be(true);
    expect(instance.get('afterCalled')).to.be(true);
  });
});

function addHooks (model, ev, dataToReceive) {
  var random = String(Math.floor(Math.random() * 1000));

  model.on('before' + ev, function (data) {
    expect(this).to.eql(model);
    expect(data).to.eql(dataToReceive);
    this.set('random', random);
    this.set('beforeCalled', true);
  });
  model.on('after' + ev, function (data) {
    expect(this).to.eql(model);
    expect(data).to.eql(dataToReceive);
    this.set('afterCalled', true);
    expect(this.get('beforeCalled')).to.be(true);
    expect(this.get('random')).to.eql(random);
  });
}


text:
package com.jhipster.sample.domain.enumeration;

/**
 * The WeightUnit enumeration.
 */
public enum WeightUnit {
    KG,LB
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>SMTP::Rset()</title>

SMTP :: boolean rset ( resource connection )

Return TRUE if has been successfully sent, FALSE if not.

Send "RSET" SMTP command.

See Also: SMTP::Data()

[ Comments ]

Last update: Sunday, June 24, 2007


text:
import { Socket } from "net";
import RawIPC = require("node-ipc");
let ipc = new RawIPC.IPC();
ipc = RawIPC;
ipc.config.appspace = "./x";
ipc.config.encoding = "base64";
ipc.config.id = "id1";
ipc.config.interfaces = {
    localAddress: true,
    family: true,
    hints: false,
    localPort: true,
    lookup: false,
};
ipc.config.logDepth = 6;
ipc.config.logInColor = true;
ipc.config.maxConnections = 200;
ipc.config.maxRetries = false;
ipc.config.networkHost = "127.0.0.1";
ipc.config.networkPort = 8000;
ipc.config.rawBuffer = true;
ipc.config.retry = 1000;
ipc.config.silent = true;
ipc.config.socketRoot = "";
ipc.config.stopRetrying = false;
ipc.config.sync = true;
ipc.config.tls = {
    rejectUnauthorized: false,
    public: "",
    private: "",
};
ipc.connectTo("world");
ipc.connectTo("world", () => { });
ipc.connectTo("id1", "path1", () => { });
ipc.connectToNet("world");
ipc.connectToNet("world", () => { });
ipc.connectToNet("world", "myapp.com", 3435);
ipc.connectToNet("world", "myapp.com", 3435, () => { });
ipc.connectToNet("world", 3435, () => { });
ipc.disconnect("id");
ipc.serve();
ipc.serve(null);
ipc.serve("path", () => { });
ipc.serve(() => { });
ipc.serveNet();
ipc.serveNet("udp4");
ipc.serveNet(() => { });
ipc.serveNet("udp4", () => { });
ipc.serveNet(3435);
ipc.serveNet("MyMostAwesomeApp.com", 3435, () => { });
ipc.serveNet("MyMostAwesomeApp.com", 3435, "udp4", () => { });
ipc.of.world.on("error", (err: any) => { });
ipc.of.world.on("connect", () => { });
ipc.of.world.on("disconnect", () => { });
ipc.of.world.on("data", (buf: Buffer) => { buf.byteLength; });
ipc.of.world.on("socket.disconnected", (socket: Socket, id: string) => { id.toLowerCase(); });
ipc.of.world.on("message", (data: any, data2: any) => { });
ipc.server.emit("event", [1, 2, 3]);
const myBuffer = new Buffer(6).fill(0);
declare const socket: Socket;
ipc.server.emit(socket, myBuffer);
ipc.server.emit([10, 20, 30]);
ipc.server.emit({ address: 'localhost', port: 8000 }, "message", { id: ipc.config.id, message: 'Goodbye' });


text:
<?php

namespace Larapack\Hooks\Events;

use Larapack\Hooks\Hook;

class UninstallingHook
{
    public $hook;

    /**
     * Create a new event instance.
     *
     * @param \Larapack\Hooks\Hook $hook
     */
    public function __construct(Hook $hook)
    {
        $this->hook = $hook;
    }
}


text:
Caching soffit content in the portal is available _via_ the standard HTTP header
`Cache-Control`.  You must set `Cache-Control` as an HTTP response header to
take advantage of this feature.

### Example

``` http
Cache-Control: public, max-age=300
```

Cache scope may be `public` (shared by all users) or `private` (cached
per-user).  Specify `max-age` in seconds.

Cache re-validation is not yet supported, so...

``` http
Cache-Control: no-store
```

and...

``` http
Cache-Control: no-cache
```

currently have the same effect.


text: SELECT a FROM t1 WHERE r < 32767 ORDER BY r


text:
#ifndef __DALI_INTEGRATION_TAP_GESTURE_H__
#define __DALI_INTEGRATION_TAP_GESTURE_H__

// INTERNAL INCLUDES
#include <dali/integration-api/events/gesture-event.h>
#include <dali/public-api/math/vector2.h>

namespace Dali DALI_IMPORT_API
{

namespace Integration
{

/**
 * If the adaptor detects a tap gesture, then it should create an instance of this structure and
 * send it to the Core.
 *
 * A Tap Gesture event should be in one of three states:
 * - Possible:  When the user first puts their finger down - Core needs to hit test the down point so
 *              that a tap (down and up quickly) is also on the same actor.
 * - Started:   If a tap is detected (No Finished state is expected).
 * - Cancelled: If, after a down event, no tap is detected, or a system interruption.
 *
 * A Started state will be ignored if a Possible state does not precede it.
 */
struct TapGestureEvent : public GestureEvent
{
  // Construction & Destruction

  /**
   * Default Constructor
   * @param[in]  state  Possible, denotes down press;
   *                    Started, of a tap occurs; and
   *                    Cancelled, when tap does not occur.
   */
  TapGestureEvent( Gesture::State state );

  /**
   * Virtual destructor
   */
  virtual ~TapGestureEvent();

  // Data

  /**
   * @copydoc Dali::TapGesture::numberOfTaps
   */
  unsigned int numberOfTaps;

  /**
   * @copydoc Dali::TapGesture::numberOfTouches
   */
  unsigned int numberOfTouches;

  /**
   * This is the point, in screen coordinates, where the tap occurred.
   * If a multi-touch tap, then this should be the centroid of all the touch points.
   */
  Vector2 point;
};

} // namespace Integration

} // namespace Dali

#endif // __DALI_INTEGRATION_TAP_GESTURE_H__


text:
set -e
source helpers.sh

start_up

CRYPTO_PROFILE="RSA"
setup_fapi $CRYPTO_PROFILE

function cleanup {
    tss2 delete --path=/
    shut_down
}

trap cleanup EXIT

KEY_PATH=HS/SRK/myRSASign

tss2 provision

tss2 createkey --path=$KEY_PATH --type="noDa, sign" --authValue=""

tss2 list

PROFILE_NAME=$( tss2 list --searchPath= --pathList=- | cut -d "/" -f2 )
SIGN_OBJECT=/$PROFILE_NAME/$KEY_PATH

if [ `tss2 list --searchPath=$KEY_PATH --pathList=-` != $SIGN_OBJECT ]; then
  echo "tss2_list single object failed"
  exit 1
fi

exit 0


text:
[Home](./index.md) > [typeioc](./typeioc.md) > [IDecoratorRegistration](./typeioc.idecoratorregistration.md) > [within](./typeioc.idecoratorregistration.within.md)

## IDecoratorRegistration.within() method

Specifies resolution instance scope. Scope determines how resolved service instances behave in between resolutions

Signature:

```typescript
within(scope: ScopeType): WithDecoratorRegister<T>;
```

## Parameters

|  Parameter | Type | Description |
|  --- | --- | --- |
|  scope | ScopeType | the value of the scope [ScopeType](./typeioc.scopetype.md) |

Returns:

`WithDecoratorRegister<T>`

- an instance of [WithDecoratorRegister](./typeioc.withdecoratorregister.md) interface


text:
/**
 * Parses the number x and returns its sign. For positive x returns 1, for
 * negative, -1. For 0 and -0, returns 0 and -0 respectively. For any number
 * that parses to NaN, returns NaN.
 *
 * @param {number} x
 * @return {number}
 */
export function sign(x) {
  x = Number(x);

  // If x is 0, -0, or NaN, return it.
  if (!x) {
    return x;
  }

  return x > 0 ? 1 : -1;
}

/**
 * Sets the Math.sign polyfill if it does not exist.
 * @param {!Window} win
 */
export function install(win) {
  if (!win.Math.sign) {
    win.Object.defineProperty(win.Math, 'sign', {
      enumerable: false,
      configurable: true,
      writable: true,
      value: sign,
    });
  }
}