code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
define(['App', 'jquery', 'underscore', 'backbone', 'hbs!template/subreddit-picker-item', 'view/basem-view'],
function(App, $, _, Backbone, SRPitemTmpl, BaseView) {
return BaseView.extend({
template: SRPitemTmpl,
events: {
'click .add': 'subscribe',
'click .remove': 'unsubscribe'
},
initialize: function(data) {
this.model = data.model;
},
subscribe: function(e) {
e.preventDefault()
e.stopPropagation()
var target = this.$(e.currentTarget)
target.removeClass('add').addClass('remove').html('unsubscribe')
var params = {
action: 'sub',
sr: this.model.get('name'),
sr_name: this.model.get('name'),
uh: $.cookie('modhash')
};
console.log(params)
this.api("api/subscribe", 'POST', params, function(data) {
console.log("subscribe done", data)
//edit the window and cookie
App.trigger('header:refreshSubreddits')
});
},
unsubscribe: function(e) {
e.preventDefault()
e.stopPropagation()
var target = this.$(e.currentTarget)
target.removeClass('remove').addClass('add').html('subscribe')
var params = {
action: 'unsub',
sr: this.model.get('name'),
uh: $.cookie('modhash')
};
console.log(params)
this.api("api/subscribe", 'POST', params, function(data) {
console.log("unsubscribe done", data)
App.trigger('header:refreshSubreddits')
});
}
});
}); | BenjaminAdams/RedditJS | public/js/app/view/subreddit-picker-item-view.js | JavaScript | bsd-3-clause | 1,957 |
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\helpers;
use Yii;
use yii\base\InvalidParamException;
use yii\db\ActiveRecordInterface;
use yii\validators\StringValidator;
use yii\web\Request;
use yii\base\Model;
/**
* BaseHtml provides concrete implementation for [[Html]].
*
* Do not use BaseHtml. Use [[Html]] instead.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class BaseHtml
{
/**
* @var array list of void elements (element name => 1)
* @see http://www.w3.org/TR/html-markup/syntax.html#void-element
*/
public static $voidElements = [
'area' => 1,
'base' => 1,
'br' => 1,
'col' => 1,
'command' => 1,
'embed' => 1,
'hr' => 1,
'img' => 1,
'input' => 1,
'keygen' => 1,
'link' => 1,
'meta' => 1,
'param' => 1,
'source' => 1,
'track' => 1,
'wbr' => 1,
];
/**
* @var array the preferred order of attributes in a tag. This mainly affects the order of the attributes
* that are rendered by [[renderTagAttributes()]].
*/
public static $attributeOrder = [
'type',
'id',
'class',
'name',
'value',
'href',
'src',
'action',
'method',
'selected',
'checked',
'readonly',
'disabled',
'multiple',
'size',
'maxlength',
'width',
'height',
'rows',
'cols',
'alt',
'title',
'rel',
'media',
];
/**
* @var array list of tag attributes that should be specially handled when their values are of array type.
* In particular, if the value of the `data` attribute is `['name' => 'xyz', 'age' => 13]`, two attributes
* will be generated instead of one: `data-name="xyz" data-age="13"`.
* @since 2.0.3
*/
public static $dataAttributes = ['data', 'data-ng', 'ng'];
/**
* Encodes special characters into HTML entities.
* The [[\yii\base\Application::charset|application charset]] will be used for encoding.
* @param string $content the content to be encoded
* @param boolean $doubleEncode whether to encode HTML entities in `$content`. If false,
* HTML entities in `$content` will not be further encoded.
* @return string the encoded content
* @see decode()
* @see http://www.php.net/manual/en/function.htmlspecialchars.php
*/
public static function encode($content, $doubleEncode = true)
{
return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, Yii::$app ? Yii::$app->charset : 'UTF-8', $doubleEncode);
}
/**
* Decodes special HTML entities back to the corresponding characters.
* This is the opposite of [[encode()]].
* @param string $content the content to be decoded
* @return string the decoded content
* @see encode()
* @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php
*/
public static function decode($content)
{
return htmlspecialchars_decode($content, ENT_QUOTES);
}
/**
* Generates a complete HTML tag.
* @param string $name the tag name
* @param string $content the content to be enclosed between the start and end tags. It will not be HTML-encoded.
* If this is coming from end users, you should consider [[encode()]] it to prevent XSS attacks.
* @param array $options the HTML tag attributes (HTML options) in terms of name-value pairs.
* These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
*
* For example when using `['class' => 'my-class', 'target' => '_blank', 'value' => null]` it will result in the
* html attributes rendered like this: `class="my-class" target="_blank"`.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated HTML tag
* @see beginTag()
* @see endTag()
*/
public static function tag($name, $content = '', $options = [])
{
$html = "<$name" . static::renderTagAttributes($options) . '>';
return isset(static::$voidElements[strtolower($name)]) ? $html : "$html$content</$name>";
}
/**
* Generates a start tag.
* @param string $name the tag name
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated start tag
* @see endTag()
* @see tag()
*/
public static function beginTag($name, $options = [])
{
return "<$name" . static::renderTagAttributes($options) . '>';
}
/**
* Generates an end tag.
* @param string $name the tag name
* @return string the generated end tag
* @see beginTag()
* @see tag()
*/
public static function endTag($name)
{
return "</$name>";
}
/**
* Generates a style tag.
* @param string $content the style content
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated style tag
*/
public static function style($content, $options = [])
{
return static::tag('style', $content, $options);
}
/**
* Generates a script tag.
* @param string $content the script content
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated script tag
*/
public static function script($content, $options = [])
{
return static::tag('script', $content, $options);
}
/**
* Generates a link tag that refers to an external CSS file.
* @param array|string $url the URL of the external CSS file. This parameter will be processed by [[Url::to()]].
* @param array $options the tag options in terms of name-value pairs. The following option is specially handled:
*
* - condition: specifies the conditional comments for IE, e.g., `lt IE 9`. When this is specified,
* the generated `link` tag will be enclosed within the conditional comments. This is mainly useful
* for supporting old versions of IE browsers.
* - noscript: if set to true, `link` tag will be wrapped into `<noscript>` tags.
*
* The rest of the options will be rendered as the attributes of the resulting link tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated link tag
* @see Url::to()
*/
public static function cssFile($url, $options = [])
{
if (!isset($options['rel'])) {
$options['rel'] = 'stylesheet';
}
$options['href'] = Url::to($url);
if (isset($options['condition'])) {
$condition = $options['condition'];
unset($options['condition']);
return self::wrapIntoCondition(static::tag('link', '', $options), $condition);
} elseif (isset($options['noscript']) && $options['noscript'] === true) {
unset($options['noscript']);
return "<noscript>" . static::tag('link', '', $options) . "</noscript>";
} else {
return static::tag('link', '', $options);
}
}
/**
* Generates a script tag that refers to an external JavaScript file.
* @param string $url the URL of the external JavaScript file. This parameter will be processed by [[Url::to()]].
* @param array $options the tag options in terms of name-value pairs. The following option is specially handled:
*
* - condition: specifies the conditional comments for IE, e.g., `lt IE 9`. When this is specified,
* the generated `script` tag will be enclosed within the conditional comments. This is mainly useful
* for supporting old versions of IE browsers.
*
* The rest of the options will be rendered as the attributes of the resulting script tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated script tag
* @see Url::to()
*/
public static function jsFile($url, $options = [])
{
$options['src'] = Url::to($url);
if (isset($options['condition'])) {
$condition = $options['condition'];
unset($options['condition']);
return self::wrapIntoCondition(static::tag('script', '', $options), $condition);
} else {
return static::tag('script', '', $options);
}
}
/**
* Wraps given content into conditional comments for IE, e.g., `lt IE 9`.
* @param string $content raw HTML content.
* @param string $condition condition string.
* @return string generated HTML.
*/
private static function wrapIntoCondition($content, $condition)
{
if (strpos($condition, '!IE') !== false) {
return "<!--[if $condition]><!-->\n" . $content . "\n<!--<![endif]-->";
}
return "<!--[if $condition]>\n" . $content . "\n<![endif]-->";
}
/**
* Generates the meta tags containing CSRF token information.
* @return string the generated meta tags
* @see Request::enableCsrfValidation
*/
public static function csrfMetaTags()
{
$request = Yii::$app->getRequest();
if ($request instanceof Request && $request->enableCsrfValidation) {
return static::tag('meta', '', ['name' => 'csrf-param', 'content' => $request->csrfParam]) . "\n "
. static::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]) . "\n";
} else {
return '';
}
}
/**
* Generates a form start tag.
* @param array|string $action the form action URL. This parameter will be processed by [[Url::to()]].
* @param string $method the form submission method, such as "post", "get", "put", "delete" (case-insensitive).
* Since most browsers only support "post" and "get", if other methods are given, they will
* be simulated using "post", and a hidden input will be added which contains the actual method type.
* See [[\yii\web\Request::methodParam]] for more details.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated form start tag.
* @see endForm()
*/
public static function beginForm($action = '', $method = 'post', $options = [])
{
$action = Url::to($action);
$hiddenInputs = [];
$request = Yii::$app->getRequest();
if ($request instanceof Request) {
if (strcasecmp($method, 'get') && strcasecmp($method, 'post')) {
// simulate PUT, DELETE, etc. via POST
$hiddenInputs[] = static::hiddenInput($request->methodParam, $method);
$method = 'post';
}
if ($request->enableCsrfValidation && !strcasecmp($method, 'post')) {
$hiddenInputs[] = static::hiddenInput($request->csrfParam, $request->getCsrfToken());
}
}
if (!strcasecmp($method, 'get') && ($pos = strpos($action, '?')) !== false) {
// query parameters in the action are ignored for GET method
// we use hidden fields to add them back
foreach (explode('&', substr($action, $pos + 1)) as $pair) {
if (($pos1 = strpos($pair, '=')) !== false) {
$hiddenInputs[] = static::hiddenInput(
urldecode(substr($pair, 0, $pos1)),
urldecode(substr($pair, $pos1 + 1))
);
} else {
$hiddenInputs[] = static::hiddenInput(urldecode($pair), '');
}
}
$action = substr($action, 0, $pos);
}
$options['action'] = $action;
$options['method'] = $method;
$form = static::beginTag('form', $options);
if (!empty($hiddenInputs)) {
$form .= "\n" . implode("\n", $hiddenInputs);
}
return $form;
}
/**
* Generates a form end tag.
* @return string the generated tag
* @see beginForm()
*/
public static function endForm()
{
return '</form>';
}
/**
* Generates a hyperlink tag.
* @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code
* such as an image tag. If this is coming from end users, you should consider [[encode()]]
* it to prevent XSS attacks.
* @param array|string|null $url the URL for the hyperlink tag. This parameter will be processed by [[Url::to()]]
* and will be used for the "href" attribute of the tag. If this parameter is null, the "href" attribute
* will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated hyperlink
* @see \yii\helpers\Url::to()
*/
public static function a($text, $url = null, $options = [])
{
if ($url !== null) {
$options['href'] = Url::to($url);
}
return static::tag('a', $text, $options);
}
/**
* Generates a mailto hyperlink.
* @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code
* such as an image tag. If this is coming from end users, you should consider [[encode()]]
* it to prevent XSS attacks.
* @param string $email email address. If this is null, the first parameter (link body) will be treated
* as the email address and used.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated mailto link
*/
public static function mailto($text, $email = null, $options = [])
{
$options['href'] = 'mailto:' . ($email === null ? $text : $email);
return static::tag('a', $text, $options);
}
/**
* Generates an image tag.
* @param array|string $src the image URL. This parameter will be processed by [[Url::to()]].
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated image tag
*/
public static function img($src, $options = [])
{
$options['src'] = Url::to($src);
if (!isset($options['alt'])) {
$options['alt'] = '';
}
return static::tag('img', '', $options);
}
/**
* Generates a label tag.
* @param string $content label text. It will NOT be HTML-encoded. Therefore you can pass in HTML code
* such as an image tag. If this is is coming from end users, you should [[encode()]]
* it to prevent XSS attacks.
* @param string $for the ID of the HTML element that this label is associated with.
* If this is null, the "for" attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated label tag
*/
public static function label($content, $for = null, $options = [])
{
$options['for'] = $for;
return static::tag('label', $content, $options);
}
/**
* Generates a button tag.
* @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
* Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
* you should consider [[encode()]] it to prevent XSS attacks.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated button tag
*/
public static function button($content = 'Button', $options = [])
{
if (!isset($options['type'])) {
$options['type'] = 'button';
}
return static::tag('button', $content, $options);
}
/**
* Generates a submit button tag.
* @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
* Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
* you should consider [[encode()]] it to prevent XSS attacks.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated submit button tag
*/
public static function submitButton($content = 'Submit', $options = [])
{
$options['type'] = 'submit';
return static::button($content, $options);
}
/**
* Generates a reset button tag.
* @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
* Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
* you should consider [[encode()]] it to prevent XSS attacks.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated reset button tag
*/
public static function resetButton($content = 'Reset', $options = [])
{
$options['type'] = 'reset';
return static::button($content, $options);
}
/**
* Generates an input type of the given type.
* @param string $type the type attribute.
* @param string $name the name attribute. If it is null, the name attribute will not be generated.
* @param string $value the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated input tag
*/
public static function input($type, $name = null, $value = null, $options = [])
{
if (!isset($options['type'])) {
$options['type'] = $type;
}
$options['name'] = $name;
$options['value'] = $value === null ? null : (string) $value;
return static::tag('input', '', $options);
}
/**
* Generates an input button.
* @param string $label the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated button tag
*/
public static function buttonInput($label = 'Button', $options = [])
{
$options['type'] = 'button';
$options['value'] = $label;
return static::tag('input', '', $options);
}
/**
* Generates a submit input button.
* @param string $label the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated button tag
*/
public static function submitInput($label = 'Submit', $options = [])
{
$options['type'] = 'submit';
$options['value'] = $label;
return static::tag('input', '', $options);
}
/**
* Generates a reset input button.
* @param string $label the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the attributes of the button tag. The values will be HTML-encoded using [[encode()]].
* Attributes whose value is null will be ignored and not put in the tag returned.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated button tag
*/
public static function resetInput($label = 'Reset', $options = [])
{
$options['type'] = 'reset';
$options['value'] = $label;
return static::tag('input', '', $options);
}
/**
* Generates a text input field.
* @param string $name the name attribute.
* @param string $value the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated text input tag
*/
public static function textInput($name, $value = null, $options = [])
{
return static::input('text', $name, $value, $options);
}
/**
* Generates a hidden input field.
* @param string $name the name attribute.
* @param string $value the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated hidden input tag
*/
public static function hiddenInput($name, $value = null, $options = [])
{
return static::input('hidden', $name, $value, $options);
}
/**
* Generates a password input field.
* @param string $name the name attribute.
* @param string $value the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated password input tag
*/
public static function passwordInput($name, $value = null, $options = [])
{
return static::input('password', $name, $value, $options);
}
/**
* Generates a file input field.
* To use a file input field, you should set the enclosing form's "enctype" attribute to
* be "multipart/form-data". After the form is submitted, the uploaded file information
* can be obtained via $_FILES[$name] (see PHP documentation).
* @param string $name the name attribute.
* @param string $value the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated file input tag
*/
public static function fileInput($name, $value = null, $options = [])
{
return static::input('file', $name, $value, $options);
}
/**
* Generates a text area input.
* @param string $name the input name
* @param string $value the input value. Note that it will be encoded using [[encode()]].
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated text area tag
*/
public static function textarea($name, $value = '', $options = [])
{
$options['name'] = $name;
return static::tag('textarea', static::encode($value), $options);
}
/**
* Generates a radio button input.
* @param string $name the name attribute.
* @param boolean $checked whether the radio button should be checked.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - uncheck: string, the value associated with the uncheck state of the radio button. When this attribute
* is present, a hidden input will be generated so that if the radio button is not checked and is submitted,
* the value of this attribute will still be submitted to the server via the hidden input.
* - label: string, a label displayed next to the radio button. It will NOT be HTML-encoded. Therefore you can pass
* in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
* When this option is specified, the radio button will be enclosed by a label tag.
* - labelOptions: array, the HTML attributes for the label tag. Do not set this option unless you set the "label" option.
*
* The rest of the options will be rendered as the attributes of the resulting radio button tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated radio button tag
*/
public static function radio($name, $checked = false, $options = [])
{
$options['checked'] = (bool) $checked;
$value = array_key_exists('value', $options) ? $options['value'] : '1';
if (isset($options['uncheck'])) {
// add a hidden field so that if the radio button is not selected, it still submits a value
$hidden = static::hiddenInput($name, $options['uncheck']);
unset($options['uncheck']);
} else {
$hidden = '';
}
if (isset($options['label'])) {
$label = $options['label'];
$labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : [];
unset($options['label'], $options['labelOptions']);
$content = static::label(static::input('radio', $name, $value, $options) . ' ' . $label, null, $labelOptions);
return $hidden . $content;
} else {
return $hidden . static::input('radio', $name, $value, $options);
}
}
/**
* Generates a checkbox input.
* @param string $name the name attribute.
* @param boolean $checked whether the checkbox should be checked.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - uncheck: string, the value associated with the uncheck state of the checkbox. When this attribute
* is present, a hidden input will be generated so that if the checkbox is not checked and is submitted,
* the value of this attribute will still be submitted to the server via the hidden input.
* - label: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass
* in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
* When this option is specified, the checkbox will be enclosed by a label tag.
* - labelOptions: array, the HTML attributes for the label tag. Do not set this option unless you set the "label" option.
*
* The rest of the options will be rendered as the attributes of the resulting checkbox tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated checkbox tag
*/
public static function checkbox($name, $checked = false, $options = [])
{
$options['checked'] = (bool) $checked;
$value = array_key_exists('value', $options) ? $options['value'] : '1';
if (isset($options['uncheck'])) {
// add a hidden field so that if the checkbox is not selected, it still submits a value
$hidden = static::hiddenInput($name, $options['uncheck']);
unset($options['uncheck']);
} else {
$hidden = '';
}
if (isset($options['label'])) {
$label = $options['label'];
$labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : [];
unset($options['label'], $options['labelOptions']);
$content = static::label(static::input('checkbox', $name, $value, $options) . ' ' . $label, null, $labelOptions);
return $hidden . $content;
} else {
return $hidden . static::input('checkbox', $name, $value, $options);
}
}
/**
* Generates a drop-down list.
* @param string $name the input name
* @param string $selection the selected value
* @param array $items the option data items. The array keys are option values, and the array values
* are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
* For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
* If you have a list of data models, you may convert them into the format described above using
* [[\yii\helpers\ArrayHelper::map()]].
*
* Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
* the labels will also be HTML-encoded.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - prompt: string, a prompt text to be displayed as the first option;
* - options: array, the attributes for the select option tags. The array keys must be valid option values,
* and the array values are the extra attributes for the corresponding option tags. For example,
*
* ~~~
* [
* 'value1' => ['disabled' => true],
* 'value2' => ['label' => 'value 2'],
* ];
* ~~~
*
* - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
* except that the array keys represent the optgroup labels specified in $items.
* - encodeSpaces: bool, whether to encode spaces in option prompt and option value with ` ` character.
* Defaults to false.
* - encode: bool, whether to encode option prompt and option value characters.
* Defaults to `true`. This option is available since 2.0.3.
*
* The rest of the options will be rendered as the attributes of the resulting tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated drop-down list tag
*/
public static function dropDownList($name, $selection = null, $items = [], $options = [])
{
if (!empty($options['multiple'])) {
return static::listBox($name, $selection, $items, $options);
}
$options['name'] = $name;
unset($options['unselect']);
$selectOptions = static::renderSelectOptions($selection, $items, $options);
return static::tag('select', "\n" . $selectOptions . "\n", $options);
}
/**
* Generates a list box.
* @param string $name the input name
* @param string|array $selection the selected value(s)
* @param array $items the option data items. The array keys are option values, and the array values
* are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
* For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
* If you have a list of data models, you may convert them into the format described above using
* [[\yii\helpers\ArrayHelper::map()]].
*
* Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
* the labels will also be HTML-encoded.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - prompt: string, a prompt text to be displayed as the first option;
* - options: array, the attributes for the select option tags. The array keys must be valid option values,
* and the array values are the extra attributes for the corresponding option tags. For example,
*
* ~~~
* [
* 'value1' => ['disabled' => true],
* 'value2' => ['label' => 'value 2'],
* ];
* ~~~
*
* - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
* except that the array keys represent the optgroup labels specified in $items.
* - unselect: string, the value that will be submitted when no option is selected.
* When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
* mode, we can still obtain the posted unselect value.
* - encodeSpaces: bool, whether to encode spaces in option prompt and option value with ` ` character.
* Defaults to false.
* - encode: bool, whether to encode option prompt and option value characters.
* Defaults to `true`. This option is available since 2.0.3.
*
* The rest of the options will be rendered as the attributes of the resulting tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated list box tag
*/
public static function listBox($name, $selection = null, $items = [], $options = [])
{
if (!array_key_exists('size', $options)) {
$options['size'] = 4;
}
if (!empty($options['multiple']) && !empty($name) && substr_compare($name, '[]', -2, 2)) {
$name .= '[]';
}
$options['name'] = $name;
if (isset($options['unselect'])) {
// add a hidden field so that if the list box has no option being selected, it still submits a value
if (!empty($name) && substr_compare($name, '[]', -2, 2) === 0) {
$name = substr($name, 0, -2);
}
$hidden = static::hiddenInput($name, $options['unselect']);
unset($options['unselect']);
} else {
$hidden = '';
}
$selectOptions = static::renderSelectOptions($selection, $items, $options);
return $hidden . static::tag('select', "\n" . $selectOptions . "\n", $options);
}
/**
* Generates a list of checkboxes.
* A checkbox list allows multiple selection, like [[listBox()]].
* As a result, the corresponding submitted value is an array.
* @param string $name the name attribute of each checkbox.
* @param string|array $selection the selected value(s).
* @param array $items the data item used to generate the checkboxes.
* The array keys are the checkbox values, while the array values are the corresponding labels.
* @param array $options options (name => config) for the checkbox list container tag.
* The following options are specially handled:
*
* - tag: string, the tag name of the container element.
* - unselect: string, the value that should be submitted when none of the checkboxes is selected.
* By setting this option, a hidden input will be generated.
* - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
* This option is ignored if `item` option is set.
* - separator: string, the HTML code that separates items.
* - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
* - item: callable, a callback that can be used to customize the generation of the HTML code
* corresponding to a single item in $items. The signature of this callback must be:
*
* ~~~
* function ($index, $label, $name, $checked, $value)
* ~~~
*
* where $index is the zero-based index of the checkbox in the whole list; $label
* is the label for the checkbox; and $name, $value and $checked represent the name,
* value and the checked status of the checkbox input, respectively.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated checkbox list
*/
public static function checkboxList($name, $selection = null, $items = [], $options = [])
{
if (substr($name, -2) !== '[]') {
$name .= '[]';
}
$formatter = isset($options['item']) ? $options['item'] : null;
$itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : [];
$encode = !isset($options['encode']) || $options['encode'];
$lines = [];
$index = 0;
foreach ($items as $value => $label) {
$checked = $selection !== null &&
(!is_array($selection) && !strcmp($value, $selection)
|| is_array($selection) && in_array($value, $selection));
if ($formatter !== null) {
$lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
} else {
$lines[] = static::checkbox($name, $checked, array_merge($itemOptions, [
'value' => $value,
'label' => $encode ? static::encode($label) : $label,
]));
}
$index++;
}
if (isset($options['unselect'])) {
// add a hidden field so that if the list box has no option being selected, it still submits a value
$name2 = substr($name, -2) === '[]' ? substr($name, 0, -2) : $name;
$hidden = static::hiddenInput($name2, $options['unselect']);
} else {
$hidden = '';
}
$separator = isset($options['separator']) ? $options['separator'] : "\n";
$tag = isset($options['tag']) ? $options['tag'] : 'div';
unset($options['tag'], $options['unselect'], $options['encode'], $options['separator'], $options['item'], $options['itemOptions']);
return $hidden . static::tag($tag, implode($separator, $lines), $options);
}
/**
* Generates a list of radio buttons.
* A radio button list is like a checkbox list, except that it only allows single selection.
* @param string $name the name attribute of each radio button.
* @param string|array $selection the selected value(s).
* @param array $items the data item used to generate the radio buttons.
* The array keys are the radio button values, while the array values are the corresponding labels.
* @param array $options options (name => config) for the radio button list container tag.
* The following options are specially handled:
*
* - tag: string, the tag name of the container element.
* - unselect: string, the value that should be submitted when none of the radio buttons is selected.
* By setting this option, a hidden input will be generated.
* - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
* This option is ignored if `item` option is set.
* - separator: string, the HTML code that separates items.
* - itemOptions: array, the options for generating the radio button tag using [[radio()]].
* - item: callable, a callback that can be used to customize the generation of the HTML code
* corresponding to a single item in $items. The signature of this callback must be:
*
* ~~~
* function ($index, $label, $name, $checked, $value)
* ~~~
*
* where $index is the zero-based index of the radio button in the whole list; $label
* is the label for the radio button; and $name, $value and $checked represent the name,
* value and the checked status of the radio button input, respectively.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated radio button list
*/
public static function radioList($name, $selection = null, $items = [], $options = [])
{
$encode = !isset($options['encode']) || $options['encode'];
$formatter = isset($options['item']) ? $options['item'] : null;
$itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : [];
$lines = [];
$index = 0;
foreach ($items as $value => $label) {
$checked = $selection !== null &&
(!is_array($selection) && !strcmp($value, $selection)
|| is_array($selection) && in_array($value, $selection));
if ($formatter !== null) {
$lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
} else {
$lines[] = static::radio($name, $checked, array_merge($itemOptions, [
'value' => $value,
'label' => $encode ? static::encode($label) : $label,
]));
}
$index++;
}
$separator = isset($options['separator']) ? $options['separator'] : "\n";
if (isset($options['unselect'])) {
// add a hidden field so that if the list box has no option being selected, it still submits a value
$hidden = static::hiddenInput($name, $options['unselect']);
} else {
$hidden = '';
}
$tag = isset($options['tag']) ? $options['tag'] : 'div';
unset($options['tag'], $options['unselect'], $options['encode'], $options['separator'], $options['item'], $options['itemOptions']);
return $hidden . static::tag($tag, implode($separator, $lines), $options);
}
/**
* Generates an unordered list.
* @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
* Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
* @param array $options options (name => config) for the radio button list. The following options are supported:
*
* - encode: boolean, whether to HTML-encode the items. Defaults to true.
* This option is ignored if the `item` option is specified.
* - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
* - item: callable, a callback that is used to generate each individual list item.
* The signature of this callback must be:
*
* ~~~
* function ($item, $index)
* ~~~
*
* where $index is the array key corresponding to `$item` in `$items`. The callback should return
* the whole list item tag.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated unordered list. An empty list tag will be returned if `$items` is empty.
*/
public static function ul($items, $options = [])
{
$tag = isset($options['tag']) ? $options['tag'] : 'ul';
$encode = !isset($options['encode']) || $options['encode'];
$formatter = isset($options['item']) ? $options['item'] : null;
$itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : [];
unset($options['tag'], $options['encode'], $options['item'], $options['itemOptions']);
if (empty($items)) {
return static::tag($tag, '', $options);
}
$results = [];
foreach ($items as $index => $item) {
if ($formatter !== null) {
$results[] = call_user_func($formatter, $item, $index);
} else {
$results[] = static::tag('li', $encode ? static::encode($item) : $item, $itemOptions);
}
}
return static::tag($tag, "\n" . implode("\n", $results) . "\n", $options);
}
/**
* Generates an ordered list.
* @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
* Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
* @param array $options options (name => config) for the radio button list. The following options are supported:
*
* - encode: boolean, whether to HTML-encode the items. Defaults to true.
* This option is ignored if the `item` option is specified.
* - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
* - item: callable, a callback that is used to generate each individual list item.
* The signature of this callback must be:
*
* ~~~
* function ($item, $index)
* ~~~
*
* where $index is the array key corresponding to `$item` in `$items`. The callback should return
* the whole list item tag.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated ordered list. An empty string is returned if `$items` is empty.
*/
public static function ol($items, $options = [])
{
$options['tag'] = 'ol';
return static::ul($items, $options);
}
/**
* Generates a label tag for the given model attribute.
* The label text is the label associated with the attribute, obtained via [[Model::getAttributeLabel()]].
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* The following options are specially handled:
*
* - label: this specifies the label to be displayed. Note that this will NOT be [[encode()|encoded]].
* If this is not set, [[Model::getAttributeLabel()]] will be called to get the label for display
* (after encoding).
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated label tag
*/
public static function activeLabel($model, $attribute, $options = [])
{
$for = array_key_exists('for', $options) ? $options['for'] : static::getInputId($model, $attribute);
$attribute = static::getAttributeName($attribute);
$label = isset($options['label']) ? $options['label'] : static::encode($model->getAttributeLabel($attribute));
unset($options['label'], $options['for']);
return static::label($label, $for, $options);
}
/**
* Generates a hint tag for the given model attribute.
* The hint text is the hint associated with the attribute, obtained via [[Model::getAttributeHint()]].
* If no hint content can be obtained, method will return an empty string.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* The following options are specially handled:
*
* - hint: this specifies the hint to be displayed. Note that this will NOT be [[encode()|encoded]].
* If this is not set, [[Model::getAttributeHint()]] will be called to get the hint for display
* (without encoding).
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated hint tag
* @since 2.0.4
*/
public static function activeHint($model, $attribute, $options = [])
{
$attribute = static::getAttributeName($attribute);
$hint = isset($options['hint']) ? $options['hint'] : $model->getAttributeHint($attribute);
if (empty($hint)) {
return '';
}
$tag = ArrayHelper::remove($options, 'tag', 'div');
unset($options['hint']);
return static::tag($tag, $hint, $options);
}
/**
* Generates a summary of the validation errors.
* If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.
* @param Model|Model[] $models the model(s) whose validation errors are to be displayed
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - header: string, the header HTML for the error summary. If not set, a default prompt string will be used.
* - footer: string, the footer HTML for the error summary.
* - encode: boolean, if set to false then the error messages won't be encoded.
*
* The rest of the options will be rendered as the attributes of the container tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* @return string the generated error summary
*/
public static function errorSummary($models, $options = [])
{
$header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii', 'Please fix the following errors:') . '</p>';
$footer = isset($options['footer']) ? $options['footer'] : '';
$encode = !isset($options['encode']) || $options['encode'] !== false;
unset($options['header'], $options['footer'], $options['encode']);
$lines = [];
if (!is_array($models)) {
$models = [$models];
}
foreach ($models as $model) {
/* @var $model Model */
foreach ($model->getFirstErrors() as $error) {
$lines[] = $encode ? Html::encode($error) : $error;
}
}
if (empty($lines)) {
// still render the placeholder for client-side validation use
$content = "<ul></ul>";
$options['style'] = isset($options['style']) ? rtrim($options['style'], ';') . '; display:none' : 'display:none';
} else {
$content = "<ul><li>" . implode("</li>\n<li>", $lines) . "</li></ul>";
}
return Html::tag('div', $header . $content . $footer, $options);
}
/**
* Generates a tag that contains the first validation error of the specified model attribute.
* Note that even if there is no validation error, this method will still return an empty error tag.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. The values will be HTML-encoded
* using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
*
* The following options are specially handled:
*
* - tag: this specifies the tag name. If not set, "div" will be used.
* - encode: boolean, if set to false then the error message won't be encoded.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated label tag
*/
public static function error($model, $attribute, $options = [])
{
$attribute = static::getAttributeName($attribute);
$error = $model->getFirstError($attribute);
$tag = isset($options['tag']) ? $options['tag'] : 'div';
$encode = !isset($options['encode']) || $options['encode'] !== false;
unset($options['tag'], $options['encode']);
return Html::tag($tag, $encode ? Html::encode($error) : $error, $options);
}
/**
* Generates an input tag for the given model attribute.
* This method will generate the "name" and "value" tag attributes automatically for the model attribute
* unless they are explicitly specified in `$options`.
* @param string $type the input type (e.g. 'text', 'password')
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated input tag
*/
public static function activeInput($type, $model, $attribute, $options = [])
{
$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
$value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
if (!array_key_exists('id', $options)) {
$options['id'] = static::getInputId($model, $attribute);
}
return static::input($type, $name, $value, $options);
}
/**
* If `maxlength` option is set true and the model attribute is validated by a string validator,
* the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
* @param Model $model the model object
* @param string $attribute the attribute name or expression.
* @param array $options the tag options in terms of name-value pairs.
*/
private static function normalizeMaxLength($model, $attribute, &$options)
{
if (isset($options['maxlength']) && $options['maxlength'] === true) {
unset($options['maxlength']);
$attrName = static::getAttributeName($attribute);
foreach ($model->getActiveValidators($attrName) as $validator) {
if ($validator instanceof StringValidator && $validator->max !== null) {
$options['maxlength'] = $validator->max;
break;
}
}
}
}
/**
* Generates a text input tag for the given model attribute.
* This method will generate the "name" and "value" tag attributes automatically for the model attribute
* unless they are explicitly specified in `$options`.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* The following special options are recognized:
*
* - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
* by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
* This is available since version 2.0.3.
*
* @return string the generated input tag
*/
public static function activeTextInput($model, $attribute, $options = [])
{
self::normalizeMaxLength($model, $attribute, $options);
return static::activeInput('text', $model, $attribute, $options);
}
/**
* Generates a hidden input tag for the given model attribute.
* This method will generate the "name" and "value" tag attributes automatically for the model attribute
* unless they are explicitly specified in `$options`.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated input tag
*/
public static function activeHiddenInput($model, $attribute, $options = [])
{
return static::activeInput('hidden', $model, $attribute, $options);
}
/**
* Generates a password input tag for the given model attribute.
* This method will generate the "name" and "value" tag attributes automatically for the model attribute
* unless they are explicitly specified in `$options`.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* The following special options are recognized:
*
* - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
* by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
* This option is available since version 2.0.6.
*
* @return string the generated input tag
*/
public static function activePasswordInput($model, $attribute, $options = [])
{
self::normalizeMaxLength($model, $attribute, $options);
return static::activeInput('password', $model, $attribute, $options);
}
/**
* Generates a file input tag for the given model attribute.
* This method will generate the "name" and "value" tag attributes automatically for the model attribute
* unless they are explicitly specified in `$options`.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated input tag
*/
public static function activeFileInput($model, $attribute, $options = [])
{
// add a hidden field so that if a model only has a file field, we can
// still use isset($_POST[$modelClass]) to detect if the input is submitted
return static::activeHiddenInput($model, $attribute, ['id' => null, 'value' => ''])
. static::activeInput('file', $model, $attribute, $options);
}
/**
* Generates a textarea tag for the given model attribute.
* The model attribute value will be used as the content in the textarea.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* The following special options are recognized:
*
* - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
* by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
* This option is available since version 2.0.6.
*
* @return string the generated textarea tag
*/
public static function activeTextarea($model, $attribute, $options = [])
{
$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
if (isset($options['value'])) {
$value = $options['value'];
unset($options['value']);
} else {
$value = static::getAttributeValue($model, $attribute);
}
if (!array_key_exists('id', $options)) {
$options['id'] = static::getInputId($model, $attribute);
}
self::normalizeMaxLength($model, $attribute, $options);
return static::textarea($name, $value, $options);
}
/**
* Generates a radio button tag together with a label for the given model attribute.
* This method will generate the "checked" tag attribute according to the model attribute value.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - uncheck: string, the value associated with the uncheck state of the radio button. If not set,
* it will take the default value '0'. This method will render a hidden input so that if the radio button
* is not checked and is submitted, the value of this attribute will still be submitted to the server
* via the hidden input. If you do not want any hidden input, you should explicitly set this option as null.
* - label: string, a label displayed next to the radio button. It will NOT be HTML-encoded. Therefore you can pass
* in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
* The radio button will be enclosed by the label tag. Note that if you do not specify this option, a default label
* will be used based on the attribute label declaration in the model. If you do not want any label, you should
* explicitly set this option as null.
* - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified.
*
* The rest of the options will be rendered as the attributes of the resulting tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated radio button tag
*/
public static function activeRadio($model, $attribute, $options = [])
{
$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
$value = static::getAttributeValue($model, $attribute);
if (!array_key_exists('value', $options)) {
$options['value'] = '1';
}
if (!array_key_exists('uncheck', $options)) {
$options['uncheck'] = '0';
}
if (!array_key_exists('label', $options)) {
$options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute)));
}
$checked = "$value" === "{$options['value']}";
if (!array_key_exists('id', $options)) {
$options['id'] = static::getInputId($model, $attribute);
}
return static::radio($name, $checked, $options);
}
/**
* Generates a checkbox tag together with a label for the given model attribute.
* This method will generate the "checked" tag attribute according to the model attribute value.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - uncheck: string, the value associated with the uncheck state of the radio button. If not set,
* it will take the default value '0'. This method will render a hidden input so that if the radio button
* is not checked and is submitted, the value of this attribute will still be submitted to the server
* via the hidden input. If you do not want any hidden input, you should explicitly set this option as null.
* - label: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass
* in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
* The checkbox will be enclosed by the label tag. Note that if you do not specify this option, a default label
* will be used based on the attribute label declaration in the model. If you do not want any label, you should
* explicitly set this option as null.
* - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified.
*
* The rest of the options will be rendered as the attributes of the resulting tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated checkbox tag
*/
public static function activeCheckbox($model, $attribute, $options = [])
{
$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
$value = static::getAttributeValue($model, $attribute);
if (!array_key_exists('value', $options)) {
$options['value'] = '1';
}
if (!array_key_exists('uncheck', $options)) {
$options['uncheck'] = '0';
}
if (!array_key_exists('label', $options)) {
$options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute)));
}
$checked = "$value" === "{$options['value']}";
if (!array_key_exists('id', $options)) {
$options['id'] = static::getInputId($model, $attribute);
}
return static::checkbox($name, $checked, $options);
}
/**
* Generates a drop-down list for the given model attribute.
* The selection of the drop-down list is taken from the value of the model attribute.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $items the option data items. The array keys are option values, and the array values
* are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
* For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
* If you have a list of data models, you may convert them into the format described above using
* [[\yii\helpers\ArrayHelper::map()]].
*
* Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
* the labels will also be HTML-encoded.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - prompt: string, a prompt text to be displayed as the first option;
* - options: array, the attributes for the select option tags. The array keys must be valid option values,
* and the array values are the extra attributes for the corresponding option tags. For example,
*
* ~~~
* [
* 'value1' => ['disabled' => true],
* 'value2' => ['label' => 'value 2'],
* ];
* ~~~
*
* - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
* except that the array keys represent the optgroup labels specified in $items.
* - encodeSpaces: bool, whether to encode spaces in option prompt and option value with ` ` character.
* Defaults to false.
* - encode: bool, whether to encode option prompt and option value characters.
* Defaults to `true`. This option is available since 2.0.3.
*
* The rest of the options will be rendered as the attributes of the resulting tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated drop-down list tag
*/
public static function activeDropDownList($model, $attribute, $items, $options = [])
{
if (empty($options['multiple'])) {
return static::activeListInput('dropDownList', $model, $attribute, $items, $options);
} else {
return static::activeListBox($model, $attribute, $items, $options);
}
}
/**
* Generates a list box.
* The selection of the list box is taken from the value of the model attribute.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $items the option data items. The array keys are option values, and the array values
* are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
* For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
* If you have a list of data models, you may convert them into the format described above using
* [[\yii\helpers\ArrayHelper::map()]].
*
* Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
* the labels will also be HTML-encoded.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - prompt: string, a prompt text to be displayed as the first option;
* - options: array, the attributes for the select option tags. The array keys must be valid option values,
* and the array values are the extra attributes for the corresponding option tags. For example,
*
* ~~~
* [
* 'value1' => ['disabled' => true],
* 'value2' => ['label' => 'value 2'],
* ];
* ~~~
*
* - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
* except that the array keys represent the optgroup labels specified in $items.
* - unselect: string, the value that will be submitted when no option is selected.
* When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
* mode, we can still obtain the posted unselect value.
* - encodeSpaces: bool, whether to encode spaces in option prompt and option value with ` ` character.
* Defaults to false.
* - encode: bool, whether to encode option prompt and option value characters.
* Defaults to `true`. This option is available since 2.0.3.
*
* The rest of the options will be rendered as the attributes of the resulting tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated list box tag
*/
public static function activeListBox($model, $attribute, $items, $options = [])
{
return static::activeListInput('listBox', $model, $attribute, $items, $options);
}
/**
* Generates a list of checkboxes.
* A checkbox list allows multiple selection, like [[listBox()]].
* As a result, the corresponding submitted value is an array.
* The selection of the checkbox list is taken from the value of the model attribute.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $items the data item used to generate the checkboxes.
* The array keys are the checkbox values, and the array values are the corresponding labels.
* Note that the labels will NOT be HTML-encoded, while the values will.
* @param array $options options (name => config) for the checkbox list container tag.
* The following options are specially handled:
*
* - tag: string, the tag name of the container element.
* - unselect: string, the value that should be submitted when none of the checkboxes is selected.
* You may set this option to be null to prevent default value submission.
* If this option is not set, an empty string will be submitted.
* - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
* This option is ignored if `item` option is set.
* - separator: string, the HTML code that separates items.
* - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
* - item: callable, a callback that can be used to customize the generation of the HTML code
* corresponding to a single item in $items. The signature of this callback must be:
*
* ~~~
* function ($index, $label, $name, $checked, $value)
* ~~~
*
* where $index is the zero-based index of the checkbox in the whole list; $label
* is the label for the checkbox; and $name, $value and $checked represent the name,
* value and the checked status of the checkbox input.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated checkbox list
*/
public static function activeCheckboxList($model, $attribute, $items, $options = [])
{
return static::activeListInput('checkboxList', $model, $attribute, $items, $options);
}
/**
* Generates a list of radio buttons.
* A radio button list is like a checkbox list, except that it only allows single selection.
* The selection of the radio buttons is taken from the value of the model attribute.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $items the data item used to generate the radio buttons.
* The array keys are the radio values, and the array values are the corresponding labels.
* Note that the labels will NOT be HTML-encoded, while the values will.
* @param array $options options (name => config) for the radio button list container tag.
* The following options are specially handled:
*
* - tag: string, the tag name of the container element.
* - unselect: string, the value that should be submitted when none of the radio buttons is selected.
* You may set this option to be null to prevent default value submission.
* If this option is not set, an empty string will be submitted.
* - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
* This option is ignored if `item` option is set.
* - separator: string, the HTML code that separates items.
* - itemOptions: array, the options for generating the radio button tag using [[radio()]].
* - item: callable, a callback that can be used to customize the generation of the HTML code
* corresponding to a single item in $items. The signature of this callback must be:
*
* ~~~
* function ($index, $label, $name, $checked, $value)
* ~~~
*
* where $index is the zero-based index of the radio button in the whole list; $label
* is the label for the radio button; and $name, $value and $checked represent the name,
* value and the checked status of the radio button input.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated radio button list
*/
public static function activeRadioList($model, $attribute, $items, $options = [])
{
return static::activeListInput('radioList', $model, $attribute, $items, $options);
}
/**
* Generates a list of input fields.
* This method is mainly called by [[activeListBox()]], [[activeRadioList()]] and [[activeCheckBoxList()]].
* @param string $type the input type. This can be 'listBox', 'radioList', or 'checkBoxList'.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $items the data item used to generate the input fields.
* The array keys are the input values, and the array values are the corresponding labels.
* Note that the labels will NOT be HTML-encoded, while the values will.
* @param array $options options (name => config) for the input list. The supported special options
* depend on the input type specified by `$type`.
* @return string the generated input list
*/
protected static function activeListInput($type, $model, $attribute, $items, $options = [])
{
$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
$selection = static::getAttributeValue($model, $attribute);
if (!array_key_exists('unselect', $options)) {
$options['unselect'] = '';
}
if (!array_key_exists('id', $options)) {
$options['id'] = static::getInputId($model, $attribute);
}
return static::$type($name, $selection, $items, $options);
}
/**
* Renders the option tags that can be used by [[dropDownList()]] and [[listBox()]].
* @param string|array $selection the selected value(s). This can be either a string for single selection
* or an array for multiple selections.
* @param array $items the option data items. The array keys are option values, and the array values
* are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
* For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
* If you have a list of data models, you may convert them into the format described above using
* [[\yii\helpers\ArrayHelper::map()]].
*
* Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
* the labels will also be HTML-encoded.
* @param array $tagOptions the $options parameter that is passed to the [[dropDownList()]] or [[listBox()]] call.
* This method will take out these elements, if any: "prompt", "options" and "groups". See more details
* in [[dropDownList()]] for the explanation of these elements.
*
* @return string the generated list options
*/
public static function renderSelectOptions($selection, $items, &$tagOptions = [])
{
$lines = [];
$encodeSpaces = ArrayHelper::remove($tagOptions, 'encodeSpaces', false);
$encode = ArrayHelper::remove($tagOptions, 'encode', true);
if (isset($tagOptions['prompt'])) {
$prompt = $encode ? static::encode($tagOptions['prompt']) : $tagOptions['prompt'];
if ($encodeSpaces) {
$prompt = str_replace(' ', ' ', $prompt);
}
$lines[] = static::tag('option', $prompt, ['value' => '']);
}
$options = isset($tagOptions['options']) ? $tagOptions['options'] : [];
$groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : [];
unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']);
$options['encodeSpaces'] = ArrayHelper::getValue($options, 'encodeSpaces', $encodeSpaces);
$options['encode'] = ArrayHelper::getValue($options, 'encode', $encode);
foreach ($items as $key => $value) {
if (is_array($value)) {
$groupAttrs = isset($groups[$key]) ? $groups[$key] : [];
if (!isset($groupAttrs['label'])) {
$groupAttrs['label'] = $key;
}
$attrs = ['options' => $options, 'groups' => $groups, 'encodeSpaces' => $encodeSpaces, 'encode' => $encode];
$content = static::renderSelectOptions($selection, $value, $attrs);
$lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs);
} else {
$attrs = isset($options[$key]) ? $options[$key] : [];
$attrs['value'] = (string) $key;
$attrs['selected'] = $selection !== null &&
(!is_array($selection) && !strcmp($key, $selection)
|| is_array($selection) && in_array($key, $selection));
$text = $encode ? static::encode($value) : $value;
if ($encodeSpaces) {
$text = str_replace(' ', ' ', $text);
}
$lines[] = static::tag('option', $text, $attrs);
}
}
return implode("\n", $lines);
}
/**
* Renders the HTML tag attributes.
*
* Attributes whose values are of boolean type will be treated as
* [boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes).
*
* Attributes whose values are null will not be rendered.
*
* The values of attributes will be HTML-encoded using [[encode()]].
*
* The "data" attribute is specially handled when it is receiving an array value. In this case,
* the array will be "expanded" and a list data attributes will be rendered. For example,
* if `'data' => ['id' => 1, 'name' => 'yii']`, then this will be rendered:
* `data-id="1" data-name="yii"`.
* Additionally `'data' => ['params' => ['id' => 1, 'name' => 'yii'], 'status' => 'ok']` will be rendered as:
* `data-params='{"id":1,"name":"yii"}' data-status="ok"`.
*
* @param array $attributes attributes to be rendered. The attribute values will be HTML-encoded using [[encode()]].
* @return string the rendering result. If the attributes are not empty, they will be rendered
* into a string with a leading white space (so that it can be directly appended to the tag name
* in a tag. If there is no attribute, an empty string will be returned.
*/
public static function renderTagAttributes($attributes)
{
if (count($attributes) > 1) {
$sorted = [];
foreach (static::$attributeOrder as $name) {
if (isset($attributes[$name])) {
$sorted[$name] = $attributes[$name];
}
}
$attributes = array_merge($sorted, $attributes);
}
$html = '';
foreach ($attributes as $name => $value) {
if (is_bool($value)) {
if ($value) {
$html .= " $name";
}
} elseif (is_array($value)) {
if (in_array($name, static::$dataAttributes)) {
foreach ($value as $n => $v) {
if (is_array($v)) {
$html .= " $name-$n='" . Json::htmlEncode($v) . "'";
} else {
$html .= " $name-$n=\"" . static::encode($v) . '"';
}
}
} elseif ($name === 'class') {
if (empty($value)) {
continue;
}
$html .= " $name=\"" . static::encode(implode(' ', $value)) . '"';
} elseif ($name === 'style') {
if (empty($value)) {
continue;
}
$html .= " $name=\"" . static::encode(static::cssStyleFromArray($value)) . '"';
} else {
$html .= " $name='" . Json::htmlEncode($value) . "'";
}
} elseif ($value !== null) {
$html .= " $name=\"" . static::encode($value) . '"';
}
}
return $html;
}
/**
* Adds a CSS class (or several classes) to the specified options.
* If the CSS class is already in the options, it will not be added again.
* If class specification at given options is an array, and some class placed there with the named (string) key,
* overriding of such key will have no effect. For example:
*
* ~~~php
* $options = ['class' => ['persistent' => 'initial']];
* Html::addCssClass($options, ['persistent' => 'override']);
* var_dump($options['class']); // outputs: array('persistent' => 'initial');
* ~~~
*
* @param array $options the options to be modified.
* @param string|array $class the CSS class(es) to be added
*/
public static function addCssClass(&$options, $class)
{
if (isset($options['class'])) {
if (is_array($options['class'])) {
$options['class'] = self::mergeCssClasses($options['class'], (array) $class);
} else {
$classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
$options['class'] = implode(' ', self::mergeCssClasses($classes, (array) $class));
}
} else {
$options['class'] = $class;
}
}
/**
* Merges already existing CSS classes with new one.
* This method provides the priority for named existing classes over additional.
* @param array $existingClasses already existing CSS classes.
* @param array $additionalClasses CSS classes to be added.
* @return array merge result.
*/
private static function mergeCssClasses(array $existingClasses, array $additionalClasses)
{
foreach ($additionalClasses as $key => $class) {
if (is_int($key) && !in_array($class, $existingClasses)) {
$existingClasses[] = $class;
} elseif (!isset($existingClasses[$key])) {
$existingClasses[$key] = $class;
}
}
return array_unique($existingClasses);
}
/**
* Removes a CSS class from the specified options.
* @param array $options the options to be modified.
* @param string|array $class the CSS class(es) to be removed
*/
public static function removeCssClass(&$options, $class)
{
if (isset($options['class'])) {
if (is_array($options['class'])) {
$classes = array_diff($options['class'], (array) $class);
if (empty($classes)) {
unset($options['class']);
} else {
$options['class'] = $classes;
}
} else {
$classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
$classes = array_diff($classes, (array) $class);
if (empty($classes)) {
unset($options['class']);
} else {
$options['class'] = implode(' ', $classes);
}
}
}
}
/**
* Adds the specified CSS style to the HTML options.
*
* If the options already contain a `style` element, the new style will be merged
* with the existing one. If a CSS property exists in both the new and the old styles,
* the old one may be overwritten if `$overwrite` is true.
*
* For example,
*
* ```php
* Html::addCssStyle($options, 'width: 100px; height: 200px');
* ```
*
* @param array $options the HTML options to be modified.
* @param string|array $style the new style string (e.g. `'width: 100px; height: 200px'`) or
* array (e.g. `['width' => '100px', 'height' => '200px']`).
* @param boolean $overwrite whether to overwrite existing CSS properties if the new style
* contain them too.
* @see removeCssStyle()
* @see cssStyleFromArray()
* @see cssStyleToArray()
*/
public static function addCssStyle(&$options, $style, $overwrite = true)
{
if (!empty($options['style'])) {
$oldStyle = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
$newStyle = is_array($style) ? $style : static::cssStyleToArray($style);
if (!$overwrite) {
foreach ($newStyle as $property => $value) {
if (isset($oldStyle[$property])) {
unset($newStyle[$property]);
}
}
}
$style = array_merge($oldStyle, $newStyle);
}
$options['style'] = is_array($style) ? static::cssStyleFromArray($style) : $style;
}
/**
* Removes the specified CSS style from the HTML options.
*
* For example,
*
* ```php
* Html::removeCssStyle($options, ['width', 'height']);
* ```
*
* @param array $options the HTML options to be modified.
* @param string|array $properties the CSS properties to be removed. You may use a string
* if you are removing a single property.
* @see addCssStyle()
*/
public static function removeCssStyle(&$options, $properties)
{
if (!empty($options['style'])) {
$style = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
foreach ((array) $properties as $property) {
unset($style[$property]);
}
$options['style'] = static::cssStyleFromArray($style);
}
}
/**
* Converts a CSS style array into a string representation.
*
* For example,
*
* ```php
* print_r(Html::cssStyleFromArray(['width' => '100px', 'height' => '200px']));
* // will display: 'width: 100px; height: 200px;'
* ```
*
* @param array $style the CSS style array. The array keys are the CSS property names,
* and the array values are the corresponding CSS property values.
* @return string the CSS style string. If the CSS style is empty, a null will be returned.
*/
public static function cssStyleFromArray(array $style)
{
$result = '';
foreach ($style as $name => $value) {
$result .= "$name: $value; ";
}
// return null if empty to avoid rendering the "style" attribute
return $result === '' ? null : rtrim($result);
}
/**
* Converts a CSS style string into an array representation.
*
* The array keys are the CSS property names, and the array values
* are the corresponding CSS property values.
*
* For example,
*
* ```php
* print_r(Html::cssStyleToArray('width: 100px; height: 200px;'));
* // will display: ['width' => '100px', 'height' => '200px']
* ```
*
* @param string $style the CSS style string
* @return array the array representation of the CSS style
*/
public static function cssStyleToArray($style)
{
$result = [];
foreach (explode(';', $style) as $property) {
$property = explode(':', $property);
if (count($property) > 1) {
$result[trim($property[0])] = trim($property[1]);
}
}
return $result;
}
/**
* Returns the real attribute name from the given attribute expression.
*
* An attribute expression is an attribute name prefixed and/or suffixed with array indexes.
* It is mainly used in tabular data input and/or input of array type. Below are some examples:
*
* - `[0]content` is used in tabular data input to represent the "content" attribute
* for the first model in tabular input;
* - `dates[0]` represents the first array element of the "dates" attribute;
* - `[0]dates[0]` represents the first array element of the "dates" attribute
* for the first model in tabular input.
*
* If `$attribute` has neither prefix nor suffix, it will be returned back without change.
* @param string $attribute the attribute name or expression
* @return string the attribute name without prefix and suffix.
* @throws InvalidParamException if the attribute name contains non-word characters.
*/
public static function getAttributeName($attribute)
{
if (preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) {
return $matches[2];
} else {
throw new InvalidParamException('Attribute name must contain word characters only.');
}
}
/**
* Returns the value of the specified attribute name or expression.
*
* For an attribute expression like `[0]dates[0]`, this method will return the value of `$model->dates[0]`.
* See [[getAttributeName()]] for more details about attribute expression.
*
* If an attribute value is an instance of [[ActiveRecordInterface]] or an array of such instances,
* the primary value(s) of the AR instance(s) will be returned instead.
*
* @param Model $model the model object
* @param string $attribute the attribute name or expression
* @return string|array the corresponding attribute value
* @throws InvalidParamException if the attribute name contains non-word characters.
*/
public static function getAttributeValue($model, $attribute)
{
if (!preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) {
throw new InvalidParamException('Attribute name must contain word characters only.');
}
$attribute = $matches[2];
$value = $model->$attribute;
if ($matches[3] !== '') {
foreach (explode('][', trim($matches[3], '[]')) as $id) {
if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) {
$value = $value[$id];
} else {
return null;
}
}
}
// https://github.com/yiisoft/yii2/issues/1457
if (is_array($value)) {
foreach ($value as $i => $v) {
if ($v instanceof ActiveRecordInterface) {
$v = $v->getPrimaryKey(false);
$value[$i] = is_array($v) ? json_encode($v) : $v;
}
}
} elseif ($value instanceof ActiveRecordInterface) {
$value = $value->getPrimaryKey(false);
return is_array($value) ? json_encode($value) : $value;
}
return $value;
}
/**
* Generates an appropriate input name for the specified attribute name or expression.
*
* This method generates a name that can be used as the input name to collect user input
* for the specified attribute. The name is generated according to the [[Model::formName|form name]]
* of the model and the given attribute name. For example, if the form name of the `Post` model
* is `Post`, then the input name generated for the `content` attribute would be `Post[content]`.
*
* See [[getAttributeName()]] for explanation of attribute expression.
*
* @param Model $model the model object
* @param string $attribute the attribute name or expression
* @return string the generated input name
* @throws InvalidParamException if the attribute name contains non-word characters.
*/
public static function getInputName($model, $attribute)
{
$formName = $model->formName();
if (!preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) {
throw new InvalidParamException('Attribute name must contain word characters only.');
}
$prefix = $matches[1];
$attribute = $matches[2];
$suffix = $matches[3];
if ($formName === '' && $prefix === '') {
return $attribute . $suffix;
} elseif ($formName !== '') {
return $formName . $prefix . "[$attribute]" . $suffix;
} else {
throw new InvalidParamException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
}
}
/**
* Generates an appropriate input ID for the specified attribute name or expression.
*
* This method converts the result [[getInputName()]] into a valid input ID.
* For example, if [[getInputName()]] returns `Post[content]`, this method will return `post-content`.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for explanation of attribute expression.
* @return string the generated input ID
* @throws InvalidParamException if the attribute name contains non-word characters.
*/
public static function getInputId($model, $attribute)
{
$name = strtolower(static::getInputName($model, $attribute));
return str_replace(['[]', '][', '[', ']', ' ', '.'], ['', '-', '-', '', '-', '-'], $name);
}
/**
* Escapes regular expression to use in JavaScript
* @param string $regexp the regular expression to be escaped.
* @return string the escaped result.
* @since 2.0.6
*/
public static function escapeJsRegularExpression($regexp)
{
$pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $regexp);
$deliminator = substr($pattern, 0, 1);
$pos = strrpos($pattern, $deliminator, 1);
$flag = substr($pattern, $pos + 1);
if ($deliminator !== '/') {
$pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $pos - 1)) . '/';
} else {
$pattern = substr($pattern, 0, $pos + 1);
}
if (!empty($flag)) {
$pattern .= preg_replace('/[^igm]/', '', $flag);
}
return $pattern;
}
}
| mcgrogan91/yii2 | framework/helpers/BaseHtml.php | PHP | bsd-3-clause | 103,758 |
/*
Copyright (C) 2013-2014 by Kristina Simpson <sweet.kristas@gmail.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgement in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "CanvasOGL.hpp"
#include "ShadersOpenGL.hpp"
#include "TextureOpenGL.hpp"
namespace KRE
{
namespace
{
CanvasPtr& get_instance()
{
static CanvasPtr res = CanvasPtr(new CanvasOGL());
return res;
}
}
CanvasOGL::CanvasOGL()
{
handleDimensionsChanged();
}
CanvasOGL::~CanvasOGL()
{
}
void CanvasOGL::handleDimensionsChanged()
{
mvp_ = glm::ortho(0.0f, float(width()), float(height()), 0.0f);
}
void CanvasOGL::blitTexture(const TexturePtr& tex, const rect& src, float rotation, const rect& dst, const Color& color) const
{
auto texture = std::dynamic_pointer_cast<OpenGLTexture>(tex);
ASSERT_LOG(texture != NULL, "Texture passed in was not of expected type.");
const float tx1 = float(src.x()) / texture->width();
const float ty1 = float(src.y()) / texture->height();
const float tx2 = src.w() == 0 ? 1.0f : float(src.x2()) / texture->width();
const float ty2 = src.h() == 0 ? 1.0f : float(src.y2()) / texture->height();
const float uv_coords[] = {
tx1, ty1,
tx2, ty1,
tx1, ty2,
tx2, ty2,
};
const float vx1 = float(dst.x());
const float vy1 = float(dst.y());
const float vx2 = float(dst.x2());
const float vy2 = float(dst.y2());
const float vtx_coords[] = {
vx1, vy1,
vx2, vy1,
vx1, vy2,
vx2, vy2,
};
glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3((vx1+vx2)/2.0f,(vy1+vy2)/2.0f,0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-(vx1+vx2)/2.0f,-(vy1+vy2)/2.0f,0.0f));
glm::mat4 mvp = mvp_ * model * getModelMatrix();
auto shader = OpenGL::ShaderProgram::defaultSystemShader();
shader->makeActive();
texture->bind();
shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp));
if(color != KRE::Color::colorWhite()) {
shader->setUniformValue(shader->getColorUniform(), (color*getColor()).asFloatVector());
} else {
shader->setUniformValue(shader->getColorUniform(), getColor().asFloatVector());
}
shader->setUniformValue(shader->getTexMapUniform(), 0);
// XXX the following line are only temporary, obviously.
//shader->SetUniformValue(shader->GetUniformIterator("discard"), 0);
glEnableVertexAttribArray(shader->getVertexAttribute()->second.location);
glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords);
glEnableVertexAttribArray(shader->getTexcoordAttribute()->second.location);
glVertexAttribPointer(shader->getTexcoordAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, uv_coords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableVertexAttribArray(shader->getTexcoordAttribute()->second.location);
glDisableVertexAttribArray(shader->getVertexAttribute()->second.location);
}
void CanvasOGL::blitTexture(const TexturePtr& tex, const std::vector<vertex_texcoord>& vtc, float rotation, const Color& color)
{
ASSERT_LOG(false, "XXX CanvasOGL::blitTexture()");
}
void CanvasOGL::blitTexture(const MaterialPtr& mat, float rotation, const rect& dst, const Color& color) const
{
ASSERT_LOG(mat != NULL, "Material was null");
const float vx1 = float(dst.x());
const float vy1 = float(dst.y());
const float vx2 = float(dst.x2());
const float vy2 = float(dst.y2());
const float vtx_coords[] = {
vx1, vy1,
vx2, vy1,
vx1, vy2,
vx2, vy2,
};
glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3((vx1+vx2)/2.0f,(vy1+vy2)/2.0f,0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-(vx1+vy1)/2.0f,-(vy1+vy1)/2.0f,0.0f));
glm::mat4 mvp = mvp_ * model * getModelMatrix();
auto shader = OpenGL::ShaderProgram::defaultSystemShader();
shader->makeActive();
shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp));
//if(color != KRE::Color::colorWhite()) {
shader->setUniformValue(shader->getColorUniform(), color.asFloatVector());
//}
shader->setUniformValue(shader->getTexMapUniform(), 0);
mat->apply();
for(auto it = mat->getTexture().begin(); it != mat->getTexture().end(); ++it) {
auto texture = std::dynamic_pointer_cast<OpenGLTexture>(*it);
ASSERT_LOG(texture != NULL, "Texture passed in was not of expected type.");
auto uv_coords = mat->getNormalisedTextureCoords(it);
texture->bind();
// XXX the following line are only temporary, obviously.
//shader->SetUniformValue(shader->GetUniformIterator("discard"), 0);
glEnableVertexAttribArray(shader->getVertexAttribute()->second.location);
glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords);
glEnableVertexAttribArray(shader->getTexcoordAttribute()->second.location);
glVertexAttribPointer(shader->getTexcoordAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, &uv_coords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableVertexAttribArray(shader->getTexcoordAttribute()->second.location);
glDisableVertexAttribArray(shader->getVertexAttribute()->second.location);
}
mat->unapply();
}
void CanvasOGL::blitTexture(const MaterialPtr& mat, const rect& src, float rotation, const rect& dst, const Color& color) const
{
ASSERT_LOG(mat != NULL, "Material was null");
const float vx1 = float(dst.x());
const float vy1 = float(dst.y());
const float vx2 = float(dst.x2());
const float vy2 = float(dst.y2());
const float vtx_coords[] = {
vx1, vy1,
vx2, vy1,
vx1, vy2,
vx2, vy2,
};
glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3((vx1+vx2)/2.0f,(vy1+vy2)/2.0f,0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-(vx1+vy1)/2.0f,-(vy1+vy1)/2.0f,0.0f));
glm::mat4 mvp = mvp_ * model * getModelMatrix();
auto shader = OpenGL::ShaderProgram::defaultSystemShader();
shader->makeActive();
shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp));
//if(color) {
shader->setUniformValue(shader->getColorUniform(), color.asFloatVector());
//}
shader->setUniformValue(shader->getTexMapUniform(), 0);
mat->apply();
for(auto it = mat->getTexture().begin(); it != mat->getTexture().end(); ++it) {
auto texture = std::dynamic_pointer_cast<OpenGLTexture>(*it);
ASSERT_LOG(texture != NULL, "Texture passed in was not of expected type.");
const float tx1 = float(src.x()) / texture->width();
const float ty1 = float(src.y()) / texture->height();
const float tx2 = src.w() == 0 ? 1.0f : float(src.x2()) / texture->width();
const float ty2 = src.h() == 0 ? 1.0f : float(src.y2()) / texture->height();
const float uv_coords[] = {
tx1, ty1,
tx2, ty1,
tx1, ty2,
tx2, ty2,
};
texture->bind();
// XXX the following line are only temporary, obviously.
//shader->SetUniformValue(shader->GetUniformIterator("discard"), 0);
glEnableVertexAttribArray(shader->getVertexAttribute()->second.location);
glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords);
glEnableVertexAttribArray(shader->getTexcoordAttribute()->second.location);
glVertexAttribPointer(shader->getTexcoordAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, &uv_coords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableVertexAttribArray(shader->getTexcoordAttribute()->second.location);
glDisableVertexAttribArray(shader->getVertexAttribute()->second.location);
}
mat->unapply();
}
void CanvasOGL::drawSolidRect(const rect& r, const Color& fill_color, const Color& stroke_color, float rotation) const
{
rectf vtx = r.as_type<float>();
const float vtx_coords[] = {
vtx.x1(), vtx.y1(),
vtx.x2(), vtx.y1(),
vtx.x1(), vtx.y2(),
vtx.x2(), vtx.y2(),
};
glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3(vtx.mid_x(),vtx.mid_y(),0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-vtx.mid_x(),-vtx.mid_y(),0.0f));
glm::mat4 mvp = mvp_ * model * getModelMatrix();
static OpenGL::ShaderProgramPtr shader = OpenGL::ShaderProgram::factory("simple");
shader->makeActive();
shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp));
// Draw a filled rect
shader->setUniformValue(shader->getColorUniform(), fill_color.asFloatVector());
glEnableVertexAttribArray(shader->getVertexAttribute()->second.location);
glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// Draw stroke if stroke_color is specified.
// XXX I think there is an easier way of doing this, with modern GL
const float vtx_coords_line[] = {
vtx.x1(), vtx.y1(),
vtx.x2(), vtx.y1(),
vtx.x2(), vtx.y2(),
vtx.x1(), vtx.y2(),
vtx.x1(), vtx.y1(),
};
shader->setUniformValue(shader->getColorUniform(), stroke_color.asFloatVector());
glEnableVertexAttribArray(shader->getVertexAttribute()->second.location);
glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords_line);
// XXX this may not be right.
glDrawArrays(GL_LINE_STRIP, 0, 5);
}
void CanvasOGL::drawSolidRect(const rect& r, const Color& fill_color, float rotate) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidRect()");
}
void CanvasOGL::drawHollowRect(const rect& r, const Color& stroke_color, float rotate) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawHollowRect()");
}
void CanvasOGL::drawLine(const point& p1, const point& p2, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawLine()");
}
void CanvasOGL::drawLines(const std::vector<glm::vec2>& varray, float line_width, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawLines()");
}
void CanvasOGL::drawLines(const std::vector<glm::vec2>& varray, float line_width, const std::vector<glm::u8vec4>& carray) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawLines()");
}
void CanvasOGL::drawLineStrip(const std::vector<glm::vec2>& points, float line_width, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawLineStrip()");
}
void CanvasOGL::drawLineLoop(const std::vector<glm::vec2>& varray, float line_width, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawLineLoop()");
}
void CanvasOGL::drawLine(const pointf& p1, const pointf& p2, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawLine()");
}
void CanvasOGL::drawPolygon(const std::vector<glm::vec2>& points, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawPolygon()");
}
void CanvasOGL::drawSolidCircle(const point& centre, double radius, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()");
}
void CanvasOGL::drawSolidCircle(const point& centre, double radius, const std::vector<uint8_t>& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()");
}
void CanvasOGL::drawHollowCircle(const point& centre, double radius, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawHollowCircle()");
}
void CanvasOGL::drawSolidCircle(const pointf& centre, double radius, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()");
}
void CanvasOGL::drawSolidCircle(const pointf& centre, double radius, const std::vector<uint8_t>& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()");
}
void CanvasOGL::drawHollowCircle(const pointf& centre, double radius, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawHollowCircle()");
}
void CanvasOGL::drawPoints(const std::vector<glm::vec2>& points, float radius, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawPoints()");
}
CanvasPtr CanvasOGL::getInstance()
{
return get_instance();
}
}
| sweetkristas/swiftly | src/kre/CanvasOGL.cpp | C++ | bsd-3-clause | 13,121 |
// Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkey
import (
"context"
"github.com/keybase/client/go/kbfs/idutil"
"github.com/keybase/client/go/kbfs/kbfscrypto"
"github.com/keybase/client/go/kbfs/kbfsmd"
"github.com/keybase/client/go/protocol/keybase1"
)
// KeyOpsConfig is a config object containing the outside helper
// instances needed by KeyOps.
type KeyOpsConfig interface {
KeyServer() KeyServer
KBPKI() idutil.KBPKI
}
// KeyOpsStandard implements the KeyOps interface and relays get/put
// requests for server-side key halves from/to the key server.
type KeyOpsStandard struct {
config KeyOpsConfig
}
// NewKeyOpsStandard creates a new KeyOpsStandard instance.
func NewKeyOpsStandard(config KeyOpsConfig) *KeyOpsStandard {
return &KeyOpsStandard{config}
}
// Test that KeyOps standard fully implements the KeyOps interface.
var _ KeyOps = (*KeyOpsStandard)(nil)
// GetTLFCryptKeyServerHalf is an implementation of the KeyOps interface.
func (k *KeyOpsStandard) GetTLFCryptKeyServerHalf(
ctx context.Context, serverHalfID kbfscrypto.TLFCryptKeyServerHalfID,
key kbfscrypto.CryptPublicKey) (kbfscrypto.TLFCryptKeyServerHalf, error) {
// get the key half from the server
serverHalf, err := k.config.KeyServer().GetTLFCryptKeyServerHalf(
ctx, serverHalfID, key)
if err != nil {
return kbfscrypto.TLFCryptKeyServerHalf{}, err
}
// get current uid and deviceKID
session, err := k.config.KBPKI().GetCurrentSession(ctx)
if err != nil {
return kbfscrypto.TLFCryptKeyServerHalf{}, err
}
// verify we got the expected key
err = kbfscrypto.VerifyTLFCryptKeyServerHalfID(
serverHalfID, session.UID, key, serverHalf)
if err != nil {
return kbfscrypto.TLFCryptKeyServerHalf{}, err
}
return serverHalf, nil
}
// PutTLFCryptKeyServerHalves is an implementation of the KeyOps interface.
func (k *KeyOpsStandard) PutTLFCryptKeyServerHalves(
ctx context.Context,
keyServerHalves kbfsmd.UserDeviceKeyServerHalves) error {
// upload the keys
return k.config.KeyServer().PutTLFCryptKeyServerHalves(ctx, keyServerHalves)
}
// DeleteTLFCryptKeyServerHalf is an implementation of the KeyOps interface.
func (k *KeyOpsStandard) DeleteTLFCryptKeyServerHalf(
ctx context.Context, uid keybase1.UID, key kbfscrypto.CryptPublicKey,
serverHalfID kbfscrypto.TLFCryptKeyServerHalfID) error {
return k.config.KeyServer().DeleteTLFCryptKeyServerHalf(
ctx, uid, key, serverHalfID)
}
| keybase/client | go/kbfs/libkey/key_ops.go | GO | bsd-3-clause | 2,520 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataExplorer.Domain.Columns;
using DataExplorer.Domain.Layouts;
namespace DataExplorer.Domain.Maps.SizeMaps
{
public class SizeMapFactory : ISizeMapFactory
{
public SizeMap Create(Column column, double targetMin, double targetMax, SortOrder sortOrder)
{
if (column.DataType == typeof(Boolean))
return new BooleanToSizeMap(targetMin, targetMax, sortOrder);
if (column.DataType == typeof(DateTime))
return new DateTimeToSizeMap(
(DateTime)column.Min,
(DateTime)column.Max,
targetMin,
targetMax,
sortOrder);
if (column.DataType == typeof(Double))
return new FloatToSizeMap(
(double)column.Min,
(double)column.Max,
targetMin,
targetMax,
sortOrder);
if (column.DataType == typeof(Int32))
return new IntegerToSizeMap(
(int)column.Min,
(int)column.Max,
targetMin,
targetMax,
sortOrder);
if (column.DataType == typeof(String))
return new StringToSizeMap(
column.Values.Cast<string>().ToList(),
targetMin,
targetMax,
sortOrder);
throw new ArgumentException("Column data type is not valid data type for an axis map.");
}
}
}
| dataexplorer/dataexplorer | Domain/Maps/SizeMaps/SizeMapFactory.cs | C# | bsd-3-clause | 1,714 |
package com.btr.proxy.search.desktop.gnome;
import java.io.File;
import java.io.IOException;
import java.net.ProxySelector;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.btr.proxy.search.ProxySearchStrategy;
import com.btr.proxy.selector.direct.NoProxySelector;
import com.btr.proxy.selector.fixed.FixedProxySelector;
import com.btr.proxy.selector.misc.ProtocolDispatchSelector;
import com.btr.proxy.selector.whitelist.ProxyBypassListSelector;
import com.btr.proxy.util.EmptyXMLResolver;
import com.btr.proxy.util.Logger;
import com.btr.proxy.util.PlatformUtil;
import com.btr.proxy.util.ProxyException;
import com.btr.proxy.util.ProxyUtil;
import com.btr.proxy.util.Logger.LogLevel;
/*****************************************************************************
* Loads the Gnome proxy settings from the Gnome GConf settings.
* <p>
* The following settings are extracted from the configuration that is stored
* in <i>.gconf</i> folder found in the user's home directory:
* </p>
* <ul>
* <li><i>/system/http_proxy/use_http_proxy</i> -> bool used only by gnome-vfs </li>
* <li><i>/system/http_proxy/host</i> -> string "my-proxy.example.com" without "http://"</li>
* <li><i>/system/http_proxy/port</i> -> int</li>
* <li><i>/system/http_proxy/use_authentication</i> -> bool</li>
* <li><i>/system/http_proxy/authentication_user</i> -> string</li>
* <li><i>/system/http_proxy/authentication_password</i> -> string</li>
* <li><i>/system/http_proxy/ignore_hosts</i> -> list-of-string</li>
* <li><i>/system/proxy/mode</i> -> string THIS IS THE CANONICAL KEY; SEE BELOW</li>
* <li><i>/system/proxy/secure_host</i> -> string "proxy-for-https.example.com"</li>
* <li><i>/system/proxy/secure_port</i> -> int</li>
* <li><i>/system/proxy/ftp_host</i> -> string "proxy-for-ftp.example.com"</li>
* <li><i>/system/proxy/ftp_port</i> -> int</li>
* <li><i>/system/proxy/socks_host</i> -> string "proxy-for-socks.example.com"</li>
* <li><i>/system/proxy/socks_port</i> -> int</li>
* <li><i>/system/proxy/autoconfig_url</i> -> string "http://proxy-autoconfig.example.com"</li>
* </ul>
* <i>/system/proxy/mode</i> can be either:<br/>
* "none" -> No proxy is used<br/>
* "manual" -> The user's configuration values are used (/system/http_proxy/{host,port,etc.})<br/>
* "auto" -> The "/system/proxy/autoconfig_url" key is used <br/>
* <p>
* GNOME Proxy_configuration settings are explained
* <a href="http://en.opensuse.org/GNOME/Proxy_configuration">here</a> in detail
* </p>
* @author Bernd Rosstauscher (proxyvole@rosstauscher.de) Copyright 2009
****************************************************************************/
public class GnomeProxySearchStrategy implements ProxySearchStrategy {
/*************************************************************************
* ProxySelector
* @see java.net.ProxySelector#ProxySelector()
************************************************************************/
public GnomeProxySearchStrategy() {
super();
}
/*************************************************************************
* Loads the proxy settings and initializes a proxy selector for the Gnome
* proxy settings.
* @return a configured ProxySelector, null if none is found.
* @throws ProxyException on file reading error.
************************************************************************/
public ProxySelector getProxySelector() throws ProxyException {
Logger.log(getClass(), LogLevel.TRACE, "Detecting Gnome proxy settings");
Properties settings = readSettings();
String type = settings.getProperty("/system/proxy/mode");
ProxySelector result = null;
if (type == null) {
String useProxy = settings.getProperty("/system/http_proxy/use_http_proxy");
if (useProxy == null) {
return null;
}
type = Boolean.parseBoolean(useProxy)?"manual":"none";
}
if ("none".equals(type)) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses no proxy");
result = NoProxySelector.getInstance();
}
if ("manual".equals(type)) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses manual proxy settings");
result = setupFixedProxySelector(settings);
}
if ("auto".equals(type)) {
String pacScriptUrl = settings.getProperty("/system/proxy/autoconfig_url", "");
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses autodetect script {0}", pacScriptUrl);
result = ProxyUtil.buildPacSelectorForUrl(pacScriptUrl);
}
// Wrap into white-list filter?
String noProxyList = settings.getProperty("/system/http_proxy/ignore_hosts", null);
if (result != null && noProxyList != null && noProxyList.trim().length() > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses proxy bypass list: {0}", noProxyList);
result = new ProxyBypassListSelector(noProxyList, result);
}
return result;
}
/*************************************************************************
* Load the proxy settings from the gconf settings XML file.
* @return the loaded settings stored in a properties object.
* @throws ProxyException on processing error.
************************************************************************/
public Properties readSettings() throws ProxyException {
Properties settings = new Properties();
try {
parseSettings("/system/proxy/", settings);
parseSettings("/system/http_proxy/", settings);
} catch (IOException e) {
Logger.log(getClass(), LogLevel.ERROR, "Gnome settings file error.", e);
throw new ProxyException(e);
}
return settings;
}
/*************************************************************************
* Finds the Gnome GConf settings file.
* @param context the gconf context to parse.
* @return a file or null if does not exist.
************************************************************************/
private File findSettingsFile(String context) {
// Normally we should inspect /etc/gconf/<version>/path to find out where the actual file is.
// But for normal systems this is always stored in .gconf folder in the user's home directory.
File userDir = new File(PlatformUtil.getUserHomeDir());
// Build directory path for context
StringBuilder path = new StringBuilder();
String[] parts = context.split("/");
for (String part : parts) {
path.append(part);
path.append(File.separator);
}
File settingsFile = new File(userDir, ".gconf"+File.separator+path.toString()+"%gconf.xml");
if (!settingsFile.exists()) {
Logger.log(getClass(), LogLevel.WARNING, "Gnome settings: {0} not found.", settingsFile);
return null;
}
return settingsFile;
}
/*************************************************************************
* Parse the fixed proxy settings and build an ProxySelector for this a
* chained configuration.
* @param settings the proxy settings to evaluate.
************************************************************************/
private ProxySelector setupFixedProxySelector(Properties settings) {
if (!hasProxySettings(settings)) {
return null;
}
ProtocolDispatchSelector ps = new ProtocolDispatchSelector();
installHttpSelector(settings, ps);
if (useForAllProtocols(settings)) {
ps.setFallbackSelector(ps.getSelector("http"));
} else {
installSecureSelector(settings, ps);
installFtpSelector(settings, ps);
installSocksSelector(settings, ps);
}
return ps;
}
/*************************************************************************
* Check if the http proxy should also be used for all other protocols.
* @param settings to inspect.
* @return true if only one proxy is configured else false.
************************************************************************/
private boolean useForAllProtocols(Properties settings) {
return Boolean.parseBoolean(
settings.getProperty("/system/http_proxy/use_same_proxy", "false"));
}
/*************************************************************************
* Checks if we have Proxy configuration settings in the properties.
* @param settings to inspect.
* @return true if we have found Proxy settings.
************************************************************************/
private boolean hasProxySettings(Properties settings) {
String proxyHost = settings.getProperty("/system/http_proxy/host", null);
return proxyHost != null && proxyHost.length() > 0;
}
/*************************************************************************
* Install a http proxy from the given settings.
* @param settings to inspect
* @param ps the dispatch selector to configure.
* @throws NumberFormatException
************************************************************************/
private void installHttpSelector(Properties settings,
ProtocolDispatchSelector ps) throws NumberFormatException {
String proxyHost = settings.getProperty("/system/http_proxy/host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/http_proxy/port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome http proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("http", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
/*************************************************************************
* Install a socks proxy from the given settings.
* @param settings to inspect
* @param ps the dispatch selector to configure.
* @throws NumberFormatException
************************************************************************/
private void installSocksSelector(Properties settings,
ProtocolDispatchSelector ps) throws NumberFormatException {
String proxyHost = settings.getProperty("/system/proxy/socks_host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/socks_port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome socks proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("socks", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
/*************************************************************************
* @param settings
* @param ps
* @throws NumberFormatException
************************************************************************/
private void installFtpSelector(Properties settings,
ProtocolDispatchSelector ps) throws NumberFormatException {
String proxyHost = settings.getProperty("/system/proxy/ftp_host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/ftp_port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome ftp proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("ftp", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
/*************************************************************************
* @param settings
* @param ps
* @throws NumberFormatException
************************************************************************/
private void installSecureSelector(Properties settings,
ProtocolDispatchSelector ps) throws NumberFormatException {
String proxyHost = settings.getProperty("/system/proxy/secure_host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/secure_port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome secure proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("https", new FixedProxySelector(proxyHost.trim(), proxyPort));
ps.setSelector("sftp", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
/*************************************************************************
* Parse the settings file and extract all network.proxy.* settings from it.
* @param context the gconf context to parse.
* @param settings the settings object to fill.
* @return the parsed properties.
* @throws IOException on read error.
************************************************************************/
private Properties parseSettings(String context, Properties settings) throws IOException {
// Read settings from file
File settingsFile = findSettingsFile(context);
if (settingsFile == null) {
return settings;
}
try {
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
documentBuilder.setEntityResolver(new EmptyXMLResolver());
Document doc = documentBuilder.parse(settingsFile);
Element root = doc.getDocumentElement();
Node entry = root.getFirstChild();
while (entry != null) {
if ("entry".equals(entry.getNodeName()) && entry instanceof Element) {
String entryName = ((Element)entry).getAttribute("name");
settings.setProperty(context+entryName, getEntryValue((Element) entry));
}
entry = entry.getNextSibling();
}
} catch (SAXException e) {
Logger.log(getClass(), LogLevel.ERROR, "Gnome settings parse error", e);
throw new IOException(e.getMessage());
} catch (ParserConfigurationException e) {
Logger.log(getClass(), LogLevel.ERROR, "Gnome settings parse error", e);
throw new IOException(e.getMessage());
}
return settings;
}
/*************************************************************************
* Parse an entry value from a given entry node.
* @param entry the XML node to inspect.
* @return the value, null if it has no value.
************************************************************************/
private String getEntryValue(Element entry) {
String type = entry.getAttribute("type");
if ("int".equals(type) || "bool".equals(type)) {
return entry.getAttribute("value");
}
if ("string".equals(type)) {
NodeList list = entry.getElementsByTagName("stringvalue");
if (list.getLength() > 0) {
return list.item(0).getTextContent();
}
}
if ("list".equals(type)) {
StringBuilder result = new StringBuilder();
NodeList list = entry.getElementsByTagName("li");
// Build comma separated list of items
for (int i = 0; i < list.getLength(); i++) {
if (result.length() > 0) {
result.append(",");
}
result.append(getEntryValue((Element) list.item(i)));
}
return result.toString();
}
return null;
}
}
| brsanthu/proxy-vole | src/main/java/com/btr/proxy/search/desktop/gnome/GnomeProxySearchStrategy.java | Java | bsd-3-clause | 14,860 |
/*
* Copyright (C) 2014 The Async HBase Authors. All rights reserved.
* This file is part of Async HBase.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the StumbleUpon nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.hbase.async;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;
import java.nio.charset.Charset;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.hbase.async.HBaseClient.ZKClient;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.socket.SocketChannel;
import org.jboss.netty.channel.socket.SocketChannelConfig;
import org.jboss.netty.channel.socket.nio.NioClientBossPool;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioWorkerPool;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.TimerTask;
import org.junit.Before;
import org.junit.Ignore;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.reflect.Whitebox;
import com.stumbleupon.async.Deferred;
@PrepareForTest({ HBaseClient.class, RegionClient.class, HBaseRpc.class,
GetRequest.class, RegionInfo.class, NioClientSocketChannelFactory.class,
Executors.class, HashedWheelTimer.class, NioClientBossPool.class,
NioWorkerPool.class })
@Ignore // ignore for test runners
public class BaseTestHBaseClient {
protected static final Charset CHARSET = Charset.forName("ASCII");
protected static final byte[] COMMA = { ',' };
protected static final byte[] TIMESTAMP = "1234567890".getBytes();
protected static final byte[] INFO = getStatic("INFO");
protected static final byte[] REGIONINFO = getStatic("REGIONINFO");
protected static final byte[] SERVER = getStatic("SERVER");
protected static final byte[] TABLE = { 't', 'a', 'b', 'l', 'e' };
protected static final byte[] KEY = { 'k', 'e', 'y' };
protected static final byte[] KEY2 = { 'k', 'e', 'y', '2' };
protected static final byte[] FAMILY = { 'f' };
protected static final byte[] QUALIFIER = { 'q', 'u', 'a', 'l' };
protected static final byte[] VALUE = { 'v', 'a', 'l', 'u', 'e' };
protected static final byte[] EMPTY_ARRAY = new byte[0];
protected static final KeyValue KV = new KeyValue(KEY, FAMILY, QUALIFIER, VALUE);
protected static final RegionInfo meta = mkregion(".META.", ".META.,,1234567890");
protected static final RegionInfo region = mkregion("table", "table,,1234567890");
protected static final int RS_PORT = 50511;
protected static final String ROOT_IP = "192.168.0.1";
protected static final String META_IP = "192.168.0.2";
protected static final String REGION_CLIENT_IP = "192.168.0.3";
protected static String MOCK_RS_CLIENT_NAME = "Mock RegionClient";
protected static String MOCK_ROOT_CLIENT_NAME = "Mock RootClient";
protected static String MOCK_META_CLIENT_NAME = "Mock MetaClient";
protected HBaseClient client = null;
/** Extracted from {@link #client}. */
protected ConcurrentSkipListMap<byte[], RegionInfo> regions_cache;
/** Extracted from {@link #client}. */
protected ConcurrentHashMap<RegionInfo, RegionClient> region2client;
/** Extracted from {@link #client}. */
protected ConcurrentHashMap<RegionClient, ArrayList<RegionInfo>> client2regions;
/** Extracted from {@link #client}. */
protected ConcurrentSkipListMap<byte[], ArrayList<HBaseRpc>> got_nsre;
/** Extracted from {@link #client}. */
protected HashMap<String, RegionClient> ip2client;
/** Extracted from {@link #client}. */
protected Counter num_nsre_rpcs;
/** Fake client supposedly connected to -ROOT-. */
protected RegionClient rootclient;
/** Fake client supposedly connected to .META.. */
protected RegionClient metaclient;
/** Fake client supposedly connected to our fake test table. */
protected RegionClient regionclient;
/** Each new region client is dumped here */
protected List<RegionClient> region_clients = new ArrayList<RegionClient>();
/** Fake Zookeeper client */
protected ZKClient zkclient;
/** Fake channel factory */
protected NioClientSocketChannelFactory channel_factory;
/** Fake channel returned from the factory */
protected SocketChannel chan;
/** Fake timer for testing */
protected FakeTimer timer;
@Before
public void before() throws Exception {
region_clients.clear();
rootclient = mock(RegionClient.class);
when(rootclient.toString()).thenReturn(MOCK_ROOT_CLIENT_NAME);
metaclient = mock(RegionClient.class);
when(metaclient.toString()).thenReturn(MOCK_META_CLIENT_NAME);
regionclient = mock(RegionClient.class);
when(regionclient.toString()).thenReturn(MOCK_RS_CLIENT_NAME);
zkclient = mock(ZKClient.class);
channel_factory = mock(NioClientSocketChannelFactory.class);
chan = mock(SocketChannel.class);
timer = new FakeTimer();
when(zkclient.getDeferredRoot()).thenReturn(new Deferred<Object>());
PowerMockito.mockStatic(Executors.class);
PowerMockito.when(Executors.defaultThreadFactory())
.thenReturn(mock(ThreadFactory.class));
PowerMockito.when(Executors.newCachedThreadPool())
.thenReturn(mock(ExecutorService.class));
PowerMockito.whenNew(NioClientSocketChannelFactory.class).withAnyArguments()
.thenReturn(channel_factory);
PowerMockito.whenNew(HashedWheelTimer.class).withAnyArguments()
.thenReturn(timer);
PowerMockito.whenNew(NioClientBossPool.class).withAnyArguments()
.thenReturn(mock(NioClientBossPool.class));
PowerMockito.whenNew(NioWorkerPool.class).withAnyArguments()
.thenReturn(mock(NioWorkerPool.class));
client = PowerMockito.spy(new HBaseClient("test-quorum-spec"));
Whitebox.setInternalState(client, "zkclient", zkclient);
Whitebox.setInternalState(client, "rootregion", rootclient);
Whitebox.setInternalState(client, "jitter_percent", 0);
regions_cache = Whitebox.getInternalState(client, "regions_cache");
region2client = Whitebox.getInternalState(client, "region2client");
client2regions = Whitebox.getInternalState(client, "client2regions");
got_nsre = Whitebox.getInternalState(client, "got_nsre");
ip2client = Whitebox.getInternalState(client, "ip2client");
injectRegionInCache(meta, metaclient, META_IP + ":" + RS_PORT);
injectRegionInCache(region, regionclient, REGION_CLIENT_IP + ":" + RS_PORT);
when(channel_factory.newChannel(any(ChannelPipeline.class)))
.thenReturn(chan);
when(chan.getConfig()).thenReturn(mock(SocketChannelConfig.class));
when(rootclient.toString()).thenReturn("Mock RootClient");
PowerMockito.doAnswer(new Answer<RegionClient>(){
@Override
public RegionClient answer(InvocationOnMock invocation) throws Throwable {
final Object[] args = invocation.getArguments();
final String endpoint = (String)args[0] + ":" + (Integer)args[1];
final RegionClient rc = mock(RegionClient.class);
when(rc.getRemoteAddress()).thenReturn(endpoint);
client2regions.put(rc, new ArrayList<RegionInfo>());
region_clients.add(rc);
return rc;
}
}).when(client, "newClient", anyString(), anyInt());
}
/**
* Injects an entry in the local caches of the client.
*/
protected void injectRegionInCache(final RegionInfo region,
final RegionClient client,
final String ip) {
regions_cache.put(region.name(), region);
region2client.put(region, client);
ArrayList<RegionInfo> regions = client2regions.get(client);
if (regions == null) {
regions = new ArrayList<RegionInfo>(1);
client2regions.put(client, regions);
}
regions.add(region);
ip2client.put(ip, client);
}
// ----------------- //
// Helper functions. //
// ----------------- //
protected void clearCaches(){
regions_cache.clear();
region2client.clear();
client2regions.clear();
}
protected static <T> T getStatic(final String fieldname) {
return Whitebox.getInternalState(HBaseClient.class, fieldname);
}
/**
* Creates a fake {@code .META.} row.
* The row contains a single entry for all keys of {@link #TABLE}.
*/
protected static ArrayList<KeyValue> metaRow() {
return metaRow(HBaseClient.EMPTY_ARRAY, HBaseClient.EMPTY_ARRAY);
}
/**
* Creates a fake {@code .META.} row.
* The row contains a single entry for {@link #TABLE}.
* @param start_key The start key of the region in this entry.
* @param stop_key The stop key of the region in this entry.
*/
protected static ArrayList<KeyValue> metaRow(final byte[] start_key,
final byte[] stop_key) {
final ArrayList<KeyValue> row = new ArrayList<KeyValue>(2);
row.add(metaRegionInfo(start_key, stop_key, false, false, TABLE));
row.add(new KeyValue(region.name(), INFO, SERVER, "localhost:54321".getBytes()));
return row;
}
protected static KeyValue metaRegionInfo( final byte[] start_key,
final byte[] stop_key, final boolean offline, final boolean splitting,
final byte[] table) {
final byte[] name = concat(table, COMMA, start_key, COMMA, TIMESTAMP);
final byte is_splitting = (byte) (splitting ? 1 : 0);
final byte[] regioninfo = concat(
new byte[] {
0, // version
(byte) stop_key.length, // vint: stop key length
},
stop_key,
offline ? new byte[] { 1 } : new byte[] { 0 }, // boolean: offline
Bytes.fromLong(name.hashCode()), // long: region ID (make it random)
new byte[] { (byte) name.length }, // vint: region name length
name, // region name
new byte[] {
is_splitting, // boolean: splitting
(byte) start_key.length, // vint: start key length
},
start_key
);
return new KeyValue(region.name(), INFO, REGIONINFO, regioninfo);
}
protected static RegionInfo mkregion(final String table, final String name) {
return new RegionInfo(table.getBytes(), name.getBytes(),
HBaseClient.EMPTY_ARRAY);
}
protected static byte[] anyBytes() {
return any(byte[].class);
}
/** Concatenates byte arrays together. */
protected static byte[] concat(final byte[]... arrays) {
int len = 0;
for (final byte[] array : arrays) {
len += array.length;
}
final byte[] result = new byte[len];
len = 0;
for (final byte[] array : arrays) {
System.arraycopy(array, 0, result, len, array.length);
len += array.length;
}
return result;
}
/** Creates a new Deferred that's already called back. */
protected static <T> Answer<Deferred<T>> newDeferred(final T result) {
return new Answer<Deferred<T>>() {
public Deferred<T> answer(final InvocationOnMock invocation) {
return Deferred.fromResult(result);
}
};
}
/**
* A fake {@link Timer} implementation that fires up tasks immediately.
* Tasks are called immediately from the current thread and a history of the
* various tasks is logged.
*/
static final class FakeTimer extends HashedWheelTimer {
final List<Map.Entry<TimerTask, Long>> tasks =
new ArrayList<Map.Entry<TimerTask, Long>>();
final ArrayList<Timeout> timeouts = new ArrayList<Timeout>();
boolean run = true;
@Override
public Timeout newTimeout(final TimerTask task,
final long delay,
final TimeUnit unit) {
try {
tasks.add(new AbstractMap.SimpleEntry<TimerTask, Long>(task, delay));
if (run) {
task.run(null); // Argument never used in this code base.
}
final Timeout timeout = mock(Timeout.class);
timeouts.add(timeout);
return timeout; // Return value never used in this code base.
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Timer task failed: " + task, e);
}
}
@Override
public Set<Timeout> stop() {
run = false;
return new HashSet<Timeout>(timeouts);
}
}
/**
* A fake {@link org.jboss.netty.util.Timer} implementation.
* Instead of executing the task it will store that task in a internal state
* and provides a function to start the execution of the stored task.
* This implementation thus allows the flexibility of simulating the
* things that will be going on during the time out period of a TimerTask.
* This was mainly return to simulate the timeout period for
* alreadyNSREdRegion test, where the region will be in the NSREd mode only
* during this timeout period, which was difficult to simulate using the
* above {@link FakeTimer} implementation, as we don't get back the control
* during the timeout period
*
* Here it will hold at most two Tasks. We have two tasks here because when
* one is being executed, it may call for newTimeOut for another task.
*/
static final class FakeTaskTimer extends HashedWheelTimer {
protected TimerTask newPausedTask = null;
protected TimerTask pausedTask = null;
@Override
public synchronized Timeout newTimeout(final TimerTask task,
final long delay,
final TimeUnit unit) {
if (pausedTask == null) {
pausedTask = task;
} else if (newPausedTask == null) {
newPausedTask = task;
} else {
throw new IllegalStateException("Cannot Pause Two Timer Tasks");
}
return null;
}
@Override
public Set<Timeout> stop() {
return null;
}
public boolean continuePausedTask() {
if (pausedTask == null) {
return false;
}
try {
if (newPausedTask != null) {
throw new IllegalStateException("Cannot be in this state");
}
pausedTask.run(null); // Argument never used in this code base
pausedTask = newPausedTask;
newPausedTask = null;
return true;
} catch (Exception e) {
throw new RuntimeException("Timer task failed: " + pausedTask, e);
}
}
}
/**
* Generate and return a mocked HBase RPC for testing purposes with a valid
* Deferred that can be called on execution.
* @param deferred A deferred to watch for results
* @return The RPC to pass through unit tests.
*/
protected HBaseRpc getMockHBaseRpc(final Deferred<Object> deferred) {
final HBaseRpc rpc = mock(HBaseRpc.class);
rpc.attempt = 0;
when(rpc.getDeferred()).thenReturn(deferred);
when(rpc.toString()).thenReturn("MockRPC");
PowerMockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
if (deferred != null) {
deferred.callback(invocation.getArguments()[0]);
} else {
System.out.println("Deferred was null!!");
}
return null;
}
}).when(rpc).callback(Object.class);
return rpc;
}
}
| manolama/asynchbase | test/BaseTestHBaseClient.java | Java | bsd-3-clause | 17,282 |
#include "gb_thread.hpp"
#include "z80.hpp"
#include "memory.hpp"
#include "rom.hpp"
#include "cart_rom_only.hpp"
#include "cart_mbc1.hpp"
#include "cart_mbc5.hpp"
#include "internal_ram.hpp"
#include "video.hpp"
#include "timer.hpp"
#include "joypad.hpp"
#include "sound.hpp"
#include "debug.hpp"
#include "assert.hpp"
#include <cstdlib>
#include <vector>
#include <fstream>
#include <memory>
#include <chrono>
namespace
{
class stop_exception {};
std::unique_ptr<gb::memory_mapping> init_cartridge(gb::rom rom)
{
switch (rom.cartridge())
{
case 0x00: // ROM only (could have little RAM)
return std::make_unique<gb::cart_rom_only>(std::move(rom));
case 0x01: // MBC1
case 0x02: // MBC1+RAM
case 0x03: // MBC1+RAM+BATTERY
return std::make_unique<gb::cart_mbc1>(std::move(rom));
case 0x19: // MBC5
case 0x1A: // MBC5+RAM
case 0x1B: // MBC5+RAM+BATTERY
return std::make_unique<gb::cart_mbc5>(std::move(rom));
default:
throw gb::unsupported_rom_exception("Unknown cartridge type");
}
}
std::unique_ptr<gb::z80_cpu> init_cpu(gb::memory_mapping &cart, gb::internal_ram &internal_ram,
gb::video &video, gb::timer &timer, gb::joypad &joypad, gb::sound &sound)
{
// Make Memory
gb::memory_map memory;
memory.add_mapping(&cart);
memory.add_mapping(&internal_ram);
memory.add_mapping(&video);
memory.add_mapping(&timer);
memory.add_mapping(&joypad);
memory.add_mapping(&sound);
memory.write8(0xff05, 0x00);
memory.write8(0xff06, 0x00);
memory.write8(0xff07, 0x00);
memory.write8(0xff10, 0x80);
memory.write8(0xff11, 0xbf);
memory.write8(0xff12, 0xf3);
memory.write8(0xff14, 0xbf);
memory.write8(0xff16, 0x3f);
memory.write8(0xff17, 0x00);
memory.write8(0xff19, 0xbf);
memory.write8(0xff1a, 0x7f);
memory.write8(0xff1b, 0xff);
memory.write8(0xff1c, 0x9f);
memory.write8(0xff1e, 0xbf);
memory.write8(0xff20, 0xff);
memory.write8(0xff21, 0x00);
memory.write8(0xff22, 0x00);
memory.write8(0xff23, 0xbf);
memory.write8(0xff24, 0x77);
memory.write8(0xff25, 0xf3);
memory.write8(0xff26, 0xf1);
memory.write8(0xff40, 0x91);
memory.write8(0xff42, 0x00);
memory.write8(0xff43, 0x00);
memory.write8(0xff45, 0x00);
memory.write8(0xff47, 0xfc);
memory.write8(0xff48, 0xff);
memory.write8(0xff49, 0xff);
memory.write8(0xff4a, 0x00);
memory.write8(0xff4b, 0x00);
memory.write8(0xffff, 0x00);
// Register file
gb::register_file registers;
registers.write8<gb::register8::a>(0x11);
registers.write8<gb::register8::f>(0xb0);
registers.write16<gb::register16::bc>(0x0013);
registers.write16<gb::register16::de>(0x00d8);
registers.write16<gb::register16::hl>(0x014d);
registers.write16<gb::register16::sp>(0xfffe);
registers.write16<gb::register16::pc>(0x0100);
// Make Cpu
return std::make_unique<gb::z80_cpu>(std::move(memory), std::move(registers));
}
}
gb::gb_hardware::gb_hardware(rom arg_rom) :
cartridge(init_cartridge(std::move(arg_rom))),
cpu(init_cpu(*cartridge, internal_ram, video, timer, joypad, sound))
{
}
#define HEAVY_DEBUG 0
gb::cputime gb::gb_hardware::tick()
{
const auto time_fde = cpu->fetch_decode_execute();
#if HEAVY_DEBUG
switch (cpu->current_opcode()->extra_bytes)
{
case 0:
debug(cpu->current_opcode()->mnemonic);
break;
case 1:
debug(cpu->current_opcode()->mnemonic, " $=", static_cast<int>(cpu->value8()));
break;
case 2:
debug(cpu->current_opcode()->mnemonic, " $=", static_cast<int>(cpu->value16()));
break;
default:
ASSERT_UNREACHABLE();
}
#endif
timer.tick(*cpu, time_fde);
const auto time_r = cpu->read();
timer.tick(*cpu, time_r);
const auto time_w = cpu->write();
timer.tick(*cpu, time_w);
const auto time = time_fde + time_r + time_w;
video.tick(*cpu, time);
#if HEAVY_DEBUG
cpu->registers().debug_print();
#endif
return time;
}
gb::gb_thread::gb_thread() :
_running(false)
{
}
gb::gb_thread::~gb_thread()
{
post_stop();
join();
}
void gb::gb_thread::start(gb::rom rom)
{
ASSERT(!_running);
_gb = std::make_unique<gb_hardware>(std::move(rom));
_thread = std::thread(&gb_thread::run, this);
_running = true;
}
void gb::gb_thread::join()
{
if (_running)
{
_thread.join();
}
}
void gb::gb_thread::post_stop()
{
command fn([](){
throw stop_exception();
});
std::lock_guard<std::mutex> lock(_mutex);
_command_queue.emplace_back(std::move(fn));
}
std::future<gb::video::raw_image> gb::gb_thread::post_get_image()
{
// TODO use capture by move (Visual Studio 2015/C++14)
auto promise = std::make_shared<std::promise<video::raw_image>>();
auto future = promise->get_future();
command fn([this, promise]() {
promise->set_value(_gb->video.image());
});
std::lock_guard<std::mutex> lock(_mutex);
_command_queue.emplace_back(std::move(fn));
return future;
}
void gb::gb_thread::post_key_down(gb::key key)
{
command fn([this, key]() {
_gb->joypad.down(key);
});
std::lock_guard<std::mutex> lock(_mutex);
_command_queue.emplace_back(std::move(fn));
}
void gb::gb_thread::post_key_up(gb::key key)
{
command fn([this, key]() {
_gb->joypad.up(key);
});
std::lock_guard<std::mutex> lock(_mutex);
_command_queue.emplace_back(std::move(fn));
}
void gb::gb_thread::run()
{
using namespace std::chrono;
using clock = steady_clock;
static_assert(clock::is_steady, "clock not steady");
static_assert(std::ratio_less_equal<clock::period, std::ratio_multiply<std::ratio<100>, std::nano>>::value,
"clock too inaccurate (period > 100ns)");
if (ASSERT_ENABLED)
debug("WARNING: asserts are enabled!");
debug("=====================================================");
// Let's go :)
std::vector<command> current_commands;
cputime gb_time(0);
auto real_time_start = clock::now();
cputime performance_gb_time(0);
nanoseconds performance_sleep_time(0);
auto performance_start = clock::now();
try
{
while (true)
{
// Command stream
{
std::lock_guard<std::mutex> lock(_mutex);
if (!_command_queue.empty())
{
std::swap(current_commands, _command_queue);
}
}
if (!current_commands.empty())
{
for (const auto &command : current_commands)
{
command();
}
current_commands.clear();
}
// Simulation itself
const auto time = _gb->tick();
// Time bookkeeping
gb_time += time;
const auto real_time = clock::now() - real_time_start;
const auto drift = duration_cast<nanoseconds>(gb_time) - real_time;
if (drift > milliseconds(5))
{
// Simulation is too fast
const auto sleep_start = clock::now();
std::this_thread::sleep_for(drift);
performance_sleep_time += (clock::now() - sleep_start);
const auto new_current_time = clock::now();
const auto new_real_time = new_current_time - real_time_start;
const auto new_drift = gb_time - duration_cast<cputime>(new_real_time);
gb_time = new_drift;
real_time_start = new_current_time;
}
else if (drift < milliseconds(-100))
{
// Simulation is too slow (reset counter to avoid an endless accumulation of negaitve time)
// This is a resync-attempt in case of a spike and avoids underflow
gb_time = cputime(0);
real_time_start = clock::now();
}
// Performance-o-meter
performance_gb_time += time;
const auto performance_now = clock::now();
const auto performance_real_time = performance_now - performance_start;
if (performance_real_time > seconds(10))
{
const auto accuracy =
duration_cast<milliseconds>(performance_gb_time - performance_real_time).count();
const double speed =
static_cast<double>(duration_cast<nanoseconds>(performance_gb_time).count()) /
static_cast<double>(duration_cast<nanoseconds>(performance_real_time - performance_sleep_time).count()) *
100.0;
debug("PERF: simulation drift in the last 10 s was ", accuracy, " ms");
debug("PERF: simulation speed in the last 10 s was ", speed, " % of required speed");
if (speed < 110.0)
{
debug("PERF WARNING: simulation speed is too low (< 110 %)");
}
performance_sleep_time = seconds(0);
performance_gb_time = cputime(0);
performance_start = performance_now;
}
}
}
catch (const stop_exception &)
{
// this might be ugly but it works well :)
}
}
| kaini/gameboy | gameboy_lib/gb_thread.cpp | C++ | bsd-3-clause | 8,162 |
//M*//////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
/****************************************************************************************\
* Very fast SAD-based (Sum-of-Absolute-Diffrences) stereo correspondence algorithm. *
* Contributed by Kurt Konolige *
\****************************************************************************************/
#include "precomp.hpp"
#include <stdio.h>
#include <limits>
#include "opencl_kernels_calib3d.hpp"
namespace cv
{
struct StereoBMParams
{
StereoBMParams(int _numDisparities=64, int _SADWindowSize=21)
{
preFilterType = StereoBM::PREFILTER_XSOBEL;
preFilterSize = 9;
preFilterCap = 31;
SADWindowSize = _SADWindowSize;
minDisparity = 0;
numDisparities = _numDisparities > 0 ? _numDisparities : 64;
textureThreshold = 10;
uniquenessRatio = 15;
speckleRange = speckleWindowSize = 0;
roi1 = roi2 = Rect(0,0,0,0);
disp12MaxDiff = -1;
dispType = CV_16S;
}
int preFilterType;
int preFilterSize;
int preFilterCap;
int SADWindowSize;
int minDisparity;
int numDisparities;
int textureThreshold;
int uniquenessRatio;
int speckleRange;
int speckleWindowSize;
Rect roi1, roi2;
int disp12MaxDiff;
int dispType;
};
static bool ocl_prefilter_norm(InputArray _input, OutputArray _output, int winsize, int prefilterCap)
{
ocl::Kernel k("prefilter_norm", ocl::calib3d::stereobm_oclsrc, cv::format("-D WSZ=%d", winsize));
if(k.empty())
return false;
int scale_g = winsize*winsize/8, scale_s = (1024 + scale_g)/(scale_g*2);
scale_g *= scale_s;
UMat input = _input.getUMat(), output;
_output.create(input.size(), input.type());
output = _output.getUMat();
size_t globalThreads[3] = { input.cols, input.rows, 1 };
k.args(ocl::KernelArg::PtrReadOnly(input), ocl::KernelArg::PtrWriteOnly(output), input.rows, input.cols,
prefilterCap, scale_g, scale_s);
return k.run(2, globalThreads, NULL, false);
}
static void prefilterNorm( const Mat& src, Mat& dst, int winsize, int ftzero, uchar* buf )
{
int x, y, wsz2 = winsize/2;
int* vsum = (int*)alignPtr(buf + (wsz2 + 1)*sizeof(vsum[0]), 32);
int scale_g = winsize*winsize/8, scale_s = (1024 + scale_g)/(scale_g*2);
const int OFS = 256*5, TABSZ = OFS*2 + 256;
uchar tab[TABSZ];
const uchar* sptr = src.ptr();
int srcstep = (int)src.step;
Size size = src.size();
scale_g *= scale_s;
for( x = 0; x < TABSZ; x++ )
tab[x] = (uchar)(x - OFS < -ftzero ? 0 : x - OFS > ftzero ? ftzero*2 : x - OFS + ftzero);
for( x = 0; x < size.width; x++ )
vsum[x] = (ushort)(sptr[x]*(wsz2 + 2));
for( y = 1; y < wsz2; y++ )
{
for( x = 0; x < size.width; x++ )
vsum[x] = (ushort)(vsum[x] + sptr[srcstep*y + x]);
}
for( y = 0; y < size.height; y++ )
{
const uchar* top = sptr + srcstep*MAX(y-wsz2-1,0);
const uchar* bottom = sptr + srcstep*MIN(y+wsz2,size.height-1);
const uchar* prev = sptr + srcstep*MAX(y-1,0);
const uchar* curr = sptr + srcstep*y;
const uchar* next = sptr + srcstep*MIN(y+1,size.height-1);
uchar* dptr = dst.ptr<uchar>(y);
for( x = 0; x < size.width; x++ )
vsum[x] = (ushort)(vsum[x] + bottom[x] - top[x]);
for( x = 0; x <= wsz2; x++ )
{
vsum[-x-1] = vsum[0];
vsum[size.width+x] = vsum[size.width-1];
}
int sum = vsum[0]*(wsz2 + 1);
for( x = 1; x <= wsz2; x++ )
sum += vsum[x];
int val = ((curr[0]*5 + curr[1] + prev[0] + next[0])*scale_g - sum*scale_s) >> 10;
dptr[0] = tab[val + OFS];
for( x = 1; x < size.width-1; x++ )
{
sum += vsum[x+wsz2] - vsum[x-wsz2-1];
val = ((curr[x]*4 + curr[x-1] + curr[x+1] + prev[x] + next[x])*scale_g - sum*scale_s) >> 10;
dptr[x] = tab[val + OFS];
}
sum += vsum[x+wsz2] - vsum[x-wsz2-1];
val = ((curr[x]*5 + curr[x-1] + prev[x] + next[x])*scale_g - sum*scale_s) >> 10;
dptr[x] = tab[val + OFS];
}
}
static bool ocl_prefilter_xsobel(InputArray _input, OutputArray _output, int prefilterCap)
{
ocl::Kernel k("prefilter_xsobel", ocl::calib3d::stereobm_oclsrc);
if(k.empty())
return false;
UMat input = _input.getUMat(), output;
_output.create(input.size(), input.type());
output = _output.getUMat();
size_t globalThreads[3] = { input.cols, input.rows, 1 };
k.args(ocl::KernelArg::PtrReadOnly(input), ocl::KernelArg::PtrWriteOnly(output), input.rows, input.cols, prefilterCap);
return k.run(2, globalThreads, NULL, false);
}
static void
prefilterXSobel( const Mat& src, Mat& dst, int ftzero )
{
int x, y;
const int OFS = 256*4, TABSZ = OFS*2 + 256;
uchar tab[TABSZ];
Size size = src.size();
for( x = 0; x < TABSZ; x++ )
tab[x] = (uchar)(x - OFS < -ftzero ? 0 : x - OFS > ftzero ? ftzero*2 : x - OFS + ftzero);
uchar val0 = tab[0 + OFS];
#if CV_SSE2
volatile bool useSIMD = checkHardwareSupport(CV_CPU_SSE2);
#endif
for( y = 0; y < size.height-1; y += 2 )
{
const uchar* srow1 = src.ptr<uchar>(y);
const uchar* srow0 = y > 0 ? srow1 - src.step : size.height > 1 ? srow1 + src.step : srow1;
const uchar* srow2 = y < size.height-1 ? srow1 + src.step : size.height > 1 ? srow1 - src.step : srow1;
const uchar* srow3 = y < size.height-2 ? srow1 + src.step*2 : srow1;
uchar* dptr0 = dst.ptr<uchar>(y);
uchar* dptr1 = dptr0 + dst.step;
dptr0[0] = dptr0[size.width-1] = dptr1[0] = dptr1[size.width-1] = val0;
x = 1;
#if CV_SSE2
if( useSIMD )
{
__m128i z = _mm_setzero_si128(), ftz = _mm_set1_epi16((short)ftzero),
ftz2 = _mm_set1_epi8(cv::saturate_cast<uchar>(ftzero*2));
for( ; x <= size.width-9; x += 8 )
{
__m128i c0 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow0 + x - 1)), z);
__m128i c1 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow1 + x - 1)), z);
__m128i d0 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow0 + x + 1)), z);
__m128i d1 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow1 + x + 1)), z);
d0 = _mm_sub_epi16(d0, c0);
d1 = _mm_sub_epi16(d1, c1);
__m128i c2 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow2 + x - 1)), z);
__m128i c3 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow3 + x - 1)), z);
__m128i d2 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow2 + x + 1)), z);
__m128i d3 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow3 + x + 1)), z);
d2 = _mm_sub_epi16(d2, c2);
d3 = _mm_sub_epi16(d3, c3);
__m128i v0 = _mm_add_epi16(d0, _mm_add_epi16(d2, _mm_add_epi16(d1, d1)));
__m128i v1 = _mm_add_epi16(d1, _mm_add_epi16(d3, _mm_add_epi16(d2, d2)));
v0 = _mm_packus_epi16(_mm_add_epi16(v0, ftz), _mm_add_epi16(v1, ftz));
v0 = _mm_min_epu8(v0, ftz2);
_mm_storel_epi64((__m128i*)(dptr0 + x), v0);
_mm_storel_epi64((__m128i*)(dptr1 + x), _mm_unpackhi_epi64(v0, v0));
}
}
#endif
for( ; x < size.width-1; x++ )
{
int d0 = srow0[x+1] - srow0[x-1], d1 = srow1[x+1] - srow1[x-1],
d2 = srow2[x+1] - srow2[x-1], d3 = srow3[x+1] - srow3[x-1];
int v0 = tab[d0 + d1*2 + d2 + OFS];
int v1 = tab[d1 + d2*2 + d3 + OFS];
dptr0[x] = (uchar)v0;
dptr1[x] = (uchar)v1;
}
}
for( ; y < size.height; y++ )
{
uchar* dptr = dst.ptr<uchar>(y);
for( x = 0; x < size.width; x++ )
dptr[x] = val0;
}
}
static const int DISPARITY_SHIFT = 4;
#if CV_SSE2
static void findStereoCorrespondenceBM_SSE2( const Mat& left, const Mat& right,
Mat& disp, Mat& cost, StereoBMParams& state,
uchar* buf, int _dy0, int _dy1 )
{
const int ALIGN = 16;
int x, y, d;
int wsz = state.SADWindowSize, wsz2 = wsz/2;
int dy0 = MIN(_dy0, wsz2+1), dy1 = MIN(_dy1, wsz2+1);
int ndisp = state.numDisparities;
int mindisp = state.minDisparity;
int lofs = MAX(ndisp - 1 + mindisp, 0);
int rofs = -MIN(ndisp - 1 + mindisp, 0);
int width = left.cols, height = left.rows;
int width1 = width - rofs - ndisp + 1;
int ftzero = state.preFilterCap;
int textureThreshold = state.textureThreshold;
int uniquenessRatio = state.uniquenessRatio;
short FILTERED = (short)((mindisp - 1) << DISPARITY_SHIFT);
ushort *sad, *hsad0, *hsad, *hsad_sub;
int *htext;
uchar *cbuf0, *cbuf;
const uchar* lptr0 = left.ptr() + lofs;
const uchar* rptr0 = right.ptr() + rofs;
const uchar *lptr, *lptr_sub, *rptr;
short* dptr = disp.ptr<short>();
int sstep = (int)left.step;
int dstep = (int)(disp.step/sizeof(dptr[0]));
int cstep = (height + dy0 + dy1)*ndisp;
short costbuf = 0;
int coststep = cost.data ? (int)(cost.step/sizeof(costbuf)) : 0;
const int TABSZ = 256;
uchar tab[TABSZ];
const __m128i d0_8 = _mm_setr_epi16(0,1,2,3,4,5,6,7), dd_8 = _mm_set1_epi16(8);
sad = (ushort*)alignPtr(buf + sizeof(sad[0]), ALIGN);
hsad0 = (ushort*)alignPtr(sad + ndisp + 1 + dy0*ndisp, ALIGN);
htext = (int*)alignPtr((int*)(hsad0 + (height+dy1)*ndisp) + wsz2 + 2, ALIGN);
cbuf0 = (uchar*)alignPtr((uchar*)(htext + height + wsz2 + 2) + dy0*ndisp, ALIGN);
for( x = 0; x < TABSZ; x++ )
tab[x] = (uchar)std::abs(x - ftzero);
// initialize buffers
memset( hsad0 - dy0*ndisp, 0, (height + dy0 + dy1)*ndisp*sizeof(hsad0[0]) );
memset( htext - wsz2 - 1, 0, (height + wsz + 1)*sizeof(htext[0]) );
for( x = -wsz2-1; x < wsz2; x++ )
{
hsad = hsad0 - dy0*ndisp; cbuf = cbuf0 + (x + wsz2 + 1)*cstep - dy0*ndisp;
lptr = lptr0 + MIN(MAX(x, -lofs), width-lofs-1) - dy0*sstep;
rptr = rptr0 + MIN(MAX(x, -rofs), width-rofs-1) - dy0*sstep;
for( y = -dy0; y < height + dy1; y++, hsad += ndisp, cbuf += ndisp, lptr += sstep, rptr += sstep )
{
int lval = lptr[0];
__m128i lv = _mm_set1_epi8((char)lval), z = _mm_setzero_si128();
for( d = 0; d < ndisp; d += 16 )
{
__m128i rv = _mm_loadu_si128((const __m128i*)(rptr + d));
__m128i hsad_l = _mm_load_si128((__m128i*)(hsad + d));
__m128i hsad_h = _mm_load_si128((__m128i*)(hsad + d + 8));
__m128i diff = _mm_adds_epu8(_mm_subs_epu8(lv, rv), _mm_subs_epu8(rv, lv));
_mm_store_si128((__m128i*)(cbuf + d), diff);
hsad_l = _mm_add_epi16(hsad_l, _mm_unpacklo_epi8(diff,z));
hsad_h = _mm_add_epi16(hsad_h, _mm_unpackhi_epi8(diff,z));
_mm_store_si128((__m128i*)(hsad + d), hsad_l);
_mm_store_si128((__m128i*)(hsad + d + 8), hsad_h);
}
htext[y] += tab[lval];
}
}
// initialize the left and right borders of the disparity map
for( y = 0; y < height; y++ )
{
for( x = 0; x < lofs; x++ )
dptr[y*dstep + x] = FILTERED;
for( x = lofs + width1; x < width; x++ )
dptr[y*dstep + x] = FILTERED;
}
dptr += lofs;
for( x = 0; x < width1; x++, dptr++ )
{
short* costptr = cost.data ? cost.ptr<short>() + lofs + x : &costbuf;
int x0 = x - wsz2 - 1, x1 = x + wsz2;
const uchar* cbuf_sub = cbuf0 + ((x0 + wsz2 + 1) % (wsz + 1))*cstep - dy0*ndisp;
cbuf = cbuf0 + ((x1 + wsz2 + 1) % (wsz + 1))*cstep - dy0*ndisp;
hsad = hsad0 - dy0*ndisp;
lptr_sub = lptr0 + MIN(MAX(x0, -lofs), width-1-lofs) - dy0*sstep;
lptr = lptr0 + MIN(MAX(x1, -lofs), width-1-lofs) - dy0*sstep;
rptr = rptr0 + MIN(MAX(x1, -rofs), width-1-rofs) - dy0*sstep;
for( y = -dy0; y < height + dy1; y++, cbuf += ndisp, cbuf_sub += ndisp,
hsad += ndisp, lptr += sstep, lptr_sub += sstep, rptr += sstep )
{
int lval = lptr[0];
__m128i lv = _mm_set1_epi8((char)lval), z = _mm_setzero_si128();
for( d = 0; d < ndisp; d += 16 )
{
__m128i rv = _mm_loadu_si128((const __m128i*)(rptr + d));
__m128i hsad_l = _mm_load_si128((__m128i*)(hsad + d));
__m128i hsad_h = _mm_load_si128((__m128i*)(hsad + d + 8));
__m128i cbs = _mm_load_si128((const __m128i*)(cbuf_sub + d));
__m128i diff = _mm_adds_epu8(_mm_subs_epu8(lv, rv), _mm_subs_epu8(rv, lv));
__m128i diff_h = _mm_sub_epi16(_mm_unpackhi_epi8(diff, z), _mm_unpackhi_epi8(cbs, z));
_mm_store_si128((__m128i*)(cbuf + d), diff);
diff = _mm_sub_epi16(_mm_unpacklo_epi8(diff, z), _mm_unpacklo_epi8(cbs, z));
hsad_h = _mm_add_epi16(hsad_h, diff_h);
hsad_l = _mm_add_epi16(hsad_l, diff);
_mm_store_si128((__m128i*)(hsad + d), hsad_l);
_mm_store_si128((__m128i*)(hsad + d + 8), hsad_h);
}
htext[y] += tab[lval] - tab[lptr_sub[0]];
}
// fill borders
for( y = dy1; y <= wsz2; y++ )
htext[height+y] = htext[height+dy1-1];
for( y = -wsz2-1; y < -dy0; y++ )
htext[y] = htext[-dy0];
// initialize sums
for( d = 0; d < ndisp; d++ )
sad[d] = (ushort)(hsad0[d-ndisp*dy0]*(wsz2 + 2 - dy0));
hsad = hsad0 + (1 - dy0)*ndisp;
for( y = 1 - dy0; y < wsz2; y++, hsad += ndisp )
for( d = 0; d < ndisp; d += 16 )
{
__m128i s0 = _mm_load_si128((__m128i*)(sad + d));
__m128i s1 = _mm_load_si128((__m128i*)(sad + d + 8));
__m128i t0 = _mm_load_si128((__m128i*)(hsad + d));
__m128i t1 = _mm_load_si128((__m128i*)(hsad + d + 8));
s0 = _mm_add_epi16(s0, t0);
s1 = _mm_add_epi16(s1, t1);
_mm_store_si128((__m128i*)(sad + d), s0);
_mm_store_si128((__m128i*)(sad + d + 8), s1);
}
int tsum = 0;
for( y = -wsz2-1; y < wsz2; y++ )
tsum += htext[y];
// finally, start the real processing
for( y = 0; y < height; y++ )
{
int minsad = INT_MAX, mind = -1;
hsad = hsad0 + MIN(y + wsz2, height+dy1-1)*ndisp;
hsad_sub = hsad0 + MAX(y - wsz2 - 1, -dy0)*ndisp;
__m128i minsad8 = _mm_set1_epi16(SHRT_MAX);
__m128i mind8 = _mm_set1_epi16(0), d8 = d0_8, mask;
for( d = 0; d < ndisp; d += 16 )
{
__m128i u0 = _mm_load_si128((__m128i*)(hsad_sub + d));
__m128i u1 = _mm_load_si128((__m128i*)(hsad + d));
__m128i v0 = _mm_load_si128((__m128i*)(hsad_sub + d + 8));
__m128i v1 = _mm_load_si128((__m128i*)(hsad + d + 8));
__m128i usad8 = _mm_load_si128((__m128i*)(sad + d));
__m128i vsad8 = _mm_load_si128((__m128i*)(sad + d + 8));
u1 = _mm_sub_epi16(u1, u0);
v1 = _mm_sub_epi16(v1, v0);
usad8 = _mm_add_epi16(usad8, u1);
vsad8 = _mm_add_epi16(vsad8, v1);
mask = _mm_cmpgt_epi16(minsad8, usad8);
minsad8 = _mm_min_epi16(minsad8, usad8);
mind8 = _mm_max_epi16(mind8, _mm_and_si128(mask, d8));
_mm_store_si128((__m128i*)(sad + d), usad8);
_mm_store_si128((__m128i*)(sad + d + 8), vsad8);
mask = _mm_cmpgt_epi16(minsad8, vsad8);
minsad8 = _mm_min_epi16(minsad8, vsad8);
d8 = _mm_add_epi16(d8, dd_8);
mind8 = _mm_max_epi16(mind8, _mm_and_si128(mask, d8));
d8 = _mm_add_epi16(d8, dd_8);
}
tsum += htext[y + wsz2] - htext[y - wsz2 - 1];
if( tsum < textureThreshold )
{
dptr[y*dstep] = FILTERED;
continue;
}
ushort CV_DECL_ALIGNED(16) minsad_buf[8], mind_buf[8];
_mm_store_si128((__m128i*)minsad_buf, minsad8);
_mm_store_si128((__m128i*)mind_buf, mind8);
for( d = 0; d < 8; d++ )
if(minsad > (int)minsad_buf[d] || (minsad == (int)minsad_buf[d] && mind > mind_buf[d]))
{
minsad = minsad_buf[d];
mind = mind_buf[d];
}
if( uniquenessRatio > 0 )
{
int thresh = minsad + (minsad * uniquenessRatio/100);
__m128i thresh8 = _mm_set1_epi16((short)(thresh + 1));
__m128i d1 = _mm_set1_epi16((short)(mind-1)), d2 = _mm_set1_epi16((short)(mind+1));
__m128i dd_16 = _mm_add_epi16(dd_8, dd_8);
d8 = _mm_sub_epi16(d0_8, dd_16);
for( d = 0; d < ndisp; d += 16 )
{
__m128i usad8 = _mm_load_si128((__m128i*)(sad + d));
__m128i vsad8 = _mm_load_si128((__m128i*)(sad + d + 8));
mask = _mm_cmpgt_epi16( thresh8, _mm_min_epi16(usad8,vsad8));
d8 = _mm_add_epi16(d8, dd_16);
if( !_mm_movemask_epi8(mask) )
continue;
mask = _mm_cmpgt_epi16( thresh8, usad8);
mask = _mm_and_si128(mask, _mm_or_si128(_mm_cmpgt_epi16(d1,d8), _mm_cmpgt_epi16(d8,d2)));
if( _mm_movemask_epi8(mask) )
break;
__m128i t8 = _mm_add_epi16(d8, dd_8);
mask = _mm_cmpgt_epi16( thresh8, vsad8);
mask = _mm_and_si128(mask, _mm_or_si128(_mm_cmpgt_epi16(d1,t8), _mm_cmpgt_epi16(t8,d2)));
if( _mm_movemask_epi8(mask) )
break;
}
if( d < ndisp )
{
dptr[y*dstep] = FILTERED;
continue;
}
}
if( 0 < mind && mind < ndisp - 1 )
{
int p = sad[mind+1], n = sad[mind-1];
d = p + n - 2*sad[mind] + std::abs(p - n);
dptr[y*dstep] = (short)(((ndisp - mind - 1 + mindisp)*256 + (d != 0 ? (p-n)*256/d : 0) + 15) >> 4);
}
else
dptr[y*dstep] = (short)((ndisp - mind - 1 + mindisp)*16);
costptr[y*coststep] = sad[mind];
}
}
}
#endif
static void
findStereoCorrespondenceBM( const Mat& left, const Mat& right,
Mat& disp, Mat& cost, const StereoBMParams& state,
uchar* buf, int _dy0, int _dy1 )
{
const int ALIGN = 16;
int x, y, d;
int wsz = state.SADWindowSize, wsz2 = wsz/2;
int dy0 = MIN(_dy0, wsz2+1), dy1 = MIN(_dy1, wsz2+1);
int ndisp = state.numDisparities;
int mindisp = state.minDisparity;
int lofs = MAX(ndisp - 1 + mindisp, 0);
int rofs = -MIN(ndisp - 1 + mindisp, 0);
int width = left.cols, height = left.rows;
int width1 = width - rofs - ndisp + 1;
int ftzero = state.preFilterCap;
int textureThreshold = state.textureThreshold;
int uniquenessRatio = state.uniquenessRatio;
short FILTERED = (short)((mindisp - 1) << DISPARITY_SHIFT);
int *sad, *hsad0, *hsad, *hsad_sub, *htext;
uchar *cbuf0, *cbuf;
const uchar* lptr0 = left.ptr() + lofs;
const uchar* rptr0 = right.ptr() + rofs;
const uchar *lptr, *lptr_sub, *rptr;
short* dptr = disp.ptr<short>();
int sstep = (int)left.step;
int dstep = (int)(disp.step/sizeof(dptr[0]));
int cstep = (height+dy0+dy1)*ndisp;
int costbuf = 0;
int coststep = cost.data ? (int)(cost.step/sizeof(costbuf)) : 0;
const int TABSZ = 256;
uchar tab[TABSZ];
sad = (int*)alignPtr(buf + sizeof(sad[0]), ALIGN);
hsad0 = (int*)alignPtr(sad + ndisp + 1 + dy0*ndisp, ALIGN);
htext = (int*)alignPtr((int*)(hsad0 + (height+dy1)*ndisp) + wsz2 + 2, ALIGN);
cbuf0 = (uchar*)alignPtr((uchar*)(htext + height + wsz2 + 2) + dy0*ndisp, ALIGN);
for( x = 0; x < TABSZ; x++ )
tab[x] = (uchar)std::abs(x - ftzero);
// initialize buffers
memset( hsad0 - dy0*ndisp, 0, (height + dy0 + dy1)*ndisp*sizeof(hsad0[0]) );
memset( htext - wsz2 - 1, 0, (height + wsz + 1)*sizeof(htext[0]) );
for( x = -wsz2-1; x < wsz2; x++ )
{
hsad = hsad0 - dy0*ndisp; cbuf = cbuf0 + (x + wsz2 + 1)*cstep - dy0*ndisp;
lptr = lptr0 + std::min(std::max(x, -lofs), width-lofs-1) - dy0*sstep;
rptr = rptr0 + std::min(std::max(x, -rofs), width-rofs-1) - dy0*sstep;
for( y = -dy0; y < height + dy1; y++, hsad += ndisp, cbuf += ndisp, lptr += sstep, rptr += sstep )
{
int lval = lptr[0];
for( d = 0; d < ndisp; d++ )
{
int diff = std::abs(lval - rptr[d]);
cbuf[d] = (uchar)diff;
hsad[d] = (int)(hsad[d] + diff);
}
htext[y] += tab[lval];
}
}
// initialize the left and right borders of the disparity map
for( y = 0; y < height; y++ )
{
for( x = 0; x < lofs; x++ )
dptr[y*dstep + x] = FILTERED;
for( x = lofs + width1; x < width; x++ )
dptr[y*dstep + x] = FILTERED;
}
dptr += lofs;
for( x = 0; x < width1; x++, dptr++ )
{
int* costptr = cost.data ? cost.ptr<int>() + lofs + x : &costbuf;
int x0 = x - wsz2 - 1, x1 = x + wsz2;
const uchar* cbuf_sub = cbuf0 + ((x0 + wsz2 + 1) % (wsz + 1))*cstep - dy0*ndisp;
cbuf = cbuf0 + ((x1 + wsz2 + 1) % (wsz + 1))*cstep - dy0*ndisp;
hsad = hsad0 - dy0*ndisp;
lptr_sub = lptr0 + MIN(MAX(x0, -lofs), width-1-lofs) - dy0*sstep;
lptr = lptr0 + MIN(MAX(x1, -lofs), width-1-lofs) - dy0*sstep;
rptr = rptr0 + MIN(MAX(x1, -rofs), width-1-rofs) - dy0*sstep;
for( y = -dy0; y < height + dy1; y++, cbuf += ndisp, cbuf_sub += ndisp,
hsad += ndisp, lptr += sstep, lptr_sub += sstep, rptr += sstep )
{
int lval = lptr[0];
for( d = 0; d < ndisp; d++ )
{
int diff = std::abs(lval - rptr[d]);
cbuf[d] = (uchar)diff;
hsad[d] = hsad[d] + diff - cbuf_sub[d];
}
htext[y] += tab[lval] - tab[lptr_sub[0]];
}
// fill borders
for( y = dy1; y <= wsz2; y++ )
htext[height+y] = htext[height+dy1-1];
for( y = -wsz2-1; y < -dy0; y++ )
htext[y] = htext[-dy0];
// initialize sums
for( d = 0; d < ndisp; d++ )
sad[d] = (int)(hsad0[d-ndisp*dy0]*(wsz2 + 2 - dy0));
hsad = hsad0 + (1 - dy0)*ndisp;
for( y = 1 - dy0; y < wsz2; y++, hsad += ndisp )
for( d = 0; d < ndisp; d++ )
sad[d] = (int)(sad[d] + hsad[d]);
int tsum = 0;
for( y = -wsz2-1; y < wsz2; y++ )
tsum += htext[y];
// finally, start the real processing
for( y = 0; y < height; y++ )
{
int minsad = INT_MAX, mind = -1;
hsad = hsad0 + MIN(y + wsz2, height+dy1-1)*ndisp;
hsad_sub = hsad0 + MAX(y - wsz2 - 1, -dy0)*ndisp;
for( d = 0; d < ndisp; d++ )
{
int currsad = sad[d] + hsad[d] - hsad_sub[d];
sad[d] = currsad;
if( currsad < minsad )
{
minsad = currsad;
mind = d;
}
}
tsum += htext[y + wsz2] - htext[y - wsz2 - 1];
if( tsum < textureThreshold )
{
dptr[y*dstep] = FILTERED;
continue;
}
if( uniquenessRatio > 0 )
{
int thresh = minsad + (minsad * uniquenessRatio/100);
for( d = 0; d < ndisp; d++ )
{
if( (d < mind-1 || d > mind+1) && sad[d] <= thresh)
break;
}
if( d < ndisp )
{
dptr[y*dstep] = FILTERED;
continue;
}
}
{
sad[-1] = sad[1];
sad[ndisp] = sad[ndisp-2];
int p = sad[mind+1], n = sad[mind-1];
d = p + n - 2*sad[mind] + std::abs(p - n);
dptr[y*dstep] = (short)(((ndisp - mind - 1 + mindisp)*256 + (d != 0 ? (p-n)*256/d : 0) + 15) >> 4);
costptr[y*coststep] = sad[mind];
}
}
}
}
static bool ocl_prefiltering(InputArray left0, InputArray right0, OutputArray left, OutputArray right, StereoBMParams* state)
{
if( state->preFilterType == StereoBM::PREFILTER_NORMALIZED_RESPONSE )
{
if(!ocl_prefilter_norm( left0, left, state->preFilterSize, state->preFilterCap))
return false;
if(!ocl_prefilter_norm( right0, right, state->preFilterSize, state->preFilterCap))
return false;
}
else
{
if(!ocl_prefilter_xsobel( left0, left, state->preFilterCap ))
return false;
if(!ocl_prefilter_xsobel( right0, right, state->preFilterCap))
return false;
}
return true;
}
struct PrefilterInvoker : public ParallelLoopBody
{
PrefilterInvoker(const Mat& left0, const Mat& right0, Mat& left, Mat& right,
uchar* buf0, uchar* buf1, StereoBMParams* _state)
{
imgs0[0] = &left0; imgs0[1] = &right0;
imgs[0] = &left; imgs[1] = &right;
buf[0] = buf0; buf[1] = buf1;
state = _state;
}
void operator()( const Range& range ) const
{
for( int i = range.start; i < range.end; i++ )
{
if( state->preFilterType == StereoBM::PREFILTER_NORMALIZED_RESPONSE )
prefilterNorm( *imgs0[i], *imgs[i], state->preFilterSize, state->preFilterCap, buf[i] );
else
prefilterXSobel( *imgs0[i], *imgs[i], state->preFilterCap );
}
}
const Mat* imgs0[2];
Mat* imgs[2];
uchar* buf[2];
StereoBMParams* state;
};
static bool ocl_stereobm( InputArray _left, InputArray _right,
OutputArray _disp, StereoBMParams* state)
{
int ndisp = state->numDisparities;
int mindisp = state->minDisparity;
int wsz = state->SADWindowSize;
int wsz2 = wsz/2;
ocl::Device devDef = ocl::Device::getDefault();
int sizeX = devDef.isIntel() ? 32 : std::max(11, 27 - devDef.maxComputeUnits()),
sizeY = sizeX - 1,
N = ndisp * 2;
cv::String opt = cv::format("-D DEFINE_KERNEL_STEREOBM -D MIN_DISP=%d -D NUM_DISP=%d"
" -D BLOCK_SIZE_X=%d -D BLOCK_SIZE_Y=%d -D WSZ=%d",
mindisp, ndisp,
sizeX, sizeY, wsz);
ocl::Kernel k("stereoBM", ocl::calib3d::stereobm_oclsrc, opt);
if(k.empty())
return false;
UMat left = _left.getUMat(), right = _right.getUMat();
int cols = left.cols, rows = left.rows;
_disp.create(_left.size(), CV_16S);
_disp.setTo((mindisp - 1) << 4);
Rect roi = Rect(Point(wsz2 + mindisp + ndisp - 1, wsz2), Point(cols-wsz2-mindisp, rows-wsz2) );
UMat disp = (_disp.getUMat())(roi);
int globalX = (disp.cols + sizeX - 1) / sizeX,
globalY = (disp.rows + sizeY - 1) / sizeY;
size_t globalThreads[3] = {N, globalX, globalY};
size_t localThreads[3] = {N, 1, 1};
int idx = 0;
idx = k.set(idx, ocl::KernelArg::PtrReadOnly(left));
idx = k.set(idx, ocl::KernelArg::PtrReadOnly(right));
idx = k.set(idx, ocl::KernelArg::WriteOnlyNoSize(disp));
idx = k.set(idx, rows);
idx = k.set(idx, cols);
idx = k.set(idx, state->textureThreshold);
idx = k.set(idx, state->uniquenessRatio);
return k.run(3, globalThreads, localThreads, false);
}
struct FindStereoCorrespInvoker : public ParallelLoopBody
{
FindStereoCorrespInvoker( const Mat& _left, const Mat& _right,
Mat& _disp, StereoBMParams* _state,
int _nstripes, size_t _stripeBufSize,
bool _useShorts, Rect _validDisparityRect,
Mat& _slidingSumBuf, Mat& _cost )
{
left = &_left; right = &_right;
disp = &_disp; state = _state;
nstripes = _nstripes; stripeBufSize = _stripeBufSize;
useShorts = _useShorts;
validDisparityRect = _validDisparityRect;
slidingSumBuf = &_slidingSumBuf;
cost = &_cost;
}
void operator()( const Range& range ) const
{
int cols = left->cols, rows = left->rows;
int _row0 = std::min(cvRound(range.start * rows / nstripes), rows);
int _row1 = std::min(cvRound(range.end * rows / nstripes), rows);
uchar *ptr = slidingSumBuf->ptr() + range.start * stripeBufSize;
int FILTERED = (state->minDisparity - 1)*16;
Rect roi = validDisparityRect & Rect(0, _row0, cols, _row1 - _row0);
if( roi.height == 0 )
return;
int row0 = roi.y;
int row1 = roi.y + roi.height;
Mat part;
if( row0 > _row0 )
{
part = disp->rowRange(_row0, row0);
part = Scalar::all(FILTERED);
}
if( _row1 > row1 )
{
part = disp->rowRange(row1, _row1);
part = Scalar::all(FILTERED);
}
Mat left_i = left->rowRange(row0, row1);
Mat right_i = right->rowRange(row0, row1);
Mat disp_i = disp->rowRange(row0, row1);
Mat cost_i = state->disp12MaxDiff >= 0 ? cost->rowRange(row0, row1) : Mat();
#if CV_SSE2
if( useShorts )
findStereoCorrespondenceBM_SSE2( left_i, right_i, disp_i, cost_i, *state, ptr, row0, rows - row1 );
else
#endif
findStereoCorrespondenceBM( left_i, right_i, disp_i, cost_i, *state, ptr, row0, rows - row1 );
if( state->disp12MaxDiff >= 0 )
validateDisparity( disp_i, cost_i, state->minDisparity, state->numDisparities, state->disp12MaxDiff );
if( roi.x > 0 )
{
part = disp_i.colRange(0, roi.x);
part = Scalar::all(FILTERED);
}
if( roi.x + roi.width < cols )
{
part = disp_i.colRange(roi.x + roi.width, cols);
part = Scalar::all(FILTERED);
}
}
protected:
const Mat *left, *right;
Mat* disp, *slidingSumBuf, *cost;
StereoBMParams *state;
int nstripes;
size_t stripeBufSize;
bool useShorts;
Rect validDisparityRect;
};
class StereoBMImpl : public StereoBM
{
public:
StereoBMImpl()
{
params = StereoBMParams();
}
StereoBMImpl( int _numDisparities, int _SADWindowSize )
{
params = StereoBMParams(_numDisparities, _SADWindowSize);
}
void compute( InputArray leftarr, InputArray rightarr, OutputArray disparr )
{
int dtype = disparr.fixedType() ? disparr.type() : params.dispType;
Size leftsize = leftarr.size();
if (leftarr.size() != rightarr.size())
CV_Error( Error::StsUnmatchedSizes, "All the images must have the same size" );
if (leftarr.type() != CV_8UC1 || rightarr.type() != CV_8UC1)
CV_Error( Error::StsUnsupportedFormat, "Both input images must have CV_8UC1" );
if (dtype != CV_16SC1 && dtype != CV_32FC1)
CV_Error( Error::StsUnsupportedFormat, "Disparity image must have CV_16SC1 or CV_32FC1 format" );
if( params.preFilterType != PREFILTER_NORMALIZED_RESPONSE &&
params.preFilterType != PREFILTER_XSOBEL )
CV_Error( Error::StsOutOfRange, "preFilterType must be = CV_STEREO_BM_NORMALIZED_RESPONSE" );
if( params.preFilterSize < 5 || params.preFilterSize > 255 || params.preFilterSize % 2 == 0 )
CV_Error( Error::StsOutOfRange, "preFilterSize must be odd and be within 5..255" );
if( params.preFilterCap < 1 || params.preFilterCap > 63 )
CV_Error( Error::StsOutOfRange, "preFilterCap must be within 1..63" );
if( params.SADWindowSize < 5 || params.SADWindowSize > 255 || params.SADWindowSize % 2 == 0 ||
params.SADWindowSize >= std::min(leftsize.width, leftsize.height) )
CV_Error( Error::StsOutOfRange, "SADWindowSize must be odd, be within 5..255 and be not larger than image width or height" );
if( params.numDisparities <= 0 || params.numDisparities % 16 != 0 )
CV_Error( Error::StsOutOfRange, "numDisparities must be positive and divisble by 16" );
if( params.textureThreshold < 0 )
CV_Error( Error::StsOutOfRange, "texture threshold must be non-negative" );
if( params.uniquenessRatio < 0 )
CV_Error( Error::StsOutOfRange, "uniqueness ratio must be non-negative" );
int FILTERED = (params.minDisparity - 1) << DISPARITY_SHIFT;
if(ocl::useOpenCL() && disparr.isUMat() && params.textureThreshold == 0)
{
UMat left, right;
if(ocl_prefiltering(leftarr, rightarr, left, right, ¶ms))
{
if(ocl_stereobm(left, right, disparr, ¶ms))
{
if( params.speckleRange >= 0 && params.speckleWindowSize > 0 )
filterSpeckles(disparr.getMat(), FILTERED, params.speckleWindowSize, params.speckleRange, slidingSumBuf);
if (dtype == CV_32F)
disparr.getUMat().convertTo(disparr, CV_32FC1, 1./(1 << DISPARITY_SHIFT), 0);
CV_IMPL_ADD(CV_IMPL_OCL);
return;
}
}
}
Mat left0 = leftarr.getMat(), right0 = rightarr.getMat();
disparr.create(left0.size(), dtype);
Mat disp0 = disparr.getMat();
preFilteredImg0.create( left0.size(), CV_8U );
preFilteredImg1.create( left0.size(), CV_8U );
cost.create( left0.size(), CV_16S );
Mat left = preFilteredImg0, right = preFilteredImg1;
int mindisp = params.minDisparity;
int ndisp = params.numDisparities;
int width = left0.cols;
int height = left0.rows;
int lofs = std::max(ndisp - 1 + mindisp, 0);
int rofs = -std::min(ndisp - 1 + mindisp, 0);
int width1 = width - rofs - ndisp + 1;
if( lofs >= width || rofs >= width || width1 < 1 )
{
disp0 = Scalar::all( FILTERED * ( disp0.type() < CV_32F ? 1 : 1./(1 << DISPARITY_SHIFT) ) );
return;
}
Mat disp = disp0;
if( dtype == CV_32F )
{
dispbuf.create(disp0.size(), CV_16S);
disp = dispbuf;
}
int wsz = params.SADWindowSize;
int bufSize0 = (int)((ndisp + 2)*sizeof(int));
bufSize0 += (int)((height+wsz+2)*ndisp*sizeof(int));
bufSize0 += (int)((height + wsz + 2)*sizeof(int));
bufSize0 += (int)((height+wsz+2)*ndisp*(wsz+2)*sizeof(uchar) + 256);
int bufSize1 = (int)((width + params.preFilterSize + 2) * sizeof(int) + 256);
int bufSize2 = 0;
if( params.speckleRange >= 0 && params.speckleWindowSize > 0 )
bufSize2 = width*height*(sizeof(Point_<short>) + sizeof(int) + sizeof(uchar));
#if CV_SSE2
bool useShorts = params.preFilterCap <= 31 && params.SADWindowSize <= 21 && checkHardwareSupport(CV_CPU_SSE2);
#else
const bool useShorts = false;
#endif
const double SAD_overhead_coeff = 10.0;
double N0 = 8000000 / (useShorts ? 1 : 4); // approx tbb's min number instructions reasonable for one thread
double maxStripeSize = std::min(std::max(N0 / (width * ndisp), (wsz-1) * SAD_overhead_coeff), (double)height);
int nstripes = cvCeil(height / maxStripeSize);
int bufSize = std::max(bufSize0 * nstripes, std::max(bufSize1 * 2, bufSize2));
if( slidingSumBuf.cols < bufSize )
slidingSumBuf.create( 1, bufSize, CV_8U );
uchar *_buf = slidingSumBuf.ptr();
parallel_for_(Range(0, 2), PrefilterInvoker(left0, right0, left, right, _buf, _buf + bufSize1, ¶ms), 1);
Rect validDisparityRect(0, 0, width, height), R1 = params.roi1, R2 = params.roi2;
validDisparityRect = getValidDisparityROI(R1.area() > 0 ? Rect(0, 0, width, height) : validDisparityRect,
R2.area() > 0 ? Rect(0, 0, width, height) : validDisparityRect,
params.minDisparity, params.numDisparities,
params.SADWindowSize);
parallel_for_(Range(0, nstripes),
FindStereoCorrespInvoker(left, right, disp, ¶ms, nstripes,
bufSize0, useShorts, validDisparityRect,
slidingSumBuf, cost));
if( params.speckleRange >= 0 && params.speckleWindowSize > 0 )
filterSpeckles(disp, FILTERED, params.speckleWindowSize, params.speckleRange, slidingSumBuf);
if (disp0.data != disp.data)
disp.convertTo(disp0, disp0.type(), 1./(1 << DISPARITY_SHIFT), 0);
}
AlgorithmInfo* info() const { return 0; }
int getMinDisparity() const { return params.minDisparity; }
void setMinDisparity(int minDisparity) { params.minDisparity = minDisparity; }
int getNumDisparities() const { return params.numDisparities; }
void setNumDisparities(int numDisparities) { params.numDisparities = numDisparities; }
int getBlockSize() const { return params.SADWindowSize; }
void setBlockSize(int blockSize) { params.SADWindowSize = blockSize; }
int getSpeckleWindowSize() const { return params.speckleWindowSize; }
void setSpeckleWindowSize(int speckleWindowSize) { params.speckleWindowSize = speckleWindowSize; }
int getSpeckleRange() const { return params.speckleRange; }
void setSpeckleRange(int speckleRange) { params.speckleRange = speckleRange; }
int getDisp12MaxDiff() const { return params.disp12MaxDiff; }
void setDisp12MaxDiff(int disp12MaxDiff) { params.disp12MaxDiff = disp12MaxDiff; }
int getPreFilterType() const { return params.preFilterType; }
void setPreFilterType(int preFilterType) { params.preFilterType = preFilterType; }
int getPreFilterSize() const { return params.preFilterSize; }
void setPreFilterSize(int preFilterSize) { params.preFilterSize = preFilterSize; }
int getPreFilterCap() const { return params.preFilterCap; }
void setPreFilterCap(int preFilterCap) { params.preFilterCap = preFilterCap; }
int getTextureThreshold() const { return params.textureThreshold; }
void setTextureThreshold(int textureThreshold) { params.textureThreshold = textureThreshold; }
int getUniquenessRatio() const { return params.uniquenessRatio; }
void setUniquenessRatio(int uniquenessRatio) { params.uniquenessRatio = uniquenessRatio; }
int getSmallerBlockSize() const { return 0; }
void setSmallerBlockSize(int) {}
Rect getROI1() const { return params.roi1; }
void setROI1(Rect roi1) { params.roi1 = roi1; }
Rect getROI2() const { return params.roi2; }
void setROI2(Rect roi2) { params.roi2 = roi2; }
void write(FileStorage& fs) const
{
fs << "name" << name_
<< "minDisparity" << params.minDisparity
<< "numDisparities" << params.numDisparities
<< "blockSize" << params.SADWindowSize
<< "speckleWindowSize" << params.speckleWindowSize
<< "speckleRange" << params.speckleRange
<< "disp12MaxDiff" << params.disp12MaxDiff
<< "preFilterType" << params.preFilterType
<< "preFilterSize" << params.preFilterSize
<< "preFilterCap" << params.preFilterCap
<< "textureThreshold" << params.textureThreshold
<< "uniquenessRatio" << params.uniquenessRatio;
}
void read(const FileNode& fn)
{
FileNode n = fn["name"];
CV_Assert( n.isString() && String(n) == name_ );
params.minDisparity = (int)fn["minDisparity"];
params.numDisparities = (int)fn["numDisparities"];
params.SADWindowSize = (int)fn["blockSize"];
params.speckleWindowSize = (int)fn["speckleWindowSize"];
params.speckleRange = (int)fn["speckleRange"];
params.disp12MaxDiff = (int)fn["disp12MaxDiff"];
params.preFilterType = (int)fn["preFilterType"];
params.preFilterSize = (int)fn["preFilterSize"];
params.preFilterCap = (int)fn["preFilterCap"];
params.textureThreshold = (int)fn["textureThreshold"];
params.uniquenessRatio = (int)fn["uniquenessRatio"];
params.roi1 = params.roi2 = Rect();
}
StereoBMParams params;
Mat preFilteredImg0, preFilteredImg1, cost, dispbuf;
Mat slidingSumBuf;
static const char* name_;
};
const char* StereoBMImpl::name_ = "StereoMatcher.BM";
Ptr<StereoBM> StereoBM::create(int _numDisparities, int _SADWindowSize)
{
return makePtr<StereoBMImpl>(_numDisparities, _SADWindowSize);
}
}
/* End of file. */
| apavlenko/opencv | modules/calib3d/src/stereobm.cpp | C++ | bsd-3-clause | 43,834 |
"use strict";
var mapnik = require('../');
var assert = require('assert');
var path = require('path');
mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'geojson.input'));
describe('mapnik.Geometry ', function() {
it('should throw with invalid usage', function() {
// geometry cannot be created directly for now
assert.throws(function() { mapnik.Geometry(); });
});
it('should access a geometry from a feature', function() {
var feature = new mapnik.Feature(1);
var point = {
"type": "MultiPoint",
"coordinates": [[0,0],[1,1]]
};
var input = {
type: "Feature",
properties: {},
geometry: point
};
var f = new mapnik.Feature.fromJSON(JSON.stringify(input));
var geom = f.geometry();
assert.equal(geom.type(),mapnik.Geometry.MultiPoint);
assert.deepEqual(JSON.parse(geom.toJSONSync()),point);
var expected_wkb = new Buffer('0104000000020000000101000000000000000000000000000000000000000101000000000000000000f03f000000000000f03f', 'hex');
assert.deepEqual(geom.toWKB(),expected_wkb);
});
it('should fail on toJSON due to bad parameters', function() {
var feature = new mapnik.Feature(1);
var point = {
"type": "MultiPoint",
"coordinates": [[0,0],[1,1]]
};
var input = {
type: "Feature",
properties: {},
geometry: point
};
var f = new mapnik.Feature.fromJSON(JSON.stringify(input));
var geom = f.geometry();
assert.equal(geom.type(),mapnik.Geometry.MultiPoint);
assert.throws(function() { geom.toJSONSync(null); });
assert.throws(function() { geom.toJSONSync({transform:null}); });
assert.throws(function() { geom.toJSONSync({transform:{}}); });
assert.throws(function() { geom.toJSON(null, function(err,json) {}); });
assert.throws(function() { geom.toJSON({transform:null}, function(err, json) {}); });
assert.throws(function() { geom.toJSON({transform:{}}, function(err, json) {}); });
});
it('should throw if we attempt to create a Feature from a geojson geometry (rather than geojson feature)', function() {
var geometry = {
type: 'Point',
coordinates: [ 7.415119300000001, 43.730364300000005 ]
};
// starts throwing, as expected, at Mapnik v3.0.9 (https://github.com/mapnik/node-mapnik/issues/560)
if (mapnik.versions.mapnik_number >= 300009) {
assert.throws(function() {
var transformed = mapnik.Feature.fromJSON(JSON.stringify(geometry));
});
}
});
it('should throw from empty geometry from toWKB', function() {
var s = new mapnik.Feature(1);
assert.throws(function() {
var geom = s.geometry().toWKB();
});
});
});
| langateam/node-mapnik | test/geometry.test.js | JavaScript | bsd-3-clause | 2,955 |
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model frontend\models\ManagerTrain */
$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => 'Manager Trains', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="manager-train-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'rangkaian_fasiliti_awam',
'cat_id',
'location',
'state_id',
'district_id',
'mukim_id',
'sub_base_id',
'cluster_id',
'kampung_id',
'alamat',
'poskod',
'nama_pengurus',
'ic',
'jantina',
'no_fon',
'date_enter',
'enter_by',
],
]) ?>
</div>
| development2016/kds-dev | frontend/views/manager-train/view.php | PHP | bsd-3-clause | 1,317 |
/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2012-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: correspondence_estimation_backprojection.hpp 7230 2012-09-21 06:31:19Z rusu $
*
*/
#ifndef PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_HPP_
#define PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_HPP_
#include <pcl/registration/correspondence_estimation_normal_shooting.h>
///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> bool
pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::initCompute ()
{
if (!source_normals_ || !target_normals_)
{
PCL_WARN ("[pcl::registration::%s::initCompute] Datasets containing normals for source/target have not been given!\n", getClassName ().c_str ());
return (false);
}
return (CorrespondenceEstimationBase<PointSource, PointTarget, Scalar>::initCompute ());
}
///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void
pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::rotatePointCloudNormals (
const pcl::PointCloud<NormalT> &cloud_in,
pcl::PointCloud<NormalT> &cloud_out,
const Eigen::Matrix<Scalar, 4, 4> &transform)
{
if (&cloud_in != &cloud_out)
{
// Note: could be replaced by cloud_out = cloud_in
cloud_out.header = cloud_in.header;
cloud_out.width = cloud_in.width;
cloud_out.height = cloud_in.height;
cloud_out.is_dense = cloud_in.is_dense;
cloud_out.points.reserve (cloud_out.points.size ());
cloud_out.points.assign (cloud_in.points.begin (), cloud_in.points.end ());
}
for (size_t i = 0; i < cloud_out.points.size (); ++i)
{
// Rotate normals (WARNING: transform.rotation () uses SVD internally!)
Eigen::Matrix<Scalar, 3, 1> nt (cloud_in[i].normal_x, cloud_in[i].normal_y, cloud_in[i].normal_z);
cloud_out[i].normal_x = static_cast<float> (transform (0, 0) * nt.coeffRef (0) + transform (0, 1) * nt.coeffRef (1) + transform (0, 2) * nt.coeffRef (2));
cloud_out[i].normal_y = static_cast<float> (transform (1, 0) * nt.coeffRef (0) + transform (1, 1) * nt.coeffRef (1) + transform (1, 2) * nt.coeffRef (2));
cloud_out[i].normal_z = static_cast<float> (transform (2, 0) * nt.coeffRef (0) + transform (2, 1) * nt.coeffRef (1) + transform (2, 2) * nt.coeffRef (2));
}
}
///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void
pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::determineCorrespondences (
pcl::Correspondences &correspondences, double max_distance)
{
if (!initCompute ())
return;
typedef typename pcl::traits::fieldList<PointTarget>::type FieldListTarget;
correspondences.resize (indices_->size ());
std::vector<int> nn_indices (k_);
std::vector<float> nn_dists (k_);
float min_dist = std::numeric_limits<float>::max ();
int min_index = 0;
pcl::Correspondence corr;
unsigned int nr_valid_correspondences = 0;
// Check if the template types are the same. If true, avoid a copy.
// Both point types MUST be registered using the POINT_CLOUD_REGISTER_POINT_STRUCT macro!
if (isSamePointType<PointSource, PointTarget> ())
{
PointTarget pt;
// Iterate over the input set of source indices
for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i)
{
tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists);
// Among the K nearest neighbours find the one with minimum perpendicular distance to the normal
min_dist = std::numeric_limits<float>::max ();
// Find the best correspondence
for (size_t j = 0; j < nn_indices.size (); j++)
{
float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x +
source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y +
source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ;
float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle);
if (dist < min_dist)
{
min_dist = dist;
min_index = static_cast<int> (j);
}
}
if (min_dist > max_distance)
continue;
corr.index_query = *idx_i;
corr.index_match = nn_indices[min_index];
corr.distance = nn_dists[min_index];//min_dist;
correspondences[nr_valid_correspondences++] = corr;
}
}
else
{
PointTarget pt;
// Iterate over the input set of source indices
for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i)
{
tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists);
// Among the K nearest neighbours find the one with minimum perpendicular distance to the normal
min_dist = std::numeric_limits<float>::max ();
// Find the best correspondence
for (size_t j = 0; j < nn_indices.size (); j++)
{
PointSource pt_src;
// Copy the source data to a target PointTarget format so we can search in the tree
pcl::for_each_type <FieldListTarget> (pcl::NdConcatenateFunctor <PointSource, PointTarget> (
input_->points[*idx_i],
pt_src));
float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x +
source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y +
source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ;
float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle);
if (dist < min_dist)
{
min_dist = dist;
min_index = static_cast<int> (j);
}
}
if (min_dist > max_distance)
continue;
corr.index_query = *idx_i;
corr.index_match = nn_indices[min_index];
corr.distance = nn_dists[min_index];//min_dist;
correspondences[nr_valid_correspondences++] = corr;
}
}
correspondences.resize (nr_valid_correspondences);
deinitCompute ();
}
///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void
pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::determineReciprocalCorrespondences (
pcl::Correspondences &correspondences, double max_distance)
{
if (!initCompute ())
return;
typedef typename pcl::traits::fieldList<PointSource>::type FieldListSource;
typedef typename pcl::traits::fieldList<PointTarget>::type FieldListTarget;
typedef typename pcl::intersect<FieldListSource, FieldListTarget>::type FieldList;
// setup tree for reciprocal search
pcl::KdTreeFLANN<PointSource> tree_reciprocal;
// Set the internal point representation of choice
if (point_representation_)
tree_reciprocal.setPointRepresentation (point_representation_);
tree_reciprocal.setInputCloud (input_, indices_);
correspondences.resize (indices_->size ());
std::vector<int> nn_indices (k_);
std::vector<float> nn_dists (k_);
std::vector<int> index_reciprocal (1);
std::vector<float> distance_reciprocal (1);
float min_dist = std::numeric_limits<float>::max ();
int min_index = 0;
pcl::Correspondence corr;
unsigned int nr_valid_correspondences = 0;
int target_idx = 0;
// Check if the template types are the same. If true, avoid a copy.
// Both point types MUST be registered using the POINT_CLOUD_REGISTER_POINT_STRUCT macro!
if (isSamePointType<PointSource, PointTarget> ())
{
PointTarget pt;
// Iterate over the input set of source indices
for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i)
{
tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists);
// Among the K nearest neighbours find the one with minimum perpendicular distance to the normal
min_dist = std::numeric_limits<float>::max ();
// Find the best correspondence
for (size_t j = 0; j < nn_indices.size (); j++)
{
float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x +
source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y +
source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ;
float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle);
if (dist < min_dist)
{
min_dist = dist;
min_index = static_cast<int> (j);
}
}
if (min_dist > max_distance)
continue;
// Check if the correspondence is reciprocal
target_idx = nn_indices[min_index];
tree_reciprocal.nearestKSearch (target_->points[target_idx], 1, index_reciprocal, distance_reciprocal);
if (*idx_i != index_reciprocal[0])
continue;
corr.index_query = *idx_i;
corr.index_match = nn_indices[min_index];
corr.distance = nn_dists[min_index];//min_dist;
correspondences[nr_valid_correspondences++] = corr;
}
}
else
{
PointTarget pt;
// Iterate over the input set of source indices
for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i)
{
tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists);
// Among the K nearest neighbours find the one with minimum perpendicular distance to the normal
min_dist = std::numeric_limits<float>::max ();
// Find the best correspondence
for (size_t j = 0; j < nn_indices.size (); j++)
{
PointSource pt_src;
// Copy the source data to a target PointTarget format so we can search in the tree
pcl::for_each_type <FieldListTarget> (pcl::NdConcatenateFunctor <PointSource, PointTarget> (
input_->points[*idx_i],
pt_src));
float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x +
source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y +
source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ;
float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle);
if (dist < min_dist)
{
min_dist = dist;
min_index = static_cast<int> (j);
}
}
if (min_dist > max_distance)
continue;
// Check if the correspondence is reciprocal
target_idx = nn_indices[min_index];
tree_reciprocal.nearestKSearch (target_->points[target_idx], 1, index_reciprocal, distance_reciprocal);
if (*idx_i != index_reciprocal[0])
continue;
corr.index_query = *idx_i;
corr.index_match = nn_indices[min_index];
corr.distance = nn_dists[min_index];//min_dist;
correspondences[nr_valid_correspondences++] = corr;
}
}
correspondences.resize (nr_valid_correspondences);
deinitCompute ();
}
#endif // PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_HPP_
| kalectro/pcl_groovy | registration/include/pcl/registration/impl/correspondence_estimation_backprojection.hpp | C++ | bsd-3-clause | 13,583 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/app/android/chrome_jni_onload.h"
#include "chrome/app/android/chrome_android_initializer.h"
#include "content/public/app/content_jni_onload.h"
namespace android {
bool OnJNIOnLoadInit() {
if (!content::android::OnJNIOnLoadInit())
return false;
return RunChrome();
}
} // namespace android
| endlessm/chromium-browser | chrome/app/android/chrome_jni_onload.cc | C++ | bsd-3-clause | 490 |
/**
* Copyright (c) 2013, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms
*/
package visualoozie.api;
public class WorkflowNode {
public enum NodeType{
START
, KILL
, DECISION
, FORK
, JOIN
, END
, ACTION
}
private String name;
private NodeType type;
private String[] to;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public NodeType getType() { return type; }
public void setType(NodeType type) { this.type = type; }
public String[] getTo() { return to; }
public void setTo(String[] to) { this.to = to; }
}
| jaoki/visualoozie | src/main/java/visualoozie/api/WorkflowNode.java | Java | bsd-3-clause | 747 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_file_execl_43.cpp
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-43.tmpl.cpp
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: file Read input from a file
* GoodSource: Fixed string
* Sinks: execl
* BadSink : execute command with execl
* Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT "cmd.exe"
#define COMMAND_ARG1 "/c"
#define COMMAND_ARG2 "dir "
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH "/bin/sh"
#define COMMAND_INT "sh"
#define COMMAND_ARG1 "-c"
#define COMMAND_ARG2 "ls "
#define COMMAND_ARG3 data
#endif
#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif
#ifdef _WIN32
#include <process.h>
#define EXECL _execl
#else /* NOT _WIN32 */
#define EXECL execl
#endif
namespace CWE78_OS_Command_Injection__char_file_execl_43
{
#ifndef OMITBAD
static void badSource(char * &data)
{
{
/* Read input from a file */
size_t dataLen = strlen(data);
FILE * pFile;
/* if there is room in data, attempt to read the input from a file */
if (100-dataLen > 1)
{
pFile = fopen(FILENAME, "r");
if (pFile != NULL)
{
/* POTENTIAL FLAW: Read data from a file */
if (fgets(data+dataLen, (int)(100-dataLen), pFile) == NULL)
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
fclose(pFile);
}
}
}
}
void bad()
{
char * data;
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
badSource(data);
/* execl - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2BSource(char * &data)
{
/* FIX: Append a fixed string to data (not user / external input) */
strcat(data, "*.*");
}
static void goodG2B()
{
char * data;
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
goodG2BSource(data);
/* execl - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE78_OS_Command_Injection__char_file_execl_43; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE78_OS_Command_Injection/s03/CWE78_OS_Command_Injection__char_file_execl_43.cpp | C++ | bsd-3-clause | 3,945 |
// +build l476xx
// Peripheral: CAN_TxMailBox_Periph Controller Area Network TxMailBox.
// Instances:
// Registers:
// 0x00 32 TIR CAN TX mailbox identifier register.
// 0x04 32 TDTR CAN mailbox data length control and time stamp register.
// 0x08 32 TDLR CAN mailbox data low register.
// 0x0C 32 TDHR CAN mailbox data high register.
// Import:
// stm32/o/l476xx/mmap
package can
// DO NOT EDIT THIS FILE. GENERATED BY stm32xgen.
| ziutek/emgo | egpath/src/stm32/hal/raw/can/l476xx--can_txmailbox.go | GO | bsd-3-clause | 444 |
"""
Vision-specific analysis functions.
$Id: featureresponses.py 7714 2008-01-24 16:42:21Z antolikjan $
"""
__version__='$Revision: 7714 $'
from math import fmod,floor,pi,sin,cos,sqrt
import numpy
from numpy.oldnumeric import Float
from numpy import zeros, array, size, empty, object_
#import scipy
try:
import pylab
except ImportError:
print "Warning: Could not import matplotlib; pylab plots will not work."
import param
import topo
from topo.base.cf import CFSheet
from topo.base.sheetview import SheetView
from topo.misc.filepath import normalize_path
from topo.misc.numbergenerator import UniformRandom
from topo.plotting.plotgroup import create_plotgroup, plotgroups
from topo.command.analysis import measure_sine_pref
max_value = 0
global_index = ()
def _complexity_rec(x,y,index,depth,fm):
"""
Recurrent helper function for complexity()
"""
global max_value
global global_index
if depth<size(fm.features):
for i in range(size(fm.features[depth].values)):
_complexity_rec(x,y,index + (i,),depth+1,fm)
else:
if max_value < fm.full_matrix[index][x][y]:
global_index = index
max_value = fm.full_matrix[index][x][y]
def complexity(full_matrix):
global global_index
global max_value
"""This function expects as an input a object of type FullMatrix which contains
responses of all neurons in a sheet to stimuly with different varying parameter values.
One of these parameters (features) has to be phase. In such case it computes the classic
modulation ratio (see Hawken et al. for definition) for each neuron and returns them as a matrix.
"""
rows,cols = full_matrix.matrix_shape
complexity = zeros(full_matrix.matrix_shape)
complex_matrix = zeros(full_matrix.matrix_shape,object_)
fftmeasure = zeros(full_matrix.matrix_shape,Float)
i = 0
for f in full_matrix.features:
if f.name == "phase":
phase_index = i
break
i=i+1
sum = 0.0
res = 0.0
average = 0.0
for x in range(rows):
for y in range(cols):
complex_matrix[x,y] = []#
max_value=-0.01
global_index = ()
_complexity_rec(x,y,(),0,full_matrix)
#compute the sum of the responses over phases given the found index of highest response
iindex = array(global_index)
sum = 0.0
for i in range(size(full_matrix.features[phase_index].values)):
iindex[phase_index] = i
sum = sum + full_matrix.full_matrix[tuple(iindex.tolist())][x][y]
#average
average = sum / float(size(full_matrix.features[phase_index].values))
res = 0.0
#compute the sum of absolute values of the responses minus average
for i in range(size(full_matrix.features[phase_index].values)):
iindex[phase_index] = i
res = res + abs(full_matrix.full_matrix[tuple(iindex.tolist())][x][y] - average)
complex_matrix[x,y] = complex_matrix[x,y] + [full_matrix.full_matrix[tuple(iindex.tolist())][x][y]]
#this is taking away the DC component
#complex_matrix[x,y] -= numpy.min(complex_matrix[x,y])
if x==15 and y==15:
pylab.figure()
pylab.plot(complex_matrix[x,y])
if x==26 and y==26:
pylab.figure()
pylab.plot(complex_matrix[x,y])
#complexity[x,y] = res / (2*sum)
fft = numpy.fft.fft(complex_matrix[x,y]+complex_matrix[x,y]+complex_matrix[x,y]+complex_matrix[x,y],2048)
first_har = 2048/len(complex_matrix[0,0])
if abs(fft[0]) != 0:
fftmeasure[x,y] = 2 *abs(fft[first_har]) /abs(fft[0])
else:
fftmeasure[x,y] = 0
return fftmeasure
def compute_ACDC_orientation_tuning_curves(full_matrix,curve_label,sheet):
""" This function allows and alternative computation of orientation tuning curve where
for each given orientation the response is computed as a maximum of AC or DC component
across the phases instead of the maximum used as a standard in Topographica"""
# this method assumes that only single frequency has been used
i = 0
for f in full_matrix.features:
if f.name == "phase":
phase_index = i
if f.name == "orientation":
orientation_index = i
if f.name == "frequency":
frequency_index = i
i=i+1
print sheet.curve_dict
if not sheet.curve_dict.has_key("orientationACDC"):
sheet.curve_dict["orientationACDC"]={}
sheet.curve_dict["orientationACDC"][curve_label]={}
rows,cols = full_matrix.matrix_shape
for o in xrange(size(full_matrix.features[orientation_index].values)):
s_w = zeros(full_matrix.matrix_shape)
for x in range(rows):
for y in range(cols):
or_response=[]
for p in xrange(size(full_matrix.features[phase_index].values)):
index = [0,0,0]
index[phase_index] = p
index[orientation_index] = o
index[frequency_index] = 0
or_response.append(full_matrix.full_matrix[tuple(index)][x][y])
fft = numpy.fft.fft(or_response+or_response+or_response+or_response,2048)
first_har = 2048/len(or_response)
s_w[x][y] = numpy.maximum(2 *abs(fft[first_har]),abs(fft[0]))
s = SheetView((s_w,sheet.bounds), sheet.name , sheet.precedence, topo.sim.time(),sheet.row_precedence)
sheet.curve_dict["orientationACDC"][curve_label].update({full_matrix.features[orientation_index].values[o]:s})
def phase_preference_scatter_plot(sheet_name,diameter=0.39):
r = UniformRandom(seed=1023)
preference_map = topo.sim[sheet_name].sheet_views['PhasePreference']
offset_magnitude = 0.03
datax = []
datay = []
(v,bb) = preference_map.view()
for z in zeros(66):
x = (r() - 0.5)*2*diameter
y = (r() - 0.5)*2*diameter
rand = r()
xoff = sin(rand*2*pi)*offset_magnitude
yoff = cos(rand*2*pi)*offset_magnitude
xx = max(min(x+xoff,diameter),-diameter)
yy = max(min(y+yoff,diameter),-diameter)
x = max(min(x,diameter),-diameter)
y = max(min(y,diameter),-diameter)
[xc1,yc1] = topo.sim[sheet_name].sheet2matrixidx(xx,yy)
[xc2,yc2] = topo.sim[sheet_name].sheet2matrixidx(x,y)
if((xc1==xc2) & (yc1==yc2)): continue
datax = datax + [v[xc1,yc1]]
datay = datay + [v[xc2,yc2]]
for i in range(0,len(datax)):
datax[i] = datax[i] * 360
datay[i] = datay[i] * 360
if(datay[i] > datax[i] + 180): datay[i]= datay[i]- 360
if((datax[i] > 180) & (datay[i]> 180)): datax[i] = datax[i] - 360; datay[i] = datay[i] - 360
if((datax[i] > 180) & (datay[i] < (datax[i]-180))): datax[i] = datax[i] - 360; #datay[i] = datay[i] - 360
f = pylab.figure()
ax = f.add_subplot(111, aspect='equal')
pylab.plot(datax,datay,'ro')
pylab.plot([0,360],[-180,180])
pylab.plot([-180,180],[0,360])
pylab.plot([-180,-180],[360,360])
ax.axis([-180,360,-180,360])
pylab.xticks([-180,0,180,360], [-180,0,180,360])
pylab.yticks([-180,0,180,360], [-180,0,180,360])
pylab.grid()
pylab.savefig(normalize_path(str(topo.sim.timestr()) + sheet_name + "_scatter.png"))
###############################################################################
# JABALERT: Should we move this plot and command to analysis.py or
# pylabplots.py, where all the rest are?
#
# In any case, it requires generalization; it should not be hardcoded
# to any particular map name, and should just do the right thing for
# most networks for which it makes sense. E.g. it already measures
# the ComplexSelectivity for all measured_sheets, but then
# plot_modulation_ratio only accepts two with specific names.
# plot_modulation_ratio should just plot whatever it is given, and
# then analyze_complexity can simply pass in whatever was measured,
# with the user controlling what is measured using the measure_map
# attribute of each Sheet. That way the complexity of any sheet could
# be measured, which is what we want.
#
# Specific changes needed:
# - Make plot_modulation_ratio accept a list of sheets and
# plot their individual modulation ratios and combined ratio.
# - Remove complex_sheet_name argument, which is no longer needed
# - Make sure it still works fine even if V1Simple doesn't exist;
# as this is just for an optional scatter plot, it's fine to skip
# it.
# - Preferably remove the filename argument by default, so that
# plots will show up in the GUI
def analyze_complexity(full_matrix,simple_sheet_name,complex_sheet_name,filename=None):
"""
Compute modulation ratio for each neuron, to distinguish complex from simple cells.
Uses full_matrix data obtained from measure_or_pref().
If there is a sheet named as specified in simple_sheet_name,
also plots its phase preference as a scatter plot.
"""
import topo
measured_sheets = [s for s in topo.sim.objects(CFSheet).values()
if hasattr(s,'measure_maps') and s.measure_maps]
for sheet in measured_sheets:
# Divide by two to get into 0-1 scale - that means simple/complex boundry is now at 0.5
complx = array(complexity(full_matrix[sheet]))/2.0
# Should this be renamed to ModulationRatio?
sheet.sheet_views['ComplexSelectivity']=SheetView((complx,sheet.bounds), sheet.name , sheet.precedence, topo.sim.time(),sheet.row_precedence)
import topo.command.pylabplots
topo.command.pylabplots.plot_modulation_ratio(full_matrix,simple_sheet_name=simple_sheet_name,complex_sheet_name=complex_sheet_name,filename=filename)
# Avoid error if no simple sheet exists
try:
phase_preference_scatter_plot(simple_sheet_name,diameter=0.24999)
except AttributeError:
print "Skipping phase preference scatter plot; could not analyze region %s." \
% simple_sheet_name
class measure_and_analyze_complexity(measure_sine_pref):
"""Macro for measuring orientation preference and then analyzing its complexity."""
def __call__(self,**params):
fm = super(measure_and_analyze_complexity,self).__call__(**params)
#from topo.command.analysis import measure_or_pref
#fm = measure_or_pref()
analyze_complexity(fm,simple_sheet_name="V1Simple",complex_sheet_name="V1Complex",filename="ModulationRatio")
pg= create_plotgroup(name='Orientation Preference and Complexity',category="Preference Maps",
doc='Measure preference for sine grating orientation.',
pre_plot_hooks=[measure_and_analyze_complexity.instance()])
pg.add_plot('Orientation Preference',[('Hue','OrientationPreference')])
pg.add_plot('Orientation Preference&Selectivity',[('Hue','OrientationPreference'),
('Confidence','OrientationSelectivity')])
pg.add_plot('Orientation Selectivity',[('Strength','OrientationSelectivity')])
pg.add_plot('Modulation Ratio',[('Strength','ComplexSelectivity')])
pg.add_plot('Phase Preference',[('Hue','PhasePreference')])
pg.add_static_image('Color Key','command/or_key_white_vert_small.png')
| jesuscript/topo-mpi | topo/analysis/vision.py | Python | bsd-3-clause | 11,628 |
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model common\models\Offer */
$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Offers'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="offer-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'),
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'code',
'text:ntext',
'created_at',
'updated_at',
],
]) ?>
</div>
| Dench/resistor | backend/views/offer/view.php | PHP | bsd-3-clause | 1,025 |
/*
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
* Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
* Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "sky/engine/config.h"
#include "sky/engine/core/events/UIEvent.h"
namespace blink {
UIEventInit::UIEventInit()
: view(nullptr)
, detail(0)
{
}
UIEvent::UIEvent()
: m_detail(0)
{
}
UIEvent::UIEvent(const AtomicString& eventType, bool canBubbleArg, bool cancelableArg, PassRefPtr<AbstractView> viewArg, int detailArg)
: Event(eventType, canBubbleArg, cancelableArg)
, m_view(viewArg)
, m_detail(detailArg)
{
}
UIEvent::UIEvent(const AtomicString& eventType, const UIEventInit& initializer)
: Event(eventType, initializer)
, m_view(initializer.view)
, m_detail(initializer.detail)
{
}
UIEvent::~UIEvent()
{
}
void UIEvent::initUIEvent(const AtomicString& typeArg, bool canBubbleArg, bool cancelableArg, PassRefPtr<AbstractView> viewArg, int detailArg)
{
if (dispatched())
return;
initEvent(typeArg, canBubbleArg, cancelableArg);
m_view = viewArg;
m_detail = detailArg;
}
bool UIEvent::isUIEvent() const
{
return true;
}
const AtomicString& UIEvent::interfaceName() const
{
return EventNames::UIEvent;
}
int UIEvent::keyCode() const
{
return 0;
}
int UIEvent::charCode() const
{
return 0;
}
int UIEvent::layerX()
{
return 0;
}
int UIEvent::layerY()
{
return 0;
}
int UIEvent::pageX() const
{
return 0;
}
int UIEvent::pageY() const
{
return 0;
}
int UIEvent::which() const
{
return 0;
}
} // namespace blink
| collinjackson/mojo | sky/engine/core/events/UIEvent.cpp | C++ | bsd-3-clause | 2,459 |
import { takeLatest, call, put } from 'redux-saga/effects';
import { gql } from 'react-apollo';
import { push } from 'react-router-redux';
import jwtDecode from 'jwt-decode';
import { setJwtToken } from '../../utils/auth';
import { bootstrap } from '../../utils/sagas';
import { registerError, registerSuccess } from './actions';
import { REGISTER } from './constants';
import { loginSuccess } from '../Login/actions';
import { client } from '../../graphql';
import { homePage } from '../../local-urls';
const RegisterMutation = gql`
mutation RegisterMutation($nick: String!, $password: String!, $name: String!, $email: String!){
register(nick: $nick, password: $password, name: $name, email: $email)
}
`;
function sendRegister(user) {
return client.mutate({ mutation: RegisterMutation, variables: user });
}
function* register({ user }) {
try {
const response = yield call(sendRegister, user);
const token = response.data.register;
const userInfo = jwtDecode(token);
setJwtToken(token);
yield put(registerSuccess());
yield put(loginSuccess(userInfo));
yield put(push(homePage()));
} catch (e) {
yield put(registerError());
}
}
function* registerSaga() {
yield takeLatest(REGISTER, register);
}
export default bootstrap([
registerSaga,
]);
| zmora-agh/zmora-ui | app/containers/Register/sagas.js | JavaScript | bsd-3-clause | 1,298 |
$(function () {
var colors = Highcharts.getOptions().colors,
categories = ['已关闭', 'NEW', '已解决'],
name = 'Browser brands',
data = [{
y: 290,
color: colors[0],
drilldown: {
name: 'close bug version',
categories: ['当前版本', '历史版本'],
data: [20,270],
color: colors[0]
}
}, {
y: 64,
color: colors[1],
drilldown: {
name: 'fix bug version',
categories: ['当前版本', '历史版本'],
data: [8,56],
color: colors[1]
}
}, {
y: 82,
color: colors[2],
drilldown: {
name: 'NEW bug versions',
categories: ['当前版本', '历史版本'],
data: [5,77],
color: colors[2]
}
}];
// Build the data arrays
var browserData = [];
var versionsData = [];
for (var i = 0; i < data.length; i++) {
// add browser data
browserData.push({
name: categories[i],
y: data[i].y,
color: data[i].color
});
// add version data
for (var j = 0; j < data[i].drilldown.data.length; j++) {
var brightness = 0.2 - (j / data[i].drilldown.data.length) / 5 ;
versionsData.push({
name: data[i].drilldown.categories[j],
y: data[i].drilldown.data[j],
color: Highcharts.Color(data[i].color).brighten(brightness).get()
});
}
}
// Create the chart
$('#container11').highcharts({
chart: {
type: 'pie'
},
title: {
text: '当前版本在历史版本总和占比'
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
plotOptions: {
pie: {
shadow: false,
center: ['50%', '50%']
}
},
tooltip: {
valueSuffix: '' //这里更改tooltip显示的单位
},
series: [{
name: 'Browsers',
data: browserData,
size: '80%',
dataLabels: {
formatter: function() {
return this.y > 5 ? this.point.name : null;
},
color: 'white',
distance: -30
}
}, {
name: 'Versions',
data: versionsData,
size: '100%',
innerSize: '80%',
dataLabels: {
formatter: function() {
// display only if larger than 1
return this.y > 0 ? '<b>'+ this.point.name +':</b> '+ this.y+'个' : null;
}
}
}]
});
}); | qualityTeam5/PO-demo | src/11.js | JavaScript | bsd-3-clause | 3,175 |
<?php
namespace BackEnd\Form;
use Zend\Form\Form;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
class LoginForm extends Form
{
protected $inputFilter;
public function __construct(){
parent::__construct('login-form');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'username',
'options' => array(
'label' => '用户名'
),
));
$this->add(array(
'name' => 'password',
'options' => array(
'label' => '密码'
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'value' => 'Login',
'type' => 'submit',
),
));
$this->setInputFilter($this->getInputFilter());
}
public function getInputFilter(){
if(!$this->inputFilter){
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'username',
'required' => true,
'validators' => array(
array('name' => 'StringLength' , 'options' => array('min' => 3 , 'max' => 20)),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'password',
'required' => true,
'validators' => array(
array('name' => 'Alnum'),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
} | aidear/jiaju | module/BackEnd/Form/LoginForm.php | PHP | bsd-3-clause | 1,856 |
/*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <proxygen/lib/http/codec/experimental/HTTP2Framer.h>
#include <cstdint>
using namespace folly::io;
using namespace folly;
namespace proxygen { namespace http2 {
const uint8_t kMaxFrameType = static_cast<uint8_t>(FrameType::ALTSVC);
const boost::optional<uint8_t> kNoPadding;
const PriorityUpdate DefaultPriority{0, false, 15};
namespace {
const uint32_t kLengthMask = 0x00ffffff;
const uint32_t kUint31Mask = 0x7fffffff;
static const uint64_t kZeroPad[32] = {0};
static const bool kStrictPadding = true;
static_assert(sizeof(kZeroPad) == 256, "bad zero padding");
void writePriorityBody(IOBufQueue& queue,
uint32_t streamDependency,
bool exclusive,
uint8_t weight) {
DCHECK_EQ(0, ~kUint31Mask & streamDependency);
if (exclusive) {
streamDependency |= ~kUint31Mask;
}
QueueAppender appender(&queue, 8);
appender.writeBE<uint32_t>(streamDependency);
appender.writeBE<uint8_t>(weight);
}
void writePadding(IOBufQueue& queue, boost::optional<uint8_t> size) {
if (size && size.get() > 0) {
auto out = queue.preallocate(size.get(), size.get());
memset(out.first, 0, size.get());
queue.postallocate(size.get());
}
}
/**
* Generate just the common frame header. This includes the padding length
* bits that sometimes come right after the frame header. Returns the
* length field written to the common frame header.
*/
size_t writeFrameHeader(IOBufQueue& queue,
uint32_t length,
FrameType type,
uint8_t flags,
uint32_t stream,
boost::optional<uint8_t> padding,
boost::optional<PriorityUpdate> priority,
std::unique_ptr<IOBuf> payload) noexcept {
size_t headerSize = kFrameHeaderSize;
// the acceptable length is now conditional based on state :(
DCHECK_EQ(0, ~kLengthMask & length);
DCHECK_EQ(0, ~kUint31Mask & stream);
// Adjust length if we will emit a priority section
if (flags & PRIORITY) {
DCHECK(FrameType::HEADERS == type);
length += kFramePrioritySize;
headerSize += kFramePrioritySize;
DCHECK_EQ(0, ~kLengthMask & length);
}
// Add or remove padding flags
if (padding) {
flags |= PADDED;
length += padding.get() + 1;
headerSize += 1;
} else {
flags &= ~PADDED;
}
if (priority) {
headerSize += kFramePrioritySize;
}
DCHECK_EQ(0, ~kLengthMask & length);
DCHECK_GE(kMaxFrameType, static_cast<uint8_t>(type));
uint32_t lengthAndType =
((kLengthMask & length) << 8) | static_cast<uint8_t>(type);
uint64_t payloadLength = 0;
if (payload && !payload->isSharedOne() &&
payload->headroom() >= headerSize &&
queue.tailroom() < headerSize) {
// Use the headroom in payload for the frame header.
// Make it appear that the payload IOBuf is empty and retreat so
// appender can access the headroom
payloadLength = payload->length();
payload->trimEnd(payloadLength);
payload->retreat(headerSize);
auto tail = payload->pop();
queue.append(std::move(payload));
payload = std::move(tail);
}
QueueAppender appender(&queue, kFrameHeaderSize);
appender.writeBE<uint32_t>(lengthAndType);
appender.writeBE<uint8_t>(flags);
appender.writeBE<uint32_t>(kUint31Mask & stream);
if (padding) {
appender.writeBE<uint8_t>(padding.get());
}
if (priority) {
DCHECK_NE(priority->streamDependency, stream) << "Circular dependecy";
writePriorityBody(queue,
priority->streamDependency,
priority->exclusive,
priority->weight);
}
if (payloadLength) {
queue.postallocate(payloadLength);
}
queue.append(std::move(payload));
return length;
}
uint32_t parseUint31(Cursor& cursor) {
// MUST ignore the 1 bit before the stream-id
return kUint31Mask & cursor.readBE<uint32_t>();
}
ErrorCode parseErrorCode(Cursor& cursor, ErrorCode& outCode) {
auto code = cursor.readBE<uint32_t>();
if (code > kMaxErrorCode) {
return ErrorCode::PROTOCOL_ERROR;
}
outCode = ErrorCode(code);
return ErrorCode::NO_ERROR;
}
PriorityUpdate parsePriorityCommon(Cursor& cursor) {
PriorityUpdate priority;
uint32_t streamAndExclusive = cursor.readBE<uint32_t>();
priority.weight = cursor.readBE<uint8_t>();
priority.exclusive = ~kUint31Mask & streamAndExclusive;
priority.streamDependency = kUint31Mask & streamAndExclusive;
return priority;
}
/**
* Given the flags for a frame and the cursor pointing at the top of the
* frame-specific section (after the common header), return the number of
* bytes to skip at the end of the frame. Caller must ensure there is at
* least 1 bytes in the cursor.
*
* @param cursor The cursor to pull data from
* @param header The frame header for the frame being parsed. The length
* field may be modified based on the number of optional
* padding length fields were read.
* @param padding The out parameter that will return the number of padding
* bytes at the end of the frame.
* @return Nothing if success. The connection error code if failure.
*/
ErrorCode
parsePadding(Cursor& cursor,
FrameHeader& header,
uint8_t& padding) noexcept {
if (frameHasPadding(header)) {
if (header.length < 1) {
return ErrorCode::FRAME_SIZE_ERROR;
}
header.length -= 1;
padding = cursor.readBE<uint8_t>();
} else {
padding = 0;
}
return ErrorCode::NO_ERROR;
}
ErrorCode
skipPadding(Cursor& cursor,
uint8_t length,
bool verify) {
if (verify) {
while (length > 0) {
auto cur = cursor.peek();
uint8_t toCmp = std::min<size_t>(cur.second, length);
if (memcmp(cur.first, kZeroPad, toCmp)) {
return ErrorCode::PROTOCOL_ERROR;
}
cursor.skip(toCmp);
length -= toCmp;
}
} else {
cursor.skip(length);
}
return ErrorCode::NO_ERROR;
}
} // anonymous namespace
bool frameAffectsCompression(FrameType t) {
return t == FrameType::HEADERS ||
t == FrameType::PUSH_PROMISE ||
t == FrameType::CONTINUATION;
}
bool frameHasPadding(const FrameHeader& header) {
return header.flags & PADDED;
}
//// Parsing ////
ErrorCode
parseFrameHeader(Cursor& cursor,
FrameHeader& header) noexcept {
DCHECK_LE(kFrameHeaderSize, cursor.totalLength());
// MUST ignore the 2 bits before the length
uint32_t lengthAndType = cursor.readBE<uint32_t>();
header.length = kLengthMask & (lengthAndType >> 8);
uint8_t type = lengthAndType & 0xff;
header.type = FrameType(type);
header.flags = cursor.readBE<uint8_t>();
header.stream = parseUint31(cursor);
return ErrorCode::NO_ERROR;
}
ErrorCode
parseData(Cursor& cursor,
FrameHeader header,
std::unique_ptr<IOBuf>& outBuf,
uint16_t& outPadding) noexcept {
DCHECK_LE(header.length, cursor.totalLength());
if (header.stream == 0) {
return ErrorCode::PROTOCOL_ERROR;
}
uint8_t padding;
const auto err = parsePadding(cursor, header, padding);
RETURN_IF_ERROR(err);
if (header.length < padding) {
return ErrorCode::PROTOCOL_ERROR;
}
// outPadding is the total number of flow-controlled pad bytes, which
// includes the length byte, if present.
outPadding = padding + ((frameHasPadding(header)) ? 1 : 0);
cursor.clone(outBuf, header.length - padding);
return skipPadding(cursor, padding, kStrictPadding);
}
ErrorCode
parseDataBegin(Cursor& cursor,
FrameHeader header,
size_t& parsed,
uint16_t& outPadding) noexcept {
uint8_t padding = 0;
const auto err = http2::parsePadding(cursor, header, padding);
RETURN_IF_ERROR(err);
if (header.length < padding) {
return ErrorCode::PROTOCOL_ERROR;
}
// outPadding is the total number of flow-controlled pad bytes, which
// includes the length byte, if present.
outPadding = padding + ((frameHasPadding(header)) ? 1 : 0);
return ErrorCode::NO_ERROR;
}
ErrorCode
parseDataEnd(Cursor& cursor,
const size_t bufLen,
const size_t pendingDataFramePaddingBytes,
size_t& toSkip) noexcept {
toSkip = std::min(pendingDataFramePaddingBytes, bufLen);
return skipPadding(cursor, toSkip, kStrictPadding);
}
ErrorCode
parseHeaders(Cursor& cursor,
FrameHeader header,
boost::optional<PriorityUpdate>& outPriority,
std::unique_ptr<IOBuf>& outBuf) noexcept {
DCHECK_LE(header.length, cursor.totalLength());
if (header.stream == 0) {
return ErrorCode::PROTOCOL_ERROR;
}
uint8_t padding;
auto err = parsePadding(cursor, header, padding);
RETURN_IF_ERROR(err);
if (header.flags & PRIORITY) {
if (header.length < kFramePrioritySize) {
return ErrorCode::FRAME_SIZE_ERROR;
}
outPriority = parsePriorityCommon(cursor);
header.length -= kFramePrioritySize;
} else {
outPriority = boost::none;
}
if (header.length < padding) {
return ErrorCode::PROTOCOL_ERROR;
}
cursor.clone(outBuf, header.length - padding);
return skipPadding(cursor, padding, kStrictPadding);
}
ErrorCode
parsePriority(Cursor& cursor,
FrameHeader header,
PriorityUpdate& outPriority) noexcept {
DCHECK_LE(header.length, cursor.totalLength());
if (header.length != kFramePrioritySize) {
return ErrorCode::FRAME_SIZE_ERROR;
}
if (header.stream == 0) {
return ErrorCode::PROTOCOL_ERROR;
}
outPriority = parsePriorityCommon(cursor);
return ErrorCode::NO_ERROR;
}
ErrorCode
parseRstStream(Cursor& cursor,
FrameHeader header,
ErrorCode& outCode) noexcept {
DCHECK_LE(header.length, cursor.totalLength());
if (header.length != kFrameRstStreamSize) {
return ErrorCode::FRAME_SIZE_ERROR;
}
if (header.stream == 0) {
return ErrorCode::PROTOCOL_ERROR;
}
return parseErrorCode(cursor, outCode);
}
ErrorCode
parseSettings(Cursor& cursor,
FrameHeader header,
std::deque<SettingPair>& settings) noexcept {
DCHECK_LE(header.length, cursor.totalLength());
if (header.stream != 0) {
return ErrorCode::PROTOCOL_ERROR;
}
if (header.flags & ACK) {
if (header.length != 0) {
return ErrorCode::FRAME_SIZE_ERROR;
}
return ErrorCode::NO_ERROR;
}
if (header.length % 6 != 0) {
return ErrorCode::FRAME_SIZE_ERROR;
}
for (; header.length > 0; header.length -= 6) {
uint16_t id = cursor.readBE<uint16_t>();
uint32_t val = cursor.readBE<uint32_t>();
settings.push_back(std::make_pair(SettingsId(id), val));
}
return ErrorCode::NO_ERROR;
}
ErrorCode
parsePushPromise(Cursor& cursor,
FrameHeader header,
uint32_t& outPromisedStream,
std::unique_ptr<IOBuf>& outBuf) noexcept {
DCHECK_LE(header.length, cursor.totalLength());
if (header.stream == 0) {
return ErrorCode::PROTOCOL_ERROR;
}
uint8_t padding;
auto err = parsePadding(cursor, header, padding);
RETURN_IF_ERROR(err);
if (header.length < kFramePushPromiseSize) {
return ErrorCode::FRAME_SIZE_ERROR;
}
header.length -= kFramePushPromiseSize;
outPromisedStream = parseUint31(cursor);
if (outPromisedStream == 0 ||
outPromisedStream & 0x1) {
// client MUST reserve an even stream id greater than 0
return ErrorCode::PROTOCOL_ERROR;
}
if (header.length < padding) {
return ErrorCode::PROTOCOL_ERROR;
}
cursor.clone(outBuf, header.length - padding);
return skipPadding(cursor, padding, kStrictPadding);
}
ErrorCode
parsePing(Cursor& cursor,
FrameHeader header,
uint64_t& outOpaqueData) noexcept {
DCHECK_LE(header.length, cursor.totalLength());
if (header.length != kFramePingSize) {
return ErrorCode::FRAME_SIZE_ERROR;
}
if (header.stream != 0) {
return ErrorCode::PROTOCOL_ERROR;
}
cursor.pull(&outOpaqueData, sizeof(outOpaqueData));
return ErrorCode::NO_ERROR;
}
ErrorCode
parseGoaway(Cursor& cursor,
FrameHeader header,
uint32_t& outLastStreamID,
ErrorCode& outCode,
std::unique_ptr<IOBuf>& outDebugData) noexcept {
DCHECK_LE(header.length, cursor.totalLength());
if (header.length < kFrameGoawaySize) {
return ErrorCode::FRAME_SIZE_ERROR;
}
if (header.stream != 0) {
return ErrorCode::PROTOCOL_ERROR;
}
outLastStreamID = parseUint31(cursor);
auto err = parseErrorCode(cursor, outCode);
RETURN_IF_ERROR(err);
header.length -= kFrameGoawaySize;
if (header.length > 0) {
cursor.clone(outDebugData, header.length);
}
return ErrorCode::NO_ERROR;
}
ErrorCode
parseWindowUpdate(Cursor& cursor,
FrameHeader header,
uint32_t& outAmount) noexcept {
DCHECK_LE(header.length, cursor.totalLength());
if (header.length != kFrameWindowUpdateSize) {
return ErrorCode::FRAME_SIZE_ERROR;
}
outAmount = parseUint31(cursor);
return ErrorCode::NO_ERROR;
}
ErrorCode
parseContinuation(Cursor& cursor,
FrameHeader header,
std::unique_ptr<IOBuf>& outBuf) noexcept {
DCHECK(header.type == FrameType::CONTINUATION);
DCHECK_LE(header.length, cursor.totalLength());
if (header.stream == 0) {
return ErrorCode::PROTOCOL_ERROR;
}
uint8_t padding;
auto err = parsePadding(cursor, header, padding);
RETURN_IF_ERROR(err);
if (header.length < padding) {
return ErrorCode::PROTOCOL_ERROR;
}
cursor.clone(outBuf, header.length - padding);
return skipPadding(cursor, padding, kStrictPadding);
}
ErrorCode
parseAltSvc(Cursor& cursor,
FrameHeader header,
uint32_t& outMaxAge,
uint32_t& outPort,
std::string& outProtocol,
std::string& outHost,
std::string& outOrigin) noexcept {
DCHECK_LE(header.length, cursor.totalLength());
if (header.length < kFrameAltSvcSizeBase) {
return ErrorCode::FRAME_SIZE_ERROR;
}
std::unique_ptr<IOBuf> tmpBuf;
outMaxAge = cursor.readBE<uint32_t>();
outPort = cursor.readBE<uint16_t>();
const auto protoLen = cursor.readBE<uint8_t>();
if (header.length < kFrameAltSvcSizeBase + protoLen) {
return ErrorCode::FRAME_SIZE_ERROR;
}
outProtocol = cursor.readFixedString(protoLen);
const auto hostLen = cursor.readBE<uint8_t>();
if (header.length < kFrameAltSvcSizeBase + protoLen + hostLen) {
return ErrorCode::FRAME_SIZE_ERROR;
}
outHost = cursor.readFixedString(hostLen);
const auto originLen = (header.length - kFrameAltSvcSizeBase -
protoLen - hostLen);
outOrigin = cursor.readFixedString(originLen);
return ErrorCode::NO_ERROR;
}
//// Egress ////
size_t
writeData(IOBufQueue& queue,
std::unique_ptr<IOBuf> data,
uint32_t stream,
boost::optional<uint8_t> padding,
bool endStream) noexcept {
DCHECK_NE(0, stream);
uint8_t flags = 0;
if (endStream) {
flags |= END_STREAM;
}
const uint64_t dataLen = data ? data->computeChainDataLength() : 0;
// Caller must not exceed peer setting for MAX_FRAME_SIZE
// TODO: look into using headroom from data to hold the frame header
const auto frameLen = writeFrameHeader(queue,
dataLen,
FrameType::DATA,
flags,
stream,
padding,
boost::none,
std::move(data));
writePadding(queue, padding);
return kFrameHeaderSize + frameLen;
}
size_t
writeHeaders(IOBufQueue& queue,
std::unique_ptr<IOBuf> headers,
uint32_t stream,
boost::optional<PriorityUpdate> priority,
boost::optional<uint8_t> padding,
bool endStream,
bool endHeaders) noexcept {
DCHECK_NE(0, stream);
const auto dataLen = (headers) ? headers->computeChainDataLength() : 0;
uint32_t flags = 0;
if (priority) {
flags |= PRIORITY;
}
if (endStream) {
flags |= END_STREAM;
}
if (endHeaders) {
flags |= END_HEADERS;
}
// padding flags handled directly inside writeFrameHeader()
const auto frameLen = writeFrameHeader(queue,
dataLen,
FrameType::HEADERS,
flags,
stream,
padding,
priority,
std::move(headers));
writePadding(queue, padding);
return kFrameHeaderSize + frameLen;
}
size_t
writePriority(IOBufQueue& queue,
uint32_t stream,
PriorityUpdate priority) noexcept {
DCHECK_NE(0, stream);
const auto frameLen = writeFrameHeader(queue,
kFramePrioritySize,
FrameType::PRIORITY,
0,
stream,
kNoPadding,
priority,
nullptr);
return kFrameHeaderSize + frameLen;
}
size_t
writeRstStream(IOBufQueue& queue,
uint32_t stream,
ErrorCode errorCode) noexcept {
DCHECK_NE(0, stream);
const auto frameLen = writeFrameHeader(queue,
kFrameRstStreamSize,
FrameType::RST_STREAM,
0,
stream,
kNoPadding,
boost::none,
nullptr);
QueueAppender appender(&queue, frameLen);
appender.writeBE<uint32_t>(static_cast<uint32_t>(errorCode));
return kFrameHeaderSize + frameLen;
}
size_t
writeSettings(IOBufQueue& queue,
const std::deque<SettingPair>& settings) {
const auto settingsSize = settings.size() * 6;
const auto frameLen = writeFrameHeader(queue,
settingsSize,
FrameType::SETTINGS,
0,
0,
kNoPadding,
boost::none,
nullptr);
QueueAppender appender(&queue, settingsSize);
for (const auto& setting: settings) {
DCHECK_LE(static_cast<uint32_t>(setting.first),
std::numeric_limits<uint16_t>::max());
appender.writeBE<uint16_t>(static_cast<uint16_t>(setting.first));
appender.writeBE<uint32_t>(setting.second);
}
return kFrameHeaderSize + frameLen;
}
size_t
writeSettingsAck(IOBufQueue& queue) {
writeFrameHeader(queue,
0,
FrameType::SETTINGS,
ACK,
0,
kNoPadding,
boost::none,
nullptr);
return kFrameHeaderSize;
}
size_t
writePushPromise(IOBufQueue& queue,
uint32_t associatedStream,
uint32_t promisedStream,
std::unique_ptr<IOBuf> headers,
boost::optional<uint8_t> padding,
bool endHeaders) noexcept {
DCHECK_NE(0, promisedStream);
DCHECK_NE(0, associatedStream);
DCHECK_EQ(0, 0x1 & promisedStream);
DCHECK_EQ(1, 0x1 & associatedStream);
DCHECK_EQ(0, ~kUint31Mask & promisedStream);
const auto dataLen = headers->computeChainDataLength();
const auto frameLen = writeFrameHeader(queue,
dataLen + kFramePushPromiseSize,
FrameType::PUSH_PROMISE,
endHeaders ? END_HEADERS : 0,
associatedStream,
padding,
boost::none,
nullptr);
QueueAppender appender(&queue, frameLen);
appender.writeBE<uint32_t>(promisedStream);
queue.append(std::move(headers));
writePadding(queue, padding);
return kFrameHeaderSize + frameLen;
}
size_t
writePing(IOBufQueue& queue,
uint64_t opaqueData,
bool ack) noexcept {
const auto frameLen = writeFrameHeader(queue,
kFramePingSize,
FrameType::PING,
ack ? ACK : 0,
0,
kNoPadding,
boost::none,
nullptr);
queue.append(&opaqueData, sizeof(opaqueData));
return kFrameHeaderSize + frameLen;
}
size_t
writeGoaway(IOBufQueue& queue,
uint32_t lastStreamID,
ErrorCode errorCode,
std::unique_ptr<IOBuf> debugData) noexcept {
uint32_t debugLen = debugData ? debugData->computeChainDataLength() : 0;
DCHECK_EQ(0, ~kLengthMask & debugLen);
const auto frameLen = writeFrameHeader(queue,
kFrameGoawaySize + debugLen,
FrameType::GOAWAY,
0,
0,
kNoPadding,
boost::none,
nullptr);
QueueAppender appender(&queue, frameLen);
appender.writeBE<uint32_t>(lastStreamID);
appender.writeBE<uint32_t>(static_cast<uint32_t>(errorCode));
queue.append(std::move(debugData));
return kFrameHeaderSize + frameLen;
}
size_t
writeWindowUpdate(IOBufQueue& queue,
uint32_t stream,
uint32_t amount) noexcept {
const auto frameLen = writeFrameHeader(queue,
kFrameWindowUpdateSize,
FrameType::WINDOW_UPDATE,
0,
stream,
kNoPadding,
boost::none,
nullptr);
DCHECK_EQ(0, ~kUint31Mask & amount);
DCHECK_LT(0, amount);
QueueAppender appender(&queue, kFrameWindowUpdateSize);
appender.writeBE<uint32_t>(amount);
return kFrameHeaderSize + frameLen;
}
size_t
writeContinuation(IOBufQueue& queue,
uint32_t stream,
bool endHeaders,
std::unique_ptr<IOBuf> headers,
boost::optional<uint8_t> padding) noexcept {
DCHECK_NE(0, stream);
const auto dataLen = headers->computeChainDataLength();
const auto frameLen = writeFrameHeader(queue,
dataLen,
FrameType::CONTINUATION,
endHeaders ? END_HEADERS : 0,
stream,
padding,
boost::none,
std::move(headers));
writePadding(queue, padding);
return kFrameHeaderSize + frameLen;
}
size_t
writeAltSvc(IOBufQueue& queue,
uint32_t stream,
uint32_t maxAge,
uint16_t port,
StringPiece protocol,
StringPiece host,
StringPiece origin) noexcept {
const auto protoLen = protocol.size();
const auto hostLen = host.size();
const auto originLen = origin.size();
const auto frameLen = protoLen + hostLen + originLen + kFrameAltSvcSizeBase;
writeFrameHeader(queue, frameLen, FrameType::ALTSVC, 0, stream, kNoPadding,
boost::none, nullptr);
QueueAppender appender(&queue, frameLen);
appender.writeBE<uint32_t>(maxAge);
appender.writeBE<uint16_t>(port);
appender.writeBE<uint8_t>(protoLen);
appender.push(reinterpret_cast<const uint8_t*>(protocol.data()), protoLen);
appender.writeBE<uint8_t>(hostLen);
appender.push(reinterpret_cast<const uint8_t*>(host.data()), hostLen);
appender.push(reinterpret_cast<const uint8_t*>(origin.data()), originLen);
return kFrameHeaderSize + frameLen;
}
const char* getFrameTypeString(FrameType type) {
switch (type) {
case FrameType::DATA: return "DATA";
case FrameType::HEADERS: return "HEADERS";
case FrameType::PRIORITY: return "PRIORITY";
case FrameType::RST_STREAM: return "RST_STREAM";
case FrameType::SETTINGS: return "SETTINGS";
case FrameType::PUSH_PROMISE: return "PUSH_PROMISE";
case FrameType::PING: return "PING";
case FrameType::GOAWAY: return "GOAWAY";
case FrameType::WINDOW_UPDATE: return "WINDOW_UPDATE";
case FrameType::CONTINUATION: return "CONTINUATION";
case FrameType::ALTSVC: return "ALTSVC";
default:
// can happen when type was cast from uint8_t
return "Unknown";
}
LOG(FATAL) << "Unreachable";
return "";
}
}}
| Orvid/proxygen | proxygen/lib/http/codec/experimental/HTTP2Framer.cpp | C++ | bsd-3-clause | 25,806 |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Fichier contenant le paramètre 'voir' de la commande 'chemin'."""
from primaires.format.fonctions import oui_ou_non
from primaires.interpreteur.masque.parametre import Parametre
from primaires.pnj.chemin import FLAGS
class PrmVoir(Parametre):
"""Commande 'chemin voir'.
"""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, "voir", "view")
self.schema = "<cle>"
self.aide_courte = "affiche le détail d'un chemin"
self.aide_longue = \
"Cette commande permet d'obtenir plus d'informations sur " \
"un chemin (ses flags actifs, ses salles et sorties...)."
def ajouter(self):
"""Méthode appelée lors de l'ajout de la commande à l'interpréteur"""
cle = self.noeud.get_masque("cle")
cle.proprietes["regex"] = r"'[a-z0-9_:]{3,}'"
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
cle = dic_masques["cle"].cle
if cle not in importeur.pnj.chemins:
personnage << "|err|Ce chemin n'existe pas.|ff|"
return
chemin = importeur.pnj.chemins[cle]
msg = "Détail sur le chemin {} :".format(chemin.cle)
msg += "\n Flags :"
for nom_flag in FLAGS.keys():
msg += "\n {}".format(nom_flag.capitalize())
msg += " : " + oui_ou_non(chemin.a_flag(nom_flag))
msg += "\n Salles du chemin :"
if len(chemin.salles) == 0:
msg += "\n Aucune"
else:
for salle, direction in chemin.salles.items():
msg += "\n " + salle.ident.ljust(20) + " "
msg += direction.ljust(10)
if salle in chemin.salles_retour and \
chemin.salles_retour[salle]:
msg += " (retour " + chemin.salles_retour[salle] + ")"
personnage << msg
| vlegoff/tsunami | src/primaires/pnj/commandes/chemin/voir.py | Python | bsd-3-clause | 3,490 |
#This is where the tests go.
| praekelt/ummeli | ummeli/providers/tests.py | Python | bsd-3-clause | 29 |
import FontAwesome from '@expo/vector-icons/build/FontAwesome';
import MaterialIcons from '@expo/vector-icons/build/MaterialIcons';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useFocusEffect } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import * as Location from 'expo-location';
import * as TaskManager from 'expo-task-manager';
import { EventEmitter, EventSubscription } from 'fbemitter';
import * as React from 'react';
import { Modal, Platform, StyleSheet, Text, View } from 'react-native';
import MapView from 'react-native-maps';
import Button from '../../components/Button';
import Colors from '../../constants/Colors';
import usePermissions from '../../utilities/usePermissions';
const STORAGE_KEY = 'expo-home-locations';
const LOCATION_UPDATES_TASK = 'location-updates';
const locationEventsEmitter = new EventEmitter();
const locationAccuracyStates: { [key in Location.Accuracy]: Location.Accuracy } = {
[Location.Accuracy.Lowest]: Location.Accuracy.Low,
[Location.Accuracy.Low]: Location.Accuracy.Balanced,
[Location.Accuracy.Balanced]: Location.Accuracy.High,
[Location.Accuracy.High]: Location.Accuracy.Highest,
[Location.Accuracy.Highest]: Location.Accuracy.BestForNavigation,
[Location.Accuracy.BestForNavigation]: Location.Accuracy.Lowest,
};
const locationActivityTypes: {
[key in Location.ActivityType]: Location.ActivityType | undefined;
} = {
[Location.ActivityType.Other]: Location.ActivityType.AutomotiveNavigation,
[Location.ActivityType.AutomotiveNavigation]: Location.ActivityType.Fitness,
[Location.ActivityType.Fitness]: Location.ActivityType.OtherNavigation,
[Location.ActivityType.OtherNavigation]: Location.ActivityType.Airborne,
[Location.ActivityType.Airborne]: undefined,
};
interface Props {
navigation: StackNavigationProp<any>;
}
type Region = {
latitude: number;
longitude: number;
latitudeDelta: number;
longitudeDelta: number;
};
type State = Pick<Location.LocationTaskOptions, 'showsBackgroundLocationIndicator'> & {
activityType: Location.ActivityType | null;
accuracy: Location.Accuracy;
isTracking: boolean;
savedLocations: any[];
initialRegion: Region | null;
};
const initialState: State = {
isTracking: false,
savedLocations: [],
activityType: null,
accuracy: Location.Accuracy.High,
initialRegion: null,
showsBackgroundLocationIndicator: false,
};
function reducer(state: State, action: Partial<State>): State {
return {
...state,
...action,
};
}
export default function BackgroundLocationMapScreen(props: Props) {
const [permission] = usePermissions(Location.requestForegroundPermissionsAsync);
React.useEffect(() => {
(async () => {
if (!(await Location.isBackgroundLocationAvailableAsync())) {
alert('Background location is not available in this application.');
props.navigation.goBack();
}
})();
}, [props.navigation]);
if (!permission) {
return (
<Text style={styles.errorText}>
Location permissions are required in order to use this feature. You can manually enable them
at any time in the "Location Services" section of the Settings app.
</Text>
);
}
return <BackgroundLocationMapView />;
}
function BackgroundLocationMapView() {
const mapViewRef = React.useRef<MapView>(null);
const [state, dispatch] = React.useReducer(reducer, initialState);
const onFocus = React.useCallback(() => {
let subscription: EventSubscription | null = null;
let isMounted = true;
(async () => {
if ((await Location.getBackgroundPermissionsAsync()).status !== 'granted') {
console.log(
'Missing background location permissions. Make sure it is granted in the OS Settings.'
);
return;
}
const { coords } = await Location.getCurrentPositionAsync();
const isTracking = await Location.hasStartedLocationUpdatesAsync(LOCATION_UPDATES_TASK);
const task = (await TaskManager.getRegisteredTasksAsync()).find(
({ taskName }) => taskName === LOCATION_UPDATES_TASK
);
const savedLocations = await getSavedLocations();
subscription = locationEventsEmitter.addListener('update', (savedLocations: any) => {
if (isMounted) dispatch({ savedLocations });
});
if (!isTracking) {
alert('Click `Start tracking` to start getting location updates.');
}
if (!isMounted) return;
dispatch({
isTracking,
accuracy: task?.options.accuracy ?? state.accuracy,
showsBackgroundLocationIndicator: task?.options.showsBackgroundLocationIndicator,
activityType: task?.options.activityType ?? null,
savedLocations,
initialRegion: {
latitude: coords.latitude,
longitude: coords.longitude,
latitudeDelta: 0.004,
longitudeDelta: 0.002,
},
});
})();
return () => {
isMounted = false;
if (subscription) {
subscription.remove();
}
};
}, [state.accuracy, state.isTracking]);
useFocusEffect(onFocus);
const startLocationUpdates = React.useCallback(
async (acc = state.accuracy) => {
if ((await Location.getBackgroundPermissionsAsync()).status !== 'granted') {
console.log(
'Missing background location permissions. Make sure it is granted in the OS Settings.'
);
return;
}
await Location.startLocationUpdatesAsync(LOCATION_UPDATES_TASK, {
accuracy: acc,
activityType: state.activityType ?? undefined,
pausesUpdatesAutomatically: state.activityType != null,
showsBackgroundLocationIndicator: state.showsBackgroundLocationIndicator,
deferredUpdatesInterval: 60 * 1000, // 1 minute
deferredUpdatesDistance: 100, // 100 meters
foregroundService: {
notificationTitle: 'expo-location-demo',
notificationBody: 'Background location is running...',
notificationColor: Colors.tintColor,
},
});
if (!state.isTracking) {
alert(
// tslint:disable-next-line max-line-length
'Now you can send app to the background, go somewhere and come back here! You can even terminate the app and it will be woken up when the new significant location change comes out.'
);
}
dispatch({
isTracking: true,
});
},
[state.isTracking, state.accuracy, state.activityType, state.showsBackgroundLocationIndicator]
);
const stopLocationUpdates = React.useCallback(async () => {
await Location.stopLocationUpdatesAsync(LOCATION_UPDATES_TASK);
dispatch({
isTracking: false,
});
}, []);
const clearLocations = React.useCallback(async () => {
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify([]));
dispatch({
savedLocations: [],
});
}, []);
const toggleTracking = React.useCallback(async () => {
await AsyncStorage.removeItem(STORAGE_KEY);
if (state.isTracking) {
await stopLocationUpdates();
} else {
await startLocationUpdates();
}
dispatch({
savedLocations: [],
});
}, [state.isTracking, startLocationUpdates, stopLocationUpdates]);
const onAccuracyChange = React.useCallback(() => {
const currentAccuracy = locationAccuracyStates[state.accuracy];
dispatch({
accuracy: currentAccuracy,
});
if (state.isTracking) {
// Restart background task with the new accuracy.
startLocationUpdates(currentAccuracy);
}
}, [state.accuracy, state.isTracking, startLocationUpdates]);
const toggleLocationIndicator = React.useCallback(() => {
dispatch({
showsBackgroundLocationIndicator: !state.showsBackgroundLocationIndicator,
});
if (state.isTracking) {
startLocationUpdates();
}
}, [state.showsBackgroundLocationIndicator, state.isTracking, startLocationUpdates]);
const toggleActivityType = React.useCallback(() => {
let nextActivityType: Location.ActivityType | null;
if (state.activityType) {
nextActivityType = locationActivityTypes[state.activityType] ?? null;
} else {
nextActivityType = Location.ActivityType.Other;
}
dispatch({
activityType: nextActivityType,
});
if (state.isTracking) {
// Restart background task with the new activity type
startLocationUpdates();
}
}, [state.activityType, state.isTracking, startLocationUpdates]);
const onCenterMap = React.useCallback(async () => {
const { coords } = await Location.getCurrentPositionAsync();
const mapView = mapViewRef.current;
if (mapView) {
mapView.animateToRegion({
latitude: coords.latitude,
longitude: coords.longitude,
latitudeDelta: 0.004,
longitudeDelta: 0.002,
});
}
}, []);
const renderPolyline = React.useCallback(() => {
if (state.savedLocations.length === 0) {
return null;
}
return (
// @ts-ignore
<MapView.Polyline
coordinates={state.savedLocations}
strokeWidth={3}
strokeColor={Colors.tintColor}
/>
);
}, [state.savedLocations]);
return (
<View style={styles.screen}>
<PermissionsModal />
<MapView
ref={mapViewRef}
style={styles.mapView}
initialRegion={state.initialRegion ?? undefined}
showsUserLocation>
{renderPolyline()}
</MapView>
<View style={styles.buttons} pointerEvents="box-none">
<View style={styles.topButtons}>
<View style={styles.buttonsColumn}>
{Platform.OS === 'android' ? null : (
<Button style={styles.button} onPress={toggleLocationIndicator}>
<View style={styles.buttonContentWrapper}>
<Text style={styles.text}>
{state.showsBackgroundLocationIndicator ? 'Hide' : 'Show'}
</Text>
<Text style={styles.text}> background </Text>
<FontAwesome name="location-arrow" size={20} color="white" />
<Text style={styles.text}> indicator</Text>
</View>
</Button>
)}
{Platform.OS === 'android' ? null : (
<Button
style={styles.button}
onPress={toggleActivityType}
title={
state.activityType
? `Activity type: ${Location.ActivityType[state.activityType]}`
: 'No activity type'
}
/>
)}
<Button
title={`Accuracy: ${Location.Accuracy[state.accuracy]}`}
style={styles.button}
onPress={onAccuracyChange}
/>
</View>
<View style={styles.buttonsColumn}>
<Button style={styles.button} onPress={onCenterMap}>
<MaterialIcons name="my-location" size={20} color="white" />
</Button>
</View>
</View>
<View style={styles.bottomButtons}>
<Button title="Clear locations" style={styles.button} onPress={clearLocations} />
<Button
title={state.isTracking ? 'Stop tracking' : 'Start tracking'}
style={styles.button}
onPress={toggleTracking}
/>
</View>
</View>
</View>
);
}
const PermissionsModal = () => {
const [showPermissionsModal, setShowPermissionsModal] = React.useState(true);
const [permission] = usePermissions(Location.getBackgroundPermissionsAsync);
return (
<Modal
animationType="slide"
transparent={false}
visible={!permission && showPermissionsModal}
onRequestClose={() => {
setShowPermissionsModal(!showPermissionsModal);
}}>
<View style={{ flex: 1, justifyContent: 'space-around', alignItems: 'center' }}>
<View style={{ flex: 2, justifyContent: 'center', alignItems: 'center' }}>
<Text style={styles.modalHeader}>Background location access</Text>
<Text style={styles.modalText}>
This app collects location data to enable updating the MapView in the background even
when the app is closed or not in use. Otherwise, your location on the map will only be
updated while the app is foregrounded.
</Text>
<Text style={styles.modalText}>
This data is not used for anything other than updating the position on the map, and this
data is never shared with anyone.
</Text>
</View>
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Button
title="Request background location permission"
style={styles.button}
onPress={async () => {
// Need both background and foreground permissions
await Location.requestForegroundPermissionsAsync();
await Location.requestBackgroundPermissionsAsync();
setShowPermissionsModal(!showPermissionsModal);
}}
/>
<Button
title="Continue without background location permission"
style={styles.button}
onPress={() => setShowPermissionsModal(!showPermissionsModal)}
/>
</View>
</View>
</Modal>
);
};
BackgroundLocationMapScreen.navigationOptions = {
title: 'Background location',
};
async function getSavedLocations() {
try {
const item = await AsyncStorage.getItem(STORAGE_KEY);
return item ? JSON.parse(item) : [];
} catch (e) {
return [];
}
}
TaskManager.defineTask(LOCATION_UPDATES_TASK, async ({ data: { locations } }: any) => {
if (locations && locations.length > 0) {
const savedLocations = await getSavedLocations();
const newLocations = locations.map(({ coords }: any) => ({
latitude: coords.latitude,
longitude: coords.longitude,
}));
// tslint:disable-next-line no-console
console.log(`Received new locations at ${new Date()}:`, locations);
savedLocations.push(...newLocations);
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(savedLocations));
locationEventsEmitter.emit('update', savedLocations);
}
});
const styles = StyleSheet.create({
screen: {
flex: 1,
},
mapView: {
flex: 1,
},
buttons: {
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
padding: 10,
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
},
topButtons: {
flexDirection: 'row',
justifyContent: 'space-between',
},
bottomButtons: {
flexDirection: 'column',
alignItems: 'flex-end',
},
buttonsColumn: {
flexDirection: 'column',
alignItems: 'flex-start',
},
button: {
paddingVertical: 5,
paddingHorizontal: 10,
marginVertical: 5,
},
buttonContentWrapper: {
flexDirection: 'row',
},
text: {
color: 'white',
fontWeight: '700',
},
errorText: {
fontSize: 15,
color: 'rgba(0,0,0,0.7)',
margin: 20,
},
modalHeader: { padding: 12, fontSize: 20, fontWeight: '800' },
modalText: { padding: 8, fontWeight: '600' },
});
| exponentjs/exponent | apps/native-component-list/src/screens/Location/BackgroundLocationMapScreen.tsx | TypeScript | bsd-3-clause | 15,261 |
using System;
namespace DistributedPrimeCalculatorApp
{
public class MessageTypes
{
public const int Terminate = 0; //tells the prime worker to stop
public const int Start = 1; //initialize the prime workers
public const int ReplyBatch = 2; //the main worker sends a batch of numbers
public const int RequestBatch = 3; //the prime worker requests a new batch
public const int Result = 4; //the prime worker sends the count back
}
}
| parallax68/MPAPI | DistributedPrimeCalculatorApp/MessageTypes.cs | C# | bsd-3-clause | 450 |
/*
Copyright (C) 2013-2014 by Kristina Simpson <sweet.kristas@gmail.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#pragma once
#include "ParticleSystemFwd.hpp"
namespace KRE
{
namespace Particles
{
enum class EmitsType {
VISUAL,
EMITTER,
AFFECTOR,
TECHNIQUE,
SYSTEM,
};
class Emitter : public EmitObject
{
public:
explicit Emitter(ParticleSystemContainer* parent, const variant& node);
virtual ~Emitter();
Emitter(const Emitter&);
int getEmittedParticleCountPerCycle(float t);
color_vector getColor() const;
Technique* getTechnique() { return technique_; }
void setParentTechnique(Technique* tq) {
technique_ = tq;
}
virtual Emitter* clone() = 0;
static Emitter* factory(ParticleSystemContainer* parent, const variant& node);
protected:
virtual void internalCreate(Particle& p, float t) = 0;
virtual bool durationExpired() { return can_be_deleted_; }
private:
virtual void handleEmitProcess(float t) override;
virtual void handleDraw() const override;
Technique* technique_;
// These are generation parameters.
ParameterPtr emission_rate_;
ParameterPtr time_to_live_;
ParameterPtr velocity_;
ParameterPtr angle_;
ParameterPtr mass_;
// This is the duration that the emitter lives for
ParameterPtr duration_;
// this is the delay till the emitter repeats.
ParameterPtr repeat_delay_;
std::unique_ptr<std::pair<glm::quat, glm::quat>> orientation_range_;
typedef std::pair<color_vector,color_vector> color_range;
std::shared_ptr<color_range> color_range_;
glm::vec4 color_;
ParameterPtr particle_width_;
ParameterPtr particle_height_;
ParameterPtr particle_depth_;
bool force_emission_;
bool force_emission_processed_;
bool can_be_deleted_;
EmitsType emits_type_;
std::string emits_name_;
void initParticle(Particle& p, float t);
void setParticleStartingValues(const std::vector<Particle>::iterator& start, const std::vector<Particle>::iterator& end);
void createParticles(std::vector<Particle>& particles, std::vector<Particle>::iterator& start, std::vector<Particle>::iterator& end, float t);
size_t calculateParticlesToEmit(float t, size_t quota, size_t current_size);
float generateAngle() const;
glm::vec3 getInitialDirection() const;
//BoxOutlinePtr debug_draw_outline_;
// working items
// Any "left over" fractional count of emitted particles
float emission_fraction_;
// time till the emitter stops emitting.
float duration_remaining_;
// time remaining till a stopped emitter restarts.
float repeat_delay_remaining_;
Emitter();
};
}
} | sweetkristas/swiftly | src/kre/ParticleSystemEmitters.hpp | C++ | bsd-3-clause | 3,459 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" This package contains the qibuild actions. """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
| aldebaran/qibuild | python/qibuild/actions/__init__.py | Python | bsd-3-clause | 365 |
package com.navisens.pojostick.navishare;
import com.navisens.motiondnaapi.MotionDna;
import com.navisens.pojostick.navisenscore.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Created by Joseph on 11/30/17.
* <p>
* NaviShare provides functionality for communicating with other devices
* </p>
*/
@SuppressWarnings("unused")
public class NaviShare implements NavisensPlugin {
private static final long QUERY_INTERVAL = 500000000;
private String host, port, room;
private boolean changed;
private boolean configured;
private boolean connected;
private NavisensCore core;
private final Set<String> rooms;
private final Set<NaviShareListener> listeners;
private long roomsQueriedAt;
@SuppressWarnings("unused")
public NaviShare() {
this.rooms = new HashSet<>();
this.listeners = new HashSet<>();
this.roomsQueriedAt = System.nanoTime();
}
/**
* Configure a server. This does not connect to it yet, but is required before calling connect.
*
* @param host server ip
* @param port server port
* @return a reference to this NaviShare
*/
@SuppressWarnings("unused")
public NaviShare configure(String host, String port) {
core.getSettings().overrideHost(null, null);
this.host = host;
this.port = port;
this.changed = true;
this.configured = true;
return this;
}
/**
* Connect to a room in the server.
*
* @param room The room to connect to
* @return Whether this device connected to a server
*/
@SuppressWarnings("unused")
public boolean connect(String room) {
core.getSettings().overrideRoom(null);
if (configured) {
if (connected && !changed) {
core.getMotionDna().setUDPRoom(room);
} else {
this.disconnect();
core.getMotionDna().startUDP(room, host, port);
this.connected = true;
}
this.changed = false;
return true;
}
return false;
}
/**
* Disconnect from the server.
*/
@SuppressWarnings("unused")
public void disconnect() {
core.getMotionDna().stopUDP();
this.connected = false;
}
/**
* Connect to a public test server. Don't use this for official release, as it is public
* and can get filled up quickly. Each organization can claim one room, so if you need
* multiple independent servers within your organization, you should test on a private
* server instead, and use configure(host, port) to target that server instead.
*/
@SuppressWarnings("unused")
public boolean testConnect() {
if (!connected) {
this.disconnect();
core.getMotionDna().startUDP();
return this.connected = true;
}
return false;
}
/**
* Send a message to all other devices on the network
*
* @param msg A string to send, recommended web safe
*/
@SuppressWarnings("unused")
public void sendMessage(String msg) {
if (connected) {
core.getMotionDna().sendUDPPacket(msg);
}
}
/**
* Add a listener to receive network events
*
* @param listener The listener to receive events
* @return Whether the listener was added successfully
*/
@SuppressWarnings("unused")
public boolean addListener(NaviShareListener listener) {
return this.listeners.add(listener);
}
/**
* Remove a listener to stop receiving events
*
* @param listener Ths listener to remove
* @return Whether the listener was removed successfully
*/
@SuppressWarnings("unused")
public boolean removeListener(NaviShareListener listener) {
return this.listeners.remove(listener);
}
/**
* Track a room so you can query its status. Call refreshRoomStatus to
* receive a new roomStatus event
*
* @param room A room to track
* @return Whether the room was added to be tracked or not
*/
@SuppressWarnings("unused")
public boolean trackRoom(String room) {
return this.rooms.add(room);
}
/**
* Stop tracking a room. Call refreshRoomStatus to receive a new roomStatusEvent
*
* @param room A room to stop tracking
* @return Whether the room was removed from tracking or not
*/
@SuppressWarnings("unused")
public boolean untrackRoom(String room) {
return this.rooms.remove(room);
}
/**
* Refresh the status of any tracked rooms. Updates will be received from the
* roomOccupancyChanged event
* @return Whether a refresh request was sent or not
*/
@SuppressWarnings("unused")
public boolean refreshRoomStatus() {
final long now = System.nanoTime();
if (connected && now - roomsQueriedAt > QUERY_INTERVAL) {
roomsQueriedAt = now;
core.getMotionDna().sendUDPQueryRooms(rooms.toArray(new String[0]));
return true;
}
return false;
}
@Override
public boolean init(NavisensCore navisensCore, Object[] objects) {
this.core = navisensCore;
core.subscribe(this, NavisensCore.NETWORK_DATA);
core.getSettings().requestNetworkRate(100);
core.applySettings();
return true;
}
@Override
public boolean stop() {
this.disconnect();
core.remove(this);
return true;
}
@Override
public void receiveMotionDna(MotionDna motionDna) {
}
@Override
public void receiveNetworkData(MotionDna motionDna) {
}
@Override
public void receiveNetworkData(MotionDna.NetworkCode networkCode, Map<String, ?> map) {
switch (networkCode) {
case RAW_NETWORK_DATA:
for (NaviShareListener listener : listeners)
listener.messageReceived((String) map.get("ID"), (String) map.get("payload"));
break;
case ROOM_CAPACITY_STATUS:
for (NaviShareListener listener : listeners)
listener.roomOccupancyChanged((Map<String, Integer>) map.get("payload"));
break;
case EXCEEDED_SERVER_ROOM_CAPACITY:
for (NaviShareListener listener : listeners)
listener.serverCapacityExceeded();
this.disconnect();
break;
case EXCEEDED_ROOM_CONNECTION_CAPACITY:
for (NaviShareListener listener : listeners)
listener.roomCapacityExceeded();
this.disconnect();
break;
}
}
@Override
public void receivePluginData(String id, int operator, Object... payload) {
}
@Override
public void reportError(MotionDna.ErrorCode errorCode, String s) {
}
}
| navisens/Android-Plugin | navishare/src/main/java/com/navisens/pojostick/navishare/NaviShare.java | Java | bsd-3-clause | 6,973 |
<?php
// WARNING, this is a read only file created by import scripts
// WARNING
// WARNING, Changes made to this file will be clobbered
// WARNING
// WARNING, Please make changes on poeditor instead of here
//
//
?>
subject: (opomnik) {if:transfer.files>1}Datoteke, pripravljene{else}Datoteka, pripravljena{endif} za prenos
subject: (opomnik) {transfer.subject}
{alternative:plain}
Spoštovani,
prejeli ste opomnik, da {if:transfer.files>1}so bile naložene datoteke{else}je bila naložena datoteka{endif} na {cfg:site_name} s strani {transfer.user_email}, Vam pa so bile dodeljene pravice za prenos {if:transfer.files>1}njihovih vsebin{else}njene vsebine{endif} :
{if:transfer.files>1}{each:transfer.files as file}
- {file.path} ({size:file.size})
{endeach}{else}
{transfer.files.first().path} ({size:transfer.files.first().size})
{endif}
Povezava za prenos: {recipient.download_link}
Prenos je na voljo do {date:transfer.expires}. Po tem datumu bo avtomatsko izbrisan.
{if:transfer.message || transfer.subject}
Osebno sporočilo od {transfer.user_email}: {transfer.subject}
{transfer.message}
{endif}
Lep pozdrav,
{cfg:site_name}
{alternative:html}
<p>
Spoštovani,
</p>
<p>
prejeli ste opomnik, da {if:transfer.files>1}so bile naložene datoteke{else}je bila naložena datoteka{endif} na {cfg:site_name} s strani {transfer.user_email}, Vam pa so bile dodeljene pravice za prenos {if:transfer.files>1}njihovih vsebin{else}njene vsebine{endif}.
</p>
<table rules="rows">
<thead>
<tr>
<th colspan="2">Podrobnosti prenosa</th>
</tr>
</thead>
<tbody>
<tr>
<td>{if:transfer.files>1}Datoteke{else}Datoteka{endif}</td>
<td>
{if:transfer.files>1}
<ul>
{each:transfer.files as file}
<li>{file.path} ({size:file.size})</li>
{endeach}
</ul>
{else}
{transfer.files.first().path} ({size:transfer.files.first().size})
{endif}
</td>
</tr>
{if:transfer.files>1}
<tr>
<td>Velikost prenosa</td>
<td>{size:transfer.size}</td>
</tr>
{endif}
<tr>
<td>Rok veljavnosti</td>
<td>{date:transfer.expires}</td>
</tr>
<tr>
<td>Povezava do prenosa</td>
<td><a href="{recipient.download_link}">{recipient.download_link}</a></td>
</tr>
</tbody>
</table>
{if:transfer.message}
<p>
Osebno sporočilo od {transfer.user_email}:
</p>
<p class="message">
<span class="subject">{transfer.subject}</span>
{transfer.message}
</p>
{endif}
<p>
Lep pozdrav,<br />
{cfg:site_name}
</p> | filesender/filesender | language/sl_SI/transfer_reminder.mail.php | PHP | bsd-3-clause | 2,784 |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Layouts
{
using NLog.Config;
/// <summary>
/// A XML Element
/// </summary>
[NLogConfigurationItem]
public class XmlElement : XmlElementBase
{
private const string DefaultElementName = "item";
/// <inheritdoc/>
public XmlElement() : this(DefaultElementName, null)
{
}
/// <inheritdoc/>
public XmlElement(string elementName, Layout elementValue) : base(elementName, elementValue)
{
}
/// <summary>
/// Name of the element
/// </summary>
/// <docgen category='Element Options' order='10' />
public string Name
{
get => base.ElementNameInternal;
set => base.ElementNameInternal = value;
}
/// <summary>
/// Value inside the element
/// </summary>
/// <docgen category='Element Options' order='10' />
public Layout Value
{
get => base.LayoutWrapper.Inner;
set => base.LayoutWrapper.Inner = value;
}
/// <summary>
/// Determines whether or not this attribute will be Xml encoded.
/// </summary>
/// <docgen category='Element Options' order='10' />
public bool Encode
{
get => base.LayoutWrapper.XmlEncode;
set => base.LayoutWrapper.XmlEncode = value;
}
}
} | 304NotModified/NLog | src/NLog/Layouts/XML/XmlElement.cs | C# | bsd-3-clause | 3,082 |
require "lita"
Lita.load_locales Dir[File.expand_path(
File.join("..", "..", "locales", "*.yml"), __FILE__
)]
require 'lita/handlers/markov'
# Lita::Handlers::Markov.template_root File.expand_path(
# File.join("..", "..", "templates"),
# __FILE__
# )
| dirk/lita-markov | lib/lita-markov.rb | Ruby | bsd-3-clause | 259 |
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is configman
#
# The Initial Developer of the Original Code is
# Mozilla Foundation
# Portions created by the Initial Developer are Copyright (C) 2011
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# K Lars Lohn, lars@mozilla.com
# Peter Bengtsson, peterbe@mozilla.com
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
import sys
import re
import datetime
import types
import inspect
import collections
import json
from required_config import RequiredConfig
from namespace import Namespace
from .datetime_util import datetime_from_ISO_string as datetime_converter
from .datetime_util import date_from_ISO_string as date_converter
import datetime_util
#------------------------------------------------------------------------------
def option_value_str(an_option):
"""return an instance of Option's value as a string.
The option instance doesn't actually have to be from the Option class. All
it requires is that the passed option instance has a ``value`` attribute.
"""
if an_option.value is None:
return ''
try:
converter = to_string_converters[type(an_option.value)]
s = converter(an_option.value)
except KeyError:
if not isinstance(an_option.value, basestring):
s = unicode(an_option.value)
else:
s = an_option.value
if an_option.from_string_converter in converters_requiring_quotes:
s = "'''%s'''" % s
return s
#------------------------------------------------------------------------------
def str_dict_keys(a_dict):
"""return a modified dict where all the keys that are anything but str get
converted to str.
E.g.
>>> result = str_dict_keys({u'name': u'Peter', u'age': 99, 1: 2})
>>> # can't compare whole dicts in doctests
>>> result['name']
u'Peter'
>>> result['age']
99
>>> result[1]
2
The reason for this is that in Python <= 2.6.4 doing
``MyClass(**{u'name': u'Peter'})`` would raise a TypeError
Note that only unicode types are converted to str types.
The reason for that is you might have a class that looks like this::
class Option(object):
def __init__(self, foo=None, bar=None, **kwargs):
...
And it's being used like this::
Option(**{u'foo':1, u'bar':2, 3:4})
Then you don't want to change that {3:4} part which becomes part of
`**kwargs` inside the __init__ method.
Using integers as parameter keys is a silly example but the point is that
due to the python 2.6.4 bug only unicode keys are converted to str.
"""
new_dict = {}
for key in a_dict:
if isinstance(key, unicode):
new_dict[str(key)] = a_dict[key]
else:
new_dict[key] = a_dict[key]
return new_dict
#------------------------------------------------------------------------------
def io_converter(input_str):
""" a conversion function for to select stdout, stderr or open a file for
writing"""
if type(input_str) is str:
input_str_lower = input_str.lower()
if input_str_lower == 'stdout':
return sys.stdout
if input_str_lower == 'stderr':
return sys.stderr
return open(input_str, "w")
return input_str
#------------------------------------------------------------------------------
def timedelta_converter(input_str):
"""a conversion function for time deltas"""
if isinstance(input_str, basestring):
days, hours, minutes, seconds = 0, 0, 0, 0
details = input_str.split(':')
if len(details) >= 4:
days = int(details[-4])
if len(details) >= 3:
hours = int(details[-3])
if len(details) >= 2:
minutes = int(details[-2])
if len(details) >= 1:
seconds = int(details[-1])
return datetime.timedelta(days=days,
hours=hours,
minutes=minutes,
seconds=seconds)
raise ValueError(input_str)
#------------------------------------------------------------------------------
def boolean_converter(input_str):
""" a conversion function for boolean
"""
return input_str.lower() in ("true", "t", "1", "y", "yes")
#------------------------------------------------------------------------------
import __builtin__
_all_named_builtins = dir(__builtin__)
def class_converter(input_str):
""" a conversion that will import a module and class name
"""
if not input_str:
return None
if '.' not in input_str and input_str in _all_named_builtins:
return eval(input_str)
parts = [x.strip() for x in input_str.split('.') if x.strip()]
try:
# first try as a complete module
package = __import__(input_str)
except ImportError:
# it must be a class from a module
if len(parts) == 1:
# since it has only one part, it must be a class from __main__
parts = ('__main__', input_str)
package = __import__('.'.join(parts[:-1]), globals(), locals(), [])
obj = package
for name in parts[1:]:
obj = getattr(obj, name)
return obj
#------------------------------------------------------------------------------
def classes_in_namespaces_converter(template_for_namespace="cls%d",
name_of_class_option='cls',
instantiate_classes=False):
"""take a comma delimited list of class names, convert each class name
into an actual class as an option within a numbered namespace. This
function creates a closure over a new function. That new function,
in turn creates a class derived from RequiredConfig. The inner function,
'class_list_converter', populates the InnerClassList with a Namespace for
each of the classes in the class list. In addition, it puts the each class
itself into the subordinate Namespace. The requirement discovery mechanism
of configman then reads the InnerClassList's requried config, pulling in
the namespaces and associated classes within.
For example, if we have a class list like this: "Alpha, Beta", then this
converter will add the following Namespaces and options to the
configuration:
"cls0" - the subordinate Namespace for Alpha
"cls0.cls" - the option containing the class Alpha itself
"cls1" - the subordinate Namespace for Beta
"cls1.cls" - the option containing the class Beta itself
Optionally, the 'class_list_converter' inner function can embue the
InnerClassList's subordinate namespaces with aggregates that will
instantiate classes from the class list. This is a convenience to the
programmer who would otherwise have to know ahead of time what the
namespace names were so that the classes could be instantiated within the
context of the correct namespace. Remember the user could completely
change the list of classes at run time, so prediction could be difficult.
"cls0" - the subordinate Namespace for Alpha
"cls0.cls" - the option containing the class Alpha itself
"cls0.cls_instance" - an instance of the class Alpha
"cls1" - the subordinate Namespace for Beta
"cls1.cls" - the option containing the class Beta itself
"cls1.cls_instance" - an instance of the class Beta
parameters:
template_for_namespace - a template for the names of the namespaces
that will contain the classes and their
associated required config options. The
namespaces will be numbered sequentially. By
default, they will be "cls1", "cls2", etc.
class_option_name - the name to be used for the class option within
the nested namespace. By default, it will choose:
"cls1.cls", "cls2.cls", etc.
instantiate_classes - a boolean to determine if there should be an
aggregator added to each namespace that
instantiates each class. If True, then each
Namespace will contain elements for the class, as
well as an aggregator that will instantiate the
class.
"""
#--------------------------------------------------------------------------
def class_list_converter(class_list_str):
"""This function becomes the actual converter used by configman to
take a string and convert it into the nested sequence of Namespaces,
one for each class in the list. It does this by creating a proxy
class stuffed with its own 'required_config' that's dynamically
generated."""
if isinstance(class_list_str, basestring):
class_list = [x.strip() for x in class_list_str.split(',')]
else:
raise TypeError('must be derivative of a basestring')
#======================================================================
class InnerClassList(RequiredConfig):
"""This nested class is a proxy list for the classes. It collects
all the config requirements for the listed classes and places them
each into their own Namespace.
"""
# we're dynamically creating a class here. The following block of
# code is actually adding class level attributes to this new class
required_config = Namespace() # 1st requirement for configman
subordinate_namespace_names = [] # to help the programmer know
# what Namespaces we added
namespace_template = template_for_namespace # save the template
# for future reference
class_option_name = name_of_class_option # save the class's option
# name for the future
# for each class in the class list
for namespace_index, a_class in enumerate(class_list):
# figure out the Namespace name
namespace_name = template_for_namespace % namespace_index
subordinate_namespace_names.append(namespace_name)
# create the new Namespace
required_config[namespace_name] = Namespace()
# add the option for the class itself
required_config[namespace_name].add_option(
name_of_class_option,
#doc=a_class.__doc__ # not helpful if too verbose
default=a_class,
from_string_converter=class_converter
)
if instantiate_classes:
# add an aggregator to instantiate the class
required_config[namespace_name].add_aggregation(
"%s_instance" % name_of_class_option,
lambda c, lc, a: lc[name_of_class_option](lc))
@classmethod
def to_str(cls):
"""this method takes this inner class object and turns it back
into the original string of classnames. This is used
primarily as for the output of the 'help' option"""
return ', '.join(
py_obj_to_str(v[name_of_class_option].value)
for v in cls.get_required_config().values()
if isinstance(v, Namespace))
return InnerClassList # result of class_list_converter
return class_list_converter # result of classes_in_namespaces_converter
#------------------------------------------------------------------------------
def regex_converter(input_str):
return re.compile(input_str)
compiled_regexp_type = type(re.compile(r'x'))
#------------------------------------------------------------------------------
from_string_converters = {
int: int,
float: float,
str: str,
unicode: unicode,
bool: boolean_converter,
dict: json.loads,
datetime.datetime: datetime_converter,
datetime.date: date_converter,
datetime.timedelta: timedelta_converter,
type: class_converter,
types.FunctionType: class_converter,
compiled_regexp_type: regex_converter,
}
#------------------------------------------------------------------------------
def py_obj_to_str(a_thing):
if a_thing is None:
return ''
if inspect.ismodule(a_thing):
return a_thing.__name__
if a_thing.__module__ == '__builtin__':
return a_thing.__name__
if a_thing.__module__ == "__main__":
return a_thing.__name__
if hasattr(a_thing, 'to_str'):
return a_thing.to_str()
return "%s.%s" % (a_thing.__module__, a_thing.__name__)
#------------------------------------------------------------------------------
def list_to_str(a_list):
return ', '.join(to_string_converters[type(x)](x) for x in a_list)
#------------------------------------------------------------------------------
to_string_converters = {
int: str,
float: str,
str: str,
unicode: unicode,
list: list_to_str,
tuple: list_to_str,
bool: lambda x: 'True' if x else 'False',
dict: json.dumps,
datetime.datetime: datetime_util.datetime_to_ISO_string,
datetime.date: datetime_util.date_to_ISO_string,
datetime.timedelta: datetime_util.timedelta_to_str,
type: py_obj_to_str,
types.ModuleType: py_obj_to_str,
types.FunctionType: py_obj_to_str,
compiled_regexp_type: lambda x: x.pattern,
}
#------------------------------------------------------------------------------
#converters_requiring_quotes = [eval, eval_to_regex_converter]
converters_requiring_quotes = [eval, regex_converter]
| AdrianGaudebert/configman | configman/converters.py | Python | bsd-3-clause | 15,400 |
<?php
//AJAX Poll System Hack Start - 5:03 PM 3/24/2007
$language['POLL_ID']='الرقم';
$language['LATEST_POLL']='آخر استفتاء';
$language['CAST_VOTE']='قدم صوتي';
$language['FETCHING_RESULTS']='جلب نتائج الاستفتاء الرجاء الانتظار';
$language['POLL_TITLE']='عنوان الاستفتاء';
$language['POLL_TITLE_MISSING']='عنوان الاستفتاء مفقود';
$language['POLLING_SYSTEM']='AJAX نظام استفتاء';
$language['CURRENT_POLLS']='الاستفتاءت الحالية';
$language['POLL_STARTED']='بدات في';
$language['POLL_ENDED']='انتهت في';
$language['POLL_LASTED']='استمرت';
$language['POLL_BY']='قدمها';
$language['POLL_VOTES']='الاصوات';
$language['POLL_STILL_ACTIVE']='فعالة';
$language['POLL_NEW']='جديد';
$language['POLL_START_NEW']='ابدى استفتاء جديد';
$language['POLL_ACTIVE']='فعال';
$language['POLL_ACTIVE_TRUE']='فعالة';
$language['POLL_ACTIVE_FALSE']='معطلة';
$language['POLL_OPTION']='خيار';
$language['POLL_OPTIONS']='خيارات';
$language['POLL_MOVE']='الى الاسفل';
$language['POLL_NEW_OPTIONS']='خيارات اخرى';
$language['POLL_SAVE']='حفظ';
$language['POLL_CANCEL']='الغاء';
$language['POLL_DELETE']='مسح';
$language['POLL_DEL_CONFIRM']='اكبس موافق لمسح الاستفتاء';
$language['POLL_VOTERS']='مصوتين الاستفتاء';
$language['POLL_IP_ADDRESS']='IP عناوين الـ';
$language['POLL_DATE']='اليوم';
$language['POLL_USER']='المستخدم';
$language['POLL_ACCOUNT_DEL']='<i>الحساب الغي</i>';
$language['POLL_BACK']='وراء';
$language['YEAR']='سنة';
$language['MONTH']='شهر';
$language['WEEK']='اسبوع';
$language['DAY']='يوم';
$language['HOUR']='ساعة';
$language['MINUTE']='دقيقة';
$language['SECOND']='ثانية';
$language['YEARS']='سنوات';
$language['MONTHS']='شهور';
$language['WEEKS']='اسابيع';
$language['DAYS']='ايام';
$language['HOURS']='سا عات';
$language['MINUTES']='دقائق';
$language['SECONDS']='ثواني';
//AJAX Poll System Hack Stop
?> | cybyd/cybyd | language/arabic/lang_polls.php | PHP | bsd-3-clause | 2,204 |
package org.mafagafogigante.dungeon.stats;
import org.mafagafogigante.dungeon.game.Id;
import org.jetbrains.annotations.NotNull;
import java.io.Serializable;
/**
* CauseOfDeath class that defines what kind of death happened and the ID of the related Item or Spell.
*/
public class CauseOfDeath implements Serializable {
private static final CauseOfDeath UNARMED = new CauseOfDeath(TypeOfCauseOfDeath.UNARMED, new Id("UNARMED"));
private final TypeOfCauseOfDeath type;
private final Id id;
/**
* Constructs a CauseOfDeath with the specified TypeOfCauseOfDeath and ID.
*
* @param type a TypeOfCauseOfDeath
* @param id an ID
*/
public CauseOfDeath(@NotNull TypeOfCauseOfDeath type, @NotNull Id id) {
this.type = type;
this.id = id;
}
/**
* Convenience method that returns a CauseOfDeath that represents an unarmed kill.
*/
public static CauseOfDeath getUnarmedCauseOfDeath() {
return UNARMED;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
CauseOfDeath that = (CauseOfDeath) object;
return id.equals(that.id) && type == that.type;
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + id.hashCode();
return result;
}
@Override
public String toString() {
return String.format("%s : %s", type, id);
}
}
| ffurkanhas/dungeon | src/main/java/org/mafagafogigante/dungeon/stats/CauseOfDeath.java | Java | bsd-3-clause | 1,483 |
// Benoit 2011-05-16
#include <ros/node_handle.h>
#include <ros/subscriber.h>
#include <ros/rate.h>
#include <eu_nifti_env_msg_ros/RequestForUUIDs.h>
#include "NIFTiROSUtil.h"
#include "UUIDsManager.h"
namespace eu
{
namespace nifti
{
namespace ocu
{
const char* UUIDsManager::TOPIC = "/eoi/RequestForUUIDs";
const u_int UUIDsManager::NUM_REQUESTED(10);
UUIDsManager* UUIDsManager::instance = NULL;
UUIDsManager* UUIDsManager::getInstance()
{
if (instance == NULL)
{
instance = new UUIDsManager();
}
return instance;
}
UUIDsManager::UUIDsManager() :
wxThread(wxTHREAD_JOINABLE)
, condition(mutexForCondition)
, keepManaging(true)
{
}
void UUIDsManager::stopManaging()
{
//printf("IN UUIDsManager::stopManaging \n");
keepManaging = false;
if (instance != NULL)
{
instance->condition.Signal(); // Will make it go out of the main loop and terminate
}
//printf("OUT UUIDsManager::stopManaging \n");
}
void* UUIDsManager::Entry()
{
//printf("%s\n", "UUIDsManager::Entry()");
::ros::ServiceClient client = NIFTiROSUtil::getNodeHandle()->serviceClient<eu_nifti_env_msg_ros::RequestForUUIDs > (TOPIC);
eu_nifti_env_msg_ros::RequestForUUIDs srv;
srv.request.numRequested = NUM_REQUESTED;
mutexForCondition.Lock(); // This must be called before the first wait()
while (keepManaging)
{
//ROS_INFO("In the loop (keepManaging)");
// This is a requirement from wxThread
// http://docs.wxwidgets.org/2.8/wx_wxthread.html#wxthreadtestdestroy
if (TestDestroy())
break;
if (!client.call(srv))
{
std::cerr << "Failed to call ROS service \"RequestForUUIDs\"" << std::endl;
//return 0; // Removed this on 2012-03-02 so that it would re-check the service every time, since CAST is unstable
}
else
{
//ROS_INFO("Got UUIDs");
{
wxMutexLocker lock(instance->mutexForQueue);
// Adds all new UUIDs to the list
for (u_int i = 0; i < srv.response.uuids.size(); i++)
{
availableUUIDs.push(srv.response.uuids.at(i));
//std::cout << "Added " << srv.response.uuids.at(i) << std::endl;
}
}
}
// Waits until more ids are needed (signal will be called on the condition)
//ROS_INFO("Before waiting");
condition.Wait();
//ROS_INFO("After waiting");
}
return 0;
}
int UUIDsManager::getUUID()
{
//ROS_INFO("int UUIDsManager::getUUID()");
int uuid;
{
wxMutexLocker lock(instance->mutexForQueue);
//ROS_INFO("Num left: %i/%i", instance->availableUUIDs.size(), NUM_REQUESTED);
//ROS_INFO("Enough? %i", instance->availableUUIDs.size() <= NUM_REQUESTED / 2);
assert(instance != NULL);
// Requests more id's when the list is half empty
if (instance->availableUUIDs.size() <= NUM_REQUESTED / 2)
{
//ROS_INFO("Will try waking up the thread to request UUIDs");
instance->condition.Signal();
if (instance->availableUUIDs.size() == 0)
{
throw "No UUID available";
}
}
uuid = instance->availableUUIDs.front();
instance->availableUUIDs.pop();
}
//ROS_INFO("int UUIDsManager::getUUID() returned %i. Num left: %i", uuid, instance->availableUUIDs.size());
return uuid;
}
}
}
}
| talkingrobots/NIFTi_OCU | nifti_user/ocu/src/UUIDsManager.cpp | C++ | bsd-3-clause | 4,758 |
package net.jloop.rejoice;
import net.jloop.rejoice.types.Symbol;
import net.jloop.rejoice.types.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MacroHelper {
public static List<Value> collect(Env env, Iterator<Value> input, Symbol terminator) {
List<Value> output = new ArrayList<>();
while (true) {
if (!input.hasNext()) {
throw new RuntimeError("MACRO", "Input stream ended before finding the terminating symbol '" + terminator.print() + "'");
}
Value next = input.next();
if (next instanceof Symbol) {
if (next.equals(terminator)) {
return output;
}
Function function = env.lookup((Symbol) next);
if (function instanceof Macro) {
env.trace().push((Symbol) next);
Iterator<Value> values = ((Macro) function).call(env, input);
while (values.hasNext()) {
output.add(values.next());
}
env.trace().pop();
} else {
output.add(next);
}
} else {
output.add(next);
}
}
}
@SuppressWarnings("unchecked")
public static <T extends Value> T match(Iterator<Value> input, Type type) {
if (!input.hasNext()) {
throw new RuntimeError("MACRO", "Unexpected EOF when attempting to match " + type.print());
}
Value next = input.next();
if (type == next.type()) {
return (T) next;
} else {
throw new RuntimeError("MACRO", "Expecting to match " + type.print() + ", but found " + next.type().print() + " with value '" + next.print() + "'");
}
}
public static void match(Iterator<Value> input, Symbol symbol) {
if (!input.hasNext()) {
throw new RuntimeError("MACRO", "Unexpected EOF when attempting to match ^symbol '" + symbol.print() + "'");
}
Value next = input.next();
if (!next.equals(symbol)) {
throw new RuntimeError("MACRO", "Expecting to match symbol '" + symbol.print() + "' , but found " + next.type().print() + " with value '" + next.print() + "'");
}
}
}
| jeremyheiler/rejoice | src/main/java/net/jloop/rejoice/MacroHelper.java | Java | bsd-3-clause | 2,365 |
import React from "react";
import { Text, View } from "react-native";
import { defaultProps, propTypes } from "./caption-prop-types";
import styles from "./styles";
const renderCredits = (style, credits) => {
if (!credits || credits === "") {
return null;
}
return (
<Text style={[styles.text, styles.credits, style.text, style.credits]}>
{credits.toUpperCase()}
</Text>
);
};
const renderText = (style, text) => {
if (!text || text === "") {
return null;
}
return <Text style={[styles.text, style.text, style.caption]}>{text}</Text>;
};
const Caption = ({ children, credits, style, text }) => (
<View>
{children}
<View style={[styles.container, style.container]}>
{renderText(style, text)}
{renderCredits(style, credits)}
</View>
</View>
);
Caption.propTypes = propTypes;
Caption.defaultProps = defaultProps;
export default Caption;
export { default as CentredCaption } from "./centred-caption";
| newsuk/times-components | packages/caption/src/caption.js | JavaScript | bsd-3-clause | 967 |
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\db;
/**
* SchemaBuilderTrait contains shortcut methods to create instances of [[ColumnSchemaBuilder]].
*
* These can be used in database migrations to define database schema types using a PHP interface.
* This is useful to define a schema in a DBMS independent way so that the application may run on
* different DBMS the same way.
*
* For example you may use the following code inside your migration files:
*
* ```php
* $this->createTable('example_table', [
* 'id' => $this->primaryKey(),
* 'name' => $this->string(64)->notNull(),
* 'type' => $this->integer()->notNull()->defaultValue(10),
* 'description' => $this->text(),
* 'rule_name' => $this->string(64),
* 'data' => $this->text(),
* 'CreatedDateTime' => $this->datetime()->notNull(),
* 'LastModifiedDateTime' => $this->datetime(),
* ]);
* ```
*
* @author Vasenin Matvey <vaseninm@gmail.com>
* @since 2.0.6
*/
trait SchemaBuilderTrait
{
/**
* @return Connection the database connection to be used for schema building.
*/
protected abstract function getDb();
/**
* Creates a primary key column.
* @param integer $length column size or precision definition.
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function primaryKey($length = null)
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_PK, $length);
}
/**
* Creates a big primary key column.
* @param integer $length column size or precision definition.
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function bigPrimaryKey($length = null)
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BIGPK, $length);
}
/**
* Creates a char column.
* @param integer $length column size definition i.e. the maximum string length.
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.8
*/
public function char($length = null)
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_CHAR, $length);
}
/**
* Creates a string column.
* @param integer $length column size definition i.e. the maximum string length.
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function string($length = null)
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_STRING, $length);
}
/**
* Creates a text column.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function text()
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TEXT);
}
/**
* Creates a smallint column.
* @param integer $length column size or precision definition.
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function smallInteger($length = null)
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_SMALLINT, $length);
}
/**
* Creates an integer column.
* @param integer $length column size or precision definition.
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function integer($length = null)
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_INTEGER, $length);
}
/**
* Creates a bigint column.
* @param integer $length column size or precision definition.
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function bigInteger($length = null)
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BIGINT, $length);
}
/**
* Creates a float column.
* @param integer $precision column value precision. First parameter passed to the column type, e.g. FLOAT(precision).
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function float($precision = null)
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_FLOAT, $precision);
}
/**
* Creates a double column.
* @param integer $precision column value precision. First parameter passed to the column type, e.g. DOUBLE(precision).
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function double($precision = null)
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DOUBLE, $precision);
}
/**
* Creates a decimal column.
* @param integer $precision column value precision, which is usually the total number of digits.
* First parameter passed to the column type, e.g. DECIMAL(precision, scale).
* This parameter will be ignored if not supported by the DBMS.
* @param integer $scale column value scale, which is usually the number of digits after the decimal point.
* Second parameter passed to the column type, e.g. DECIMAL(precision, scale).
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function decimal($precision = null, $scale = null)
{
$length = [];
if ($precision !== null) {
$length[] = $precision;
}
if ($scale !== null) {
$length[] = $scale;
}
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DECIMAL, $length);
}
/**
* Creates a datetime column.
* @param integer $precision column value precision. First parameter passed to the column type, e.g. DATETIME(precision).
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function dateTime($precision = null)
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DATETIME, $precision);
}
/**
* Creates a timestamp column.
* @param integer $precision column value precision. First parameter passed to the column type, e.g. TIMESTAMP(precision).
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function timestamp($precision = null)
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TIMESTAMP, $precision);
}
/**
* Creates a time column.
* @param integer $precision column value precision. First parameter passed to the column type, e.g. TIME(precision).
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function time($precision = null)
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TIME, $precision);
}
/**
* Creates a date column.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function date()
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DATE);
}
/**
* Creates a binary column.
* @param integer $length column size or precision definition.
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function binary($length = null)
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BINARY, $length);
}
/**
* Creates a boolean column.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function boolean()
{
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BOOLEAN);
}
/**
* Creates a money column.
* @param integer $precision column value precision, which is usually the total number of digits.
* First parameter passed to the column type, e.g. DECIMAL(precision, scale).
* This parameter will be ignored if not supported by the DBMS.
* @param integer $scale column value scale, which is usually the number of digits after the decimal point.
* Second parameter passed to the column type, e.g. DECIMAL(precision, scale).
* This parameter will be ignored if not supported by the DBMS.
* @return ColumnSchemaBuilder the column instance which can be further customized.
* @since 2.0.6
*/
public function money($precision = null, $scale = null)
{
$length = [];
if ($precision !== null) {
$length[] = $precision;
}
if ($scale !== null) {
$length[] = $scale;
}
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_MONEY, $length);
}
}
| microdisk/customre_website | vendor/yiisoft/yii2/db/SchemaBuilderTrait.php | PHP | bsd-3-clause | 10,360 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/** Get all roles */
$authManager = Yii::$app->authManager;
?>
<div class="user-assignment-form">
<?php $form = ActiveForm::begin(); ?>
<?= Html::activeHiddenInput($formModel, 'userId')?>
<label class="control-label"><?=$formModel->attributeLabels()['roles']?></label>
<input type="hidden" name="AssignmentForm[roles]" value="">
<table class="table table-striped table-bordered detail-view">
<thead>
<tr>
<th style="width:1px"></th>
<th style="width:150px">Name</th>
<th>Description</th>
</tr>
<tbody>
<?php foreach ($authManager->getRoles() as $role): ?>
<tr>
<?php
$checked = true;
if($formModel->roles==null||!is_array($formModel->roles)||count($formModel->roles)==0){
$checked = false;
}else if(!in_array($role->name, $formModel->roles) ){
$checked = false;
}
?>
<td><input <?= $checked? "checked":"" ?> type="checkbox" name="AssignmentForm[roles][]" value="<?= $role->name?>"></td>
<td><?= $role->name ?></td>
<td><?= $role->description ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php if (!Yii::$app->request->isAjax) { ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('rbac', 'Save'), ['class' => 'btn btn-success']) ?>
</div>
<?php } ?>
<?php ActiveForm::end(); ?>
</div>
| bara-artur/mailtousacom | modules/user/views/admin/assignment.php | PHP | bsd-3-clause | 1,440 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/simple_message_box.h"
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/message_loop/message_loop_current.h"
#include "base/run_loop.h"
#include "build/build_config.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/simple_message_box_internal.h"
#include "chrome/browser/ui/views/message_box_dialog.h"
#include "chrome/grit/generated_resources.h"
#include "components/constrained_window/constrained_window_views.h"
#include "components/startup_metric_utils/browser/startup_metric_utils.h"
#include "components/strings/grit/components_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/display/screen.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/controls/message_box_view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"
#if defined(OS_WIN)
#include "ui/base/win/message_box_win.h"
#include "ui/views/win/hwnd_util.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/ui/cocoa/simple_message_box_cocoa.h"
#endif
namespace {
#if defined(OS_WIN)
UINT GetMessageBoxFlagsFromType(chrome::MessageBoxType type) {
UINT flags = MB_SETFOREGROUND;
switch (type) {
case chrome::MESSAGE_BOX_TYPE_WARNING:
return flags | MB_OK | MB_ICONWARNING;
case chrome::MESSAGE_BOX_TYPE_QUESTION:
return flags | MB_YESNO | MB_ICONQUESTION;
}
NOTREACHED();
return flags | MB_OK | MB_ICONWARNING;
}
#endif
// static
chrome::MessageBoxResult ShowSync(gfx::NativeWindow parent,
const base::string16& title,
const base::string16& message,
chrome::MessageBoxType type,
const base::string16& yes_text,
const base::string16& no_text,
const base::string16& checkbox_text) {
chrome::MessageBoxResult result = chrome::MESSAGE_BOX_RESULT_NO;
// TODO(pkotwicz): Exit message loop when the dialog is closed by some other
// means than |Cancel| or |Accept|. crbug.com/404385
base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed);
MessageBoxDialog::Show(
parent, title, message, type, yes_text, no_text, checkbox_text,
base::BindOnce(
[](base::RunLoop* run_loop, chrome::MessageBoxResult* out_result,
chrome::MessageBoxResult messagebox_result) {
*out_result = messagebox_result;
run_loop->Quit();
},
&run_loop, &result));
run_loop.Run();
return result;
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// MessageBoxDialog, public:
// static
chrome::MessageBoxResult MessageBoxDialog::Show(
gfx::NativeWindow parent,
const base::string16& title,
const base::string16& message,
chrome::MessageBoxType type,
const base::string16& yes_text,
const base::string16& no_text,
const base::string16& checkbox_text,
MessageBoxDialog::MessageBoxResultCallback callback) {
if (!callback)
return ShowSync(parent, title, message, type, yes_text, no_text,
checkbox_text);
startup_metric_utils::SetNonBrowserUIDisplayed();
if (chrome::internal::g_should_skip_message_box_for_test) {
std::move(callback).Run(chrome::MESSAGE_BOX_RESULT_YES);
return chrome::MESSAGE_BOX_RESULT_DEFERRED;
}
// Views dialogs cannot be shown outside the UI thread message loop or if the
// ResourceBundle is not initialized yet.
// Fallback to logging with a default response or a Windows MessageBox.
#if defined(OS_WIN)
if (!base::MessageLoopCurrentForUI::IsSet() ||
!base::RunLoop::IsRunningOnCurrentThread() ||
!ui::ResourceBundle::HasSharedInstance()) {
LOG_IF(ERROR, !checkbox_text.empty()) << "Dialog checkbox won't be shown";
int result = ui::MessageBox(views::HWNDForNativeWindow(parent), message,
title, GetMessageBoxFlagsFromType(type));
std::move(callback).Run((result == IDYES || result == IDOK)
? chrome::MESSAGE_BOX_RESULT_YES
: chrome::MESSAGE_BOX_RESULT_NO);
return chrome::MESSAGE_BOX_RESULT_DEFERRED;
}
#elif defined(OS_MACOSX)
if (!base::MessageLoopCurrentForUI::IsSet() ||
!base::RunLoop::IsRunningOnCurrentThread() ||
!ui::ResourceBundle::HasSharedInstance()) {
// Even though this function could return a value synchronously here in
// principle, in practice call sites do not expect any behavior other than a
// return of DEFERRED and an invocation of the callback.
std::move(callback).Run(
chrome::ShowMessageBoxCocoa(message, type, checkbox_text));
return chrome::MESSAGE_BOX_RESULT_DEFERRED;
}
#else
if (!base::MessageLoopCurrentForUI::IsSet() ||
!ui::ResourceBundle::HasSharedInstance() ||
!display::Screen::GetScreen()) {
LOG(ERROR) << "Unable to show a dialog outside the UI thread message loop: "
<< title << " - " << message;
std::move(callback).Run(chrome::MESSAGE_BOX_RESULT_NO);
return chrome::MESSAGE_BOX_RESULT_DEFERRED;
}
#endif
bool is_system_modal = !parent;
#if defined(OS_MACOSX)
// Mac does not support system modals, so never ask MessageBoxDialog to
// be system modal.
is_system_modal = false;
#endif
MessageBoxDialog* dialog = new MessageBoxDialog(
title, message, type, yes_text, no_text, checkbox_text, is_system_modal);
views::Widget* widget =
constrained_window::CreateBrowserModalDialogViews(dialog, parent);
#if defined(OS_MACOSX)
// Mac does not support system modal dialogs. If there is no parent window to
// attach to, move the dialog's widget on top so other windows do not obscure
// it.
if (!parent)
widget->SetZOrderLevel(ui::ZOrderLevel::kFloatingWindow);
#endif
widget->Show();
dialog->Run(std::move(callback));
return chrome::MESSAGE_BOX_RESULT_DEFERRED;
}
void MessageBoxDialog::OnDialogAccepted() {
if (!message_box_view_->HasCheckBox() ||
message_box_view_->IsCheckBoxSelected()) {
Done(chrome::MESSAGE_BOX_RESULT_YES);
} else {
Done(chrome::MESSAGE_BOX_RESULT_NO);
}
}
base::string16 MessageBoxDialog::GetWindowTitle() const {
return window_title_;
}
void MessageBoxDialog::DeleteDelegate() {
delete this;
}
ui::ModalType MessageBoxDialog::GetModalType() const {
return is_system_modal_ ? ui::MODAL_TYPE_SYSTEM : ui::MODAL_TYPE_WINDOW;
}
views::View* MessageBoxDialog::GetContentsView() {
return message_box_view_;
}
bool MessageBoxDialog::ShouldShowCloseButton() const {
return true;
}
void MessageBoxDialog::OnWidgetActivationChanged(views::Widget* widget,
bool active) {
if (!active)
GetWidget()->Close();
}
////////////////////////////////////////////////////////////////////////////////
// MessageBoxDialog, private:
MessageBoxDialog::MessageBoxDialog(const base::string16& title,
const base::string16& message,
chrome::MessageBoxType type,
const base::string16& yes_text,
const base::string16& no_text,
const base::string16& checkbox_text,
bool is_system_modal)
: window_title_(title),
type_(type),
message_box_view_(new views::MessageBoxView(
views::MessageBoxView::InitParams(message))),
is_system_modal_(is_system_modal) {
SetButtons(type_ == chrome::MESSAGE_BOX_TYPE_QUESTION
? ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL
: ui::DIALOG_BUTTON_OK);
SetAcceptCallback(base::BindOnce(&MessageBoxDialog::OnDialogAccepted,
base::Unretained(this)));
SetCancelCallback(base::BindOnce(&MessageBoxDialog::Done,
base::Unretained(this),
chrome::MESSAGE_BOX_RESULT_NO));
SetCloseCallback(base::BindOnce(&MessageBoxDialog::Done,
base::Unretained(this),
chrome::MESSAGE_BOX_RESULT_NO));
base::string16 ok_text = yes_text;
if (ok_text.empty()) {
ok_text =
type_ == chrome::MESSAGE_BOX_TYPE_QUESTION
? l10n_util::GetStringUTF16(IDS_CONFIRM_MESSAGEBOX_YES_BUTTON_LABEL)
: l10n_util::GetStringUTF16(IDS_OK);
}
SetButtonLabel(ui::DIALOG_BUTTON_OK, ok_text);
// Only MESSAGE_BOX_TYPE_QUESTION has a Cancel button.
if (type_ == chrome::MESSAGE_BOX_TYPE_QUESTION) {
base::string16 cancel_text = no_text;
if (cancel_text.empty())
cancel_text = l10n_util::GetStringUTF16(IDS_CANCEL);
SetButtonLabel(ui::DIALOG_BUTTON_CANCEL, cancel_text);
}
if (!checkbox_text.empty())
message_box_view_->SetCheckBoxLabel(checkbox_text);
chrome::RecordDialogCreation(chrome::DialogIdentifier::SIMPLE_MESSAGE_BOX);
}
MessageBoxDialog::~MessageBoxDialog() {
GetWidget()->RemoveObserver(this);
}
void MessageBoxDialog::Run(MessageBoxResultCallback result_callback) {
GetWidget()->AddObserver(this);
result_callback_ = std::move(result_callback);
}
void MessageBoxDialog::Done(chrome::MessageBoxResult result) {
CHECK(!result_callback_.is_null());
std::move(result_callback_).Run(result);
}
views::Widget* MessageBoxDialog::GetWidget() {
return message_box_view_->GetWidget();
}
const views::Widget* MessageBoxDialog::GetWidget() const {
return message_box_view_->GetWidget();
}
namespace chrome {
void ShowWarningMessageBox(gfx::NativeWindow parent,
const base::string16& title,
const base::string16& message) {
MessageBoxDialog::Show(parent, title, message,
chrome::MESSAGE_BOX_TYPE_WARNING, base::string16(),
base::string16(), base::string16());
}
void ShowWarningMessageBoxWithCheckbox(
gfx::NativeWindow parent,
const base::string16& title,
const base::string16& message,
const base::string16& checkbox_text,
base::OnceCallback<void(bool checked)> callback) {
MessageBoxDialog::Show(parent, title, message,
chrome::MESSAGE_BOX_TYPE_WARNING, base::string16(),
base::string16(), checkbox_text,
base::BindOnce(
[](base::OnceCallback<void(bool checked)> callback,
MessageBoxResult message_box_result) {
std::move(callback).Run(message_box_result ==
MESSAGE_BOX_RESULT_YES);
},
base::Passed(std::move(callback))));
}
MessageBoxResult ShowQuestionMessageBox(gfx::NativeWindow parent,
const base::string16& title,
const base::string16& message) {
return MessageBoxDialog::Show(
parent, title, message, chrome::MESSAGE_BOX_TYPE_QUESTION,
base::string16(), base::string16(), base::string16());
}
MessageBoxResult ShowMessageBoxWithButtonText(gfx::NativeWindow parent,
const base::string16& title,
const base::string16& message,
const base::string16& yes_text,
const base::string16& no_text) {
return MessageBoxDialog::Show(parent, title, message,
chrome::MESSAGE_BOX_TYPE_QUESTION, yes_text,
no_text, base::string16());
}
} // namespace chrome
| endlessm/chromium-browser | chrome/browser/ui/views/message_box_dialog.cc | C++ | bsd-3-clause | 12,172 |
<?php
session_start();
// ---------------- PRE DEFINED VARIABLES ---------------- //
if ($_SESSION['user_name']=='') {
$user_name_session = $_POST['id'];
echo "no session set";
} else {
$user_name_session = $_SESSION['user_name'];
}
//print_r($user_name_session);
include_once('/kunden/homepages/0/d643120834/htdocs/config/index.php');
$db = new UserDashboard($_SESSION);
// $user = $db->getUserData($user_name_session);
// //print_r($user);
// $user['stats']['total'] = $db->getUserStats($user_name_session , 'total');
// $user['stats']['total'] = $db->getUserStats($user_name_session , 'fans');
// $user['id'] = $user['user_id'];
// $user['photo'] = $db->getProfilePhoto($user_name_session);
// $user['profile_url'] = 'http://freela.be/l/'.$user['user_name'];
// $user['media']['audio'] = $db->getUserMedia($user_name_session); // Grab Users Posts
// $user['stats']['tracks'] = count($user['media']['audio']);
// $user['twitter'] = $user['media']['audio'][0]['twitter'];
// ------ data fixes ------- //
if (isset($user['photo']) && $user['photo']!='' ) {
$profile_image = '<img src="'.$user['photo'].'" alt="'.$user['photo'].'" style="width:100%;">';
} else {
if (strpos($user['media']['audio'][0]['photo'], 'http://')) {
$media = 'http://freelabel.net/images/'.$user['media']['audio'][0]['photo'];
//echo 'I needs to be formated';
} else {
$media = $user['media']['audio'][0]['photo'];
//echo 'it doesnt need to be!!';
}
$profile_image = '<img src="'.$media.'" alt="from-media-'.$media.'" style="width:100%;">';
}
if ($user['custom']==''){
$user['custom'] = $db->getCustomData($user);
}
//print_r($user['media']['audio']);
//exit;
//print_r($user['user_name']);
//exit;
//echo '<hr><hr><hr>';
//print_r();
//$user_name_session = $user['user_name'];
//echo 'THEUSERER: '.$user_name_session.'<hr>';
$todays_date = date('Y-m-d');
$dashboard_options = '
<div class="btn-group-vertical dashboard-navigation " style="width:100%;">
<a onclick="loadPage(\'http://freelabel.net/submit/views/db/recent_posts.php\', \'#dashboard_view_panel\', \'dashboard\', \''.$user_name_session.'\')" class="btn btn-default btn-lg"><span class="glyphicon glyphicon-dashboard"></span> - Dashboard</a>
<a href="http://freelabel.net/@'.strtolower($user['twitter']).'" class="btn btn-default btn-lg" target="_blank" ><span class="glyphicon glyphicon-user"></span> - View Profile</a>
<a href="#music" onclick="loadPage(\'http://freelabel.net/submit/views/single_uploader.php\', \'#dashboard_view_panel\', \'dashboard\', \''.$user_name_session.'\')" class="btn btn-default btn-lg"><span class="glyphicon glyphicon-music"></span> - Music</a>
<a href="#photos" onclick="loadPage(\'http://freelabel.net/submit/views/db/user_photos.php\', \'#dashboard_view_panel\', \'dashboard\', \''.$user_name_session.'\')" class="btn btn-default btn-lg"><span class="glyphicon glyphicon-picture"></span> - Photos</a>
<a href="#videos" onclick="loadPage(\'http://freelabel.net/submit/views/db/video_saver.php\', \'#dashboard_view_panel\', \'dashboard\', \''.$user_name_session.'\')" class="btn btn-default btn-lg"><span class="glyphicon glyphicon-film"></span> - Videos</a>
<a href="#schedule" onclick="loadPage(\'http://freelabel.net/submit/views/db/showcase_schedule.php\', \'#dashboard_view_panel\', \'dashboard\', \''.$user_name_session.'\')" class="btn btn-default btn-lg"><span class="glyphicon glyphicon-calendar"></span> - Schedule</a>
<a href="#howtouse" onclick="loadPage(\'http://freelabel.net/submit/views/db/howtouse.php\', \'#dashboard_view_panel\', \'dashboard\', \''.$user_name_session.'\')" class="btn btn-default btn-lg" ><span class="glyphicon glyphicon-question-sign"></span> - How To Use</a>
<a href="#email" onclick="loadPage(\'http://freelabel.net/test/send_email.php\', \'#dashboard_view_panel\', \'dashboard\', \''.$user_name_session.'\')" class="btn btn-default btn-lg" ><span class="glyphicon glyphicon-envelope"></span> - Contact Support</a>
<a href="http://freelabel.net/submit/index.php?logout" class="btn btn-danger btn-lg" ><span class="glyphicon glyphicon-log-out"></span> - Logout</a>
';
$admin_options = "
<hr>
<h3>Admin Only:</h3>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/blog_poster.php', '#main_display_panel', 'dashboard', 'admin')\" class='btn btn-warning btn-lg'> <span class='glyphicon glyphicon-pencil'></span>Post</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/lead_conversion.php', '#main_display_panel', 'dashboard', 'admin')\" class='btn btn-warning btn-lg'> <span class='glyphicon glyphicon-usd'></span>Clients</a>
<a onclick=\"loadPage('http://freelabel.net/twitter/index.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-warning btn-lg'> <span class='glyphicon glyphicon-comment'></span>Twitter</a>
<a onclick=\"loadPage('http://freelabel.net/x/s.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-warning btn-lg'><span class='glyphicon glyphicon-list-alt'></span>Script</a>
<hr>
<h4>Soon-To-Be-Launched</h4>
<a onclick=\"loadPage('http://freelabel.net/twitter/index.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-warning btn-lg'> <span class='glyphicon glyphicon-comment'></span>Respond</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/blog_poster.php', '#main_display_panel', 'dashboard', 'admin')\" class='btn btn-warning btn-lg'> <span class='glyphicon glyphicon-usd'></span>Release</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/current_clients.php', '#main_display_panel', 'dashboard', 'admin')\" class='btn btn-warning btn-lg'> <span class='glyphicon glyphicon-pencil'></span>Reproduce</a>
<hr>
<h4>Still Testing</h4>
<a onclick=\"loadPage('http://freelabel.net/upload/index.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-warning btn-lg'>Uploader</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/uploadedsingles.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-warning btn-lg'>Payouts</a>
<a onclick=\"loadPage('http://freelabel.net/tweeter.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-warning btn-lg'>Saved</a>
<a onclick=\"loadPage('http://freelabel.net/tweeter.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-warning btn-lg'>Saved</a>
<a onclick=\"loadPage('http://freelabel.net/FullWidthTabs/index.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-warning btn-lg'>Full Width</a>";
$update_successful = '<script type="text/javascript">
function redirectToSite() {
alert("Your Changes Have Been Saved! Now Returning you to your Dashboard..");
window.location.assign("http://freelabel.net/submit/")
}
</script>';
$profile_builder_form = '<div class="create_profile_form_wrapper">';
//$profile_builder_form .= '<h3 >Hello, '.$user_name_session.'! </h3>';
$profile_builder_form .= '<div class="label label-warning" role="alert">You\'ll need to finish completing all the additional information regarding creating your profile, '.$user_name_session.'! </div>';
//$profile_builder_form .= '<div class="alert alert-warning" role="alert">You\'ll need to <a href="#" class="alert-link">make your payment</a> before we can get you booked in rotation!</div>';
$profile_builder_form .= "
<form name='profile_builder_form' action='http://freelabel.net/submit/views/db/campaign_info.php' method='post' enctype=\"multipart/form-data\" class='profile_builder_form panel-body row' >
<h1>Complete Profile</h1>
<p class='section-description text-muted' >Use this form to complete your FREELABEL Profile. We will use this information to build your campaign as well as tag you during promotional campaigns!</p>
<div class='col-md-3 col-sm-6' >
<h4><i class='fa fa-photo' ></i> Upload Profile Photo</h4><input type='file' class='form-control' name='photo' required>
</div>
<div class='col-md-3 col-sm-6' >
<h4><i class='fa fa-comment'></i> Display Name</h4>
<input type='text' class='form-control' name='artist_name' placeholder='What is your Artist or Brand Name?' required>
</div>
<div class='col-md-3 col-sm-6' >
<h4><i class='fa fa-map-marker'></i> Location</h4>
<input type='text' class='form-control' name='artist_location' placeholder='Where are you from?' required>
</div>
<div class='col-md-3 col-sm-6' >
<h4><i class='fa fa-users'></i> Brand or Management <small>(optional)</small></h4>
<input type='text' class='form-control' name='artist_location' placeholder='Enter management contact information (Name, Phone, Email, etc..)' >
</div>
<div class='col-md-12'>
<h4><i class='fa fa-book'></i> Artist Bio</h4><br>
<textarea name='artist_description' class='form-control' rows='4' cols='53' placeholder='Tell us a little (or alot) about yourself..'></textarea>
</div>
<h1>Link Social Media</h1>
<div class=' col-md-4 col-sm-6' >
<h4><i class='fa fa-twitter'></i> Twitter</h4>
<input type='text' class='form-control' name='artist_twitter' placeholder='Enter your Twitter username.. (include \"@\" sign)' required >
</div>
<div class=' col-md-4 col-sm-6' >
<h4><i class='fa fa-instagram'></i> Instagram <small>(optional)</small></h4>
<input type='text' class='form-control' name='artist_twitter' placeholder='Enter Your Instagram Username.. (include \"@\" sign)' >
</div>
<div class=' col-md-4 col-sm-6' >
<h4><i class='fa fa-soundcloud'></i> Soundcloud <small>(optional)</small></h4>
<input type='text' class='form-control' name='artist_twitter' placeholder='Enter Your Soundcloud Username.. (include \"@\" sign)' >
</div>
<div class=' col-md-4 col-sm-6' >
<h4><i class='fa fa-youtube'></i> Youtube <small>(optional)</small></h4>
<input type='text' class='form-control' name='artist_twitter' placeholder='Enter Your Youtube Username.. (include \"@\" sign)' >
</div>
<div class=' col-md-4 col-sm-6' >
<h4><i class='fa fa-paypal'></i> Paypal <small>(optional)</small></h4>
<input type='text' class='form-control' name='artist_twitter' placeholder='Enter Your Paypal Email..' >
</div>
<div class=' col-md-4 col-sm-6' >
<h4><i class='fa fa-snapchat'></i> Snapchat <small>(optional)</small></h4>
<input type='text' class='form-control' name='artist_twitter' placeholder='Enter Your Paypal Email..' >
</div>
<div class='col-md-12'>
<input name='update_profile' type='submit' class='btn btn-warning complete-profile-button' value='SAVE PROFILE'>
</div>
<input type='hidden' name='id' value='".$user_name_session."' >
<input type='hidden' name='update_profile'>
<br>
</form>
<hr>
</div>";
$confirm_profile = "
<h2 id='subtitle'>Confirm Profile!</h2>
<div id='body'>
<h2>Make sure your information is correct before we make these changes to your profile!</h2>
<br><br>
<table id='body'>
<tr>
<td>
<img id='preview_photo' src='".$full_photo_path."'>
</td>
<td>
<span id='sub_label' >Arist Name:</span> <span id='pricing1' >".$artist_name."</span><br>
<span id='sub_label' >Twitter UserName:</span> <span id='pricing1' >".$artist_twitter."</span><br>
<span id='sub_label' >Artist Location:</span> <span id='pricing1' >".$artist_location."</span><br>
<h3>Description:</h3><br>
".$artist_description."
<center>
<button class='confirm_update' type='button' onclick='redirectToSite()'>SAVE CHANGES TO PROFILE</button>
</center>
</td>
</tr>
</table>
<br><br>
</div>";
?>
<style type="text/css">
#preview_photo {
width:400px;
vertical-align: text-top;
}
#profile_builder_form {
width:300px;
}
.download_button {
display:block;
}
.create_profile_form_wrapper h3 {
color:#101010;
}
.uploaded_singles {
border-radius:0px;
}
.more-options-button {
display:none;
}
.events-panel {
text-align: left;
}
.dashboard-panel {
min-height: 50vh;
}
.db-details {
color:#303030;
font-size: 0.75em;
}
.overflow {
max-height:300px;
overflow-y:scroll;
}
.profile_builder_form input, .profile_builder_form textarea, .profile_builder_form select, .profile_builder_form option {
font-size: 125%;
padding:2.5%;
margin-bottom:2.5%;
}
.complete-profile-button {
margin:auto;
display:block;
}
.form-section-title h3 {
color:#e3e3e3;
}
.events-panel {
padding-bottom:0px;
margin-bottom:4%;
border-bottom:2px solid #101010;
}
.overflow, .dashboard-profile-details {
min-height: 80vh;
}
.events-panel .overflow {
height:80vh;
}
</style>
<script type="text/javascript">
$(function(){
var pleaseWait = 'Please wait..';
$('.more-options-button').click(function(){
$('.more-options').slideToggle('fast');
});
$('#edit-default-pxhoto').change(function() {
// ------ NEW NEW NEW NEW ------ //
$('.photo-upload-results').html(' ');
$('#edit-default-photo').append(pleaseWait);
//$('.confirm-upload-buttons').prepend('<p class="wait" style="color:#303030;">Please wait..<p>');
//$('.confirm-upload-buttons').hide('fast');
var path = 'submit/updateprofile.php';
var data;
var formdata_PHO = $('#edit-default-photo')[0].files[0];
var formdata = new FormData();
// Add the file to the request.
formdata.append('photos[]', formdata_PHO);
//var formdata = $('#single_upload_form').serialize();
//console.log(formdata_PHO);
//alert(formdata_PHO);
$.ajax({
// Uncomment the following to send cross-domain cookies:
xhrFields: {withCredentials: true},
url: path,
//dataType: 'json',
method: 'POST',
cache : false,
processData: false,
contentType: false,
fileElementId: 'image-upload',
data: formdata,
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("multipart/form-data");
}
},
// Now you should be able to do this:
mimeType: 'multipart/form-data' //Property added in 1.5.1
}).always(function () {
//alert(formdata_PHO);
console.log(formdata_PHO);
//$('#confirm_upload').html('please wait..');
//$(this).removeClass('fileupload-processing');
}).fail(function(jqXHR){
alert(jqXHR.statusText + 'oh no it didnt work!')
}).done(function (result) {
//alert('YES');
$('.edit-default-form').append(result);
//$('.confirm-upload-buttons').show('fast');
// $('.confirm-upload-buttons').css('opacity',1);
//$('.wait').hide('fast');
})
});
});
function showPhotoOptions(id) {
//alert(id);
$('.edit-profile-block').slideToggle('fast');
}
</script>
<?php
// IF ARTIST PROFILE EXISTS, SHOW PANELS
include(ROOT.'inc/connection.php');
if ($user_name == false) {
$user_name = 'no username';
}
// ------------------------------------------------------- //
// CHECK IF EXISTS IN ARTIST WEBSITE DATABASE
// ------------------------------------------------------- //
$sql ="SELECT * FROM user_profiles WHERE id='".$user_name_session."'";
$result = mysqli_query($con,$sql);
if($row = mysqli_fetch_array($result))
{
// ------------------------------------------------------- //
// IF EXISTS, DISPLAY FULL USER DATA & CONTROL OPTIONS
// ------------------------------------------------------- //
// PROFILE IMAGE
$profile_info = '
<a target="_blank" href="'.$user['profile_url'].'">'.$profile_image.'</a>';
$profile_options.="
<!--
<a onclick=\"loadPage('http://freelabel.net/mag/pull_mag.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-default lead_control'><span class=\"glyphicon glyphicon-signal\"></span>Feed</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/user_photos.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-default lead_control'><span class=\"glyphicon glyphicon-picture\"></span>Photos</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/recent_posts.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-default lead_control'><span class=\"glyphicon glyphicon-envelope\"></span>Messages</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/recent_uploads.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-default lead_control'><span class=\"glyphicon glyphicon-envelope\"></span>Notifications</a>
-->
<a class='btn btn-default lead_control' href='".$user['profile_url']."' target='_blank' ><span class=\"glyphicon glyphicon-phone\"></span>View Website</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/recent_posts.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-default lead_control'><span class=\"glyphicon glyphicon-cloud-upload\"></span>Your Uploads</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/showcase_schedule.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-default lead_control'><span class=\"glyphicon glyphicon-calendar\"></span>Your Schedule</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/howtouse.php', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-default lead_control'><span class=\"glyphicon glyphicon-shopping-cart\"></span>Help</a>
<a class='btn btn-default lead_control more-options-button'><span class=\"glyphicon glyphicon-cog\"></span>Settings</a>
<div class='more-options' style='display:none;'>
".$user['custom']."
</div>
";
$profile_info.='
<div class="" id="dashboard_profile_photo" >
<!--<h5 class="sub_title" >http://FREELA.BE/L/'.$user_name_session.'</h5>-->
';
/*$profile_info .= "
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/lead_conversion.php?leads=today', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-default lead_control'><span class=\"glyphicon glyphicon-usd\"></span>Leads</a>
<a class='btn btn-default lead_control' onclick=\"loadPage('http://freelabel.net/rssreader/cosign.php?control=update&rss=1', '#main_display_panel', 'mag')\" ><span class=\"glyphicon glyphicon-usd\"></span>RSS</a>
<a class='btn btn-default lead_control schedule' onclick=\"loadWidget('schedule')\"><span class=\"glyphicon glyphicon-usd\"></span>Schedule</a>
<a class='btn btn-default lead_control twitter' onclick=\"loadWidget('twitter')\"><span class=\"glyphicon glyphicon-usd\"></span>Twitter</a>
<a class='btn btn-default lead_control submissions' onclick=\"loadWidget('submissions')\"><span class=\"glyphicon glyphicon-usd\"></span>Submissions</a>
<a class='btn btn-default lead_control clients' onclick=\"loadWidget('clients')\"><span class=\"glyphicon glyphicon-usd\"></span>Clients</a>
<a onclick=\"loadPage('http://freelabel.net/x/s.php', '#lead_widget_container', 'dashboard', 'admin')\" class='btn btn-default lead_control'><span class='glyphicon glyphicon-list-alt'></span>Script</a>";*/
/*
$profile_info .= "
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/lead_conversion.php?leads=today', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-default lead_control'><span class=\"glyphicon glyphicon-signal\"></span>Feed</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/lead_conversion.php?leads=today', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-default lead_control'><span class=\"glyphicon glyphicon-envelope\"></span>Messages</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/lead_conversion.php?leads=today', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-default lead_control'><span class=\"glyphicon glyphicon-envelope\"></span>Notifications</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/lead_conversion.php?leads=today', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-default lead_control'><span class=\"glyphicon glyphicon-music\"></span>Audio</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/lead_conversion.php?leads=today', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-default lead_control'><span class=\"glyphicon glyphicon-picture\"></span>Photos</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/lead_conversion.php?leads=today', '#main_display_panel', 'dashboard', '".$user_name_session."')\" class='btn btn-default lead_control'><span class=\"glyphicon glyphicon-shopping-cart\"></span>Products</a>
<a class='btn btn-default lead_control' onclick=\"loadPage('http://freelabel.net/rssreader/cosign.php?control=update&rss=1', '#main_display_panel', 'mag')\" ><span class=\"glyphicon glyphicon-calendar\"></span>Schedule</a>
<a class='btn btn-default lead_control' href='http://freelabel.net/x/?i=".$user_name_session."' target='_blank' ><span class=\"glyphicon glyphicon-user\"></span>View Website</a>
";*/
$profile_info .= '
<div class="panel-body profile_default_options">
<a onclick="showPhotoOptions('.$user['user_id'].')" class=\'btn btn-default btn-xs col-md-6\' id="update_photo_button"> <span class="glyphicon glyphicon-pencil"></span>Change Default</a>
<!--<a onclick="loadPage(\'http://freelabel.net/submit/views/db/user_photos.php\', \'#main_display_panel\', \'dashboard\', \''.$user_name_session.'\')" class=\'btn btn-default btn-xs col-md-6\'> <span class="glyphicon glyphicon-plus"></span>Photos</a>-->
<div id=\'dashboard_navigation\' style=\'margin-top:5%;display:none;\' >
<!--<a class=\'btn btn-primary\' href="http://freelabel.net/submit/" style=\'display:none;\'>Artist Control Panel</a>
<a class=\'btn btn-primary\' href="edit.php">View Profile</a>
<a class=\'btn btn-primary\' href="edit.php">'.WORDING_EDIT_USER_DATA.'</a>
<a class=\'btn btn-danger\' href="../index.php?logout">'.WORDING_LOGOUT.'</a>-->
</div>
</div>
<div class="edit-profile-block" style="display:none;background-color:#e3e3e3;border-radius:10px;padding:2% 1%" >
<form action="http://freelabel.net/submit/updateprofile.php" method="POST" enctype="multipart/form-data" class="edit-default-form">
<span id="photo-upload-results" ></span>
<input type="file" name="file" id="edit-default-photo">
<br>
<input type="hidden" name="user_name" value="'.$user['user_name'].'">
<input type="hidden" name="user_id" value="'.$user['user_id'].'">
<input type="submit" value="UPDATE PHOTO" class="btn btn-primary">
</form>
</div>
</div>';
/*echo "
<div class=''>
<!--<h1 class='panel-heading'>Uploads</h1>-->
<nav class='panel-body upload_buttons'>
<a onclick=\"window.open('http://upload.freelabel.net/?uid=". $user_name_session. "')\" class='btn btn-success btn-lg col-md-3'> <span class=\"glyphicon glyphicon-plus\"></span>Upload</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/user_photos.php', '#main_display_panel', 'dashboard', '". $user_name_session. "')\" class='btn btn-warning btn-lg col-md-3'> <span class=\"glyphicon glyphicon-camera\"></span>Photos</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/recent_posts.php', '#main_display_panel', 'dashboard', '". $user_name_session. "')\" class='btn btn-warning btn-lg col-md-3'> <span class=\"glyphicon glyphicon-music\"></span>Music</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/video_saver.php', '#recent_post_wrapper', 'dashboard', '". $user_name_session. "','','facetime-video')\" class='btn btn-warning btn-lg col-md-3'> <span class=\"glyphicon glyphicon-facetime-video\"></span>Videos</a>
<!--
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/recent_posts.php?control=blog&view=all#blog_posts', '#main_display_panel', 'dashboard', '". $user_name_session. "')\" class='btn btn-default btn-lg col-md-2' >All</a>
<a onclick=\"loadPage('http://freelabel.net/submit/views/db/recent_posts.php?control=blog&view=all#blog_posts', '#main_display_panel', 'dashboard', '". $user_name_session. "')\" class='btn btn-default btn-lg col-md-2' >Recent</a>
<a href='http://freelabel.net/?ctrl=trx&view=submissions#blog_posts' style='display:none;' class='btn btn-default btn-lg col-md-2' >Submissions</a>
-->
</nav>
</div>";*/
echo $upload_options;
echo '<div class="row user-dashboard-panel">';
echo '<div class="col-md-4 col-sm-4 dashboard-profile-details">';
echo $profile_info;
echo $profile_options;
echo '</div>';
echo '<div class="col-md-8 col-sm-8">';
echo '<div class="panel-body col-md-10 col-xs-10 dashboard-panel events-panel ">';
//echo '<h4 class="section_title" style="text-align:left;">Events</h4>';
echo '<div class="overflow" >';
include(ROOT.'submit/views/db/showcase_schedule.php');
echo '</div>';
echo '</div>';
echo '<div class="panel-body col-md-2 col-xs-2 dashboard-panel uploaded_singles">';
echo '<h3 class="db-details">Total Views:<h3> '.$user['stats']['total'];
echo '<h3 class="db-details">Tracks:<h3> '.$user['stats']['tracks'];
//echo 'Total Fans: '.$user['stats'];
//$user_media = $user['media']['audio'];
//include(ROOT.'submit/views/uploadedsingles.php');
echo '</div>';
echo '</div>';
echo '</div>';
// FULL ADMIN DASHBOARD PANEL
$i=0;
if ($user_name_session == 'admin'
OR $user_name_session == 'mayoalexander'
//OR $user_name_session == 'sierra'
OR $user_name_session == 'sales'
OR $user_name_session == 'Mia'
OR $user_name_session == 'nickhustle'
//OR $user_name_session == 'ghost'
) {
$i=1;
//echo $admin_options;
}
// BLOGGER DASHBOARD NAVIGATION
if ($user_name_session == 'sierra'
OR $user_name_session == 'siralexmayo'
OR $user_name_session == 'KingMilitia' ) {
$i=1;
echo $blogger_options;
}
if ($i!=1) {
echo '</div>';
}
} else {
/* --------------------------------------------
IF NOT EXISTING IN DATABASE, DISPLAY FORM OR SAVE FORM DATA
--------------------------------------------*/
if (isset($_POST["update_profile"])) {
// echo 'it worked';
// include('../../../header.php');
//echo '<pre>';
//print_r($_POST);
$profile_data['id'] = $_POST['id'];
$profile_data['name'] = $_POST['artist_name'];
$profile_data['twitter'] = $_POST['artist_twitter'];
$profile_data['location'] = $_POST['artist_location'];
$profile_data['description'] = $_POST['artist_description'];
$profile_data['photo'] = $_POST['photo'];
$profile_data['profile_url'] = $_POST['id'];
$profile_data['photo'] = $_POST['id'];
$profile_data['date_created'] = $_POST['id'];
$id = $_POST['id'];
$artist_name = $_POST['artist_name'];
$artist_twitter = $_POST['artist_twitter'];
// TWITTERFIX
$artist_twitter = str_replace('@@', '@', $artist_twitter);
$artist_twitter = str_replace('@@@', '@', $artist_twitter);
$artist_location = $_POST['artist_location'];
$artist_description = $_POST['artist_description'];
$photo = $_POST['photo'];
$tmp_name = $_FILES["photo"]["tmp_name"];
$ext_arr = explode('.',$_FILES["photo"]["name"]);
$ext_arr = array_reverse($ext_arr);
$ext = $ext_arr[0];
$name = $_FILES["photo"]["name"];
$photo_path = "uploads/".$profile_data['id'].'-'.rand(1111111111,9999999999).'.'.$ext;
$photo_path_save = "../../".$photo_path;
$full_photo_path = "http://freelabel.net/submit/".$photo_path;
//$profile_img_exists = getimagesize($full_photo_path);
$profile_url = 'http://FREELA.BE/'.strtolower($profile_data['id']);
//echo '<pre>';
//print_r($_FILES);
//print_r($photo_path_save);
//exit;
move_uploaded_file($tmp_name, $photo_path_save );
// CONFIRM PROFILE
//echo 'PROFILE UPDATED!';
// CREATE PROFILE
include('../../../inc/connection.php');
// Insert into database
$sql='INSERT INTO `amrusers`.`user_profiles` (
`id` ,
`name` ,
`twitter` ,
`location` ,
`description` ,
`photo`,
`profile_url`,
`date_created`
)
VALUES (
"'.$id.'", "'.$artist_name.'", "'.$artist_twitter.'", "'.$artist_location.'", "'.$artist_description.'", "'.$full_photo_path.'", "'.$profile_url.'", "'.$todays_date.'"
);';
if (mysqli_query($con,$sql)) {
//echo "Entry Created Successfully!";
echo '<script>
alert("Entry Created Successfully!");
window.location.assign("http://freelabel.net/users/dashboard/?ctrl=analytics");
</script>';
} else {
echo "Error creating database entry: " . mysqli_error($con);
}
//echo '<br><br><br><br><br><br>';
} else {
/* --------------------------------------------
IF NO POST DATA SENT, SHOW FORM
--------------------------------------------*/
echo $profile_builder_form;
//exit;
}
}
?>
<script type="text/javascript">
$(function(){
$('.profile_builder_form').submit(function(event){
var data = $(this).seralize();
event.preventDefault();
alert(data);
});
});
</script> | mayoalexander/fl-two | submit/views/db/campaign_info.php | PHP | bsd-3-clause | 31,569 |
#!/usr/bin/env python
import sys
def inv(s):
if s[0] == '-':
return s[1:]
elif s[0] == '+':
return '-' + s[1:]
else: # plain number
return '-' + s
if len(sys.argv) != 1:
print 'Usage:', sys.argv[0]
sys.exit(1)
for line in sys.stdin:
linesplit = line.strip().split()
if len(linesplit) == 3:
assert(linesplit[0] == 'p')
print('p ' + inv(linesplit[2]) + ' ' + linesplit[1])
elif len(linesplit) == 5:
assert(linesplit[0] == 's')
print('s ' + \
inv(linesplit[2]) + ' ' + linesplit[1] + ' ' + \
inv(linesplit[4]) + ' ' + linesplit[3] )
elif len(linesplit) == 0:
print
| hlzz/dotfiles | graphics/cgal/Segment_Delaunay_graph_Linf_2/developer_scripts/lsprotate90.py | Python | bsd-3-clause | 636 |
def test_default(cookies):
"""
Checks if default configuration is working
"""
result = cookies.bake()
assert result.exit_code == 0
assert result.project.isdir()
assert result.exception is None
| vchaptsev/cookiecutter-django-vue | tests/test_generation.py | Python | bsd-3-clause | 222 |
// Test for "sancov.py missing ...".
// First case: coverage from executable. main() is called on every code path.
// RUN: %clangxx_asan -fsanitize-coverage=func,trace-pc-guard %s -o %t -DFOOBAR -DMAIN
// RUN: rm -rf %t-dir
// RUN: mkdir -p %t-dir
// RUN: cd %t-dir
// RUN: %env_asan_opts=coverage=1:coverage_dir=%t-dir %run %t
// RUN: %sancov print *.sancov > main.txt
// RUN: rm *.sancov
// RUN: count 1 < main.txt
// RUN: %env_asan_opts=coverage=1:coverage_dir=%t-dir %run %t x
// RUN: %sancov print *.sancov > foo.txt
// RUN: rm *.sancov
// RUN: count 3 < foo.txt
// RUN: %env_asan_opts=coverage=1:coverage_dir=%t-dir %run %t x x
// RUN: %sancov print *.sancov > bar.txt
// RUN: rm *.sancov
// RUN: count 4 < bar.txt
// RUN: %sancov missing %t < foo.txt > foo-missing.txt
// RUN: sort main.txt foo-missing.txt -o foo-missing-with-main.txt
// The "missing from foo" set may contain a few bogus PCs from the sanitizer
// runtime, but it must include the entire "bar" code path as a subset. Sorted
// lists can be tested for set inclusion with diff + grep.
// RUN: diff bar.txt foo-missing-with-main.txt > %t.log || true
// RUN: not grep "^<" %t.log
// Second case: coverage from DSO.
// cd %t-dir
// RUN: %clangxx_asan -fsanitize-coverage=func,trace-pc-guard %s -o %dynamiclib -DFOOBAR -shared -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=func,trace-pc-guard %s %dynamiclib -o %t -DMAIN
// RUN: cd ..
// RUN: rm -rf %t-dir
// RUN: mkdir -p %t-dir
// RUN: cd %t-dir
// RUN: %env_asan_opts=coverage=1:coverage_dir=%t-dir %run %t x
// RUN: %sancov print %xdynamiclib_filename.*.sancov > foo.txt
// RUN: rm *.sancov
// RUN: count 2 < foo.txt
// RUN: %env_asan_opts=coverage=1:coverage_dir=%t-dir %run %t x x
// RUN: %sancov print %xdynamiclib_filename.*.sancov > bar.txt
// RUN: rm *.sancov
// RUN: count 3 < bar.txt
// RUN: %sancov missing %dynamiclib < foo.txt > foo-missing.txt
// RUN: diff bar.txt foo-missing.txt > %t.log || true
// RUN: not grep "^<" %t.log
// REQUIRES: x86-target-arch
// XFAIL: android
#include <stdio.h>
void foo1();
void foo2();
void bar1();
void bar2();
void bar3();
#if defined(FOOBAR)
void foo1() { fprintf(stderr, "foo1\n"); }
void foo2() { fprintf(stderr, "foo2\n"); }
void bar1() { fprintf(stderr, "bar1\n"); }
void bar2() { fprintf(stderr, "bar2\n"); }
void bar3() { fprintf(stderr, "bar3\n"); }
#endif
#if defined(MAIN)
int main(int argc, char **argv) {
switch (argc) {
case 1:
break;
case 2:
foo1();
foo2();
break;
case 3:
bar1();
bar2();
bar3();
break;
}
}
#endif
| youtube/cobalt | third_party/llvm-project/compiler-rt/test/asan/TestCases/Linux/coverage-missing.cc | C++ | bsd-3-clause | 2,574 |
#region License Header
// /*******************************************************************************
// * Open Behavioral Health Information Technology Architecture (OBHITA.org)
// *
// * Redistribution and use in source and binary forms, with or without
// * modification, are permitted provided that the following conditions are met:
// * * Redistributions of source code must retain the above copyright
// * notice, this list of conditions and the following disclaimer.
// * * Redistributions in binary form must reproduce the above copyright
// * notice, this list of conditions and the following disclaimer in the
// * documentation and/or other materials provided with the distribution.
// * * Neither the name of the <organization> nor the
// * names of its contributors may be used to endorse or promote products
// * derived from this software without specific prior written permission.
// *
// * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ******************************************************************************/
#endregion
namespace ProCenter.Domain.Psc
{
#region Using Statements
using System;
using Pillar.FluentRuleEngine;
using ProCenter.Domain.AssessmentModule;
using ProCenter.Domain.AssessmentModule.Rules;
#endregion
/// <summary>The PediatricSymptonChecklistRuleCollection rule collection class.</summary>
public class PediatricSymptonChecklistRuleCollection : AbstractAssessmentRuleCollection
{
private readonly IAssessmentDefinitionRepository _assessmentDefinitionRepository;
private static Guid? _pediatricSymptomCheckListAssessmentDefinitionKey;
#region Constructors and Destructors
/// <summary>Initializes a new instance of the <see cref="PediatricSymptonChecklistRuleCollection" /> class.</summary>
/// <param name="assessmentDefinitionRepository">The assessment definition repository.</param>
public PediatricSymptonChecklistRuleCollection(IAssessmentDefinitionRepository assessmentDefinitionRepository)
{
_assessmentDefinitionRepository = assessmentDefinitionRepository;
NewItemSkippingRule(() => SkipItem71250040)
.ForItemInstance<bool>("71250039")
.EqualTo(false)
.SkipItem(GetItemDefinition("71250040"));
NewRuleSet(() => ItemUpdatedRuleSet71250039, SkipItem71250040);
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the skip item71250040.
/// </summary>
/// <value>
/// The skip item71250040.
/// </value>
public IItemSkippingRule SkipItem71250040 { get; set; }
/// <summary>
/// Gets or sets the item updated rule set71250039.
/// </summary>
/// <value>
/// The item updated rule set71250039.
/// </value>
public IRuleSet ItemUpdatedRuleSet71250039 { get; set; }
#endregion
/// <summary>
/// Gets the item definition.
/// </summary>
/// <param name="itemDefinitionCode">The item definition code.</param>
/// <returns>Returns and ItemDefinition for the itemDefinitionCode if found by key.</returns>
private ItemDefinition GetItemDefinition(string itemDefinitionCode)
{
if (!_pediatricSymptomCheckListAssessmentDefinitionKey.HasValue)
{
_pediatricSymptomCheckListAssessmentDefinitionKey = _assessmentDefinitionRepository.GetKeyByCode(PediatricSymptonChecklist.AssessmentCodedConcept.Code);
}
var assessmentDefinition = _assessmentDefinitionRepository.GetByKey(_pediatricSymptomCheckListAssessmentDefinitionKey.Value);
return assessmentDefinition.GetItemDefinitionByCode(itemDefinitionCode);
}
}
}
| OBHITA/PROCenter | ProCenter.Domain.Psc/PediatricSymptonChecklistRuleCollection.cs | C# | bsd-3-clause | 4,652 |
/*
* Copyright Matt Palmer 2011-2013, All rights reserved.
*
* This code is licensed under a standard 3-clause BSD license:
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * The names of its contributors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package net.byteseek.searcher.sequence.sunday;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import net.byteseek.io.reader.Window;
import net.byteseek.io.reader.WindowReader;
import net.byteseek.matcher.bytes.ByteMatcher;
import net.byteseek.matcher.sequence.SequenceMatcher;
import net.byteseek.object.factory.DoubleCheckImmutableLazyObject;
import net.byteseek.object.factory.LazyObject;
import net.byteseek.object.factory.ObjectFactory;
import net.byteseek.searcher.SearchResult;
import net.byteseek.searcher.SearchUtils;
import net.byteseek.searcher.sequence.AbstractSequenceSearcher;
/**
*
* @author Matt Palmer
*/
public final class SundayQuickSearcher extends AbstractSequenceSearcher {
private final LazyObject<int[]> forwardInfo;
private final LazyObject<int[]> backwardInfo;
/**
* Constructs a Sunday Quick searcher given a {@link SequenceMatcher}
* to search for.
*
* @param sequence The sequence to search for.
*/
public SundayQuickSearcher(final SequenceMatcher sequence) {
super(sequence);
forwardInfo = new DoubleCheckImmutableLazyObject<int[]>(new ForwardInfoFactory());
backwardInfo = new DoubleCheckImmutableLazyObject<int[]>(new BackwardInfoFactory());
}
/**
* {@inheritDoc}
*/
@Override
public List<SearchResult<SequenceMatcher>> searchForwards(final byte[] bytes, final int fromPosition, final int toPosition) {
// Get the objects needed to search:
final int[] safeShifts = forwardInfo.get();
final SequenceMatcher sequence = getMatcher();
// Calculate safe bounds for the search:
final int length = sequence.length();
final int finalPosition = bytes.length - length;
final int lastLoopPosition = finalPosition - 1;
final int lastPosition = toPosition < lastLoopPosition?
toPosition : lastLoopPosition;
int searchPosition = fromPosition > 0?
fromPosition : 0;
// Search forwards. The loop does not check for the final
// position, as we shift on the byte after the sequence.
while (searchPosition <= lastPosition) {
if (sequence.matchesNoBoundsCheck(bytes, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
searchPosition += safeShifts[bytes[searchPosition + length] & 0xFF];
}
// Check the final position if necessary:
if (searchPosition == finalPosition &&
toPosition >= finalPosition &&
sequence.matches(bytes, finalPosition)) {
return SearchUtils.singleResult(finalPosition, sequence);
}
return SearchUtils.noResults();
}
/**
* {@inheritDoc}
*/
@Override
public List<SearchResult<SequenceMatcher>> doSearchForwards(final WindowReader reader,
final long fromPosition, final long toPosition ) throws IOException {
// Initialise
final int[] safeShifts = forwardInfo.get();
final SequenceMatcher sequence = getMatcher();
final int length = sequence.length();
long searchPosition = fromPosition;
// While there is a window to search in...
// If there is no window immediately after the sequence,
// then there is no match, since this is only invoked if the
// sequence is already crossing into another window.
Window window;
while (searchPosition <= toPosition &&
(window = reader.getWindow(searchPosition + length)) != null) {
// Initialise array search:
final byte[] array = window.getArray();
final int arrayStartPosition = reader.getWindowOffset(searchPosition + length);
final int arrayEndPosition = window.length() - 1;
final long distanceToEnd = toPosition - window.getWindowPosition() + length ;
final int finalPosition = distanceToEnd < arrayEndPosition?
(int) distanceToEnd : arrayEndPosition;
int arraySearchPosition = arrayStartPosition;
// Search fowards in the array using the reader interface to match.
// The loop does not check the final position, as we shift on the byte
// after the sequence (so would get an IndexOutOfBoundsException in the final position).
while (arraySearchPosition < finalPosition) {
if (sequence.matches(reader, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
final int shift = safeShifts[array[arraySearchPosition] & 0xFF];
searchPosition += shift;
arraySearchPosition += shift;
}
// Check final position if necessary:
if (arraySearchPosition == finalPosition ||
searchPosition == toPosition) {
if (sequence.matches(reader, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
searchPosition += safeShifts[array[arraySearchPosition] & 0xFF];
}
}
return SearchUtils.noResults();
}
/**
* {@inheritDoc}
*/
@Override
public List<SearchResult<SequenceMatcher>> searchBackwards(final byte[] bytes, final int fromPosition, final int toPosition) {
// Get objects needed to search:
final int[] safeShifts = backwardInfo.get();
final SequenceMatcher sequence = getMatcher();
// Calculate safe bounds for the search:
final int lastLoopPosition = toPosition > 1?
toPosition : 1;
final int firstPossiblePosition = bytes.length - sequence.length();
int searchPosition = fromPosition < firstPossiblePosition ?
fromPosition : firstPossiblePosition;
// Search backwards. The loop does not check the
// first position in the array, because we shift on the byte
// immediately before the current search position.
while (searchPosition >= lastLoopPosition) {
if (sequence.matchesNoBoundsCheck(bytes, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
searchPosition -= safeShifts[bytes[searchPosition - 1] & 0xFF];
}
// Check for first position if necessary:
if (searchPosition == 0 &&
toPosition < 1 &&
sequence.matches(bytes, 0)) {
return SearchUtils.singleResult(0, sequence);
}
return SearchUtils.noResults();
}
/**
* {@inheritDoc}
*/
@Override
public List<SearchResult<SequenceMatcher>> doSearchBackwards(final WindowReader reader,
final long fromPosition, final long toPosition ) throws IOException {
// Initialise
final int[] safeShifts = forwardInfo.get();
final SequenceMatcher sequence = getMatcher();
long searchPosition = fromPosition;
// While there is a window to search in...
// If there is no window immediately before the sequence,
// then there is no match, since this is only invoked if the
// sequence is already crossing into another window.
Window window;
while (searchPosition >= toPosition &&
(window = reader.getWindow(searchPosition - 1)) != null) {
// Initialise array search:
final byte[] array = window.getArray();
final int arrayStartPosition = reader.getWindowOffset(searchPosition - 1);
// Search to the beginning of the array, or the final search position,
// whichver comes first.
final long endRelativeToWindow = toPosition - window.getWindowPosition();
final int arrayEndSearchPosition = endRelativeToWindow > 0?
(int) endRelativeToWindow : 0;
int arraySearchPosition = arrayStartPosition;
// Search backwards in the array using the reader interface to match.
// The loop does not check the final position, as we shift on the byte
// before it.
while (arraySearchPosition > arrayEndSearchPosition) {
if (sequence.matches(reader, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
final int shift = safeShifts[array[arraySearchPosition] & 0xFF];
searchPosition -= shift;
arraySearchPosition -= shift;
}
// Check final position if necessary:
if (arraySearchPosition == arrayEndSearchPosition ||
searchPosition == toPosition) {
if (sequence.matches(reader, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
searchPosition -= safeShifts[array[arraySearchPosition] & 0xFF];
}
}
return SearchUtils.noResults();
}
/**
* {@inheritDoc}
*/
@Override
public void prepareForwards() {
forwardInfo.get();
}
/**
* {@inheritDoc}
*/
@Override
public void prepareBackwards() {
backwardInfo.get();
}
@Override
public String toString() {
return getClass().getSimpleName() + "[sequence:" + matcher + ']';
}
private final class ForwardInfoFactory implements ObjectFactory<int[]> {
private ForwardInfoFactory() {
}
/**
* Calculates the safe shifts to use if searching forwards.
* A safe shift is either the length of the sequence plus one, if the
* byte does not appear in the {@link SequenceMatcher}, or
* the shortest distance it appears from the end of the matcher.
*/
@Override
public int[] create() {
// First set the default shift to the length of the sequence plus one.
final int[] shifts = new int[256];
final SequenceMatcher sequence = getMatcher();
final int numBytes = sequence.length();
Arrays.fill(shifts, numBytes + 1);
// Now set specific byte shifts for the bytes actually in
// the sequence itself. The shift is the distance of each character
// from the end of the sequence, where the last position equals 1.
// Each position can match more than one byte (e.g. if a byte class appears).
for (int sequenceByteIndex = 0; sequenceByteIndex < numBytes; sequenceByteIndex++) {
final ByteMatcher aMatcher = sequence.getMatcherForPosition(sequenceByteIndex);
final byte[] matchingBytes = aMatcher.getMatchingBytes();
final int distanceFromEnd = numBytes - sequenceByteIndex;
for (final byte b : matchingBytes) {
shifts[b & 0xFF] = distanceFromEnd;
}
}
return shifts;
}
}
private final class BackwardInfoFactory implements ObjectFactory<int[]> {
private BackwardInfoFactory() {
}
/**
* Calculates the safe shifts to use if searching backwards.
* A safe shift is either the length of the sequence plus one, if the
* byte does not appear in the {@link SequenceMatcher}, or
* the shortest distance it appears from the beginning of the matcher.
*/
@Override
public int[] create() {
// First set the default shift to the length of the sequence
// (negative if search direction is reversed)
final int[] shifts = new int[256];
final SequenceMatcher sequence = getMatcher();
final int numBytes = sequence.length();
Arrays.fill(shifts, numBytes + 1);
// Now set specific byte shifts for the bytes actually in
// the sequence itself. The shift is the distance of each character
// from the start of the sequence, where the first position equals 1.
// Each position can match more than one byte (e.g. if a byte class appears).
for (int sequenceByteIndex = numBytes - 1; sequenceByteIndex >= 0; sequenceByteIndex--) {
final ByteMatcher aMatcher = sequence.getMatcherForPosition(sequenceByteIndex);
final byte[] matchingBytes = aMatcher.getMatchingBytes();
final int distanceFromStart = sequenceByteIndex + 1;
for (final byte b : matchingBytes) {
shifts[b & 0xFF] = distanceFromStart;
}
}
return shifts;
}
}
} | uzen/byteseek | src/net/byteseek/searcher/sequence/sunday/SundayQuickSearcher.java | Java | bsd-3-clause | 14,817 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use app\models\general\GeneralLabel;
/* @var $this yii\web\View */
/* @var $model app\models\RefPemohonJaringanAntarabangsa */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="ref-pemohon-jaringan-antarabangsa-form">
<p class="text-muted"><span style="color: red">*</span> <?= GeneralLabel::lapangan_mandatori ?></p>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'desc')->textInput(['maxlength' => true]) ?>
<?php $model->isNewRecord ? $model->aktif = 1: $model->aktif = $model->aktif ; ?>
<?= $form->field($model, 'aktif')->radioList(array(true=>GeneralLabel::yes,false=>GeneralLabel::no)); ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? GeneralLabel::create : GeneralLabel::update, ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| hung101/kbs | frontend/views/ref-pemohon-jaringan-antarabangsa/_form.php | PHP | bsd-3-clause | 982 |
#!/usr/bin/env python
# -*- mode: python; sh-basic-offset: 4; indent-tabs-mode: nil; coding: utf-8 -*-
# vim: tabstop=4 softtabstop=4 expandtab shiftwidth=4 fileencoding=utf-8
#
# Shell command
# Copyright 2010, Jeremy Grosser <synack@digg.com>
import argparse
import os
import sys
import clusto
from clusto import script_helper
class Console(script_helper.Script):
'''
Use clusto's hardware port mappings to console to a remote server
using the serial console.
'''
def __init__(self):
script_helper.Script.__init__(self)
def _add_arguments(self, parser):
user = os.environ.get('USER')
parser.add_argument('--user', '-u', default=user,
help='SSH User (you can also set this in clusto.conf too'
'in console.user: --user > clusto.conf:console.user > "%s")' % user)
parser.add_argument('server', nargs=1,
help='Object to console to (IP or name)')
def add_subparser(self, subparsers):
parser = self._setup_subparser(subparsers)
self._add_arguments(parser)
def run(self, args):
try:
server = clusto.get(args.server[0])
if not server:
raise LookupError('Object "%s" does not exist' % args.server)
except Exception as e:
self.debug(e)
self.error('No object like "%s" was found' % args.server)
return 1
server = server[0]
if not hasattr(server, 'console'):
self.error('The object %s lacks a console method' % server.name)
return 2
user = os.environ.get('USER')
if args.user:
self.debug('Grabbing user from parameter')
user = args.user
else:
self.debug('Grabbing user from config file or default')
user = self.get_conf('console.user', user)
self.debug('User is "%s"' % user)
return(server.console(ssh_user=user))
def main():
console, args = script_helper.init_arguments(Console)
return(console.run(args))
if __name__ == '__main__':
sys.exit(main())
| sanyaade-mobiledev/clusto | src/clusto/commands/console.py | Python | bsd-3-clause | 2,107 |
/**
* Copyright (c) 2013, impossibl.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of impossibl.com nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.impossibl.postgres.system.procs;
/**
* Marker interface for dynamically loaded postgis data types, to be used by {@link ServiceLoader}.
*/
public interface OptionalProcProvider extends ProcProvider {
}
| frode-carlsen/pgjdbc-ng | src/main/java/com/impossibl/postgres/system/procs/OptionalProcProvider.java | Java | bsd-3-clause | 1,789 |
//
// $Id$
package org.ductilej.tests;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests handling of varags with parameterized variable argument. Edge case extraordinaire!
*/
public class ParamVarArgsTest
{
public static interface Predicate<T> {
boolean apply (T arg);
}
public static <T> Predicate<T> or (final Predicate<? super T>... preds) {
return new Predicate<T>() {
public boolean apply (T arg) {
for (Predicate<? super T> pred : preds) {
if (pred.apply(arg)) {
return true;
}
}
return false;
}
};
}
@SuppressWarnings("unchecked") // this use of parameterized varargs is safe
@Test public void testParamVarArgs () {
Predicate<Integer> test = or(FALSE);
assertEquals(false, test.apply(1));
}
protected static final Predicate<Integer> FALSE = new Predicate<Integer>() {
public boolean apply (Integer arg) {
return false;
}
};
}
| scaladyno/ductilej | src/test/java/org/ductilej/tests/ParamVarArgsTest.java | Java | bsd-3-clause | 1,100 |
package ga;
import engine.*;
import java.util.*;
public class GAPopulation {
/* Evolutionary parameters: */
public int size; // size of the population
public int ngens; // total number of generations
public int currgen; // current generation
/* Crossover parameters */
int tournamentK; // size of tournament
int elite; // size of elite
int immigrant; // number of new random individuals
double mutrate; // chance that a mutation will occur
double xoverrate; // chance that the xover will occur
/* Containers */
public ArrayList<Genome> individual;
Genome parent;
Trainer T;
/* Progress data */
public double[] max_fitness;
public double[] avg_fitness;
public double[] terminals; // average total number of terminals
public double[] bigterminals; // average total number of sig. terminals
/**
* Initialize and load parameters.
* Parameter comp is a node from a previous
* scenario, which is used for distance calculations.
*/
public GAPopulation(Genome comp)
{
individual = new ArrayList<Genome>();
parent = comp;
// reading parameters
Parameter param = Parameter.getInstance();
String paramval;
paramval = param.getParam("population size");
if (paramval != null)
size = Integer.valueOf(paramval);
else
{
System.err.println("\"population size\" not defined on parameter file.");
size = 10;
}
paramval = param.getParam("generation number");
if (paramval != null)
ngens = Integer.valueOf(paramval);
else
{
System.err.println("\"generation number\" not defined on parameter file.");
ngens = 10;
}
paramval = param.getParam("tournament K");
if (paramval != null)
tournamentK = Integer.valueOf(paramval);
else
{
System.err.println("\"tournament K\" not defined on parameter file.");
tournamentK = 5;
}
paramval = param.getParam("elite size");
if (paramval != null)
elite = Integer.valueOf(paramval);
else
{
System.err.println("\"elite size\" not defined on parameter file.");
elite = 1;
}
paramval = param.getParam("immigrant size");
if (paramval != null)
immigrant = Integer.valueOf(paramval);
else
{
System.err.println("\"immigrant size\" not defined on parameter file.");
immigrant = 0;;
}
paramval = param.getParam("mutation rate");
if (paramval != null)
mutrate = Double.valueOf(paramval);
else
{
System.err.println("\"mutation rate\" not defined on parameter file.");
mutrate = 0.01;
}
paramval = param.getParam("crossover rate");
if (paramval != null)
xoverrate = Double.valueOf(paramval);
else
{
System.err.println("\"crossover rate\" not defined on parameter file.");
xoverrate = 0.9;
}
}
/**
* Initialize the new population and the local
* variables. Startd is the target date for the
* @param startd
*/
public void initPopulation(Date startd)
{
T = new Trainer(startd);
currgen = 0;
for (int i = 0; i < size; i++)
{
Genome n = new Genome();
n.init();
individual.add(n);
}
max_fitness = new double[ngens];
avg_fitness = new double[ngens];
terminals = new double[ngens];
bigterminals = new double[ngens];
}
/**
* Runs one generation loop
*
*/
public void runGeneration()
{
eval();
breed();
currgen++;
}
/**
* update the values of the maxfitness/avg fitness/etc
* public arrays;
*/
public void updateStatus()
{
Parameter p = Parameter.getInstance();
String param = p.getParam("asset treshold");
double tresh = Double.valueOf(param);
avg_fitness[currgen-1] = 0;
terminals[currgen-1] = 0;
bigterminals[currgen-1] = 0;
for (int i = 0; i < individual.size(); i++)
{
avg_fitness[currgen-1] += individual.get(i).fitness;
terminals[currgen-1] += individual.get(i).countAsset(0.0);
bigterminals[currgen-1] += individual.get(i).countAsset(tresh);
}
max_fitness[currgen-1] = individual.get(0).fitness;
avg_fitness[currgen-1] /= size;
terminals[currgen-1] /= size;
bigterminals[currgen-1] /= size;
}
/**
* Calculates the fitness value for each individual
* in the population.
*/
public void eval()
{
for (int i = 0; i < size; i++)
{
individual.get(i).eval(T);
}
Collections.sort(individual);
}
/**
* Perform selection, crossover, mutation in
* order to create a new population.
*
* Assumes the eval function has already been
* performed.
*
*/
public void breed()
{
RNG d = RNG.getInstance();
ArrayList<Genome> nextGen = new ArrayList<Genome>();
Genome p1,p2;
// elite: (few copied individuals)
for (int i = 0; i < elite; i++)
{
nextGen.add(individual.get(i).copy());
}
// immigrant: (usually 0)
for (int i = 0; i < immigrant; i++)
{
Genome n = new Genome();
n.init();
nextGen.add(n);
}
// crossover:
for (int i = 0; i < size - (immigrant + elite); i+=2)
{
// selection - the selection function should
// return copies already.
p1 = Tournament();
p2 = Tournament();
// rolls for xover
if (d.nextDouble() < xoverrate)
{
p1.crossover(p2);
}
// rolls for mutation
if (d.nextDouble() < mutrate)
p1.mutation();
if (d.nextDouble() < mutrate)
p2.mutation();
nextGen.add(p1);
nextGen.add(p2);
}
individual = nextGen;
}
/**
* Select one parent from the population by using
* fitness-proportional tournament selection
* (eat candidate has a chance proportional to his
* fitness of being chosen).
*
* The function copy the chosen candidate and send
* him back.
* @return
*/
public Genome Tournament()
{
RNG d = RNG.getInstance();
Genome[] list = new Genome[tournamentK];
double[] rank = new double[tournamentK];
double sum = 0.0;
double ticket = 0.0;
double min = 0.0;
/* Selects individuals and removes negative fitness */
for (int i = 0; i < tournamentK; i++)
{
list[i] = individual.get(d.nextInt(size));
if (list[i].fitness < min)
min = list[i].fitness;
}
/* I'm not sure if this is the best way to
* make the proportion between the fitnesses.
* Some sort of scaling factor should be put here
* to avoit high fitnesses from superdominating.
*
* But maybe the tournament proccess already guarantees this?
*/
for (int i = 0; i < tournamentK; i++)
{
sum += list[i].fitness - min;
rank[i] = sum;
}
ticket = d.nextDouble()*sum;
for (int i = 0; i < tournamentK; i++)
{
if ((ticket) <= rank[i])
return list[i].copy();
}
// should never get here
System.err.println("x" + ticket + " + " + sum);
System.err.println("Warning: MemeTournament - reached unreachable line");
return list[0].copy();
}
}
| caranha/MTGA-old | code/ga/GAPopulation.java | Java | bsd-3-clause | 6,710 |
//=====================================================================//
/*! @file
@brief R8C LCD メイン @n
for ST7567 SPI (128 x 32) @n
LCD: Aitendo M-G0812P7567
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/R8C/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/command.hpp"
#include "common/format.hpp"
#include "common/trb_io.hpp"
#include "common/spi_io.hpp"
#include "chip/ST7565.hpp"
#include "common/monograph.hpp"
namespace {
device::trb_io<utils::null_task, uint8_t> timer_b_;
typedef utils::fifo<uint8_t, 16> buffer;
typedef device::uart_io<device::UART0, buffer, buffer> uart;
uart uart_;
utils::command<64> command_;
// LCD SCL: P4_2(1)
typedef device::PORT<device::PORT4, device::bitpos::B2> SPI_SCL;
// LCD SDA: P4_5(12)
typedef device::PORT<device::PORT4, device::bitpos::B5> SPI_SDA;
// MISO, MOSI, SCK
typedef device::spi_io<device::NULL_PORT, SPI_SDA, SPI_SCL, device::soft_spi_mode::CK10> SPI;
SPI spi_;
// LCD /CS: P3_7(2)
typedef device::PORT<device::PORT3, device::bitpos::B7> LCD_SEL;
// LCD A0: P1_6(14)
typedef device::PORT<device::PORT1, device::bitpos::B6> LCD_A0;
// LCD RESET
typedef device::NULL_PORT LCD_RES;
typedef chip::ST7565<SPI, LCD_SEL, LCD_A0, LCD_RES> LCD;
LCD lcd_(spi_);
class PLOT {
public:
typedef int8_t value_type;
static const int8_t WIDTH = 128;
static const int8_t HEIGHT = 64;
void clear(uint8_t v = 0)
{
}
void operator() (int8_t x, int8_t y, bool val)
{
if(x < 0 || x >= WIDTH) return;
if(y < 0 || y >= HEIGHT) return;
}
};
graphics::kfont_null kfont_;
graphics::monograph<PLOT> bitmap_(kfont_);
}
extern "C" {
void sci_putch(char ch) {
uart_.putch(ch);
}
char sci_getch(void) {
return uart_.getch();
}
uint16_t sci_length() {
return uart_.length();
}
void sci_puts(const char* str) {
uart_.puts(str);
}
void TIMER_RB_intr(void) {
timer_b_.itask();
}
void UART0_TX_intr(void) {
uart_.isend();
}
void UART0_RX_intr(void) {
uart_.irecv();
}
}
static uint8_t v_ = 91;
static uint8_t m_ = 123;
#if 0
static void randmize_(uint8_t v, uint8_t m)
{
v_ = v;
m_ = m;
}
#endif
static uint8_t rand_()
{
v_ += v_ << 2;
++v_;
uint8_t n = 0;
if(m_ & 0x02) n = 1;
if(m_ & 0x40) n ^= 1;
m_ += m_;
if(n == 0) ++m_;
return v_ ^ m_;
}
// __attribute__ ((section (".exttext")))
int main(int argc, char *argv[])
{
using namespace device;
// クロック関係レジスタ・プロテクト解除
PRCR.PRC0 = 1;
// 高速オンチップオシレーターへ切り替え(20MHz)
// ※ F_CLK を設定する事(Makefile内)
OCOCR.HOCOE = 1;
utils::delay::micro_second(1); // >=30us(125KHz)
SCKCR.HSCKSEL = 1;
CKSTPR.SCKSEL = 1;
// タイマーB初期化
{
uint8_t ir_level = 2;
timer_b_.start(60, ir_level);
}
// UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in])
// ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意!
{
utils::PORT_MAP(utils::port_map::P14::TXD0);
utils::PORT_MAP(utils::port_map::P15::RXD0);
uint8_t ir_level = 1;
uart_.start(57600, ir_level);
}
// SPI 開始
{
spi_.start(10000000);
}
// LCD を開始
{
lcd_.start(0x00);
spi_.start(0); // Boost SPI clock
bitmap_.clear(0);
}
sci_puts("Start R8C LCD monitor\n");
command_.set_prompt("# ");
// LED シグナル用ポートを出力
// PD1.B0 = 1;
uint8_t cnt = 0;
uint16_t x = rand_() & 127;
uint16_t y = rand_() & 31;
uint16_t xx;
uint16_t yy;
uint8_t loop = 20;
while(1) {
timer_b_.sync();
/// lcd_.copy(bitmap_.fb(), bitmap_.page_num());
if(loop >= 20) {
loop = 0;
bitmap_.clear(0);
bitmap_.frame(0, 0, 128, 32, 1);
}
xx = rand_() & 127;
yy = rand_() & 31;
bitmap_.line(x, y, xx, yy, 1);
x = xx;
y = yy;
++loop;
// bitmap_.line(0, 0, 127, 31, 1);
// bitmap_.line(0, 31, 127, 0, 1);
if(cnt >= 20) {
cnt = 0;
}
++cnt;
// コマンド入力と、コマンド解析
if(command_.service()) {
}
}
}
| hirakuni45/R8C | LCD_DOT_sample/main.cpp | C++ | bsd-3-clause | 4,261 |
<?php
namespace Application\Entity\Repository;
use Doctrine\ORM\EntityRepository;
Class RubricsRepository extends EntityRepository{
} | Romez/zend.local | module/Application/src/Application/Entity/Repository/RubricsRepository.php | PHP | bsd-3-clause | 137 |
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "book".
*
* @property integer $id
* @property string $title
* @property string $published_date
*
* @property BookAuthor[] $bookAuthors
* @property BookGenre[] $bookGenres
*/
class Book extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'book';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title', 'published_date'], 'required'],
[['published_date'], 'safe'],
[['title'], 'string', 'max' => 256]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Title',
'published_date' => 'Published Date',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getBookAuthors()
{
return $this->hasMany('book_author', ['book_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getBookGenres()
{
return $this->hasMany('book_genre', ['book_id' => 'id']);
}
/**
* @inheritdoc
* @return BookQuery the active query used by this AR class.
*/
public static function find()
{
return new BookQuery(get_called_class());
}
}
| uaman89/library | models/Book.php | PHP | bsd-3-clause | 1,418 |
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "content".
*
* @property integer $id
* @property string $title
* @property integer $moderation
* @property integer $listsql_id
* @property integer $parent_id
* @property integer $grade_id
* @property string $comment_TutorAboutPupil1
* @property integer $mark_TutorAboutPupil1
* @property string $date_TutorAboutPupil1
* @property string $comment_Pupil1AboutTutor
* @property integer $mark_Pupil1AboutTutor
* @property string $date_Pupil1AboutTutor
* @property string $commentMaximum_TutorAboutPupil1
* @property integer $markMaximum_TutorAboutPupil1
* @property string $dateMaximum_TutorAboutPupil1
* @property string $commentMaximum_Pupil1AboutTutor
* @property integer $markMaximum_Pupil1AboutTutor
* @property string $dateMaximum_Pupil1AboutTutor
* @property string $comment_Pupil1AboutPupil1
* @property integer $mark_Pupil1AboutPupil1
* @property string $date_Pupil1AboutPupil1
* @property string $commentMaximum_Pupil1AboutPupil1
* @property integer $markMaximum_Pupil1AboutPupil1
* @property string $dateMaximum_Pupil1AboutPupil1
*/
class Content extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'content';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title', 'moderation', 'listsql_id', 'parent_id', 'comment_TutorAboutPupil1', 'mark_TutorAboutPupil1', 'date_TutorAboutPupil1', 'comment_Pupil1AboutTutor', 'mark_Pupil1AboutTutor', 'date_Pupil1AboutTutor', 'commentMaximum_TutorAboutPupil1', 'markMaximum_TutorAboutPupil1', 'dateMaximum_TutorAboutPupil1', 'commentMaximum_Pupil1AboutTutor', 'markMaximum_Pupil1AboutTutor', 'dateMaximum_Pupil1AboutTutor', 'comment_Pupil1AboutPupil1', 'mark_Pupil1AboutPupil1', 'date_Pupil1AboutPupil1', 'commentMaximum_Pupil1AboutPupil1', 'markMaximum_Pupil1AboutPupil1', 'dateMaximum_Pupil1AboutPupil1'], 'required'],
[['moderation', 'listsql_id', 'parent_id', 'grade_id', 'mark_TutorAboutPupil1', 'mark_Pupil1AboutTutor', 'markMaximum_TutorAboutPupil1', 'markMaximum_Pupil1AboutTutor', 'mark_Pupil1AboutPupil1', 'markMaximum_Pupil1AboutPupil1'], 'integer'],
[['comment_TutorAboutPupil1', 'comment_Pupil1AboutTutor', 'commentMaximum_TutorAboutPupil1', 'commentMaximum_Pupil1AboutTutor', 'comment_Pupil1AboutPupil1', 'commentMaximum_Pupil1AboutPupil1'], 'string'],
[['date_TutorAboutPupil1', 'date_Pupil1AboutTutor', 'dateMaximum_TutorAboutPupil1', 'dateMaximum_Pupil1AboutTutor', 'date_Pupil1AboutPupil1', 'dateMaximum_Pupil1AboutPupil1'], 'safe'],
[['title'], 'string', 'max' => 500],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Title',
'moderation' => 'Moderation',
'listsql_id' => 'Listsql ID',
'parent_id' => 'Parent ID',
'grade_id' => 'Grade ID',
'comment_TutorAboutPupil1' => 'Comment Tutor About Pupil1',
'mark_TutorAboutPupil1' => 'Mark Tutor About Pupil1',
'date_TutorAboutPupil1' => 'Date Tutor About Pupil1',
'comment_Pupil1AboutTutor' => 'Comment Pupil1 About Tutor',
'mark_Pupil1AboutTutor' => 'Mark Pupil1 About Tutor',
'date_Pupil1AboutTutor' => 'Date Pupil1 About Tutor',
'commentMaximum_TutorAboutPupil1' => 'Comment Maximum Tutor About Pupil1',
'markMaximum_TutorAboutPupil1' => 'Mark Maximum Tutor About Pupil1',
'dateMaximum_TutorAboutPupil1' => 'Date Maximum Tutor About Pupil1',
'commentMaximum_Pupil1AboutTutor' => 'Comment Maximum Pupil1 About Tutor',
'markMaximum_Pupil1AboutTutor' => 'Mark Maximum Pupil1 About Tutor',
'dateMaximum_Pupil1AboutTutor' => 'Date Maximum Pupil1 About Tutor',
'comment_Pupil1AboutPupil1' => 'Comment Pupil1 About Pupil1',
'mark_Pupil1AboutPupil1' => 'Mark Pupil1 About Pupil1',
'date_Pupil1AboutPupil1' => 'Date Pupil1 About Pupil1',
'commentMaximum_Pupil1AboutPupil1' => 'Comment Maximum Pupil1 About Pupil1',
'markMaximum_Pupil1AboutPupil1' => 'Mark Maximum Pupil1 About Pupil1',
'dateMaximum_Pupil1AboutPupil1' => 'Date Maximum Pupil1 About Pupil1',
];
}
}
| halva202/halva202.by | backend/models/160501/Content.php | PHP | bsd-3-clause | 4,464 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/settings/tray_settings.h"
#include "ash/shell.h"
#include "ash/system/power/power_status_view.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_views.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "grit/ash_resources.h"
#include "grit/ash_strings.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/accessibility/accessible_view_state.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/view.h"
namespace ash {
namespace internal {
namespace tray {
class SettingsDefaultView : public ash::internal::ActionableView {
public:
explicit SettingsDefaultView(user::LoginStatus status)
: login_status_(status),
label_(NULL),
power_status_view_(NULL) {
SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal,
ash::kTrayPopupPaddingHorizontal, 0,
ash::kTrayPopupPaddingBetweenItems));
bool power_view_right_align = false;
if (login_status_ != user::LOGGED_IN_NONE &&
login_status_ != user::LOGGED_IN_LOCKED) {
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
views::ImageView* icon =
new ash::internal::FixedSizedImageView(0, ash::kTrayPopupItemHeight);
icon->SetImage(
rb.GetImageNamed(IDR_AURA_UBER_TRAY_SETTINGS).ToImageSkia());
AddChildView(icon);
string16 text = rb.GetLocalizedString(IDS_ASH_STATUS_TRAY_SETTINGS);
label_ = new views::Label(text);
AddChildView(label_);
SetAccessibleName(text);
power_view_right_align = true;
}
PowerSupplyStatus power_status =
ash::Shell::GetInstance()->tray_delegate()->GetPowerSupplyStatus();
if (power_status.battery_is_present) {
power_status_view_ = new ash::internal::PowerStatusView(
ash::internal::PowerStatusView::VIEW_DEFAULT, power_view_right_align);
AddChildView(power_status_view_);
UpdatePowerStatus(power_status);
}
}
virtual ~SettingsDefaultView() {}
void UpdatePowerStatus(const PowerSupplyStatus& status) {
if (power_status_view_)
power_status_view_->UpdatePowerStatus(status);
}
// Overridden from ash::internal::ActionableView.
virtual bool PerformAction(const ui::Event& event) OVERRIDE {
if (login_status_ == user::LOGGED_IN_NONE ||
login_status_ == user::LOGGED_IN_LOCKED)
return false;
ash::Shell::GetInstance()->tray_delegate()->ShowSettings();
return true;
}
// Overridden from views::View.
virtual void Layout() OVERRIDE {
views::View::Layout();
if (label_ && power_status_view_) {
// Let the box-layout do the layout first. Then move power_status_view_
// to right align if it is created.
gfx::Size size = power_status_view_->GetPreferredSize();
gfx::Rect bounds(size);
bounds.set_x(width() - size.width() - ash::kTrayPopupPaddingBetweenItems);
bounds.set_y((height() - size.height()) / 2);
power_status_view_->SetBoundsRect(bounds);
}
}
// Overridden from views::View.
virtual void ChildPreferredSizeChanged(views::View* child) OVERRIDE {
views::View::ChildPreferredSizeChanged(child);
Layout();
}
private:
user::LoginStatus login_status_;
views::Label* label_;
ash::internal::PowerStatusView* power_status_view_;
DISALLOW_COPY_AND_ASSIGN(SettingsDefaultView);
};
} // namespace tray
TraySettings::TraySettings(SystemTray* system_tray)
: SystemTrayItem(system_tray),
default_view_(NULL) {
}
TraySettings::~TraySettings() {}
views::View* TraySettings::CreateTrayView(user::LoginStatus status) {
return NULL;
}
views::View* TraySettings::CreateDefaultView(user::LoginStatus status) {
if ((status == user::LOGGED_IN_NONE || status == user::LOGGED_IN_LOCKED) &&
(!ash::Shell::GetInstance()->tray_delegate()->
GetPowerSupplyStatus().battery_is_present))
return NULL;
CHECK(default_view_ == NULL);
default_view_ = new tray::SettingsDefaultView(status);
return default_view_;
}
views::View* TraySettings::CreateDetailedView(user::LoginStatus status) {
NOTIMPLEMENTED();
return NULL;
}
void TraySettings::DestroyTrayView() {
}
void TraySettings::DestroyDefaultView() {
default_view_ = NULL;
}
void TraySettings::DestroyDetailedView() {
}
void TraySettings::UpdateAfterLoginStatusChange(user::LoginStatus status) {
}
// Overridden from PowerStatusObserver.
void TraySettings::OnPowerStatusChanged(const PowerSupplyStatus& status) {
if (default_view_)
default_view_->UpdatePowerStatus(status);
}
} // namespace internal
} // namespace ash
| leighpauls/k2cro4 | ash/system/settings/tray_settings.cc | C++ | bsd-3-clause | 5,055 |
var Turtle = function () {
this.d = 0;
this.x = 0;
this.y = 0;
this.rounding = false;
this.invert = false;
}
Turtle.prototype.setX = function (val) {
this.x = val;
return this;
}
Turtle.prototype.setY = function (val) {
this.y = val;
return this;
}
Turtle.prototype.setDegree = function (deg) {
this.d = deg;
return this;
}
Turtle.prototype.setInvert = function (bool) {
this.invert = bool;
return this;
}
Turtle.prototype.setRounding = function (bool) {
this.rounding = bool;
return this;
}
Turtle.prototype.rt = function (degrees) {
if (this.invert) {
this.d += degrees;
} else {
this.d -= degrees;
this.d += 360; // to ensure that the number is positive
}
this.d %= 360;
return this;
}
Turtle.prototype.lt = function (degrees) {
if (this.invert) {
this.d -= degrees;
this.d += 360; // to ensure that the number is positive
} else {
this.d += degrees;
}
this.d %= 360;
return this;
}
Turtle.prototype.adj = function (degrees, hyp) {
var adj = Math.cos(degrees * Math.PI / 180) * hyp;
if (this.rounding) {
return Math.round(adj);
} else {
return adj;
}
}
Turtle.prototype.opp = function (degrees, hyp) {
var opp = Math.sin(degrees * Math.PI / 180) * hyp;
if (this.rounding) {
return Math.round(opp);
} else {
return opp;
}
}
Turtle.prototype.fd = function (magnitude) {
if (this.d < 90) {
// x == adjacent
this.x += this.adj(this.d, magnitude);
// y == opposite
this.y += this.opp(this.d, magnitude);
} else if (this.d < 180) {
// x == -opposite
this.x -= this.opp(this.d - 90, magnitude);
// y == adjacent
this.y += this.adj(this.d - 90, magnitude);
} else if (this.d < 270) {
// x == -adjacent
this.x -= this.adj(this.d - 180, magnitude);
// y == -opposite
this.y -= this.opp(this.d - 180, magnitude);
} else if (this.d < 360) {
// x == opposite
this.x += this.opp(this.d - 270, magnitude);
// y == -adjacent
this.y -= this.adj(this.d - 270, magnitude);
}
return this;
}
Turtle.prototype.bk = function (magnitude) {
if (this.d < 90) {
// x -= adjacent
this.x -= this.adj(this.d, magnitude);
// y -= opposite
this.y -= this.opp(this.d, magnitude);
} else if (this.d < 180) {
// x == +opposite
this.x += this.opp(this.d - 90, magnitude);
// y == -adjacent
this.y -= this.adj(this.d - 90, magnitude);
} else if (this.d < 270) {
// x == opposite
this.x += this.adj(this.d - 180, magnitude);
// y == adjacent
this.y += this.opp(this.d - 180, magnitude);
} else if (this.d < 360) {
// x == -opposite
this.x -= this.opp(this.d - 270, magnitude);
// y == adjacent
this.y += this.adj(this.d - 270, magnitude);
}
return this;
} | gief/turtlejs | src/turtle.js | JavaScript | bsd-3-clause | 3,007 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_82_bad.cpp
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.label.xml
Template File: sources-sink-82_bad.tmpl.cpp
*/
/*
* @description
* CWE: 121 Stack Based Buffer Overflow
* BadSource: Set data pointer to the bad buffer
* GoodSource: Set data pointer to the good buffer
* Sinks: memcpy
* BadSink : Copy twoIntsStruct array to data using memcpy
* Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_82.h"
namespace CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_82
{
void CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_82_bad::action(twoIntsStruct * data)
{
{
twoIntsStruct source[100];
{
size_t i;
/* Initialize array */
for (i = 0; i < 100; i++)
{
source[i].intOne = 0;
source[i].intTwo = 0;
}
}
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
memcpy(data, source, 100*sizeof(twoIntsStruct));
printStructLine(&data[0]);
}
}
}
#endif /* OMITBAD */
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE121_Stack_Based_Buffer_Overflow/s04/CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_82_bad.cpp | C++ | bsd-3-clause | 1,401 |
# -*- coding: utf-8 -*-
"""
Display a fortune-telling, swimming fish.
Wanda has no use what-so-ever. It only takes up disk space and compilation time,
and if loaded, it also takes up precious bar space, memory, and cpu cycles.
Anybody found using it should be promptly sent for a psychiatric evaluation.
Configuration parameters:
cache_timeout: refresh interval for this module (default 0)
format: display format for this module
(default '{nomotion}[{fortune} ]{wanda}{motion}')
fortune_timeout: refresh interval for fortune (default 60)
Format placeholders:
{fortune} one of many aphorisms or vague prophecies
{wanda} name of one of the most commonly kept freshwater aquarium fish
{motion} biologically propelled motion through a liquid medium
{nomotion} opposite behavior of motion to prevent modules from shifting
Optional:
fortune-mod: the fortune cookie program from bsd games
Examples:
```
# disable motions when not in use
wanda_the_fish {
format = '[\?if=fortune {nomotion}][{fortune} ]'
format += '{wanda}[\?if=fortune {motion}]'
}
# no updates, no motions, yes fortunes, you click
wanda_the_fish {
format = '[{fortune} ]{wanda}'
cache_timeout = -1
}
# wanda moves, fortunes stays
wanda_the_fish {
format = '[{fortune} ]{nomotion}{wanda}{motion}'
}
# wanda is swimming too fast, slow down wanda
wanda_the_fish {
cache_timeout = 2
}
```
@author lasers
SAMPLE OUTPUT
[
{'full_text': 'innovate, v.: To annoy people.'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
idle
[
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>3', 'color': '#ff8c00'},
]
py3status
[
{'full_text': 'py3status is so cool!'},
{'full_text': ' <', 'color': '#ffa500'},
{'full_text': '\xba', 'color': '#add8e6'},
{'full_text': ',', 'color': '#ff8c00'},
{'full_text': '))', 'color': '#ffa500'},
{'full_text': '))>< ', 'color': '#ff8c00'},
]
"""
from time import time
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 0
format = "{nomotion}[{fortune} ]{wanda}{motion}"
fortune_timeout = 60
def post_config_hook(self):
body = (
"[\?color=orange&show <"
"[\?color=lightblue&show º]"
"[\?color=darkorange&show ,]))"
"[\?color=darkorange&show ))>%s]]"
)
wanda = [body % fin for fin in ("<", ">", "<", "3")]
self.wanda = [self.py3.safe_format(x) for x in wanda]
self.wanda_length = len(self.wanda)
self.index = 0
self.fortune_command = ["fortune", "-as"]
self.fortune = self.py3.storage_get("fortune") or None
self.toggled = self.py3.storage_get("toggled") or False
self.motions = {"motion": " ", "nomotion": ""}
# deal with {new,old} timeout between storage
fortune_timeout = self.py3.storage_get("fortune_timeout")
timeout = None
if self.fortune_timeout != fortune_timeout:
timeout = time() + self.fortune_timeout
self.time = (
timeout or self.py3.storage_get("time") or (time() + self.fortune_timeout)
)
def _set_fortune(self, state=None, new=False):
if not self.fortune_command:
return
if new:
try:
fortune_data = self.py3.command_output(self.fortune_command)
except self.py3.CommandError:
self.fortune = ""
self.fortune_command = None
else:
self.fortune = " ".join(fortune_data.split())
self.time = time() + self.fortune_timeout
elif state is None:
if self.toggled and time() >= self.time:
self._set_fortune(new=True)
else:
self.toggled = state
if state:
self._set_fortune(new=True)
else:
self.fortune = None
def _set_motion(self):
for k in self.motions:
self.motions[k] = "" if self.motions[k] else " "
def _set_wanda(self):
self.index += 1
if self.index >= self.wanda_length:
self.index = 0
def wanda_the_fish(self):
self._set_fortune()
self._set_motion()
self._set_wanda()
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{
"fortune": self.fortune,
"motion": self.motions["motion"],
"nomotion": self.motions["nomotion"],
"wanda": self.wanda[self.index],
},
),
}
def kill(self):
self.py3.storage_set("toggled", self.toggled)
self.py3.storage_set("fortune", self.fortune)
self.py3.storage_set("fortune_timeout", self.fortune_timeout)
self.py3.storage_set("time", self.time)
def on_click(self, event):
if not self.fortune_command:
return
self._set_fortune(not self.toggled)
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
| Andrwe/py3status | py3status/modules/wanda_the_fish.py | Python | bsd-3-clause | 5,569 |
/**
* (c) 2017 TIBCO Software Inc. All rights reserved.
*
* Except as specified below, this software is licensed pursuant to the Eclipse Public License v. 1.0.
* The details can be found in the file LICENSE.
*
* The following proprietary files are included as a convenience, and may not be used except pursuant
* to valid license to Composite Information Server or TIBCO(R) Data Virtualization Server:
* csadmin-XXXX.jar, csarchive-XXXX.jar, csbase-XXXX.jar, csclient-XXXX.jar, cscommon-XXXX.jar,
* csext-XXXX.jar, csjdbc-XXXX.jar, csserverutil-XXXX.jar, csserver-XXXX.jar, cswebapi-XXXX.jar,
* and customproc-XXXX.jar (where -XXXX is an optional version number). Any included third party files
* are licensed under the terms contained in their own accompanying LICENSE files, generally named .LICENSE.txt.
*
* This software is licensed AS-IS. Support for this software is not covered by standard maintenance agreements with TIBCO.
* If you would like to obtain assistance with this software, such assistance may be obtained through a separate paid consulting
* agreement with TIBCO.
*
*/
package com.tibco.ps.deploytool.services;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContextException;
import com.tibco.ps.common.CommonConstants;
import com.tibco.ps.common.exception.CompositeException;
import com.tibco.ps.common.util.CommonUtils;
import com.tibco.ps.deploytool.dao.ServerDAO;
import com.tibco.ps.deploytool.dao.wsapi.ServerWSDAOImpl;
public class ServerManagerImpl implements ServerManager {
private ServerDAO serverDAO = null;
// Get the configuration property file set in the environment with a default of deploy.properties
String propertyFile = CommonUtils.getFileOrSystemPropertyValue(CommonConstants.propertyFile, "CONFIG_PROPERTY_FILE");
private static Log logger = LogFactory.getLog(ServerManagerImpl.class);
// @Override
public void startServer(String serverId, String pathToServersXML) throws CompositeException {
String prefix = "startServer";
// Extract variables for the serverId
serverId = CommonUtils.extractVariable(prefix, serverId, propertyFile, true);
if(logger.isDebugEnabled()){
logger.debug(" Entering ServerManagerImpl.start() with following params - serverId: " + serverId + ", pathToServersXML: " + pathToServersXML);
}
try {
serverManagerAction(ServerDAO.action.START.name(), serverId, pathToServersXML);
} catch (CompositeException e) {
logger.error("Error while starting server: " , e);
throw new ApplicationContextException(e.getMessage(), e);
}
}
// @Override
public void stopServer(String serverId, String pathToServersXML) throws CompositeException {
String prefix = "stopServer";
// Extract variables for the serverId
serverId = CommonUtils.extractVariable(prefix, serverId, propertyFile, true);
if(logger.isDebugEnabled()){
logger.debug(" Entering ServerManagerImpl.start() with following params - serverId: " + serverId + ", pathToServersXML: " + pathToServersXML);
}
try {
serverManagerAction(ServerDAO.action.STOP.name(), serverId, pathToServersXML);
} catch (CompositeException e) {
logger.error("Error while stopping server: " , e);
throw new ApplicationContextException(e.getMessage(), e);
}
}
// @Override
public void restartServer(String serverId, String pathToServersXML) throws CompositeException {
String prefix = "restartServer";
// Extract variables for the serverId
serverId = CommonUtils.extractVariable(prefix, serverId, propertyFile, true);
if(logger.isDebugEnabled()){
logger.debug(" Entering ServerManagerImpl.start() with following params - serverId: " + serverId + ", pathToServersXML: " + pathToServersXML);
}
try {
serverManagerAction(ServerDAO.action.RESTART.name(), serverId, pathToServersXML);
} catch (CompositeException e) {
logger.error("Error while restarting server: " , e);
throw new ApplicationContextException(e.getMessage(), e);
}
}
private void serverManagerAction(String actionName, String serverId, String pathToServersXML) throws CompositeException {
String prefix = "serverManagerAction";
String processedIds = null;
// Extract variables for the serverId
serverId = CommonUtils.extractVariable(prefix, serverId, propertyFile, true);
// Set the Module Action Objective
String s1 = (serverId == null) ? "no_serverId" : "Ids="+serverId;
System.setProperty("MODULE_ACTION_OBJECTIVE", actionName+" : "+s1);
// Validate whether the files exist or not
if (!CommonUtils.fileExists(pathToServersXML)) {
throw new CompositeException("File ["+pathToServersXML+"] does not exist.");
}
try {
if(logger.isInfoEnabled()){
logger.info("processing action "+ actionName + " on server "+ serverId);
}
getServerDAO().takeServerManagerAction(actionName, serverId, pathToServersXML);
} catch (CompositeException e) {
logger.error("Error on server action (" + actionName + "): ", e);
throw new ApplicationContextException(e.getMessage(), e);
}
}
/**
* @return serverDAO
*/
public ServerDAO getServerDAO() {
if(this.serverDAO == null){
this.serverDAO = new ServerWSDAOImpl();
}
return serverDAO;
}
/**
* @param set serverDAO
*/
public void setServerDAO(ServerDAO serverDAO) {
this.serverDAO = serverDAO;
}
}
| cisco/PDTool | src/com/tibco/ps/deploytool/services/ServerManagerImpl.java | Java | bsd-3-clause | 5,374 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-05 14:25
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("elections", "0049_move_status")]
operations = [
migrations.RemoveField(model_name="election", name="rejection_reason"),
migrations.RemoveField(model_name="election", name="suggested_status"),
migrations.RemoveField(model_name="election", name="suggestion_reason"),
]
| DemocracyClub/EveryElection | every_election/apps/elections/migrations/0050_auto_20181005_1425.py | Python | bsd-3-clause | 512 |
from __future__ import print_function
import re
import logging
logging.basicConfig(level=logging.INFO)
class Executor(object):
def __init__(self, op_map):
processed = {}
for pattern, f in op_map.iteritems():
s = self._build_pattern_groups(pattern.lower())
processed[re.compile(s)] = f
self.operations = processed
def execute(self, context, op):
s = "%04x" % op
for pattern, f in self.operations.iteritems():
m = pattern.match(s)
if m:
return f(context, *[int(v, base=16) for v in m.groups()])
assert False, s
def _build_pattern_groups(self, pattern):
s = pattern.replace('?', '.')
for id in ['x', 'y', 'z']:
m = re.search('%s+' % id, s)
if m:
s = s[:m.start()] + ('(.{%s})' % (m.end() - m.start())) + s[m.end():]
return '^' + s + '$'
def set_mem_v0_vx(context, x):
for i in range(x):
context.memory.write_byte(context.index_reg + i, context.v[i])
context.pc += 2
def fill_v0_vx(context, x):
for i in range(x+1):
context.v[i] = context.memory.get_byte(context.index_reg + i)
context.pc += 2
def set_bcd_vx(context, x):
val = int(context.v[x])
context.memory.write_byte(context.index_reg, val / 100)
context.memory.write_byte(context.index_reg + 1, val % 100 / 10)
context.memory.write_byte(context.index_reg + 2, val % 100 % 10)
context.pc += 2
def set_i_font(context, x):
context.index_reg = context.memory.get_font_address(context.v[x])
context.pc += 2
def add_reg_ind(context, x):
context.index_reg += context.v[x]
context.pc += 2
def set_delay_timer(context, x):
context.delay_timer = context.v[x]
context.pc += 2
def set_sound_timer(context, x):
context.sound_timer = context.v[x]
context.pc += 2
def set_vx_key_pressed(context, x):
context.v[x] = context.keypad.wait_for_keypress()
context.pc += 2
def set_vx_delay_timer(context, x):
context.v[x] = context.delay_timer
context.pc += 2
def skip_key_vx(context, x, result=True):
if context.keypad.is_keypressed(context.v[x]) == result:
context.pc += 2
context.pc += 2
def draw_sprite(context, x, y, n):
sprite = []
for cb in range(n):
sprite.append(context.memory.get_byte(context.index_reg + cb))
collision = context.screen.draw(context.v[x], context.v[y], sprite)
context.v[15] = collision
context.pc += 2
def jump_nnn_v0(context, nnn):
context.pc = context.v[0] + nnn
def set_vx_rand(context, x, nn):
import random
context.v[x] = random.randint(0, 0xFF) & nn
context.pc += 2
def jump_noteq(context, x, y):
if context.v[x] != context.v[y]:
context.pc += 2
context.pc += 2
def shift_vy_left(context, x, y):
context.v[15] = context.v[15] >> 7 # First value
context.v[x] = (context.v[y] << 1) % 255
context.pc += 2
def shift_right(context, x, y):
context.v[15] = context.v[y] & 0x1
context.v[x] = context.v[y] >> 1
context.pc += 2
def sub_vx_vy_vf(context, x, y):
logging.info('Setting V[X] = V[X] - V[Y], V[F] = 1 if V[Y] > V[X]')
context.v[15] = 1 if context.v[y] > context.v[x] else 0
context.v[x] = context.v[x] - context.v[y]
context.pc += 2
def add_vx_vy(context, x, y):
logging.info('Setting V[X] = V[X] + V[Y]')
val = context.v[x] + context.v[y]
context.v[15] = 1 if val > 255 else 0
context.v[x] = val % 256
context.pc += 2
def sub_vx_vy(context, x, y):
logging.info('Setting V[X] = V[X] - V[Y]')
val = context.v[x] - context.v[y]
context.v[15] = 1 if val < 0 else 0
context.v[x] = val % 256
context.pc += 2
def set_vx_or_vy(context, x, y):
logging.info('Setting V[X] = V[X] | V[Y]')
context.v[x] = context.v[x] | context.v[y]
context.pc += 2
def set_vx_xor_vy(context, x, y):
logging.info('Setting V[X] = V[X] ^ V[Y]')
context.v[x] = context.v[x] ^ context.v[y]
context.pc += 2
def set_vx_and_vy(context, x, y):
logging.info('Setting V[X] = V[X] & V[Y]')
context.v[x] = context.v[x] & context.v[y]
context.pc += 2
def set_vx_vy(context, x, y):
logging.info('Setting V[X] = V[Y]')
context.v[x] = context.v[y]
context.pc += 2
def add_reg(context, x, nnn):
logging.info('Adding NNN to V[X]')
context.v[x] = (context.v[x] + nnn) % 256
context.pc += 2
def set_i(context, nnn):
logging.info('Setting NNN to index_reg')
context.index_reg = nnn
context.pc += 2
def pop_stack(context):
logging.info('Returning from a subroutine')
context.pc = context.stack.pop()
def call_rca1082(context, address): #TODO
print("operation not implemented yet:", address)
context.pc += 1
def clear(context):
logging.info('Clearing screen')
context.screen.clear()
context.pc += 2
def jump(context, address):
logging.info('Jump at 0x%2x address' % address)
context.pc = address
def call(context, address):
logging.info('Calling subroutine at 0x%2x address' % address)
context.pc += 2
context.stack.append(context.pc)
context.pc = address
def skip_equal(context, x, nnn, ifeq=True):
logging.info('Skip if V[X] === NNN is %s' % ifeq)
if (context.v[x] == nnn) == ifeq:
context.pc += 2
context.pc += 2
def skip_eq_reg(context, x, y):
logging.info('Skip if V[X] === V[Y]')
if context.v[x] == context.v[y]:
context.pc += 2
context.pc += 2
def set_reg(context, x, nnn):
logging.info('Set NNN to cpu reg V[x]')
context.v[x] = nnn
context.pc += 2
op_map = {
'0?E0': clear,
'0?EE': pop_stack,
'0XXX': call_rca1082,
'1XXX': jump,
'2XXX': call,
'3XYY': skip_equal,
'4XYY': lambda context, x, nn: skip_equal(context, x, nn, ifeq = False),
'5XY0': skip_eq_reg,
'6XYY': set_reg,
'7XYY': add_reg,
'8XY0': set_vx_vy,
'8XY1': set_vx_or_vy,
'8XY2': set_vx_and_vy,
'8XY3': set_vx_xor_vy,
'8XY4': add_vx_vy,
'8XY5': sub_vx_vy,
'8XY6': shift_right,
'8XY7': sub_vx_vy_vf,
'8XYE': shift_vy_left,
'9XY0': jump_noteq,
'AXXX': set_i,
'BXXX': jump_nnn_v0,
'CXYY': set_vx_rand,
'DXYZ': draw_sprite,
'EX9E': lambda context, x: skip_key_vx(x, result=False),
'EXA1': skip_key_vx,
'FX07': set_vx_delay_timer,
'FX0A': set_vx_key_pressed,
'FX15': set_delay_timer,
'FX18': set_sound_timer,
'FX1E': add_reg_ind,
'FX29': set_i_font,
'FX33': set_bcd_vx,
'FX55': set_mem_v0_vx,
'FX65': fill_v0_vx
}
| martindimondo/PyC8 | chip8/operations.py | Python | bsd-3-clause | 6,673 |
/*
* Created on Oct 18, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.tolweb.tapestry;
import java.util.Collection;
import org.apache.tapestry.BaseComponent;
import org.apache.tapestry.IRequestCycle;
import org.tolweb.hibernate.TitleIllustration;
import org.tolweb.tapestry.injections.BaseInjectable;
import org.tolweb.tapestry.injections.ImageInjectable;
import org.tolweb.treegrow.main.Contributor;
import org.tolweb.treegrow.main.ImageVersion;
import org.tolweb.treegrow.main.NodeImage;
import org.tolweb.treegrow.main.StringUtils;
/**
* @author dmandel
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public abstract class TitleIllustrations extends BaseComponent implements
ImageInjectable, BaseInjectable {
@SuppressWarnings("unchecked")
public abstract Collection getIllustrations();
public abstract TitleIllustration getCurrentIllustration();
public abstract void setCurrentIllustration(TitleIllustration value);
public abstract void setIsSingleIllustration(boolean value);
public abstract boolean getIsSingleIllustration();
public abstract int getIndex();
public abstract void setContributor(Contributor contributor);
public String getAltText() {
if (getCurrentIllustration().getImage() != null) {
NodeImage img = getCurrentIllustration().getImage();
if (StringUtils.notEmpty(img.getAltText())) {
return img.getAltText();
} else {
return " ";
}
} else {
return " ";
}
}
public void prepareForRender(IRequestCycle cycle) {
super.prepareForRender(cycle);
if (getIllustrations() != null && getIllustrations().size() == 1) {
setIsSingleIllustration(true);
} else {
setIsSingleIllustration(false);
}
}
public String getCurrentImageLocation() {
TitleIllustration currentIllustration = getCurrentIllustration();
ImageVersion version = currentIllustration.getVersion();
String url;
if (StringUtils.isEmpty(version.getFileName())) {
url = getImageDAO().generateAndSaveVersion(version);
} else {
url = getImageUtils().getVersionUrl(currentIllustration.getVersion());
}
return url;
}
public String getCurrentImageClass() {
if (getIsSingleIllustration()) {
return "singletillus";
} else {
return null;
}
}
}
| tolweb/tolweb-app | OnlineContributors/src/org/tolweb/tapestry/TitleIllustrations.java | Java | bsd-3-clause | 2,683 |
//---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_ParticleState.cpp
//! \author Alex Robinson
//! \brief Basic particle state class definition.
//!
//---------------------------------------------------------------------------//
// FRENSIE Includes
#include "MonteCarlo_ParticleState.hpp"
#include "Utility_PhysicalConstants.hpp"
#include "Utility_DirectionHelpers.hpp"
namespace MonteCarlo{
// Default constructor
/*! \details The default constructor should only be called before loading the
* particle state from an archive.
*/
ParticleState::ParticleState()
: d_history_number( 0 ),
d_particle_type(),
d_position(),
d_direction{0.0,0.0,1.0},
d_energy( 0.0 ),
d_time( 0.0 ),
d_collision_number( 0 ),
d_generation_number( 0 ),
d_weight( 1.0 ),
d_cell( Geometry::ModuleTraits::invalid_internal_cell_handle ),
d_lost( false ),
d_gone( false ),
d_ray( d_position, d_direction, false )
{ /* ... */ }
// Constructor
ParticleState::ParticleState(
const ParticleState::historyNumberType history_number,
const ParticleType type )
: d_history_number( history_number ),
d_particle_type( type ),
d_position(),
d_direction(),
d_energy( 0.0 ),
d_time( 0.0 ),
d_collision_number( 0 ),
d_generation_number( 0 ),
d_weight( 1.0 ),
d_cell( Geometry::ModuleTraits::invalid_internal_cell_handle ),
d_lost( false ),
d_gone( false ),
d_ray( d_position, d_direction, false )
{ /* ... */ }
// Copy constructor
/*! \details When copied, the new particle is assumed to not be lost and
* not be gone.
*/
ParticleState::ParticleState( const ParticleState& existing_base_state,
const ParticleType new_type,
const bool increment_generation_number,
const bool reset_collision_number )
: d_history_number( existing_base_state.d_history_number ),
d_particle_type( new_type ),
d_position{existing_base_state.d_position[0],
existing_base_state.d_position[1],
existing_base_state.d_position[2]},
d_direction{existing_base_state.d_direction[0],
existing_base_state.d_direction[1],
existing_base_state.d_direction[2]},
d_energy( existing_base_state.d_energy ),
d_time( existing_base_state.d_time ),
d_collision_number( existing_base_state.d_collision_number ),
d_generation_number( existing_base_state.d_generation_number ),
d_weight( existing_base_state.d_weight ),
d_cell( existing_base_state.d_cell ),
d_lost( false ),
d_gone( false ),
d_ray( d_position, d_direction, false )
{
// Increment the generation number if requested
if( increment_generation_number )
++d_generation_number;
// Reset the collision number if requested
if( reset_collision_number )
d_collision_number = 0u;
}
// Clone the particle state but change the history number
/*! \details This method returns a heap-allocated pointer. It is only safe
* to call this method inside of a smart pointer constructor or reset method.
* The clone will only need a new history number in very rare circumstances
* (e.g. state source).
*/
ParticleState* ParticleState::clone(
const ParticleState::historyNumberType new_history_number ) const
{
ParticleState* clone_state = this->clone();
clone_state->d_history_number = new_history_number;
return clone_state;
}
// Return the history number
ParticleState::historyNumberType ParticleState::getHistoryNumber() const
{
return d_history_number;
}
// Return the particle type
ParticleType ParticleState::getParticleType() const
{
return d_particle_type;
}
// Return the cell handle for the cell containing the particle
Geometry::ModuleTraits::InternalCellHandle ParticleState::getCell() const
{
return d_cell;
}
// Set the cell containing the particle
void ParticleState::setCell(
const Geometry::ModuleTraits::InternalCellHandle cell )
{
// Make sure the cell handle is valid
testPrecondition( cell !=
Geometry::ModuleTraits::invalid_internal_cell_handle);
d_cell = cell;
}
// Return the x position of the particle
double ParticleState::getXPosition() const
{
return d_position[0];
}
// Return the y position of the particle
double ParticleState::getYPosition() const
{
return d_position[1];
}
// Return the z position of the particle
double ParticleState::getZPosition() const
{
return d_position[2];
}
// Return the position of the particle
const double* ParticleState::getPosition() const
{
return d_position;
}
// Set the position of the particle
void ParticleState::setPosition( const double x_position,
const double y_position,
const double z_position )
{
// Make sure the coordinates are valid
testPrecondition( !ST::isnaninf( x_position ) );
testPrecondition( !ST::isnaninf( y_position ) );
testPrecondition( !ST::isnaninf( z_position ) );
d_position[0] = x_position;
d_position[1] = y_position;
d_position[2] = z_position;
}
// Return the x direction of the particle
double ParticleState::getXDirection() const
{
return d_direction[0];
}
// Return the y direction of the particle
double ParticleState::getYDirection() const
{
return d_direction[1];
}
// Return the z direction of the particle
double ParticleState::getZDirection() const
{
return d_direction[2];
}
// Return the direction of the particle
const double* ParticleState::getDirection() const
{
return d_direction;
}
// Set the direction of the particle
void ParticleState::setDirection( const double x_direction,
const double y_direction,
const double z_direction )
{
// Make sure the direction coordinates are valid
testPrecondition( !ST::isnaninf( x_direction ) );
testPrecondition( !ST::isnaninf( y_direction ) );
testPrecondition( !ST::isnaninf( z_direction ) );
// Make sure the direction is a unit vector
testPrecondition( Utility::validDirection( x_direction,
y_direction,
z_direction ) );
d_direction[0] = x_direction;
d_direction[1] = y_direction;
d_direction[2] = z_direction;
}
// Rotate the direction of the particle using polar a. cosine and azimuthal a.
/*! \details The polar angle cosine and azimuthal angle are w.r.t. the
* current particle direction and not the global coordinate system. These
* are the variables the commonly occur when sampling a new direction
* for the particle from a scattering distribution. This function is therefore
* meant to avoid duplicate code that would otherwise arise when determining
* the new particle direction
*/
void ParticleState::rotateDirection( const double polar_angle_cosine,
const double azimuthal_angle )
{
// Make sure the current particle direction is valid (initialized)
testPrecondition( Utility::validDirection( this->getDirection() ) );
// Make sure the polar angle cosine is valid
testPrecondition( polar_angle_cosine >= -1.0 );
testPrecondition( polar_angle_cosine <= 1.0 );
// Make sure the azimuthal angle is valid
testPrecondition( azimuthal_angle >= 0.0 );
testPrecondition( azimuthal_angle <= 2*Utility::PhysicalConstants::pi );
double outgoing_direction[3];
Utility::rotateDirectionThroughPolarAndAzimuthalAngle( polar_angle_cosine,
azimuthal_angle,
this->getDirection(),
outgoing_direction );
this->setDirection( outgoing_direction );
}
// Advance the particle along its direction by the requested distance
void ParticleState::advance( const double distance )
{
// Make sure the distance is valid
testPrecondition( !ST::isnaninf( distance ) );
d_position[0] += d_direction[0]*distance;
d_position[1] += d_direction[1]*distance;
d_position[2] += d_direction[2]*distance;
// Compute the time to traverse the distance
d_time += calculateTraversalTime( distance );
}
// Set the energy of the particle
/*! The default implementation is only valid for massless particles (It is
* assumed that the speed of the particle does not change with the energy).
*/
void ParticleState::setEnergy( const ParticleState::energyType energy )
{
// Make sure the energy is valid
testPrecondition( !ST::isnaninf( energy ) );
testPrecondition( energy > 0.0 );
d_energy = energy;
}
// Return the time state of the particle
ParticleState::timeType ParticleState::getTime() const
{
return d_time;
}
// Set the time state of the particle
void ParticleState::setTime( const ParticleState::timeType time )
{
d_time = time;
}
// Return the collision number of the particle
ParticleState::collisionNumberType ParticleState::getCollisionNumber() const
{
return d_collision_number;
}
// Increment the collision number
void ParticleState::incrementCollisionNumber()
{
++d_collision_number;
}
// Reset the collision number
/*! \details This should rarely be used - try to rely on the contructor to
* reset the collision number.
*/
void ParticleState::resetCollisionNumber()
{
d_collision_number = 0u;
}
// Return the generation number of the particle
ParticleState::generationNumberType ParticleState::getGenerationNumber() const
{
return d_generation_number;
}
// Increment the generation number
void ParticleState::incrementGenerationNumber()
{
++d_generation_number;
}
// Return the weight of the particle
double ParticleState::getWeight() const
{
return d_weight;
}
// Set the weight of the particle
void ParticleState::setWeight( const double weight )
{
d_weight = weight;
}
// Multiply the weight of the particle by a factor
void ParticleState::multiplyWeight( const double weight_factor )
{
// Make sure that the current weight is valid
testPrecondition( d_weight > 0.0 );
d_weight *= weight_factor;
}
// Return if the particle is lost
bool ParticleState::isLost() const
{
return d_lost;
}
// Set the particle as lost
void ParticleState::setAsLost()
{
d_lost = true;
}
// Return if the particle is gone
bool ParticleState::isGone() const
{
return d_gone;
}
// Set the particle as gone
void ParticleState::setAsGone()
{
d_gone = true;
}
} // end MonteCarlo
//---------------------------------------------------------------------------//
// end MonteCarlo_ParticleState.cpp
//---------------------------------------------------------------------------//
| lkersting/SCR-2123 | packages/monte_carlo/core/src/MonteCarlo_ParticleState.cpp | C++ | bsd-3-clause | 10,274 |
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
namespace Respect\Validation\Rules;
/**
* @group rule
* @covers Respect\Validation\Rules\PrimeNumber
* @covers Respect\Validation\Exceptions\PrimeNumberException
*/
class PrimeNumberTest extends \PHPUnit_Framework_TestCase
{
protected $object;
protected function setUp()
{
$this->object = new PrimeNumber();
}
/**
* @dataProvider providerForPrimeNumber
*/
public function testPrimeNumber($input)
{
$this->assertTrue($this->object->__invoke($input));
$this->assertTrue($this->object->check($input));
$this->assertTrue($this->object->assert($input));
}
/**
* @dataProvider providerForNotPrimeNumber
* @expectedException Respect\Validation\Exceptions\PrimeNumberException
*/
public function testNotPrimeNumber($input)
{
$this->assertFalse($this->object->__invoke($input));
$this->assertFalse($this->object->assert($input));
}
public function providerForPrimeNumber()
{
return array(
array(3),
array(5),
array(7),
array('3'),
array('5'),
array('+7'),
);
}
public function providerForNotPrimeNumber()
{
return array(
array(''),
array(null),
array(0),
array(10),
array(25),
array(36),
array(-1),
array('-1'),
array('25'),
array('0'),
array('a'),
array(' '),
array('Foo'),
);
}
}
| zinovyev/Validation | tests/unit/Rules/PrimeNumberTest.php | PHP | bsd-3-clause | 1,843 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/set_time_dialog.h"
#include "base/metrics/user_metrics.h"
#include "base/strings/string16.h"
#include "chrome/common/url_constants.h"
#include "chromeos/login/login_state/login_state.h"
#include "ui/gfx/geometry/size.h"
namespace chromeos {
namespace {
// Dialog width and height in DIPs.
const int kDefaultWidth = 530;
const int kDefaultHeightWithTimezone = 286;
const int kDefaultHeightWithoutTimezone = 228;
} // namespace
// static
void SetTimeDialog::ShowDialog(gfx::NativeWindow parent) {
base::RecordAction(base::UserMetricsAction("Options_SetTimeDialog_Show"));
auto* dialog = new SetTimeDialog();
dialog->ShowSystemDialog(parent);
}
// static
bool SetTimeDialog::ShouldShowTimezone() {
// After login the user should set the timezone via Settings, which applies
// additional restrictions.
return !LoginState::Get()->IsUserLoggedIn();
}
SetTimeDialog::SetTimeDialog()
: SystemWebDialogDelegate(GURL(chrome::kChromeUISetTimeURL),
base::string16() /* title */) {}
SetTimeDialog::~SetTimeDialog() = default;
void SetTimeDialog::GetDialogSize(gfx::Size* size) const {
size->SetSize(kDefaultWidth, ShouldShowTimezone()
? kDefaultHeightWithTimezone
: kDefaultHeightWithoutTimezone);
}
} // namespace chromeos
| endlessm/chromium-browser | chrome/browser/chromeos/set_time_dialog.cc | C++ | bsd-3-clause | 1,543 |
/*
* GaussianKernel.java
*
* Created on September 25, 2004, 4:52 PM
*/
package jpview.graphics;
/**
* This class creates a kernel for use by an AffineTransformOp
*
* @author clyon
*/
public class GaussianKernel {
private int radius = 5;
private float sigma = 1;
private float[] kernel;
/** Creates a new instance of GaussianKernel */
public GaussianKernel() {
kernel = makeKernel();
}
/**
* Creates a gaussian kernel with the provided radius
*
* @param r
* the radius for the gaussian kernel
*/
public GaussianKernel(int r) {
radius = r;
kernel = makeKernel();
}
/**
* Creates a gaussian kernel with the provided radius and sigma value
*
* @param r
* the radius of the blur
* @param s
* the sigma value for the kernel
*/
public GaussianKernel(int r, float s) {
radius = r;
sigma = s;
kernel = makeKernel();
}
private float[] makeKernel() {
kernel = new float[radius * radius];
float sum = 0;
for (int y = 0; y < radius; y++) {
for (int x = 0; x < radius; x++) {
int off = y * radius + x;
int xx = x - radius / 2;
int yy = y - radius / 2;
kernel[off] = (float) Math.pow(Math.E, -(xx * xx + yy * yy)
/ (2 * (sigma * sigma)));
sum += kernel[off];
}
}
for (int i = 0; i < kernel.length; i++)
kernel[i] /= sum;
return kernel;
}
/**
* Dumps a string representation of the kernel to standard out
*/
public void dump() {
for (int x = 0; x < radius; x++) {
for (int y = 0; y < radius; y++) {
System.out.print(kernel[y * radius + x] + "\t");
}
System.out.println();
}
}
/**
* returns the kernel as a float [] suitable for use with an affine
* transform
*
* @return the kernel values
*/
public float[] getKernel() {
return kernel;
}
public static void main(String args[]) {
GaussianKernel gk = new GaussianKernel(5, 100f);
gk.dump();
}
}
| synergynet/synergynet3 | synergynet3-museum-parent/synergynet3-museum-table/src/main/java/jpview/graphics/GaussianKernel.java | Java | bsd-3-clause | 2,024 |
<?php
/**
* This file is part of the proophsoftware/event-machine.
* (c) 2017-2019 prooph software GmbH <contact@prooph.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ProophExample\FunctionalFlavour;
use Prooph\EventMachine\Messaging\Message;
use Prooph\EventMachine\Messaging\MessageBag;
use Prooph\EventMachine\Runtime\Functional\Port;
use ProophExample\FunctionalFlavour\Api\Command;
use ProophExample\FunctionalFlavour\Api\Event;
use ProophExample\FunctionalFlavour\Api\Query;
final class ExampleFunctionalPort implements Port
{
/**
* {@inheritdoc}
*/
public function deserialize(Message $message)
{
//Note: we use a very simple mapping strategy here
//You could also use a deserializer or other techniques
switch ($message->messageType()) {
case Message::TYPE_COMMAND:
return Command::createFromNameAndPayload($message->messageName(), $message->payload());
case Message::TYPE_EVENT:
return Event::createFromNameAndPayload($message->messageName(), $message->payload());
case Message::TYPE_QUERY:
return Query::createFromNameAndPayload($message->messageName(), $message->payload());
}
}
/**
* {@inheritdoc}
*/
public function serializePayload($customMessage): array
{
//Since, we use objects with public properties as custom messages, casting to array is enough
//In a production setting, you should use your own immutable messages and a serializer
return (array) $customMessage;
}
/**
* {@inheritdoc}
*/
public function decorateEvent($customEvent): MessageBag
{
return new MessageBag(
Event::nameOf($customEvent),
MessageBag::TYPE_EVENT,
$customEvent
);
}
/**
* {@inheritdoc}
*/
public function getAggregateIdFromCommand(string $aggregateIdPayloadKey, $command): string
{
//Duck typing, do not do this in production but rather use your own interfaces
return $command->{$aggregateIdPayloadKey};
}
/**
* {@inheritdoc}
*/
public function callCommandPreProcessor($customCommand, $preProcessor)
{
//Duck typing, do not do this in production but rather use your own interfaces
return $preProcessor->preProcess($customCommand);
}
/**
* {@inheritdoc}
*/
public function callContextProvider($customCommand, $contextProvider)
{
//Duck typing, do not do this in production but rather use your own interfaces
return $contextProvider->provide($customCommand);
}
}
| proophsoftware/event-machine | examples/FunctionalFlavour/ExampleFunctionalPort.php | PHP | bsd-3-clause | 2,788 |
Гость создан | Veredior/filesender | language/ru_RU/guest_created.mail.php | PHP | bsd-3-clause | 23 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net.impl;
import android.content.Context;
import android.os.Build;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.util.Log;
import org.chromium.base.ObserverList;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeClassQualifiedName;
import org.chromium.base.annotations.UsedByReflection;
import org.chromium.net.BidirectionalStream;
import org.chromium.net.CronetEngine;
import org.chromium.net.NetworkQualityRttListener;
import org.chromium.net.NetworkQualityThroughputListener;
import org.chromium.net.RequestFinishedInfo;
import org.chromium.net.UrlRequest;
import org.chromium.net.urlconnection.CronetHttpURLConnection;
import org.chromium.net.urlconnection.CronetURLStreamHandlerFactory;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandlerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.concurrent.GuardedBy;
/**
* CronetEngine using Chromium HTTP stack implementation.
*/
@JNINamespace("cronet")
@UsedByReflection("CronetEngine.java")
@VisibleForTesting
public class CronetUrlRequestContext extends CronetEngine {
private static final int LOG_NONE = 3; // LOG(FATAL), no VLOG.
private static final int LOG_DEBUG = -1; // LOG(FATAL...INFO), VLOG(1)
private static final int LOG_VERBOSE = -2; // LOG(FATAL...INFO), VLOG(2)
static final String LOG_TAG = "ChromiumNetwork";
/**
* Synchronize access to mUrlRequestContextAdapter and shutdown routine.
*/
private final Object mLock = new Object();
private final ConditionVariable mInitCompleted = new ConditionVariable(false);
private final AtomicInteger mActiveRequestCount = new AtomicInteger(0);
private long mUrlRequestContextAdapter = 0;
private Thread mNetworkThread;
private boolean mNetworkQualityEstimatorEnabled;
/**
* Locks operations on network quality listeners, because listener
* addition and removal may occur on a different thread from notification.
*/
private final Object mNetworkQualityLock = new Object();
/**
* Locks operations on the list of RequestFinishedInfo.Listeners, because operations can happen
* on any thread.
*/
private final Object mFinishedListenerLock = new Object();
@GuardedBy("mNetworkQualityLock")
private final ObserverList<NetworkQualityRttListener> mRttListenerList =
new ObserverList<NetworkQualityRttListener>();
@GuardedBy("mNetworkQualityLock")
private final ObserverList<NetworkQualityThroughputListener> mThroughputListenerList =
new ObserverList<NetworkQualityThroughputListener>();
@GuardedBy("mFinishedListenerLock")
private final List<RequestFinishedInfo.Listener> mFinishedListenerList =
new ArrayList<RequestFinishedInfo.Listener>();
/**
* Synchronize access to mCertVerifierData.
*/
private ConditionVariable mWaitGetCertVerifierDataComplete = new ConditionVariable();
/** Holds CertVerifier data. */
private String mCertVerifierData;
@UsedByReflection("CronetEngine.java")
public CronetUrlRequestContext(final CronetEngine.Builder builder) {
CronetLibraryLoader.ensureInitialized(builder.getContext(), builder);
nativeSetMinLogLevel(getLoggingLevel());
synchronized (mLock) {
mUrlRequestContextAdapter = nativeCreateRequestContextAdapter(
createNativeUrlRequestContextConfig(builder.getContext(), builder));
if (mUrlRequestContextAdapter == 0) {
throw new NullPointerException("Context Adapter creation failed.");
}
mNetworkQualityEstimatorEnabled = builder.networkQualityEstimatorEnabled();
}
// Init native Chromium URLRequestContext on main UI thread.
Runnable task = new Runnable() {
@Override
public void run() {
CronetLibraryLoader.ensureInitializedOnMainThread(builder.getContext());
synchronized (mLock) {
// mUrlRequestContextAdapter is guaranteed to exist until
// initialization on main and network threads completes and
// initNetworkThread is called back on network thread.
nativeInitRequestContextOnMainThread(mUrlRequestContextAdapter);
}
}
};
// Run task immediately or post it to the UI thread.
if (Looper.getMainLooper() == Looper.myLooper()) {
task.run();
} else {
new Handler(Looper.getMainLooper()).post(task);
}
}
@VisibleForTesting
public static long createNativeUrlRequestContextConfig(
final Context context, CronetEngine.Builder builder) {
final long urlRequestContextConfig = nativeCreateRequestContextConfig(
builder.getUserAgent(), builder.storagePath(), builder.quicEnabled(),
builder.getDefaultQuicUserAgentId(context), builder.http2Enabled(),
builder.sdchEnabled(), builder.dataReductionProxyKey(),
builder.dataReductionProxyPrimaryProxy(), builder.dataReductionProxyFallbackProxy(),
builder.dataReductionProxySecureProxyCheckUrl(), builder.cacheDisabled(),
builder.httpCacheMode(), builder.httpCacheMaxSize(), builder.experimentalOptions(),
builder.mockCertVerifier(), builder.networkQualityEstimatorEnabled(),
builder.publicKeyPinningBypassForLocalTrustAnchorsEnabled(),
builder.certVerifierData());
for (Builder.QuicHint quicHint : builder.quicHints()) {
nativeAddQuicHint(urlRequestContextConfig, quicHint.mHost, quicHint.mPort,
quicHint.mAlternatePort);
}
for (Builder.Pkp pkp : builder.publicKeyPins()) {
nativeAddPkp(urlRequestContextConfig, pkp.mHost, pkp.mHashes, pkp.mIncludeSubdomains,
pkp.mExpirationDate.getTime());
}
return urlRequestContextConfig;
}
@Override
public UrlRequest createRequest(String url, UrlRequest.Callback callback, Executor executor,
int priority, Collection<Object> requestAnnotations, boolean disableCache,
boolean disableConnectionMigration) {
synchronized (mLock) {
checkHaveAdapter();
boolean metricsCollectionEnabled = false;
synchronized (mFinishedListenerLock) {
metricsCollectionEnabled = !mFinishedListenerList.isEmpty();
}
return new CronetUrlRequest(this, url, priority, callback, executor, requestAnnotations,
metricsCollectionEnabled, disableCache, disableConnectionMigration);
}
}
@Override
public BidirectionalStream createBidirectionalStream(String url,
BidirectionalStream.Callback callback, Executor executor, String httpMethod,
List<Map.Entry<String, String>> requestHeaders,
@BidirectionalStream.Builder.StreamPriority int priority, boolean disableAutoFlush,
boolean delayRequestHeadersUntilFirstFlush) {
synchronized (mLock) {
checkHaveAdapter();
return new CronetBidirectionalStream(this, url, priority, callback, executor,
httpMethod, requestHeaders, disableAutoFlush,
delayRequestHeadersUntilFirstFlush);
}
}
@Override
public boolean isEnabled() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
@Override
public String getVersionString() {
return "Cronet/" + ImplVersion.getVersion();
}
@Override
public void shutdown() {
synchronized (mLock) {
checkHaveAdapter();
if (mActiveRequestCount.get() != 0) {
throw new IllegalStateException("Cannot shutdown with active requests.");
}
// Destroying adapter stops the network thread, so it cannot be
// called on network thread.
if (Thread.currentThread() == mNetworkThread) {
throw new IllegalThreadStateException("Cannot shutdown from network thread.");
}
}
// Wait for init to complete on main and network thread (without lock,
// so other thread could access it).
mInitCompleted.block();
synchronized (mLock) {
// It is possible that adapter is already destroyed on another thread.
if (!haveRequestContextAdapter()) {
return;
}
nativeDestroy(mUrlRequestContextAdapter);
mUrlRequestContextAdapter = 0;
}
}
@Override
public void startNetLogToFile(String fileName, boolean logAll) {
synchronized (mLock) {
checkHaveAdapter();
nativeStartNetLogToFile(mUrlRequestContextAdapter, fileName, logAll);
}
}
@Override
public void stopNetLog() {
synchronized (mLock) {
checkHaveAdapter();
nativeStopNetLog(mUrlRequestContextAdapter);
}
}
@Override
public String getCertVerifierData(long timeout) {
if (timeout < 0) {
throw new IllegalArgumentException("timeout must be a positive value");
} else if (timeout == 0) {
timeout = 100;
}
mWaitGetCertVerifierDataComplete.close();
synchronized (mLock) {
checkHaveAdapter();
nativeGetCertVerifierData(mUrlRequestContextAdapter);
}
mWaitGetCertVerifierDataComplete.block(timeout);
return mCertVerifierData;
}
// This method is intentionally non-static to ensure Cronet native library
// is loaded by class constructor.
@Override
public byte[] getGlobalMetricsDeltas() {
return nativeGetHistogramDeltas();
}
@VisibleForTesting
@Override
public void configureNetworkQualityEstimatorForTesting(
boolean useLocalHostRequests, boolean useSmallerResponses) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mLock) {
checkHaveAdapter();
nativeConfigureNetworkQualityEstimatorForTesting(
mUrlRequestContextAdapter, useLocalHostRequests, useSmallerResponses);
}
}
@Override
public void addRttListener(NetworkQualityRttListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
if (mRttListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideRTTObservations(mUrlRequestContextAdapter, true);
}
}
mRttListenerList.addObserver(listener);
}
}
@Override
public void removeRttListener(NetworkQualityRttListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
mRttListenerList.removeObserver(listener);
if (mRttListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideRTTObservations(mUrlRequestContextAdapter, false);
}
}
}
}
@Override
public void addThroughputListener(NetworkQualityThroughputListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
if (mThroughputListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideThroughputObservations(mUrlRequestContextAdapter, true);
}
}
mThroughputListenerList.addObserver(listener);
}
}
@Override
public void removeThroughputListener(NetworkQualityThroughputListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
mThroughputListenerList.removeObserver(listener);
if (mThroughputListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideThroughputObservations(mUrlRequestContextAdapter, false);
}
}
}
}
@Override
public void addRequestFinishedListener(RequestFinishedInfo.Listener listener) {
synchronized (mFinishedListenerLock) {
mFinishedListenerList.add(listener);
}
}
@Override
public void removeRequestFinishedListener(RequestFinishedInfo.Listener listener) {
synchronized (mFinishedListenerLock) {
mFinishedListenerList.remove(listener);
}
}
@Override
public URLConnection openConnection(URL url) {
return openConnection(url, Proxy.NO_PROXY);
}
@Override
public URLConnection openConnection(URL url, Proxy proxy) {
if (proxy.type() != Proxy.Type.DIRECT) {
throw new UnsupportedOperationException();
}
String protocol = url.getProtocol();
if ("http".equals(protocol) || "https".equals(protocol)) {
return new CronetHttpURLConnection(url, this);
}
throw new UnsupportedOperationException("Unexpected protocol:" + protocol);
}
@Override
public URLStreamHandlerFactory createURLStreamHandlerFactory() {
return new CronetURLStreamHandlerFactory(this);
}
/**
* Mark request as started to prevent shutdown when there are active
* requests.
*/
void onRequestStarted() {
mActiveRequestCount.incrementAndGet();
}
/**
* Mark request as finished to allow shutdown when there are no active
* requests.
*/
void onRequestDestroyed() {
mActiveRequestCount.decrementAndGet();
}
@VisibleForTesting
public long getUrlRequestContextAdapter() {
synchronized (mLock) {
checkHaveAdapter();
return mUrlRequestContextAdapter;
}
}
private void checkHaveAdapter() throws IllegalStateException {
if (!haveRequestContextAdapter()) {
throw new IllegalStateException("Engine is shut down.");
}
}
private boolean haveRequestContextAdapter() {
return mUrlRequestContextAdapter != 0;
}
/**
* @return loggingLevel see {@link #LOG_NONE}, {@link #LOG_DEBUG} and
* {@link #LOG_VERBOSE}.
*/
private int getLoggingLevel() {
int loggingLevel;
if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
loggingLevel = LOG_VERBOSE;
} else if (Log.isLoggable(LOG_TAG, Log.DEBUG)) {
loggingLevel = LOG_DEBUG;
} else {
loggingLevel = LOG_NONE;
}
return loggingLevel;
}
@SuppressWarnings("unused")
@CalledByNative
private void initNetworkThread() {
synchronized (mLock) {
mNetworkThread = Thread.currentThread();
mInitCompleted.open();
}
Thread.currentThread().setName("ChromiumNet");
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
@SuppressWarnings("unused")
@CalledByNative
private void onRttObservation(final int rttMs, final long whenMs, final int source) {
synchronized (mNetworkQualityLock) {
for (final NetworkQualityRttListener listener : mRttListenerList) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onRttObservation(rttMs, whenMs, source);
}
};
postObservationTaskToExecutor(listener.getExecutor(), task);
}
}
}
@SuppressWarnings("unused")
@CalledByNative
private void onThroughputObservation(
final int throughputKbps, final long whenMs, final int source) {
synchronized (mNetworkQualityLock) {
for (final NetworkQualityThroughputListener listener : mThroughputListenerList) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onThroughputObservation(throughputKbps, whenMs, source);
}
};
postObservationTaskToExecutor(listener.getExecutor(), task);
}
}
}
@SuppressWarnings("unused")
@CalledByNative
private void onGetCertVerifierData(String certVerifierData) {
mCertVerifierData = certVerifierData;
mWaitGetCertVerifierDataComplete.open();
}
void reportFinished(final CronetUrlRequest request) {
final RequestFinishedInfo requestInfo = request.getRequestFinishedInfo();
ArrayList<RequestFinishedInfo.Listener> currentListeners;
synchronized (mFinishedListenerLock) {
currentListeners = new ArrayList<RequestFinishedInfo.Listener>(mFinishedListenerList);
}
for (final RequestFinishedInfo.Listener listener : currentListeners) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onRequestFinished(requestInfo);
}
};
postObservationTaskToExecutor(listener.getExecutor(), task);
}
}
private static void postObservationTaskToExecutor(Executor executor, Runnable task) {
try {
executor.execute(task);
} catch (RejectedExecutionException failException) {
Log.e(CronetUrlRequestContext.LOG_TAG, "Exception posting task to executor",
failException);
}
}
// Native methods are implemented in cronet_url_request_context_adapter.cc.
private static native long nativeCreateRequestContextConfig(String userAgent,
String storagePath, boolean quicEnabled, String quicUserAgentId, boolean http2Enabled,
boolean sdchEnabled, String dataReductionProxyKey,
String dataReductionProxyPrimaryProxy, String dataReductionProxyFallbackProxy,
String dataReductionProxySecureProxyCheckUrl, boolean disableCache, int httpCacheMode,
long httpCacheMaxSize, String experimentalOptions, long mockCertVerifier,
boolean enableNetworkQualityEstimator,
boolean bypassPublicKeyPinningForLocalTrustAnchors, String certVerifierData);
private static native void nativeAddQuicHint(
long urlRequestContextConfig, String host, int port, int alternatePort);
private static native void nativeAddPkp(long urlRequestContextConfig, String host,
byte[][] hashes, boolean includeSubdomains, long expirationTime);
private static native long nativeCreateRequestContextAdapter(long urlRequestContextConfig);
private static native int nativeSetMinLogLevel(int loggingLevel);
private static native byte[] nativeGetHistogramDeltas();
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeDestroy(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeStartNetLogToFile(long nativePtr, String fileName, boolean logAll);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeStopNetLog(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeGetCertVerifierData(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeInitRequestContextOnMainThread(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeConfigureNetworkQualityEstimatorForTesting(
long nativePtr, boolean useLocalHostRequests, boolean useSmallerResponses);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeProvideRTTObservations(long nativePtr, boolean should);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeProvideThroughputObservations(long nativePtr, boolean should);
}
| danakj/chromium | components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java | Java | bsd-3-clause | 21,435 |
/*L
* Copyright Oracle Inc
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details.
*/
/*
* eXist Open Source Native XML Database
* Copyright (C) 2001-04 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
*/
package org.exist.storage.index;
import java.nio.ByteBuffer;
import org.exist.storage.DBBroker;
import org.exist.storage.journal.LogException;
import org.exist.storage.txn.Txn;
/**
* @author wolf
*
*/
public class RemoveValueLoggable extends AbstractBFileLoggable {
protected long page;
protected short tid;
protected byte[] oldData;
protected int offset = 0;
protected int len;
/**
*
*
* @param page
* @param tid
* @param oldData
* @param offset
* @param len
* @param fileId
* @param transaction
*/
public RemoveValueLoggable(Txn transaction, byte fileId, long page, short tid, byte[] oldData, int offset, int len) {
super(BFile.LOG_REMOVE_VALUE, fileId, transaction);
this.page = page;
this.tid = tid;
this.oldData = oldData;
this.offset = offset;
this.len = len;
}
/**
* @param broker
* @param transactionId
*/
public RemoveValueLoggable(DBBroker broker, long transactionId) {
super(broker, transactionId);
}
public void write(ByteBuffer out) {
super.write(out);
out.putInt((int) page);
out.putShort(tid);
out.putShort((short) len);
out.put(oldData, offset, len);
}
public void read(ByteBuffer in) {
super.read(in);
page = in.getInt();
tid = in.getShort();
len = in.getShort();
oldData = new byte[len];
in.get(oldData);
}
public int getLogSize() {
return super.getLogSize() + len + 8;
}
public void redo() throws LogException {
getIndexFile().redoRemoveValue(this);
}
public void undo() throws LogException {
getIndexFile().undoRemoveValue(this);
}
public String dump() {
return super.dump() + " - remove value with tid " + tid + " from page " + page;
}
}
| NCIP/cadsr-cgmdr-nci-uk | src/org/exist/storage/index/RemoveValueLoggable.java | Java | bsd-3-clause | 3,088 |
/*
-- MAGMA (version 2.1.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date August 2016
@generated from sparse-iter/control/magma_zutil_sparse.cpp, normal z -> s, Tue Aug 30 09:38:47 2016
@author Hartwig Anzt
Utilities for testing MAGMA-sparse.
*/
#include <cuda_runtime_api.h>
#include "magmasparse_internal.h"
#define PRECISION_s
// --------------------
static const char *usage_sparse_short =
"%% Usage: %s [options] [-h|--help] matrices\n\n";
static const char *usage_sparse =
"Options are:\n"
" --solver Possibility to choose a solver:\n"
" CG, PCG, BICGSTAB, PBICGSTAB, GMRES, PGMRES, LOBPCG, JACOBI,\n"
" BAITER, IDR, PIDR, CGS, PCGS, TFQMR, PTFQMR, QMR, PQMR, BICG,\n"
" PBICG, BOMBARDMENT, ITERREF.\n"
" --basic Use non-optimized version\n"
" --ev x For eigensolvers, set number of eigenvalues/eigenvectors to compute.\n"
" --restart For GMRES: possibility to choose the restart.\n"
" For IDR: Number of distinct subspaces (1,2,4,8).\n"
" --atol x Set an absolute residual stopping criterion.\n"
" --verbose x Possibility to print intermediate residuals every x iteration.\n"
" --maxiter x Set an upper limit for the iteration count.\n"
" --rtol x Set a relative residual stopping criterion.\n"
" --format Possibility to choose a format for the sparse matrix:\n"
" CSR, ELL, SELLP, CUSPARSECSR\n"
" --blocksize x Set a specific blocksize for SELL-P format.\n"
" --alignment x Set a specific alignment for SELL-P format.\n"
" --mscale Possibility to scale the original matrix:\n"
" NOSCALE no scaling\n"
" UNITDIAG symmetric scaling to unit diagonal\n"
" --precond x Possibility to choose a preconditioner:\n"
" CG, BICGSTAB, GMRES, LOBPCG, JACOBI,\n"
" BAITER, IDR, CGS, TFQMR, QMR, BICG\n"
" BOMBARDMENT, ITERREF, ILU, PARILU, PARILUT, NONE.\n"
" --patol atol Absolute residual stopping criterion for preconditioner.\n"
" --prtol rtol Relative residual stopping criterion for preconditioner.\n"
" --piters k Iteration count for iterative preconditioner.\n"
" --plevels k Number of ILU levels.\n"
" --triolver k Solver for triangular ILU factors: e.g. CUSOLVE, JACOBI, ISAI.\n"
" --ppattern k Pattern used for ISAI preconditioner.\n"
" --psweeps x Number of iterative ParILU sweeps.\n"
" --trisolver Possibility to choose a triangular solver for ILU preconditioning: e.g. JACOBI, ISAI.\n"
" --ppattern k Possibility to choose a pattern for the trisolver: ISAI(k) or Block Jacobi.\n"
" --piters k Number of preconditioner relaxation steps, e.g. for ISAI or (Block) Jacobi trisolver.\n"
" --patol x Set an absolute residual stopping criterion for the preconditioner.\n"
" Corresponds to the relative fill-in in PARILUT.\n"
" --prtol x Set a relative residual stopping criterion for the preconditioner.\n"
" Corresponds to the replacement ratio in PARILUT.\n";
/**
Purpose
-------
Parses input options for a solver
Arguments
---------
@param[in]
argc int
command line input
@param[in]
argv char**
command line input
@param[in,out]
opts magma_sopts *
magma solver options
@param[out]
matrices int
counter how many linear systems to process
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_saux
********************************************************************/
extern "C"
magma_int_t
magma_sparse_opts(
int argc,
char** argv,
magma_sopts *opts,
int *matrices,
magma_queue_t queue )
{
magma_int_t info = MAGMA_SUCCESS;
// fill in default values
opts->input_format = Magma_CSR;
opts->blocksize = 32;
opts->alignment = 1;
opts->output_format = Magma_CSR;
opts->input_location = Magma_CPU;
opts->output_location = Magma_CPU;
opts->scaling = Magma_NOSCALE;
#if defined(PRECISION_z) | defined(PRECISION_d)
opts->solver_par.atol = 1e-16;
opts->solver_par.rtol = 1e-10;
#else
opts->solver_par.atol = 1e-8;
opts->solver_par.rtol = 1e-5;
#endif
opts->solver_par.maxiter = 1000;
opts->solver_par.verbose = 0;
opts->solver_par.version = 0;
opts->solver_par.restart = 50;
opts->solver_par.num_eigenvalues = 0;
opts->precond_par.solver = Magma_NONE;
opts->precond_par.trisolver = Magma_CUSOLVE;
#if defined(PRECISION_z) | defined(PRECISION_d)
opts->precond_par.atol = 1e-16;
opts->precond_par.rtol = 1e-10;
#else
opts->precond_par.atol = 0;
opts->precond_par.rtol = 1e-5;
#endif
opts->precond_par.maxiter = 100;
opts->precond_par.restart = 10;
opts->precond_par.levels = 0;
opts->precond_par.sweeps = 5;
opts->precond_par.maxiter = 1;
opts->precond_par.pattern = 1;
opts->solver_par.solver = Magma_CGMERGE;
printf( usage_sparse_short, argv[0] );
int ndevices;
cudaGetDeviceCount( &ndevices );
int basic = 0;
for( int i = 1; i < argc; ++i ) {
if ( strcmp("--format", argv[i]) == 0 && i+1 < argc ) {
i++;
if ( strcmp("CSR", argv[i]) == 0 ) {
opts->output_format = Magma_CSR;
} else if ( strcmp("ELL", argv[i]) == 0 ) {
opts->output_format = Magma_ELL;
} else if ( strcmp("SELLP", argv[i]) == 0 ) {
opts->output_format = Magma_SELLP;
} else if ( strcmp("CUSPARSECSR", argv[i]) == 0 ) {
opts->output_format = Magma_CUCSR;
} else {
printf( "%%error: invalid format, use default (CSR).\n" );
}
} else if ( strcmp("--mscale", argv[i]) == 0 && i+1 < argc ) {
i++;
if ( strcmp("NOSCALE", argv[i]) == 0 ) {
opts->scaling = Magma_NOSCALE;
}
else if ( strcmp("UNITDIAG", argv[i]) == 0 ) {
opts->scaling = Magma_UNITDIAG;
}
else if ( strcmp("UNITROW", argv[i]) == 0 ) {
opts->scaling = Magma_UNITROW;
}
else {
printf( "%%error: invalid scaling, use default.\n" );
}
} else if ( strcmp("--solver", argv[i]) == 0 && i+1 < argc ) {
i++;
if ( strcmp("CG", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_CGMERGE;
}
else if ( strcmp("PCG", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PCGMERGE;
}
else if ( strcmp("BICG", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_BICG;
}
else if ( strcmp("PBICG", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PBICG;
}
else if ( strcmp("BICGSTAB", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_BICGSTABMERGE;
}
else if ( strcmp("PBICGSTAB", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PBICGSTABMERGE;
}
else if ( strcmp("QMR", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_QMRMERGE;
}
else if ( strcmp("PQMR", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PQMRMERGE;
}
else if ( strcmp("TFQMR", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_TFQMRMERGE;
}
else if ( strcmp("PTFQMR", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PTFQMRMERGE;
}
else if ( strcmp("GMRES", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_GMRES;
}
else if ( strcmp("PGMRES", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PGMRES;
}
else if ( strcmp("LOBPCG", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_LOBPCG;
}
else if ( strcmp("LSQR", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_LSQR;
}
else if ( strcmp("JACOBI", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_JACOBI;
}
else if ( strcmp("BA", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_BAITER;
}
else if ( strcmp("BAO", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_BAITERO;
}
else if ( strcmp("IDR", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_IDRMERGE;
}
else if ( strcmp("PIDR", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PIDRMERGE;
}
else if ( strcmp("CGS", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_CGSMERGE;
}
else if ( strcmp("PCGS", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_PCGSMERGE;
}
else if ( strcmp("BOMBARDMENT", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_BOMBARDMERGE;
}
else if ( strcmp("ITERREF", argv[i]) == 0 ) {
opts->solver_par.solver = Magma_ITERREF;
}
else {
printf( "%%error: invalid solver.\n" );
}
} else if ( strcmp("--restart", argv[i]) == 0 && i+1 < argc ) {
opts->solver_par.restart = atoi( argv[++i] );
} else if ( strcmp("--precond", argv[i]) == 0 && i+1 < argc ) {
i++;
if ( strcmp("CG", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_CGMERGE;
}
else if ( strcmp("PCG", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PCG;
}
else if ( strcmp("BICGSTAB", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_BICGSTABMERGE;
}
else if ( strcmp("QMR", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_QMRMERGE;
}
else if ( strcmp("TFQMR", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_TFQMRMERGE;
}
else if ( strcmp("PTFQMR", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PTFQMRMERGE;
}
else if ( strcmp("GMRES", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_GMRES;
}
else if ( strcmp("PGMRES", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PGMRES;
}
else if ( strcmp("LOBPCG", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_LOBPCG;
}
else if ( strcmp("JACOBI", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_JACOBI;
}
else if ( strcmp("BA", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_BAITER;
}
else if ( strcmp("BAO", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_BAITERO;
}
else if ( strcmp("IDR", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_IDRMERGE;
}
else if ( strcmp("PIDR", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PIDRMERGE;
}
else if ( strcmp("CGS", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_CGSMERGE;
}
else if ( strcmp("PCGS", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PCGSMERGE;
}
else if ( strcmp("BOMBARDMENT", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_BOMBARD;
}
else if ( strcmp("ITERREF", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_ITERREF;
}
else if ( strcmp("ILU", argv[i]) == 0 || strcmp("IC", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_ILU;
}
else if ( strcmp("PARILU", argv[i]) == 0 || strcmp("AIC", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PARILU;
}
else if ( strcmp("PARICT", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PARICT;
}
else if ( strcmp("PARILUT", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_PARILUT;
}
else if ( strcmp("CUSTOMIC", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_CUSTOMIC;
}
else if ( strcmp("CUSTOMILU", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_CUSTOMILU;
}
else if ( strcmp("ISAI", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_ISAI;
}
else if ( strcmp("NONE", argv[i]) == 0 ) {
opts->precond_par.solver = Magma_NONE;
}
else {
printf( "%%error: invalid preconditioner.\n" );
}
} else if ( strcmp("--trisolver", argv[i]) == 0 && i+1 < argc ) {
i++;
if ( strcmp("CG", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_CGMERGE;
}
else if ( strcmp("BICGSTAB", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_BICGSTABMERGE;
}
else if ( strcmp("QMR", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_QMRMERGE;
}
else if ( strcmp("TFQMR", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_TFQMRMERGE;
}
else if ( strcmp("GMRES", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_GMRES;
}
else if ( strcmp("JACOBI", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_JACOBI;
}
else if ( strcmp("BA", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_BAITER;
}
else if ( strcmp("BAO", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_BAITERO;
}
else if ( strcmp("IDR", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_IDRMERGE;
}
else if ( strcmp("CGS", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_CGSMERGE;
}
else if ( strcmp("CUSOLVE", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_CUSOLVE;
}
else if ( strcmp("ISAI", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_ISAI;
}
else if ( strcmp("NONE", argv[i]) == 0 ) {
opts->precond_par.trisolver = Magma_NONE;
}
else {
printf( "%%error: invalid trisolver.\n" );
}
} else if ( strcmp("--basic", argv[i]) == 0 && i+1 < argc ) {
basic = 1;
} else if ( strcmp("--prestart", argv[i]) == 0 && i+1 < argc ) {
opts->precond_par.restart = atoi( argv[++i] );
} else if ( strcmp("--patol", argv[i]) == 0 && i+1 < argc ) {
sscanf( argv[++i], "%f", &opts->precond_par.atol );
}else if ( strcmp("--prtol", argv[i]) == 0 && i+1 < argc ) {
sscanf( argv[++i], "%f", &opts->precond_par.rtol );
} else if ( strcmp("--piters", argv[i]) == 0 && i+1 < argc ) {
opts->precond_par.maxiter = atoi( argv[++i] );
} else if ( strcmp("--ppattern", argv[i]) == 0 && i+1 < argc ) {
opts->precond_par.pattern = atoi( argv[++i] );
} else if ( strcmp("--psweeps", argv[i]) == 0 && i+1 < argc ) {
opts->precond_par.sweeps = atoi( argv[++i] );
} else if ( strcmp("--plevels", argv[i]) == 0 && i+1 < argc ) {
opts->precond_par.levels = atoi( argv[++i] );
} else if ( strcmp("--blocksize", argv[i]) == 0 && i+1 < argc ) {
opts->blocksize = atoi( argv[++i] );
} else if ( strcmp("--alignment", argv[i]) == 0 && i+1 < argc ) {
opts->alignment = atoi( argv[++i] );
} else if ( strcmp("--verbose", argv[i]) == 0 && i+1 < argc ) {
opts->solver_par.verbose = atoi( argv[++i] );
} else if ( strcmp("--maxiter", argv[i]) == 0 && i+1 < argc ) {
opts->solver_par.maxiter = atoi( argv[++i] );
} else if ( strcmp("--atol", argv[i]) == 0 && i+1 < argc ) {
sscanf( argv[++i], "%f", &opts->solver_par.atol );
} else if ( strcmp("--rtol", argv[i]) == 0 && i+1 < argc ) {
sscanf( argv[++i], "%f", &opts->solver_par.rtol );
} else if ( strcmp("--ev", argv[i]) == 0 && i+1 < argc ) {
opts->solver_par.num_eigenvalues = atoi( argv[++i] );
} else if ( strcmp("--version", argv[i]) == 0 && i+1 < argc ) {
opts->solver_par.version = atoi( argv[++i] );
}
// ----- usage
else if ( strcmp("-h", argv[i]) == 0 ||
strcmp("--help", argv[i]) == 0 ) {
fprintf( stderr, usage_sparse, argv[0] );
} else {
*matrices = i;
break;
}
}
if( basic == 1 ){
if ( opts->solver_par.solver == Magma_CGMERGE ) {
opts->solver_par.solver = Magma_CG;
}
else if ( opts->solver_par.solver == Magma_PCGMERGE) {
opts->solver_par.solver = Magma_PCG;
}
else if ( opts->solver_par.solver == Magma_BICGSTABMERGE ) {
opts->solver_par.solver = Magma_BICGSTAB;
}
else if ( opts->solver_par.solver == Magma_PBICGSTAB ) {
opts->solver_par.solver = Magma_PBICGSTAB;
}
else if ( opts->solver_par.solver == Magma_TFQMRMERGE ) {
opts->solver_par.solver = Magma_TFQMR;
}
else if ( opts->solver_par.solver == Magma_PTFQMRMERGE) {
opts->solver_par.solver = Magma_PTFQMR;
}
else if ( opts->solver_par.solver == Magma_CGSMERGE ) {
opts->solver_par.solver = Magma_CGS;
}
else if ( opts->solver_par.solver == Magma_PCGSMERGE) {
opts->solver_par.solver = Magma_PCGS;
}
else if ( opts->solver_par.solver == Magma_QMRMERGE ) {
opts->solver_par.solver = Magma_QMR;
}
else if ( opts->solver_par.solver == Magma_PQMRMERGE) {
opts->solver_par.solver = Magma_PQMR;
}
else if ( opts->solver_par.solver == Magma_QMRMERGE ) {
opts->solver_par.solver = Magma_QMR;
}
else if ( opts->solver_par.solver == Magma_PCGMERGE) {
opts->solver_par.solver = Magma_PCG;
}
else if ( opts->solver_par.solver == Magma_IDRMERGE) {
opts->solver_par.solver = Magma_IDR;
}
else if ( opts->solver_par.solver == Magma_PIDRMERGE) {
opts->solver_par.solver = Magma_PIDR;
}
else if ( opts->solver_par.solver == Magma_BOMBARDMERGE) {
opts->solver_par.solver = Magma_BOMBARD;
}
}
// make sure preconditioner is NONE for unpreconditioned systems
if ( opts->solver_par.solver != Magma_PCG &&
opts->solver_par.solver != Magma_PCGMERGE &&
opts->solver_par.solver != Magma_PGMRES &&
opts->solver_par.solver != Magma_PBICGSTAB &&
opts->solver_par.solver != Magma_PBICGSTABMERGE &&
opts->solver_par.solver != Magma_ITERREF &&
opts->solver_par.solver != Magma_PIDR &&
opts->solver_par.solver != Magma_PIDRMERGE &&
opts->solver_par.solver != Magma_PCGS &&
opts->solver_par.solver != Magma_PCGSMERGE &&
opts->solver_par.solver != Magma_PTFQMR &&
opts->solver_par.solver != Magma_PQMRMERGE &&
opts->solver_par.solver != Magma_PTFQMRMERGE &&
opts->solver_par.solver != Magma_PQMR &&
opts->solver_par.solver != Magma_PBICG &&
opts->solver_par.solver != Magma_LSQR &&
opts->solver_par.solver != Magma_LOBPCG ){
opts->precond_par.solver = Magma_NONE;
}
// ensure to take a symmetric preconditioner for the PCG
if ( ( opts->solver_par.solver == Magma_PCG || opts->solver_par.solver == Magma_PCGMERGE )
&& opts->precond_par.solver == Magma_ILU )
opts->precond_par.solver = Magma_ICC;
if ( ( opts->solver_par.solver == Magma_PCG || opts->solver_par.solver == Magma_PCGMERGE )
&& opts->precond_par.solver == Magma_PARILU )
opts->precond_par.solver = Magma_PARIC;
return info;
}
| maxhutch/magma | sparse-iter/control/magma_sutil_sparse.cpp | C++ | bsd-3-clause | 21,167 |
// $Id$
//
// Copyright (C) 2007-2013 Greg Landrum
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <GraphMol/RDKitBase.h>
#include <GraphMol/Fingerprints/AtomPairs.h>
#include <GraphMol/Subgraphs/Subgraphs.h>
#include <DataStructs/SparseIntVect.h>
#include <RDGeneral/hash/hash.hpp>
#include <boost/cstdint.hpp>
#include <boost/dynamic_bitset.hpp>
#include <boost/foreach.hpp>
namespace RDKit {
namespace AtomPairs {
unsigned int numPiElectrons(const Atom *atom) {
PRECONDITION(atom, "no atom");
unsigned int res = 0;
if (atom->getIsAromatic()) {
res = 1;
} else if (atom->getHybridization() != Atom::SP3) {
unsigned int val = static_cast<unsigned int>(atom->getExplicitValence());
val -= atom->getNumExplicitHs();
CHECK_INVARIANT(val >= atom->getDegree(),
"explicit valence exceeds atom degree");
res = val - atom->getDegree();
}
return res;
}
boost::uint32_t getAtomCode(const Atom *atom, unsigned int branchSubtract,
bool includeChirality) {
PRECONDITION(atom, "no atom");
boost::uint32_t code;
unsigned int numBranches = 0;
if (atom->getDegree() > branchSubtract) {
numBranches = atom->getDegree() - branchSubtract;
}
code = numBranches % maxNumBranches;
unsigned int nPi = numPiElectrons(atom) % maxNumPi;
code |= nPi << numBranchBits;
unsigned int typeIdx = 0;
unsigned int nTypes = 1 << numTypeBits;
while (typeIdx < nTypes) {
if (atomNumberTypes[typeIdx] ==
static_cast<unsigned int>(atom->getAtomicNum())) {
break;
} else if (atomNumberTypes[typeIdx] >
static_cast<unsigned int>(atom->getAtomicNum())) {
typeIdx = nTypes;
break;
}
++typeIdx;
}
if (typeIdx == nTypes) --typeIdx;
code |= typeIdx << (numBranchBits + numPiBits);
if (includeChirality) {
std::string cipCode;
if (atom->getPropIfPresent(common_properties::_CIPCode, cipCode)) {
boost::uint32_t offset = numBranchBits + numPiBits + numTypeBits;
if (cipCode == "R") {
code |= 1 << offset;
} else if (cipCode == "S") {
code |= 2 << offset;
}
}
}
POSTCONDITION(code < (1 << (codeSize + (includeChirality ? 2 : 0))),
"code exceeds number of bits");
return code;
};
boost::uint32_t getAtomPairCode(boost::uint32_t codeI, boost::uint32_t codeJ,
unsigned int dist, bool includeChirality) {
PRECONDITION(dist < maxPathLen, "dist too long");
boost::uint32_t res = dist;
res |= std::min(codeI, codeJ) << numPathBits;
res |= std::max(codeI, codeJ)
<< (numPathBits + codeSize + (includeChirality ? numChiralBits : 0));
return res;
}
template <typename T1, typename T2>
void updateElement(SparseIntVect<T1> &v, T2 elem) {
v.setVal(elem, v.getVal(elem) + 1);
}
template <typename T1>
void updateElement(ExplicitBitVect &v, T1 elem) {
v.setBit(elem % v.getNumBits());
}
template <typename T>
void setAtomPairBit(boost::uint32_t i, boost::uint32_t j,
boost::uint32_t nAtoms,
const std::vector<boost::uint32_t> &atomCodes,
const double *dm, T *bv, unsigned int minLength,
unsigned int maxLength, bool includeChirality) {
unsigned int dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
boost::uint32_t bitId =
getAtomPairCode(atomCodes[i], atomCodes[j], dist, includeChirality);
updateElement(*bv, static_cast<boost::uint32_t>(bitId));
}
}
SparseIntVect<boost::int32_t> *getAtomPairFingerprint(
const ROMol &mol, const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
return getAtomPairFingerprint(mol, 1, maxPathLen - 1, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality, use2D,
confId);
};
SparseIntVect<boost::int32_t> *getAtomPairFingerprint(
const ROMol &mol, unsigned int minLength, unsigned int maxLength,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
SparseIntVect<boost::int32_t> *res = new SparseIntVect<boost::int32_t>(
1 << (numAtomPairFingerprintBits + 2 * (includeChirality ? 2 : 0)));
const double *dm;
if (use2D) {
dm = MolOps::getDistanceMat(mol);
} else {
dm = MolOps::get3DDistanceMat(mol, confId);
}
const unsigned int nAtoms = mol.getNumAtoms();
std::vector<boost::uint32_t> atomCodes;
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()] %
((1 << codeSize) - 1));
}
}
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
unsigned int i = (*atomItI)->getIdx();
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=
ignoreAtoms->end()) {
continue;
}
if (!fromAtoms) {
for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;
atomItJ != mol.endAtoms(); ++atomItJ) {
unsigned int j = (*atomItJ)->getIdx();
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=
ignoreAtoms->end()) {
continue;
}
setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,
includeChirality);
}
} else {
BOOST_FOREACH (boost::uint32_t j, *fromAtoms) {
if (j != i) {
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=
ignoreAtoms->end()) {
continue;
}
setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,
includeChirality);
}
}
}
}
return res;
}
SparseIntVect<boost::int32_t> *getHashedAtomPairFingerprint(
const ROMol &mol, unsigned int nBits, unsigned int minLength,
unsigned int maxLength, const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
SparseIntVect<boost::int32_t> *res = new SparseIntVect<boost::int32_t>(nBits);
const double *dm;
if (use2D) {
dm = MolOps::getDistanceMat(mol);
} else {
dm = MolOps::get3DDistanceMat(mol, confId);
}
const unsigned int nAtoms = mol.getNumAtoms();
std::vector<boost::uint32_t> atomCodes;
atomCodes.reserve(nAtoms);
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()]);
}
}
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
unsigned int i = (*atomItI)->getIdx();
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=
ignoreAtoms->end()) {
continue;
}
if (!fromAtoms) {
for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;
atomItJ != mol.endAtoms(); ++atomItJ) {
unsigned int j = (*atomItJ)->getIdx();
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=
ignoreAtoms->end()) {
continue;
}
unsigned int dist =
static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
boost::uint32_t bit = 0;
gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));
gboost::hash_combine(bit, dist);
gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));
updateElement(*res, static_cast<boost::int32_t>(bit % nBits));
}
}
} else {
BOOST_FOREACH (boost::uint32_t j, *fromAtoms) {
if (j != i) {
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=
ignoreAtoms->end()) {
continue;
}
unsigned int dist =
static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
boost::uint32_t bit = 0;
gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));
gboost::hash_combine(bit, dist);
gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));
updateElement(*res, static_cast<boost::int32_t>(bit % nBits));
}
}
}
}
}
return res;
}
ExplicitBitVect *getHashedAtomPairFingerprintAsBitVect(
const ROMol &mol, unsigned int nBits, unsigned int minLength,
unsigned int maxLength, const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants,
unsigned int nBitsPerEntry, bool includeChirality, bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
static int bounds[4] = {1, 2, 4, 8};
unsigned int blockLength = nBits / nBitsPerEntry;
SparseIntVect<boost::int32_t> *sres = getHashedAtomPairFingerprint(
mol, blockLength, minLength, maxLength, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality, use2D, confId);
ExplicitBitVect *res = new ExplicitBitVect(nBits);
if (nBitsPerEntry != 4) {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second > static_cast<int>(i))
res->setBit(val.first * nBitsPerEntry + i);
}
}
} else {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second >= bounds[i]) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
}
delete sres;
return res;
}
boost::uint64_t getTopologicalTorsionCode(
const std::vector<boost::uint32_t> &pathCodes, bool includeChirality) {
bool reverseIt = false;
unsigned int i = 0;
unsigned int j = pathCodes.size() - 1;
while (i < j) {
if (pathCodes[i] > pathCodes[j]) {
reverseIt = true;
break;
} else if (pathCodes[i] < pathCodes[j]) {
break;
}
++i;
--j;
}
int shiftSize = codeSize + (includeChirality ? numChiralBits : 0);
boost::uint64_t res = 0;
if (reverseIt) {
for (unsigned int i = 0; i < pathCodes.size(); ++i) {
res |= static_cast<boost::uint64_t>(pathCodes[pathCodes.size() - i - 1])
<< (shiftSize * i);
}
} else {
for (unsigned int i = 0; i < pathCodes.size(); ++i) {
res |= static_cast<boost::uint64_t>(pathCodes[i]) << (shiftSize * i);
}
}
return res;
}
size_t getTopologicalTorsionHash(
const std::vector<boost::uint32_t> &pathCodes) {
bool reverseIt = false;
unsigned int i = 0;
unsigned int j = pathCodes.size() - 1;
while (i < j) {
if (pathCodes[i] > pathCodes[j]) {
reverseIt = true;
break;
} else if (pathCodes[i] < pathCodes[j]) {
break;
}
++i;
--j;
}
boost::uint32_t res = 0;
if (reverseIt) {
for (unsigned int i = 0; i < pathCodes.size(); ++i) {
gboost::hash_combine(res, pathCodes[pathCodes.size() - i - 1]);
}
} else {
for (unsigned int i = 0; i < pathCodes.size(); ++i) {
gboost::hash_combine(res, pathCodes[i]);
}
}
return res;
}
SparseIntVect<boost::int64_t> *getTopologicalTorsionFingerprint(
const ROMol &mol, unsigned int targetSize,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
boost::uint64_t sz = 1;
sz = (sz << (targetSize *
(codeSize + (includeChirality ? numChiralBits : 0))));
// NOTE: this -1 is incorrect but it's needed for backwards compatibility.
// hopefully we'll never have a case with a torsion that hits this.
//
// mmm, bug compatible.
sz -= 1;
SparseIntVect<boost::int64_t> *res = new SparseIntVect<boost::int64_t>(sz);
std::vector<boost::uint32_t> atomCodes;
atomCodes.reserve(mol.getNumAtoms());
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
// need to add to the atomCode here because we subtract off up to 2 below
// as part of the branch correction
atomCodes.push_back(
(*atomInvariants)[(*atomItI)->getIdx()] % ((1 << codeSize) - 1) + 2);
}
}
boost::dynamic_bitset<> *fromAtomsBV = 0;
if (fromAtoms) {
fromAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (boost::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }
}
boost::dynamic_bitset<> *ignoreAtomsBV = 0;
if (ignoreAtoms) {
ignoreAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (boost::uint32_t fAt, *ignoreAtoms) {
ignoreAtomsBV->set(fAt);
}
}
boost::dynamic_bitset<> pAtoms(mol.getNumAtoms());
PATH_LIST paths = findAllPathsOfLengthN(mol, targetSize, false);
for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();
++pathIt) {
bool keepIt = true;
if (fromAtomsBV) {
keepIt = false;
}
std::vector<boost::uint32_t> pathCodes;
const PATH_TYPE &path = *pathIt;
if (fromAtomsBV) {
if (fromAtomsBV->test(static_cast<boost::uint32_t>(path.front())) ||
fromAtomsBV->test(static_cast<boost::uint32_t>(path.back()))) {
keepIt = true;
}
}
if (keepIt && ignoreAtomsBV) {
BOOST_FOREACH (int pElem, path) {
if (ignoreAtomsBV->test(pElem)) {
keepIt = false;
break;
}
}
}
if (keepIt) {
pAtoms.reset();
for (PATH_TYPE::const_iterator pIt = path.begin(); pIt < path.end();
++pIt) {
// look for a cycle that doesn't start at the first atom
// we can't effectively canonicalize these at the moment
// (was github #811)
if (pIt != path.begin() && *pIt != *(path.begin()) && pAtoms[*pIt]) {
pathCodes.clear();
break;
}
pAtoms.set(*pIt);
unsigned int code = atomCodes[*pIt] - 1;
// subtract off the branching number:
if (pIt != path.begin() && pIt + 1 != path.end()) {
--code;
}
pathCodes.push_back(code);
}
if (pathCodes.size()) {
boost::int64_t code =
getTopologicalTorsionCode(pathCodes, includeChirality);
updateElement(*res, code);
}
}
}
delete fromAtomsBV;
delete ignoreAtomsBV;
return res;
}
namespace {
template <typename T>
void TorsionFpCalc(T *res, const ROMol &mol, unsigned int nBits,
unsigned int targetSize,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants,
bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
std::vector<boost::uint32_t> atomCodes;
atomCodes.reserve(mol.getNumAtoms());
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
// need to add to the atomCode here because we subtract off up to 2 below
// as part of the branch correction
atomCodes.push_back(((*atomInvariants)[(*atomItI)->getIdx()] << 1) + 1);
}
}
boost::dynamic_bitset<> *fromAtomsBV = 0;
if (fromAtoms) {
fromAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (boost::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }
}
boost::dynamic_bitset<> *ignoreAtomsBV = 0;
if (ignoreAtoms) {
ignoreAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (boost::uint32_t fAt, *ignoreAtoms) {
ignoreAtomsBV->set(fAt);
}
}
PATH_LIST paths = findAllPathsOfLengthN(mol, targetSize, false);
for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();
++pathIt) {
bool keepIt = true;
if (fromAtomsBV) {
keepIt = false;
}
const PATH_TYPE &path = *pathIt;
if (fromAtomsBV) {
if (fromAtomsBV->test(static_cast<boost::uint32_t>(path.front())) ||
fromAtomsBV->test(static_cast<boost::uint32_t>(path.back()))) {
keepIt = true;
}
}
if (keepIt && ignoreAtomsBV) {
BOOST_FOREACH (int pElem, path) {
if (ignoreAtomsBV->test(pElem)) {
keepIt = false;
break;
}
}
}
if (keepIt) {
std::vector<boost::uint32_t> pathCodes(targetSize);
for (unsigned int i = 0; i < targetSize; ++i) {
unsigned int code = atomCodes[path[i]] - 1;
// subtract off the branching number:
if (i > 0 && i < targetSize - 1) {
--code;
}
pathCodes[i] = code;
}
size_t bit = getTopologicalTorsionHash(pathCodes);
updateElement(*res, bit % nBits);
}
}
delete fromAtomsBV;
delete ignoreAtomsBV;
}
} // end of local namespace
SparseIntVect<boost::int64_t> *getHashedTopologicalTorsionFingerprint(
const ROMol &mol, unsigned int nBits, unsigned int targetSize,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
SparseIntVect<boost::int64_t> *res = new SparseIntVect<boost::int64_t>(nBits);
TorsionFpCalc(res, mol, nBits, targetSize, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality);
return res;
}
ExplicitBitVect *getHashedTopologicalTorsionFingerprintAsBitVect(
const ROMol &mol, unsigned int nBits, unsigned int targetSize,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants,
unsigned int nBitsPerEntry, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
static int bounds[4] = {1, 2, 4, 8};
unsigned int blockLength = nBits / nBitsPerEntry;
SparseIntVect<boost::int64_t> *sres =
new SparseIntVect<boost::int64_t>(blockLength);
TorsionFpCalc(sres, mol, blockLength, targetSize, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality);
ExplicitBitVect *res = new ExplicitBitVect(nBits);
if (nBitsPerEntry != 4) {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second > static_cast<int>(i))
res->setBit(val.first * nBitsPerEntry + i);
}
}
} else {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second >= bounds[i]) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
}
delete sres;
return res;
}
} // end of namespace AtomPairs
} // end of namespace RDKit
| adalke/rdkit | Code/GraphMol/Fingerprints/AtomPairs.cpp | C++ | bsd-3-clause | 21,277 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_Ldap
*/
namespace Zend\Ldap\Collection;
use Zend\Ldap;
use Zend\Ldap\Exception;
use Zend\Stdlib\ErrorHandler;
/**
* Zend\Ldap\Collection\DefaultIterator is the default collection iterator implementation
* using ext/ldap
*
* @category Zend
* @package Zend_Ldap
*/
class DefaultIterator implements \Iterator, \Countable
{
const ATTRIBUTE_TO_LOWER = 1;
const ATTRIBUTE_TO_UPPER = 2;
const ATTRIBUTE_NATIVE = 3;
/**
* LDAP Connection
*
* @var \Zend\Ldap\Ldap
*/
protected $ldap = null;
/**
* Result identifier resource
*
* @var resource
*/
protected $resultId = null;
/**
* Current result entry identifier
*
* @var resource
*/
protected $current = null;
/**
* Number of items in query result
*
* @var integer
*/
protected $itemCount = -1;
/**
* The method that will be applied to the attribute's names.
*
* @var integer|callable
*/
protected $attributeNameTreatment = self::ATTRIBUTE_TO_LOWER;
/**
* Constructor.
*
* @param \Zend\Ldap\Ldap $ldap
* @param resource $resultId
* @throws \Zend\Ldap\Exception\LdapException if no entries was found.
* @return DefaultIterator
*/
public function __construct(Ldap\Ldap $ldap, $resultId)
{
$this->ldap = $ldap;
$this->resultId = $resultId;
$resource = $ldap->getResource();
ErrorHandler::start();
$this->itemCount = ldap_count_entries($resource, $resultId);
ErrorHandler::stop();
if ($this->itemCount === false) {
throw new Exception\LdapException($this->ldap, 'counting entries');
}
}
public function __destruct()
{
$this->close();
}
/**
* Closes the current result set
*
* @return bool
*/
public function close()
{
$isClosed = false;
if (is_resource($this->resultId)) {
ErrorHandler::start();
$isClosed = ldap_free_result($this->resultId);
ErrorHandler::stop();
$this->resultId = null;
$this->current = null;
}
return $isClosed;
}
/**
* Gets the current LDAP connection.
*
* @return \Zend\Ldap\Ldap
*/
public function getLDAP()
{
return $this->ldap;
}
/**
* Sets the attribute name treatment.
*
* Can either be one of the following constants
* - Zend\Ldap\Collection\DefaultIterator::ATTRIBUTE_TO_LOWER
* - Zend\Ldap\Collection\DefaultIterator::ATTRIBUTE_TO_UPPER
* - Zend\Ldap\Collection\DefaultIterator::ATTRIBUTE_NATIVE
* or a valid callback accepting the attribute's name as it's only
* argument and returning the new attribute's name.
*
* @param integer|callable $attributeNameTreatment
* @return DefaultIterator Provides a fluent interface
*/
public function setAttributeNameTreatment($attributeNameTreatment)
{
if (is_callable($attributeNameTreatment)) {
if (is_string($attributeNameTreatment) && !function_exists($attributeNameTreatment)) {
$this->attributeNameTreatment = self::ATTRIBUTE_TO_LOWER;
} elseif (is_array($attributeNameTreatment)
&& !method_exists($attributeNameTreatment[0], $attributeNameTreatment[1])
) {
$this->attributeNameTreatment = self::ATTRIBUTE_TO_LOWER;
} else {
$this->attributeNameTreatment = $attributeNameTreatment;
}
} else {
$attributeNameTreatment = (int)$attributeNameTreatment;
switch ($attributeNameTreatment) {
case self::ATTRIBUTE_TO_LOWER:
case self::ATTRIBUTE_TO_UPPER:
case self::ATTRIBUTE_NATIVE:
$this->attributeNameTreatment = $attributeNameTreatment;
break;
default:
$this->attributeNameTreatment = self::ATTRIBUTE_TO_LOWER;
break;
}
}
return $this;
}
/**
* Returns the currently set attribute name treatment
*
* @return integer|callable
*/
public function getAttributeNameTreatment()
{
return $this->attributeNameTreatment;
}
/**
* Returns the number of items in current result
* Implements Countable
*
* @return int
*/
public function count()
{
return $this->itemCount;
}
/**
* Return the current result item
* Implements Iterator
*
* @return array|null
* @throws \Zend\Ldap\Exception\LdapException
*/
public function current()
{
if (!is_resource($this->current)) {
$this->rewind();
}
if (!is_resource($this->current)) {
return null;
}
$entry = array('dn' => $this->key());
$ber_identifier = null;
$resource = $this->ldap->getResource();
ErrorHandler::start();
$name = ldap_first_attribute(
$resource, $this->current,
$ber_identifier
);
ErrorHandler::stop();
while ($name) {
ErrorHandler::start();
$data = ldap_get_values_len($resource, $this->current, $name);
ErrorHandler::stop();
if (!$data) {
$data = array();
}
if (isset($data['count'])) {
unset($data['count']);
}
switch ($this->attributeNameTreatment) {
case self::ATTRIBUTE_TO_LOWER:
$attrName = strtolower($name);
break;
case self::ATTRIBUTE_TO_UPPER:
$attrName = strtoupper($name);
break;
case self::ATTRIBUTE_NATIVE:
$attrName = $name;
break;
default:
$attrName = call_user_func($this->attributeNameTreatment, $name);
break;
}
$entry[$attrName] = $data;
ErrorHandler::start();
$name = ldap_next_attribute(
$resource, $this->current,
$ber_identifier
);
ErrorHandler::stop();
}
ksort($entry, SORT_LOCALE_STRING);
return $entry;
}
/**
* Return the result item key
* Implements Iterator
*
* @throws \Zend\Ldap\Exception\LdapException
* @return string|null
*/
public function key()
{
if (!is_resource($this->current)) {
$this->rewind();
}
if (is_resource($this->current)) {
$resource = $this->ldap->getResource();
ErrorHandler::start();
$currentDn = ldap_get_dn($resource, $this->current);
ErrorHandler::stop();
if ($currentDn === false) {
throw new Exception\LdapException($this->ldap, 'getting dn');
}
return $currentDn;
} else {
return null;
}
}
/**
* Move forward to next result item
* Implements Iterator
*
* @throws \Zend\Ldap\Exception\LdapException
*/
public function next()
{
$code = 0;
if (is_resource($this->current) && $this->itemCount > 0) {
$resource = $this->ldap->getResource();
ErrorHandler::start();
$this->current = ldap_next_entry($resource, $this->current);
ErrorHandler::stop();
if ($this->current === false) {
$msg = $this->ldap->getLastError($code);
if ($code === Exception\LdapException::LDAP_SIZELIMIT_EXCEEDED) {
// we have reached the size limit enforced by the server
return;
} elseif ($code > Exception\LdapException::LDAP_SUCCESS) {
throw new Exception\LdapException($this->ldap, 'getting next entry (' . $msg . ')');
}
}
} else {
$this->current = false;
}
}
/**
* Rewind the Iterator to the first result item
* Implements Iterator
*
*
* @throws \Zend\Ldap\Exception\LdapException
*/
public function rewind()
{
if (is_resource($this->resultId)) {
$resource = $this->ldap->getResource();
ErrorHandler::start();
$this->current = ldap_first_entry($resource, $this->resultId);
ErrorHandler::stop();
if ($this->current === false
&& $this->ldap->getLastErrorCode() > Exception\LdapException::LDAP_SUCCESS
) {
throw new Exception\LdapException($this->ldap, 'getting first entry');
}
}
}
/**
* Check if there is a current result item
* after calls to rewind() or next()
* Implements Iterator
*
* @return boolean
*/
public function valid()
{
return (is_resource($this->current));
}
}
| OtsList/OtsList.eu-AAC-for-OpenTibia | vendor/ZF2/library/Zend/Ldap/Collection/DefaultIterator.php | PHP | bsd-3-clause | 9,869 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\HalfproductSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="halfproduct-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id_product') ?>
<?= $form->field($model, 'kode') ?>
<?= $form->field($model, 'nama') ?>
<?= $form->field($model, 'package') ?>
<?= $form->field($model, 'panjang') ?>
<?php // echo $form->field($model, 'lebar') ?>
<?php // echo $form->field($model, 'berat') ?>
<?php // echo $form->field($model, 'flag') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div> | hendrihmwn/propensiA08 | views/halfproduct/_search.php | PHP | bsd-3-clause | 923 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioHurtHandler : MonoBehaviour {
// Static reference to singleton object
public static AudioHurtHandler instance;
public AudioClip[] myClip;
// Use this for initialization
void Start ()
{
instance = gameObject.GetComponent<AudioHurtHandler>();
}
public void playSound ()
{
audio.PlayOneShot(myClip[Random.Range(0,myClip.Length)]);
//wait ();
}
IEnumerator wait()
{
yield return new WaitForSeconds(1);
}
}
| Socapex/polyGamesHackathon | Assets/Scripts/AudioHurtHandler.cs | C# | bsd-3-clause | 533 |
<?php namespace estvoyage\risingsun\comparison\unary\container\payload;
use estvoyage\risingsun\{ container, comparison, ointeger, block };
class disjunction
implements
comparison\unary\container\payload
{
private
$operand,
$recipient
;
function __construct($operand, comparison\recipient $recipient)
{
$this->operand = $operand;
$this->recipient = $recipient;
}
function containerIteratorEngineControllerForUnaryComparisonAtPositionIs(comparison\unary $comparison, ointeger $position, container\iterator\engine\controller $controller)
{
$comparison
->recipientOfComparisonWithOperandIs(
$this->operand,
new comparison\recipient\block(
new block\functor(
function($nboolean) use ($controller)
{
$this->recipient->nbooleanIs($nboolean);
(new comparison\unary\with\true\boolean)
->recipientOfComparisonWithOperandIs(
$nboolean,
new comparison\recipient\functor\ok(
function() use ($controller)
{
$controller->remainingIterationsInContainerIteratorEngineAreUseless();
}
)
)
;
}
)
)
)
;
}
}
| estvoyage/risingsun | src/comparison/unary/container/payload/disjunction.php | PHP | bsd-3-clause | 1,166 |
<?php
namespace UForm\Form\Element;
use UForm\Filtering\FilterChain;
use UForm\Form\Element;
/**
* Element that intends to contain other elements.
* It only aims to be a common parent for Group and Collection
*
* In some ways it is opposed to the Primary element that cant contain other elements
*
* @see UForm\Form\Element\Container\Group
* @see UForm\Form\Element\Container\Collection
* @see UForm\Form\Element\Container\Primary
* @semanticType container
*/
abstract class Container extends Element
{
public function __construct($name = null)
{
parent::__construct($name);
$this->addSemanticType('container');
}
/**
* Get an element by its name
* @param $name
* @return Element
*/
abstract public function getElement($name);
/**
* Get the elements contained in this container.
* Values are required because a collection requires values to be generated
* @param mixed $values used for the "collection" element that is rendered according to a value set
* @return Element[] the elements contained in this container
*/
abstract public function getElements($values = null);
/**
* Get an element located directly in this element. There is an exception for unnamed elements :
* we will search inside directElements of unnamed elements
* @param string $name name of the element to get
* @param mixed $values used for the "collection" element that is rendered according to a value set
* @return null|Element|Container the element found or null if the element does not exist
*/
public function getDirectElement($name, $values = null)
{
foreach ($this->getElements($values) as $elm) {
if ($name == $elm->getName()) {
return $elm;
} elseif (!$elm->getName() && $elm instanceof Container) {
/* @var $elm \UForm\Form\Element\Container */
$element = $elm->getDirectElement($name);
if ($element) {
return $element;
}
}
}
return null;
}
/**
* Get direct elements with the given name
* @param $name
* @param null $values
* @return Element[]
*/
public function getDirectElements($name, $values = null)
{
$elements = [];
foreach ($this->getElements($values) as $elm) {
if ($name == $elm->getName()) {
$elements[] = $elm;
} elseif (!$elm->getName() && $elm instanceof Container) {
/* @var $elm \UForm\Form\Element\Container */
$elements += $elm->getDirectElements($name, $values);
}
}
return $elements;
}
/**
* check if this element contains at least one element that is an instance of the given type
* @param string $className the name of the class to search for
* @return bool true if the instance was found
*/
public function hasDirectElementInstance($className)
{
foreach ($this->getElements() as $el) {
if (is_a($el, $className)) {
return true;
}
}
return false;
}
/**
* Check if this element contains at least one element with the given semantic type
* @param string $type the type to search for
* @return bool true if the semantic type was found
*/
public function hasDirectElementSemanticType($type)
{
foreach ($this->getElements() as $el) {
if ($el->hasSemanticType($type)) {
return true;
}
}
return false;
}
public function prepareFilterChain(FilterChain $filterChain)
{
parent::prepareFilterChain($filterChain);
foreach ($this->getElements() as $v) {
$v->prepareFilterChain($filterChain);
}
}
/**
* @inheritdoc
*/
public function setParent(Container $parent)
{
$r = parent::setParent($parent);
foreach ($this->getElements() as $element) {
$element->refreshParent();
}
return $r;
}
}
| gsouf/UForm | src/UForm/Form/Element/Container.php | PHP | bsd-3-clause | 4,172 |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 03 10:16:39 2013
@author: Grahesh
"""
import pandas
from qstkutil import DataAccess as da
import numpy as np
import math
import copy
import qstkutil.qsdateutil as du
import datetime as dt
import qstkutil.DataAccess as da
import qstkutil.tsutil as tsu
import qstkstudy.EventProfiler as ep
"""
Accepts a list of symbols along with start and end date
Returns the Event Matrix which is a pandas Datamatrix
Event matrix has the following structure :
|IBM |GOOG|XOM |MSFT| GS | JP |
(d1)|nan |nan | 1 |nan |nan | 1 |
(d2)|nan | 1 |nan |nan |nan |nan |
(d3)| 1 |nan | 1 |nan | 1 |nan |
(d4)|nan | 1 |nan | 1 |nan |nan |
...................................
...................................
Also, d1 = start date
nan = no information about any event.
1 = status bit(positively confirms the event occurence)
"""
# Get the data from the data store
storename = "NSEData" # get data from our daily prices source
# Available field names: open, close, high, low, close, actual_close, volume
closefield = "close"
volumefield = "volume"
window = 10
def getHalfYearEndDates(timestamps):
newTS=[]
tempYear=timestamps[0].year
flag=1
for x in range(0, len(timestamps)-1):
if(timestamps[x].year==tempYear):
if(timestamps[x].month==4 and flag==1):
newTS.append(timestamps[x-1])
flag=0
if(timestamps[x].month==10):
newTS.append(timestamps[x-1])
tempYear=timestamps[x].year+1
flag=1
return newTS
def findEvents(symbols, startday,endday, marketSymbol,verbose=False):
# Reading the Data for the list of Symbols.
timeofday=dt.timedelta(hours=16)
timestamps = du.getNSEdays(startday,endday,timeofday)
endOfHalfYear=getHalfYearEndDates(timestamps)
dataobj = da.DataAccess('NSEData')
if verbose:
print __name__ + " reading data"
# Reading the Data
close = dataobj.get_data(timestamps, symbols, closefield)
# Completing the Data - Removing the NaN values from the Matrix
close = (close.fillna(method='ffill')).fillna(method='backfill')
# Calculating Daily Returns for the Market
tsu.returnize0(close.values)
# Calculating the Returns of the Stock Relative to the Market
# So if a Stock went up 5% and the Market rised 3%. The the return relative to market is 2%
mktneutDM = close - close[marketSymbol]
np_eventmat = copy.deepcopy(mktneutDM)
for sym in symbols:
for time in timestamps:
np_eventmat[sym][time]=np.NAN
if verbose:
print __name__ + " finding events"
# Generating the Event Matrix
# Event described is : Analyzing half year events for given stocks.
for symbol in symbols:
for i in endOfHalfYear:
np_eventmat[symbol][i] = 1.0 #overwriting by the bit, marking the event
return np_eventmat
#################################################
################ MAIN CODE ######################
#################################################
symbols = np.loadtxt('NSE500port.csv',dtype='S13',comments='#', skiprows=1)
# You might get a message about some files being missing, don't worry about it.
#symbols =['SPY','BFRE','ATCS','RSERF','GDNEF','LAST','ATTUF','JBFCF','CYVA','SPF','XPO','EHECF','TEMO','AOLS','CSNT','REMI','GLRP','AIFLY','BEE','DJRT','CHSTF','AICAF']
#symbols=['NSE','3MINDIA.NS','AARTIIND.NS','ABAN.NS','ABB.NS','ABGSHIP.NS','ABIRLANUV.NS','ACC.NS','ADANIENT.NS','ADANIPORT.NS','ADANIPOWE.NS','ADVANTA.NS','ALLCARGO.NS','AIAENG.NS','AIL.NS','AZKOINDIA.NS']
startday = dt.datetime(2011,1,1)
endday = dt.datetime(2012,1,1)
eventMatrix = findEvents(symbols,startday,endday,marketSymbol='NSE500',verbose=True)
eventMatrix.to_csv('eventmatrix.csv', sep=',')
eventProfiler = ep.EventProfiler(eventMatrix,startday,endday,lookback_days=20,lookforward_days=20,verbose=True)
eventProfiler.study(filename="HalfYearEventStudy.jpg",plotErrorBars=True,plotMarketNeutral=True,plotEvents=False,marketSymbol='NSE500')
| grahesh/Stock-Market-Event-Analysis | Examples/Event Analysis/Half-Yearly End/Half_Year_End_Analysis.py | Python | bsd-3-clause | 4,522 |
<?php
include_once 'dynamic_db_connection.php';
/**
* This is the model class for table "THEME_MANAGEMENT".
*
* The followings are the available columns in table 'THEME_MANAGEMENT':
* @property string $PID
* @property string $THEME
*/
class Theme_Management extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Theme_Management the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'THEME_MANAGEMENT';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('THEME', 'length', 'max'=>20),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('USER_ID,ID, THEME', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'USER_ID' => 'Userid',
'THEME' => 'Theme',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('USER_ID',$this->USER_ID,true);
$criteria->compare('THEME',$this->THEME,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
} | Rathilesh/FMS_V1 | protected/models/Theme_Management.php | PHP | bsd-3-clause | 2,079 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "platform/fonts/shaping/RunSegmenter.h"
#include "platform/fonts/ScriptRunIterator.h"
#include "platform/fonts/SmallCapsIterator.h"
#include "platform/fonts/SymbolsIterator.h"
#include "platform/fonts/UTF16TextIterator.h"
#include "platform/text/Character.h"
#include "wtf/Assertions.h"
namespace blink {
RunSegmenter::RunSegmenter(const UChar* buffer, unsigned bufferSize, FontOrientation runOrientation, FontVariant variant)
: m_bufferSize(bufferSize)
, m_candidateRange({ 0, 0, USCRIPT_INVALID_CODE, OrientationIterator::OrientationKeep, SmallCapsIterator::SmallCapsSameCase })
, m_scriptRunIterator(adoptPtr(new ScriptRunIterator(buffer, bufferSize)))
, m_orientationIterator(runOrientation == FontOrientation::VerticalMixed ? adoptPtr(new OrientationIterator(buffer, bufferSize, runOrientation)) : nullptr)
, m_smallCapsIterator(variant == FontVariantSmallCaps ? adoptPtr(new SmallCapsIterator(buffer, bufferSize)) : nullptr)
, m_symbolsIterator(adoptPtr(new SymbolsIterator(buffer, bufferSize)))
, m_lastSplit(0)
, m_scriptRunIteratorPosition(0)
, m_orientationIteratorPosition(runOrientation == FontOrientation::VerticalMixed ? 0 : m_bufferSize)
, m_smallCapsIteratorPosition(variant == FontVariantSmallCaps ? 0 : m_bufferSize)
, m_symbolsIteratorPosition(0)
, m_atEnd(false)
{
}
void RunSegmenter::consumeScriptIteratorPastLastSplit()
{
ASSERT(m_scriptRunIterator);
if (m_scriptRunIteratorPosition <= m_lastSplit && m_scriptRunIteratorPosition < m_bufferSize) {
while (m_scriptRunIterator->consume(m_scriptRunIteratorPosition, m_candidateRange.script)) {
if (m_scriptRunIteratorPosition > m_lastSplit)
return;
}
}
}
void RunSegmenter::consumeOrientationIteratorPastLastSplit()
{
if (m_orientationIterator && m_orientationIteratorPosition <= m_lastSplit && m_orientationIteratorPosition < m_bufferSize) {
while (m_orientationIterator->consume(&m_orientationIteratorPosition, &m_candidateRange.renderOrientation)) {
if (m_orientationIteratorPosition > m_lastSplit)
return;
}
}
}
void RunSegmenter::consumeSmallCapsIteratorPastLastSplit()
{
if (m_smallCapsIterator && m_smallCapsIteratorPosition <= m_lastSplit && m_smallCapsIteratorPosition < m_bufferSize) {
while (m_smallCapsIterator->consume(&m_smallCapsIteratorPosition, &m_candidateRange.smallCapsBehavior)) {
if (m_smallCapsIteratorPosition > m_lastSplit)
return;
}
}
}
void RunSegmenter::consumeSymbolsIteratorPastLastSplit()
{
ASSERT(m_symbolsIterator);
if (m_symbolsIteratorPosition <= m_lastSplit && m_symbolsIteratorPosition < m_bufferSize) {
while (m_symbolsIterator->consume(&m_symbolsIteratorPosition, &m_candidateRange.fontFallbackPriority)) {
if (m_symbolsIteratorPosition > m_lastSplit)
return;
}
}
}
bool RunSegmenter::consume(RunSegmenterRange* nextRange)
{
if (m_atEnd || !m_bufferSize)
return false;
consumeScriptIteratorPastLastSplit();
consumeOrientationIteratorPastLastSplit();
consumeSmallCapsIteratorPastLastSplit();
consumeSymbolsIteratorPastLastSplit();
if (m_scriptRunIteratorPosition <= m_orientationIteratorPosition
&& m_scriptRunIteratorPosition <= m_smallCapsIteratorPosition
&& m_scriptRunIteratorPosition <= m_symbolsIteratorPosition) {
m_lastSplit = m_scriptRunIteratorPosition;
}
if (m_orientationIteratorPosition <= m_scriptRunIteratorPosition
&& m_orientationIteratorPosition <= m_smallCapsIteratorPosition
&& m_orientationIteratorPosition <= m_symbolsIteratorPosition) {
m_lastSplit = m_orientationIteratorPosition;
}
if (m_smallCapsIteratorPosition <= m_scriptRunIteratorPosition
&& m_smallCapsIteratorPosition <= m_orientationIteratorPosition
&& m_smallCapsIteratorPosition <= m_symbolsIteratorPosition) {
m_lastSplit = m_smallCapsIteratorPosition;
}
if (m_symbolsIteratorPosition <= m_scriptRunIteratorPosition
&& m_symbolsIteratorPosition <= m_orientationIteratorPosition
&& m_symbolsIteratorPosition <= m_smallCapsIteratorPosition) {
m_lastSplit = m_symbolsIteratorPosition;
}
m_candidateRange.start = m_candidateRange.end;
m_candidateRange.end = m_lastSplit;
*nextRange = m_candidateRange;
m_atEnd = m_lastSplit == m_bufferSize;
return true;
}
} // namespace blink
| was4444/chromium.src | third_party/WebKit/Source/platform/fonts/shaping/RunSegmenter.cpp | C++ | bsd-3-clause | 4,699 |
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=campus_rec',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];
| henrybagus/seminar | config/db.php | PHP | bsd-3-clause | 183 |
require_dependency 'spree/calculator'
module Spree
class PaymentCalculator::PerItem < Calculator
preference :amount, :decimal, :default => 0
attr_accessible :preferred_amount
def self.description
I18n.t(:flat_rate_per_item)
end
def compute(object=nil)
return 0 if object.nil?
self.preferred_amount * object.line_items.reduce(0) do |sum, value|
if !matching_products || matching_products.include?(value.product)
value_to_add = value.quantity
else
value_to_add = 0
end
sum + value_to_add
end
end
# Returns all products that match this calculator, but only if the calculator
# is attached to a promotion. If attached to a ShippingMethod, nil is returned.
def matching_products
# Regression check for #1596
# Calculator::PerItem can be used in two cases.
# The first is in a typical promotion, providing a discount per item of a particular item
# The second is a ShippingMethod, where it applies to an entire order
#
# Shipping methods do not have promotions attached, but promotions do
# Therefore we must check for promotions
if self.calculable.respond_to?(:promotion)
self.calculable.promotion.rules.map(&:products).flatten
end
end
end
end | damianogiacomello/spree_payment_calculator | app/model/spree/payment_calculator/per_item.rb | Ruby | bsd-3-clause | 1,325 |
import {InputWidget, InputWidgetView} from "./input_widget"
import {input} from "core/dom"
import * as p from "core/properties"
import {bk_input} from "styles/widgets/inputs"
export class TextInputView extends InputWidgetView {
model: TextInput
protected input_el: HTMLInputElement
connect_signals(): void {
super.connect_signals()
this.connect(this.model.properties.name.change, () => this.input_el.name = this.model.name || "")
this.connect(this.model.properties.value.change, () => this.input_el.value = this.model.value)
this.connect(this.model.properties.disabled.change, () => this.input_el.disabled = this.model.disabled)
this.connect(this.model.properties.placeholder.change, () => this.input_el.placeholder = this.model.placeholder)
}
render(): void {
super.render()
this.input_el = input({
type: "text",
class: bk_input,
name: this.model.name,
value: this.model.value,
disabled: this.model.disabled,
placeholder: this.model.placeholder,
})
this.input_el.addEventListener("change", () => this.change_input())
this.group_el.appendChild(this.input_el)
}
change_input(): void {
this.model.value = this.input_el.value
super.change_input()
}
}
export namespace TextInput {
export type Attrs = p.AttrsOf<Props>
export type Props = InputWidget.Props & {
value: p.Property<string>
placeholder: p.Property<string>
}
}
export interface TextInput extends TextInput.Attrs {}
export class TextInput extends InputWidget {
properties: TextInput.Props
constructor(attrs?: Partial<TextInput.Attrs>) {
super(attrs)
}
static initClass(): void {
this.prototype.default_view = TextInputView
this.define<TextInput.Props>({
value: [ p.String, "" ],
placeholder: [ p.String, "" ],
})
}
}
TextInput.initClass()
| timsnyder/bokeh | bokehjs/src/lib/models/widgets/text_input.ts | TypeScript | bsd-3-clause | 1,868 |
#!/usr/bin/python
# Copyright (c) 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
A chain with four possible intermediates with different notBefore and notAfter
dates, for testing path bulding prioritization.
"""
import sys
sys.path += ['../..']
import gencerts
DATE_A = '150101120000Z'
DATE_B = '150102120000Z'
DATE_C = '180101120000Z'
DATE_D = '180102120000Z'
root = gencerts.create_self_signed_root_certificate('Root')
root.set_validity_range(DATE_A, DATE_D)
int_ac = gencerts.create_intermediate_certificate('Intermediate', root)
int_ac.set_validity_range(DATE_A, DATE_C)
int_ad = gencerts.create_intermediate_certificate('Intermediate', root)
int_ad.set_validity_range(DATE_A, DATE_D)
int_ad.set_key(int_ac.get_key())
int_bc = gencerts.create_intermediate_certificate('Intermediate', root)
int_bc.set_validity_range(DATE_B, DATE_C)
int_bc.set_key(int_ac.get_key())
int_bd = gencerts.create_intermediate_certificate('Intermediate', root)
int_bd.set_validity_range(DATE_B, DATE_D)
int_bd.set_key(int_ac.get_key())
target = gencerts.create_end_entity_certificate('Target', int_ac)
target.set_validity_range(DATE_A, DATE_D)
gencerts.write_chain('The root', [root], out_pem='root.pem')
gencerts.write_chain('Intermediate with validity range A..C',
[int_ac], out_pem='int_ac.pem')
gencerts.write_chain('Intermediate with validity range A..D',
[int_ad], out_pem='int_ad.pem')
gencerts.write_chain('Intermediate with validity range B..C',
[int_bc], out_pem='int_bc.pem')
gencerts.write_chain('Intermediate with validity range B..D',
[int_bd], out_pem='int_bd.pem')
gencerts.write_chain('The target', [target], out_pem='target.pem')
| endlessm/chromium-browser | net/data/path_builder_unittest/validity_date_prioritization/generate-certs.py | Python | bsd-3-clause | 1,833 |
<?php
include_once "../../includes/easyparliament/init.php";
if (($date = get_http_var('d')) && preg_match('#^\d\d\d\d-\d\d-\d\d$#', $date)) {
$this_page = 'hansard_date';
$PAGE->set_hansard_headings(array('date'=>$date));
$URL = new URL($this_page);
$db = new ParlDB;
$q = $db->query("SELECT MIN(hdate) AS hdate FROM hansard WHERE hdate > '$date'");
if ($q->rows() > 0 && $q->field(0, 'hdate') != NULL) {
$URL->insert( array( 'd'=>$q->field(0, 'hdate') ) );
$title = format_date($q->field(0, 'hdate'), SHORTDATEFORMAT);
$nextprevdata['next'] = array (
'hdate' => $q->field(0, 'hdate'),
'url' => $URL->generate(),
'body' => 'Next day',
'title' => $title
);
}
$q = $db->query("SELECT MAX(hdate) AS hdate FROM hansard WHERE hdate < '$date'");
if ($q->rows() > 0 && $q->field(0, 'hdate') != NULL) {
$URL->insert( array( 'd'=>$q->field(0, 'hdate') ) );
$title = format_date($q->field(0, 'hdate'), SHORTDATEFORMAT);
$nextprevdata['prev'] = array (
'hdate' => $q->field(0, 'hdate'),
'url' => $URL->generate(),
'body' => 'Previous day',
'title' => $title
);
}
# $year = substr($date, 0, 4);
# $URL = new URL($hansardmajors[1]['page_year']);
# $URL->insert(array('y'=>$year));
# $nextprevdata['up'] = array (
# 'body' => "All of $year",
# 'title' => '',
# 'url' => $URL->generate()
# );
$DATA->set_page_metadata($this_page, 'nextprev', $nextprevdata);
$PAGE->page_start();
$PAGE->stripe_start();
include_once INCLUDESPATH . 'easyparliament/recess.php';
$time = strtotime($date);
$dayofweek = date('w', $time);
$recess = recess_prettify(date('j', $time), date('n', $time), date('Y', $time), 1);
if ($recess[0]) {
print '<p>The Houses of Parliament are in their ' . $recess[0] . ' at this time.</p>';
} elseif ($dayofweek == 0 || $dayofweek == 6) {
print '<p>The Houses of Parliament do not meet at weekends.</p>';
} else {
$data = array(
'date' => $date
);
foreach (array_keys($hansardmajors) as $major) {
$URL = new URL($hansardmajors[$major]['page_all']);
$URL->insert(array('d'=>$date));
$data[$major] = array('listurl'=>$URL->generate());
}
major_summary($data);
}
$PAGE->stripe_end(array(
array (
'type' => 'nextprev'
),
));
$PAGE->page_end();
} else {
header("Location: http://" . DOMAIN . "/");
exit;
}
| palfrey/twfy | www/docs/hansard/index.php | PHP | bsd-3-clause | 2,395 |
/*
* Copyright 2019 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/dawn/GrDawnBuffer.h"
#include "src/gpu/dawn/GrDawnStagingBuffer.h"
#include "src/gpu/dawn/GrDawnGpu.h"
namespace {
wgpu::BufferUsage GrGpuBufferTypeToDawnUsageBit(GrGpuBufferType type) {
switch (type) {
case GrGpuBufferType::kVertex:
return wgpu::BufferUsage::Vertex;
case GrGpuBufferType::kIndex:
return wgpu::BufferUsage::Index;
case GrGpuBufferType::kXferCpuToGpu:
return wgpu::BufferUsage::CopySrc;
case GrGpuBufferType::kXferGpuToCpu:
return wgpu::BufferUsage::CopyDst;
default:
SkASSERT(!"buffer type not supported by Dawn");
return wgpu::BufferUsage::Vertex;
}
}
}
GrDawnBuffer::GrDawnBuffer(GrDawnGpu* gpu, size_t sizeInBytes, GrGpuBufferType type,
GrAccessPattern pattern)
: INHERITED(gpu, sizeInBytes, type, pattern) {
wgpu::BufferDescriptor bufferDesc;
bufferDesc.size = sizeInBytes;
bufferDesc.usage = GrGpuBufferTypeToDawnUsageBit(type) | wgpu::BufferUsage::CopyDst;
fBuffer = this->getDawnGpu()->device().CreateBuffer(&bufferDesc);
this->registerWithCache(SkBudgeted::kYes);
}
GrDawnBuffer::~GrDawnBuffer() {
}
void GrDawnBuffer::onMap() {
if (this->wasDestroyed()) {
return;
}
GrStagingBuffer::Slice slice = getGpu()->allocateStagingBufferSlice(this->size());
fStagingBuffer = static_cast<GrDawnStagingBuffer*>(slice.fBuffer)->buffer();
fStagingOffset = slice.fOffset;
fMapPtr = slice.fData;
}
void GrDawnBuffer::onUnmap() {
if (this->wasDestroyed()) {
return;
}
fMapPtr = nullptr;
getDawnGpu()->getCopyEncoder()
.CopyBufferToBuffer(fStagingBuffer, fStagingOffset, fBuffer, 0, this->size());
}
bool GrDawnBuffer::onUpdateData(const void* src, size_t srcSizeInBytes) {
if (this->wasDestroyed()) {
return false;
}
this->onMap();
memcpy(fMapPtr, src, srcSizeInBytes);
this->onUnmap();
return true;
}
GrDawnGpu* GrDawnBuffer::getDawnGpu() const {
SkASSERT(!this->wasDestroyed());
return static_cast<GrDawnGpu*>(this->getGpu());
}
| endlessm/chromium-browser | third_party/skia/src/gpu/dawn/GrDawnBuffer.cpp | C++ | bsd-3-clause | 2,347 |
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.phpdoctrine.org>.
*/
namespace Doctrine\ORM\Mapping;
/**
* A MappingException indicates that something is wrong with the mapping setup.
*
* @since 2.0
*/
class MappingException extends \Doctrine\ORM\ORMException
{
public static function pathRequired()
{
return new self("Specifying the paths to your entities is required ".
"in the AnnotationDriver to retrieve all class names.");
}
public static function identifierRequired($entityName)
{
return new self("No identifier/primary key specified for Entity '$entityName'."
. " Every Entity must have an identifier/primary key.");
}
public static function invalidInheritanceType($entityName, $type)
{
return new self("The inheritance type '$type' specified for '$entityName' does not exist.");
}
public static function generatorNotAllowedWithCompositeId()
{
return new self("Id generators can't be used with a composite id.");
}
public static function missingFieldName()
{
return new self("The association mapping misses the 'fieldName' attribute.");
}
public static function missingTargetEntity($fieldName)
{
return new self("The association mapping '$fieldName' misses the 'targetEntity' attribute.");
}
public static function missingSourceEntity($fieldName)
{
return new self("The association mapping '$fieldName' misses the 'sourceEntity' attribute.");
}
public static function mappingFileNotFound($entityName, $fileName)
{
return new self("No mapping file found named '$fileName' for class '$entityName'.");
}
public static function mappingNotFound($className, $fieldName)
{
return new self("No mapping found for field '$fieldName' on class '$className'.");
}
public static function oneToManyRequiresMappedBy($fieldName)
{
return new self("OneToMany mapping on field '$fieldName' requires the 'mappedBy' attribute.");
}
public static function joinTableRequired($fieldName)
{
return new self("The mapping of field '$fieldName' requires an the 'joinTable' attribute.");
}
/**
* Called if a required option was not found but is required
*
* @param string $field which field cannot be processed?
* @param string $expectedOption which option is required
* @param string $hint Can optionally be used to supply a tip for common mistakes,
* e.g. "Did you think of the plural s?"
* @return MappingException
*/
static function missingRequiredOption($field, $expectedOption, $hint = '')
{
$message = "The mapping of field '{$field}' is invalid: The option '{$expectedOption}' is required.";
if ( ! empty($hint)) {
$message .= ' (Hint: ' . $hint . ')';
}
return new self($message);
}
/**
* Generic exception for invalid mappings.
*
* @param string $fieldName
*/
public static function invalidMapping($fieldName)
{
return new self("The mapping of field '$fieldName' is invalid.");
}
/**
* Exception for reflection exceptions - adds the entity name,
* because there might be long classnames that will be shortened
* within the stacktrace
*
* @param string $entity The entity's name
* @param \ReflectionException $previousException
*/
public static function reflectionFailure($entity, \ReflectionException $previousException)
{
return new self('An error occurred in ' . $entity, 0, $previousException);
}
public static function joinColumnMustPointToMappedField($className, $joinColumn)
{
return new self('The column ' . $joinColumn . ' must be mapped to a field in class '
. $className . ' since it is referenced by a join column of another class.');
}
public static function classIsNotAValidEntityOrMappedSuperClass($className)
{
return new self('Class '.$className.' is not a valid entity or mapped super class.');
}
public static function propertyTypeIsRequired($className, $propertyName)
{
return new self("The attribute 'type' is required for the column description of property ".$className."::\$".$propertyName.".");
}
public static function tableIdGeneratorNotImplemented($className)
{
return new self("TableIdGenerator is not yet implemented for use with class ".$className);
}
/**
*
* @param string $entity The entity's name
* @param string $fieldName The name of the field that was already declared
*/
public static function duplicateFieldMapping($entity, $fieldName) {
return new self('Property "'.$fieldName.'" in "'.$entity.'" was already declared, but it must be declared only once');
}
public static function duplicateAssociationMapping($entity, $fieldName) {
return new self('Property "'.$fieldName.'" in "'.$entity.'" was already declared, but it must be declared only once');
}
public static function singleIdNotAllowedOnCompositePrimaryKey($entity) {
return new self('Single id is not allowed on composite primary key in entity '.$entity);
}
public static function unsupportedOptimisticLockingType($entity, $fieldName, $unsupportedType) {
return new self('Locking type "'.$unsupportedType.'" (specified in "'.$entity.'", field "'.$fieldName.'") '
.'is not supported by Doctrine.'
);
}
public static function fileMappingDriversRequireConfiguredDirectoryPath($path = null)
{
if ( ! empty($path)) {
$path = '[' . $path . ']';
}
return new self(
'File mapping drivers must have a valid directory path, ' .
'however the given path ' . $path . ' seems to be incorrect!'
);
}
/**
* Throws an exception that indicates that a class used in a discriminator map does not exist.
* An example would be an outdated (maybe renamed) classname.
*
* @param string $className The class that could not be found
* @param string $owningClass The class that declares the discriminator map.
* @return self
*/
public static function invalidClassInDiscriminatorMap($className, $owningClass) {
return new self(
"Entity class '$className' used in the discriminator map of class '$owningClass' ".
"does not exist."
);
}
public static function missingDiscriminatorMap($className)
{
return new self("Entity class '$className' is using inheritance but no discriminator map was defined.");
}
public static function missingDiscriminatorColumn($className)
{
return new self("Entity class '$className' is using inheritance but no discriminator column was defined.");
}
public static function invalidDiscriminatorColumnType($className, $type)
{
return new self("Discriminator column type on entity class '$className' is not allowed to be '$type'. 'string' or 'integer' type variables are suggested!");
}
public static function cannotVersionIdField($className, $fieldName)
{
return new self("Setting Id field '$fieldName' as versionale in entity class '$className' is not supported.");
}
/**
* @param string $className
* @param string $columnName
* @return self
*/
public static function duplicateColumnName($className, $columnName)
{
return new self("Duplicate definition of column '".$columnName."' on entity '".$className."' in a field or discriminator column mapping.");
}
} | notmessenger/ZF-REST-API | library/Doctrine/ORM/Mapping/MappingException.php | PHP | bsd-3-clause | 8,678 |
/*
* Copyright (c) 2016, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.dva.argus.service.metric.transform;
import com.salesforce.dva.argus.entity.Metric;
import com.salesforce.dva.argus.system.SystemAssert;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* COUNT, GROUP, UNION.
*
* @author rzhang
*/
public class MetricUnionTransform implements Transform {
//~ Static fields/initializers *******************************************************************************************************************
/** The metric name for this transform is result. */
public static final String RESULT_METRIC_NAME = "result";
//~ Instance fields ******************************************************************************************************************************
private final ValueReducer valueUnionReducer;
private final String defaultScope;
private final String defaultMetricName;
//~ Constructors *********************************************************************************************************************************
/**
* Creates a new ReduceTransform object.
*
* @param valueUnionReducer valueReducerOrMapping The valueMapping.
*/
protected MetricUnionTransform(ValueReducer valueUnionReducer) {
this.defaultScope = TransformFactory.Function.UNION.name();
this.defaultMetricName = TransformFactory.DEFAULT_METRIC_NAME;
this.valueUnionReducer = valueUnionReducer;
}
//~ Methods **************************************************************************************************************************************
@Override
public String getResultScopeName() {
return defaultScope;
}
/**
* If constants is not null, apply mapping transform to metrics list. Otherwise, apply reduce transform to metrics list
*
* @param metrics The metrics to transform.
*
* @return The transformed metrics.
*/
@Override
public List<Metric> transform(List<Metric> metrics) {
return union(metrics);
}
/**
* Performs a columnar union of metrics.
*
* @param metrics The metrics to merge.
*
* @return The merged metrics.
*/
public List<Metric> union(List<Metric> metrics) {
SystemAssert.requireArgument(metrics != null, "Cannot transform empty metric/metrics");
if (metrics.isEmpty()) {
return metrics;
}
Metric newMetric = reduce(metrics);
Map<Long, String> reducedDatapoints = newMetric.getDatapoints();
Set<Long> sharedTimestamps = reducedDatapoints.keySet();
Map<Long, String> unionDatapoints = new TreeMap<Long, String>();
for (Metric metric : metrics) {
for (Map.Entry<Long, String> entry : metric.getDatapoints().entrySet()) {
if (!sharedTimestamps.contains(entry.getKey())) {
unionDatapoints.put(entry.getKey(), entry.getValue());
}
}
}
newMetric.addDatapoints(unionDatapoints);
return Arrays.asList(newMetric);
}
/**
* Reduce transform for the list of metrics.
*
* @param metrics The list of metrics to reduce.
*
* @return The reduced metric.
*/
protected Metric reduce(List<Metric> metrics) {
SystemAssert.requireArgument(metrics != null, "Cannot transform empty metric/metrics");
/*
* if (metrics.isEmpty()) { return new Metric(defaultScope, defaultMetricName); }
*/
MetricDistiller distiller = new MetricDistiller();
distiller.distill(metrics);
Map<Long, List<String>> collated = collate(metrics);
Map<Long, String> minDatapoints = reduce(collated, metrics);
String newMetricName = distiller.getMetric() == null ? defaultMetricName : distiller.getMetric();
Metric newMetric = new Metric(defaultScope, newMetricName);
newMetric.setDisplayName(distiller.getDisplayName());
newMetric.setUnits(distiller.getUnits());
newMetric.setTags(distiller.getTags());
newMetric.setDatapoints(minDatapoints);
return newMetric;
}
private Map<Long, List<String>> collate(List<Metric> metrics) {
Map<Long, List<String>> collated = new HashMap<Long, List<String>>();
for (Metric metric : metrics) {
for (Map.Entry<Long, String> point : metric.getDatapoints().entrySet()) {
if (!collated.containsKey(point.getKey())) {
collated.put(point.getKey(), new ArrayList<String>());
}
collated.get(point.getKey()).add(point.getValue());
}
}
return collated;
}
private Map<Long, String> reduce(Map<Long, List<String>> collated, List<Metric> metrics) {
Map<Long, String> reducedDatapoints = new HashMap<>();
for (Map.Entry<Long, List<String>> entry : collated.entrySet()) {
if (entry.getValue().size() < metrics.size()) {
continue;
}
reducedDatapoints.put(entry.getKey(), this.valueUnionReducer.reduce(entry.getValue()));
}
return reducedDatapoints;
}
@Override
public List<Metric> transform(List<Metric> metrics, List<String> constants) {
throw new UnsupportedOperationException("Union transform can't be used with constants!");
}
@Override
public List<Metric> transform(List<Metric>... listOfList) {
throw new UnsupportedOperationException("Union doesn't need list of list");
}
}
/* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
| rmelick/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/service/metric/transform/MetricUnionTransform.java | Java | bsd-3-clause | 7,287 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/url_request/url_fetcher_core.h"
#include <stdint.h>
#include "base/bind.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/profiler/scoped_tracker.h"
#include "base/sequenced_task_runner.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/thread_task_runner_handle.h"
#include "base/tracked_objects.h"
#include "net/base/elements_upload_data_stream.h"
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/base/request_priority.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/upload_data_stream.h"
#include "net/base/upload_file_element_reader.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/redirect_info.h"
#include "net/url_request/url_fetcher_delegate.h"
#include "net/url_request/url_fetcher_response_writer.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_throttler_manager.h"
namespace {
const int kBufferSize = 4096;
const int kUploadProgressTimerInterval = 100;
bool g_ignore_certificate_requests = false;
void EmptyCompletionCallback(int result) {}
} // namespace
namespace net {
// URLFetcherCore::Registry ---------------------------------------------------
URLFetcherCore::Registry::Registry() {}
URLFetcherCore::Registry::~Registry() {}
void URLFetcherCore::Registry::AddURLFetcherCore(URLFetcherCore* core) {
DCHECK(!ContainsKey(fetchers_, core));
fetchers_.insert(core);
}
void URLFetcherCore::Registry::RemoveURLFetcherCore(URLFetcherCore* core) {
DCHECK(ContainsKey(fetchers_, core));
fetchers_.erase(core);
}
void URLFetcherCore::Registry::CancelAll() {
while (!fetchers_.empty())
(*fetchers_.begin())->CancelURLRequest(ERR_ABORTED);
}
// URLFetcherCore -------------------------------------------------------------
// static
base::LazyInstance<URLFetcherCore::Registry>
URLFetcherCore::g_registry = LAZY_INSTANCE_INITIALIZER;
URLFetcherCore::URLFetcherCore(URLFetcher* fetcher,
const GURL& original_url,
URLFetcher::RequestType request_type,
URLFetcherDelegate* d)
: fetcher_(fetcher),
original_url_(original_url),
request_type_(request_type),
delegate_(d),
delegate_task_runner_(base::ThreadTaskRunnerHandle::Get()),
load_flags_(LOAD_NORMAL),
response_code_(URLFetcher::RESPONSE_CODE_INVALID),
buffer_(new IOBuffer(kBufferSize)),
url_request_data_key_(NULL),
was_fetched_via_proxy_(false),
upload_content_set_(false),
upload_range_offset_(0),
upload_range_length_(0),
referrer_policy_(
URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
is_chunked_upload_(false),
was_cancelled_(false),
stop_on_redirect_(false),
stopped_on_redirect_(false),
automatically_retry_on_5xx_(true),
num_retries_on_5xx_(0),
max_retries_on_5xx_(0),
num_retries_on_network_changes_(0),
max_retries_on_network_changes_(0),
current_upload_bytes_(-1),
current_response_bytes_(0),
total_response_bytes_(-1) {
CHECK(original_url_.is_valid());
}
void URLFetcherCore::Start() {
DCHECK(delegate_task_runner_.get());
DCHECK(request_context_getter_.get()) << "We need an URLRequestContext!";
if (network_task_runner_.get()) {
DCHECK_EQ(network_task_runner_,
request_context_getter_->GetNetworkTaskRunner());
} else {
network_task_runner_ = request_context_getter_->GetNetworkTaskRunner();
}
DCHECK(network_task_runner_.get()) << "We need an IO task runner";
network_task_runner_->PostTask(
FROM_HERE, base::Bind(&URLFetcherCore::StartOnIOThread, this));
}
void URLFetcherCore::Stop() {
if (delegate_task_runner_.get()) // May be NULL in tests.
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
delegate_ = NULL;
fetcher_ = NULL;
if (!network_task_runner_.get())
return;
if (network_task_runner_->RunsTasksOnCurrentThread()) {
CancelURLRequest(ERR_ABORTED);
} else {
network_task_runner_->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::CancelURLRequest, this, ERR_ABORTED));
}
}
void URLFetcherCore::SetUploadData(const std::string& upload_content_type,
const std::string& upload_content) {
AssertHasNoUploadData();
DCHECK(!is_chunked_upload_);
DCHECK(upload_content_type_.empty());
// Empty |upload_content_type| is allowed iff the |upload_content| is empty.
DCHECK(upload_content.empty() || !upload_content_type.empty());
upload_content_type_ = upload_content_type;
upload_content_ = upload_content;
upload_content_set_ = true;
}
void URLFetcherCore::SetUploadFilePath(
const std::string& upload_content_type,
const base::FilePath& file_path,
uint64 range_offset,
uint64 range_length,
scoped_refptr<base::TaskRunner> file_task_runner) {
AssertHasNoUploadData();
DCHECK(!is_chunked_upload_);
DCHECK_EQ(upload_range_offset_, 0ULL);
DCHECK_EQ(upload_range_length_, 0ULL);
DCHECK(upload_content_type_.empty());
DCHECK(!upload_content_type.empty());
upload_content_type_ = upload_content_type;
upload_file_path_ = file_path;
upload_range_offset_ = range_offset;
upload_range_length_ = range_length;
upload_file_task_runner_ = file_task_runner;
upload_content_set_ = true;
}
void URLFetcherCore::SetUploadStreamFactory(
const std::string& upload_content_type,
const URLFetcher::CreateUploadStreamCallback& factory) {
AssertHasNoUploadData();
DCHECK(!is_chunked_upload_);
DCHECK(upload_content_type_.empty());
upload_content_type_ = upload_content_type;
upload_stream_factory_ = factory;
upload_content_set_ = true;
}
void URLFetcherCore::SetChunkedUpload(const std::string& content_type) {
if (!is_chunked_upload_) {
AssertHasNoUploadData();
DCHECK(upload_content_type_.empty());
}
// Empty |content_type| is not allowed here, because it is impossible
// to ensure non-empty upload content as it is not yet supplied.
DCHECK(!content_type.empty());
upload_content_type_ = content_type;
upload_content_.clear();
is_chunked_upload_ = true;
}
void URLFetcherCore::AppendChunkToUpload(const std::string& content,
bool is_last_chunk) {
DCHECK(delegate_task_runner_.get());
DCHECK(network_task_runner_.get());
network_task_runner_->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::CompleteAddingUploadDataChunk, this, content,
is_last_chunk));
}
void URLFetcherCore::SetLoadFlags(int load_flags) {
load_flags_ = load_flags;
}
int URLFetcherCore::GetLoadFlags() const {
return load_flags_;
}
void URLFetcherCore::SetReferrer(const std::string& referrer) {
referrer_ = referrer;
}
void URLFetcherCore::SetReferrerPolicy(
URLRequest::ReferrerPolicy referrer_policy) {
referrer_policy_ = referrer_policy;
}
void URLFetcherCore::SetExtraRequestHeaders(
const std::string& extra_request_headers) {
extra_request_headers_.Clear();
extra_request_headers_.AddHeadersFromString(extra_request_headers);
}
void URLFetcherCore::AddExtraRequestHeader(const std::string& header_line) {
extra_request_headers_.AddHeaderFromString(header_line);
}
void URLFetcherCore::SetRequestContext(
URLRequestContextGetter* request_context_getter) {
DCHECK(!request_context_getter_.get());
DCHECK(request_context_getter);
request_context_getter_ = request_context_getter;
}
void URLFetcherCore::SetFirstPartyForCookies(
const GURL& first_party_for_cookies) {
DCHECK(first_party_for_cookies_.is_empty());
first_party_for_cookies_ = first_party_for_cookies;
}
void URLFetcherCore::SetURLRequestUserData(
const void* key,
const URLFetcher::CreateDataCallback& create_data_callback) {
DCHECK(key);
DCHECK(!create_data_callback.is_null());
url_request_data_key_ = key;
url_request_create_data_callback_ = create_data_callback;
}
void URLFetcherCore::SetStopOnRedirect(bool stop_on_redirect) {
stop_on_redirect_ = stop_on_redirect;
}
void URLFetcherCore::SetAutomaticallyRetryOn5xx(bool retry) {
automatically_retry_on_5xx_ = retry;
}
void URLFetcherCore::SetMaxRetriesOn5xx(int max_retries) {
max_retries_on_5xx_ = max_retries;
}
int URLFetcherCore::GetMaxRetriesOn5xx() const {
return max_retries_on_5xx_;
}
base::TimeDelta URLFetcherCore::GetBackoffDelay() const {
return backoff_delay_;
}
void URLFetcherCore::SetAutomaticallyRetryOnNetworkChanges(int max_retries) {
max_retries_on_network_changes_ = max_retries;
}
void URLFetcherCore::SaveResponseToFileAtPath(
const base::FilePath& file_path,
scoped_refptr<base::SequencedTaskRunner> file_task_runner) {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
SaveResponseWithWriter(scoped_ptr<URLFetcherResponseWriter>(
new URLFetcherFileWriter(file_task_runner, file_path)));
}
void URLFetcherCore::SaveResponseToTemporaryFile(
scoped_refptr<base::SequencedTaskRunner> file_task_runner) {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
SaveResponseWithWriter(scoped_ptr<URLFetcherResponseWriter>(
new URLFetcherFileWriter(file_task_runner, base::FilePath())));
}
void URLFetcherCore::SaveResponseWithWriter(
scoped_ptr<URLFetcherResponseWriter> response_writer) {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
response_writer_ = response_writer.Pass();
}
HttpResponseHeaders* URLFetcherCore::GetResponseHeaders() const {
return response_headers_.get();
}
// TODO(panayiotis): socket_address_ is written in the IO thread,
// if this is accessed in the UI thread, this could result in a race.
// Same for response_headers_ above and was_fetched_via_proxy_ below.
HostPortPair URLFetcherCore::GetSocketAddress() const {
return socket_address_;
}
bool URLFetcherCore::WasFetchedViaProxy() const {
return was_fetched_via_proxy_;
}
const GURL& URLFetcherCore::GetOriginalURL() const {
return original_url_;
}
const GURL& URLFetcherCore::GetURL() const {
return url_;
}
const URLRequestStatus& URLFetcherCore::GetStatus() const {
return status_;
}
int URLFetcherCore::GetResponseCode() const {
return response_code_;
}
const ResponseCookies& URLFetcherCore::GetCookies() const {
return cookies_;
}
void URLFetcherCore::ReceivedContentWasMalformed() {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
if (network_task_runner_.get()) {
network_task_runner_->PostTask(
FROM_HERE, base::Bind(&URLFetcherCore::NotifyMalformedContent, this));
}
}
bool URLFetcherCore::GetResponseAsString(
std::string* out_response_string) const {
URLFetcherStringWriter* string_writer =
response_writer_ ? response_writer_->AsStringWriter() : NULL;
if (!string_writer)
return false;
*out_response_string = string_writer->data();
UMA_HISTOGRAM_MEMORY_KB("UrlFetcher.StringResponseSize",
(string_writer->data().length() / 1024));
return true;
}
bool URLFetcherCore::GetResponseAsFilePath(bool take_ownership,
base::FilePath* out_response_path) {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
URLFetcherFileWriter* file_writer =
response_writer_ ? response_writer_->AsFileWriter() : NULL;
if (!file_writer)
return false;
*out_response_path = file_writer->file_path();
if (take_ownership) {
// Intentionally calling a file_writer_ method directly without posting
// the task to network_task_runner_.
//
// This is for correctly handling the case when file_writer_->DisownFile()
// is soon followed by URLFetcherCore::Stop(). We have to make sure that
// DisownFile takes effect before Stop deletes file_writer_.
//
// This direct call should be thread-safe, since DisownFile itself does no
// file operation. It just flips the state to be referred in destruction.
file_writer->DisownFile();
}
return true;
}
void URLFetcherCore::OnReceivedRedirect(URLRequest* request,
const RedirectInfo& redirect_info,
bool* defer_redirect) {
DCHECK_EQ(request, request_.get());
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (stop_on_redirect_) {
stopped_on_redirect_ = true;
url_ = redirect_info.new_url;
response_code_ = request_->GetResponseCode();
was_fetched_via_proxy_ = request_->was_fetched_via_proxy();
request->Cancel();
OnReadCompleted(request, 0);
}
}
void URLFetcherCore::OnResponseStarted(URLRequest* request) {
DCHECK_EQ(request, request_.get());
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (request_->status().is_success()) {
response_code_ = request_->GetResponseCode();
response_headers_ = request_->response_headers();
socket_address_ = request_->GetSocketAddress();
was_fetched_via_proxy_ = request_->was_fetched_via_proxy();
total_response_bytes_ = request_->GetExpectedContentSize();
}
ReadResponse();
}
void URLFetcherCore::OnCertificateRequested(
URLRequest* request,
SSLCertRequestInfo* cert_request_info) {
DCHECK_EQ(request, request_.get());
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (g_ignore_certificate_requests) {
request->ContinueWithCertificate(NULL);
} else {
request->Cancel();
}
}
void URLFetcherCore::OnReadCompleted(URLRequest* request,
int bytes_read) {
DCHECK(request == request_);
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (!stopped_on_redirect_)
url_ = request->url();
URLRequestThrottlerManager* throttler_manager =
request->context()->throttler_manager();
if (throttler_manager)
url_throttler_entry_ = throttler_manager->RegisterRequestUrl(url_);
do {
if (!request_->status().is_success() || bytes_read <= 0)
break;
current_response_bytes_ += bytes_read;
InformDelegateDownloadProgress();
const int result =
WriteBuffer(new DrainableIOBuffer(buffer_.get(), bytes_read));
if (result < 0) {
// Write failed or waiting for write completion.
return;
}
} while (request_->Read(buffer_.get(), kBufferSize, &bytes_read));
const URLRequestStatus status = request_->status();
if (status.is_success())
request_->GetResponseCookies(&cookies_);
// See comments re: HEAD requests in ReadResponse().
if (!status.is_io_pending() || request_type_ == URLFetcher::HEAD) {
status_ = status;
ReleaseRequest();
// No more data to write.
const int result = response_writer_->Finish(
base::Bind(&URLFetcherCore::DidFinishWriting, this));
if (result != ERR_IO_PENDING)
DidFinishWriting(result);
}
}
void URLFetcherCore::CancelAll() {
g_registry.Get().CancelAll();
}
int URLFetcherCore::GetNumFetcherCores() {
return g_registry.Get().size();
}
void URLFetcherCore::SetIgnoreCertificateRequests(bool ignored) {
g_ignore_certificate_requests = ignored;
}
URLFetcherCore::~URLFetcherCore() {
// |request_| should be NULL. If not, it's unsafe to delete it here since we
// may not be on the IO thread.
DCHECK(!request_.get());
}
void URLFetcherCore::StartOnIOThread() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (!response_writer_)
response_writer_.reset(new URLFetcherStringWriter);
const int result = response_writer_->Initialize(
base::Bind(&URLFetcherCore::DidInitializeWriter, this));
if (result != ERR_IO_PENDING)
DidInitializeWriter(result);
}
void URLFetcherCore::StartURLRequest() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (was_cancelled_) {
// Since StartURLRequest() is posted as a *delayed* task, it may
// run after the URLFetcher was already stopped.
return;
}
DCHECK(request_context_getter_.get());
DCHECK(!request_.get());
g_registry.Get().AddURLFetcherCore(this);
current_response_bytes_ = 0;
request_ = request_context_getter_->GetURLRequestContext()->CreateRequest(
original_url_, DEFAULT_PRIORITY, this);
request_->set_stack_trace(stack_trace_);
int flags = request_->load_flags() | load_flags_;
if (is_chunked_upload_)
request_->EnableChunkedUpload();
request_->SetLoadFlags(flags);
request_->SetReferrer(referrer_);
request_->set_referrer_policy(referrer_policy_);
request_->set_first_party_for_cookies(first_party_for_cookies_.is_empty() ?
original_url_ : first_party_for_cookies_);
if (url_request_data_key_ && !url_request_create_data_callback_.is_null()) {
request_->SetUserData(url_request_data_key_,
url_request_create_data_callback_.Run());
}
switch (request_type_) {
case URLFetcher::GET:
break;
case URLFetcher::POST:
case URLFetcher::PUT:
case URLFetcher::PATCH: {
// Upload content must be set.
DCHECK(is_chunked_upload_ || upload_content_set_);
request_->set_method(
request_type_ == URLFetcher::POST ? "POST" :
request_type_ == URLFetcher::PUT ? "PUT" : "PATCH");
if (!upload_content_type_.empty()) {
extra_request_headers_.SetHeader(HttpRequestHeaders::kContentType,
upload_content_type_);
}
if (!upload_content_.empty()) {
scoped_ptr<UploadElementReader> reader(new UploadBytesElementReader(
upload_content_.data(), upload_content_.size()));
request_->set_upload(
ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0));
} else if (!upload_file_path_.empty()) {
scoped_ptr<UploadElementReader> reader(
new UploadFileElementReader(upload_file_task_runner_.get(),
upload_file_path_,
upload_range_offset_,
upload_range_length_,
base::Time()));
request_->set_upload(
ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0));
} else if (!upload_stream_factory_.is_null()) {
scoped_ptr<UploadDataStream> stream = upload_stream_factory_.Run();
DCHECK(stream);
request_->set_upload(stream.Pass());
}
current_upload_bytes_ = -1;
// TODO(kinaba): http://crbug.com/118103. Implement upload callback in the
// layer and avoid using timer here.
upload_progress_checker_timer_.reset(
new base::RepeatingTimer<URLFetcherCore>());
upload_progress_checker_timer_->Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(kUploadProgressTimerInterval),
this,
&URLFetcherCore::InformDelegateUploadProgress);
break;
}
case URLFetcher::HEAD:
request_->set_method("HEAD");
break;
case URLFetcher::DELETE_REQUEST:
request_->set_method("DELETE");
break;
default:
NOTREACHED();
}
if (!extra_request_headers_.IsEmpty())
request_->SetExtraRequestHeaders(extra_request_headers_);
request_->Start();
}
void URLFetcherCore::DidInitializeWriter(int result) {
if (result != OK) {
CancelURLRequest(result);
delegate_task_runner_->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::InformDelegateFetchIsComplete, this));
return;
}
StartURLRequestWhenAppropriate();
}
void URLFetcherCore::StartURLRequestWhenAppropriate() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (was_cancelled_)
return;
DCHECK(request_context_getter_.get());
int64 delay = 0;
if (!original_url_throttler_entry_.get()) {
URLRequestThrottlerManager* manager =
request_context_getter_->GetURLRequestContext()->throttler_manager();
if (manager) {
original_url_throttler_entry_ =
manager->RegisterRequestUrl(original_url_);
}
}
if (original_url_throttler_entry_.get()) {
delay = original_url_throttler_entry_->ReserveSendingTimeForNextRequest(
GetBackoffReleaseTime());
}
if (delay == 0) {
StartURLRequest();
} else {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, base::Bind(&URLFetcherCore::StartURLRequest, this),
base::TimeDelta::FromMilliseconds(delay));
}
}
void URLFetcherCore::CancelURLRequest(int error) {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (request_.get()) {
request_->CancelWithError(error);
ReleaseRequest();
}
// Set the error manually.
// Normally, calling URLRequest::CancelWithError() results in calling
// OnReadCompleted() with bytes_read = -1 via an asynchronous task posted by
// URLRequestJob::NotifyDone(). But, because the request was released
// immediately after being canceled, the request could not call
// OnReadCompleted() which overwrites |status_| with the error status.
status_.set_status(URLRequestStatus::CANCELED);
status_.set_error(error);
// Release the reference to the request context. There could be multiple
// references to URLFetcher::Core at this point so it may take a while to
// delete the object, but we cannot delay the destruction of the request
// context.
request_context_getter_ = NULL;
first_party_for_cookies_ = GURL();
url_request_data_key_ = NULL;
url_request_create_data_callback_.Reset();
was_cancelled_ = true;
}
void URLFetcherCore::OnCompletedURLRequest(
base::TimeDelta backoff_delay) {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
// Save the status and backoff_delay so that delegates can read it.
if (delegate_) {
backoff_delay_ = backoff_delay;
InformDelegateFetchIsComplete();
}
}
void URLFetcherCore::InformDelegateFetchIsComplete() {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
if (delegate_)
delegate_->OnURLFetchComplete(fetcher_);
}
void URLFetcherCore::NotifyMalformedContent() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (url_throttler_entry_.get()) {
int status_code = response_code_;
if (status_code == URLFetcher::RESPONSE_CODE_INVALID) {
// The status code will generally be known by the time clients
// call the |ReceivedContentWasMalformed()| function (which ends up
// calling the current function) but if it's not, we need to assume
// the response was successful so that the total failure count
// used to calculate exponential back-off goes up.
status_code = 200;
}
url_throttler_entry_->ReceivedContentWasMalformed(status_code);
}
}
void URLFetcherCore::DidFinishWriting(int result) {
if (result != OK) {
CancelURLRequest(result);
delegate_task_runner_->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::InformDelegateFetchIsComplete, this));
return;
}
// If the file was successfully closed, then the URL request is complete.
RetryOrCompleteUrlFetch();
}
void URLFetcherCore::RetryOrCompleteUrlFetch() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
base::TimeDelta backoff_delay;
// Checks the response from server.
if (response_code_ >= 500 ||
status_.error() == ERR_TEMPORARILY_THROTTLED) {
// When encountering a server error, we will send the request again
// after backoff time.
++num_retries_on_5xx_;
// Note that backoff_delay may be 0 because (a) the
// URLRequestThrottlerManager and related code does not
// necessarily back off on the first error, (b) it only backs off
// on some of the 5xx status codes, (c) not all URLRequestContexts
// have a throttler manager.
base::TimeTicks backoff_release_time = GetBackoffReleaseTime();
backoff_delay = backoff_release_time - base::TimeTicks::Now();
if (backoff_delay < base::TimeDelta())
backoff_delay = base::TimeDelta();
if (automatically_retry_on_5xx_ &&
num_retries_on_5xx_ <= max_retries_on_5xx_) {
StartOnIOThread();
return;
}
} else {
backoff_delay = base::TimeDelta();
}
// Retry if the request failed due to network changes.
if (status_.error() == ERR_NETWORK_CHANGED &&
num_retries_on_network_changes_ < max_retries_on_network_changes_) {
++num_retries_on_network_changes_;
// Retry soon, after flushing all the current tasks which may include
// further network change observers.
network_task_runner_->PostTask(
FROM_HERE, base::Bind(&URLFetcherCore::StartOnIOThread, this));
return;
}
request_context_getter_ = NULL;
first_party_for_cookies_ = GURL();
url_request_data_key_ = NULL;
url_request_create_data_callback_.Reset();
bool posted = delegate_task_runner_->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::OnCompletedURLRequest, this, backoff_delay));
// If the delegate message loop does not exist any more, then the delegate
// should be gone too.
DCHECK(posted || !delegate_);
}
void URLFetcherCore::ReleaseRequest() {
upload_progress_checker_timer_.reset();
request_.reset();
g_registry.Get().RemoveURLFetcherCore(this);
}
base::TimeTicks URLFetcherCore::GetBackoffReleaseTime() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (!original_url_throttler_entry_.get())
return base::TimeTicks();
base::TimeTicks original_url_backoff =
original_url_throttler_entry_->GetExponentialBackoffReleaseTime();
base::TimeTicks destination_url_backoff;
if (url_throttler_entry_.get() &&
original_url_throttler_entry_.get() != url_throttler_entry_.get()) {
destination_url_backoff =
url_throttler_entry_->GetExponentialBackoffReleaseTime();
}
return original_url_backoff > destination_url_backoff ?
original_url_backoff : destination_url_backoff;
}
void URLFetcherCore::CompleteAddingUploadDataChunk(
const std::string& content, bool is_last_chunk) {
if (was_cancelled_) {
// Since CompleteAddingUploadDataChunk() is posted as a *delayed* task, it
// may run after the URLFetcher was already stopped.
return;
}
DCHECK(is_chunked_upload_);
DCHECK(request_.get());
DCHECK(!content.empty());
request_->AppendChunkToUpload(content.data(),
static_cast<int>(content.length()),
is_last_chunk);
}
int URLFetcherCore::WriteBuffer(scoped_refptr<DrainableIOBuffer> data) {
while (data->BytesRemaining() > 0) {
const int result = response_writer_->Write(
data.get(),
data->BytesRemaining(),
base::Bind(&URLFetcherCore::DidWriteBuffer, this, data));
if (result < 0) {
if (result != ERR_IO_PENDING)
DidWriteBuffer(data, result);
return result;
}
data->DidConsume(result);
}
return OK;
}
void URLFetcherCore::DidWriteBuffer(scoped_refptr<DrainableIOBuffer> data,
int result) {
if (result < 0) { // Handle errors.
CancelURLRequest(result);
response_writer_->Finish(base::Bind(&EmptyCompletionCallback));
delegate_task_runner_->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::InformDelegateFetchIsComplete, this));
return;
}
// Continue writing.
data->DidConsume(result);
if (WriteBuffer(data) < 0)
return;
// Finished writing buffer_. Read some more, unless the request has been
// cancelled and deleted.
DCHECK_EQ(0, data->BytesRemaining());
if (request_.get())
ReadResponse();
}
void URLFetcherCore::ReadResponse() {
// Some servers may treat HEAD requests as GET requests. To free up the
// network connection as soon as possible, signal that the request has
// completed immediately, without trying to read any data back (all we care
// about is the response code and headers, which we already have).
int bytes_read = 0;
if (request_->status().is_success() &&
(request_type_ != URLFetcher::HEAD)) {
if (!request_->Read(buffer_.get(), kBufferSize, &bytes_read))
bytes_read = -1; // Match OnReadCompleted() interface contract.
}
OnReadCompleted(request_.get(), bytes_read);
}
void URLFetcherCore::InformDelegateUploadProgress() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (request_.get()) {
int64 current = request_->GetUploadProgress().position();
if (current_upload_bytes_ != current) {
current_upload_bytes_ = current;
int64 total = -1;
if (!is_chunked_upload_) {
total = static_cast<int64>(request_->GetUploadProgress().size());
// Total may be zero if the UploadDataStream::Init has not been called
// yet. Don't send the upload progress until the size is initialized.
if (!total)
return;
}
delegate_task_runner_->PostTask(
FROM_HERE,
base::Bind(
&URLFetcherCore::InformDelegateUploadProgressInDelegateThread,
this, current, total));
}
}
}
void URLFetcherCore::InformDelegateUploadProgressInDelegateThread(
int64 current, int64 total) {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
if (delegate_)
delegate_->OnURLFetchUploadProgress(fetcher_, current, total);
}
void URLFetcherCore::InformDelegateDownloadProgress() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
// TODO(pkasting): Remove ScopedTracker below once crbug.com/455952 is fixed.
tracked_objects::ScopedTracker tracking_profile2(
FROM_HERE_WITH_EXPLICIT_FUNCTION(
"455952 delegate_task_runner_->PostTask()"));
delegate_task_runner_->PostTask(
FROM_HERE,
base::Bind(
&URLFetcherCore::InformDelegateDownloadProgressInDelegateThread,
this, current_response_bytes_, total_response_bytes_));
}
void URLFetcherCore::InformDelegateDownloadProgressInDelegateThread(
int64 current, int64 total) {
DCHECK(delegate_task_runner_->BelongsToCurrentThread());
if (delegate_)
delegate_->OnURLFetchDownloadProgress(fetcher_, current, total);
}
void URLFetcherCore::AssertHasNoUploadData() const {
DCHECK(!upload_content_set_);
DCHECK(upload_content_.empty());
DCHECK(upload_file_path_.empty());
DCHECK(upload_stream_factory_.is_null());
}
} // namespace net
| ltilve/chromium | net/url_request/url_fetcher_core.cc | C++ | bsd-3-clause | 30,529 |
<?php
class SortWeightRegistry {
public static $override_default_sort = true;
public static $relations = array();
public static $default_sorts = array(); // original default_sort
public static $add_weight_columns = array();
public static $direction = 'ASC'; // ASC || DESC
public static $module_path;
public static function set_module_path($directory)
{
self::$module_path = $directory;
}
public static function decorate($class, $relationName = null) {
if(!isset(self::$relations[$class]))
{
self::$relations[$class] = array();
}
// if relationName is false, enable the sorting on object iteslf (skip SortWeight map)
if(!class_exists($class) || !$sng = new $class())
{
user_error('Unknown class passed (' . $class .')', E_USER_WARNING);
}
elseif($relationName === null )
{
user_error('You must provide the Component to order for ' . $class, E_USER_WARNING);
}
elseif(!$sng->hasMethod($relationName) || !$component = $sng->$relationName())
{
user_error('Component "' . $relationName . '" must exist on ' . $class,E_USER_WARNING);
}
elseif(isset(self::$relations[$class][$relationName]))
{
user_error('Component "' . $relationName . '" already decorates ' . $class,E_USER_WARNING);
}
else
{
$relationClass = ($component->is_a('ComponentSet')) ?
$component->childClass : $component->class;
self::$relations[$class][$relationName] = $relationClass;
$current_sort = Object::get_static($relationClass, 'default_sort');
if(self::$override_default_sort || empty($current_sort))
{
Object::set_static($relationClass,'default_sort','[SortWeight]');
if($current_sort != '[SortWeight]')
{
self::$default_sorts[$relationClass] = $current_sort;
}
}
if(!Object::has_extension($relationClass,'SortWeightDecoration'))
{
Object::add_extension($relationClass,'SortWeightDecoration');
}
return;
}
return user_error('SortWeight decoration failed for ' . __CLASS__ . '::' . __FUNCTION__ . "(\"$class\",\"$relationName\")",E_USER_WARNING);
}
} | briceburg/silverstripe-sortweight | code/SortWeightRegistry.php | PHP | bsd-3-clause | 2,131 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/password_manager/core/browser/sql_table_builder.h"
#include <algorithm>
#include <set>
#include <utility>
#include "base/numerics/safe_conversions.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "sql/database.h"
#include "sql/transaction.h"
namespace password_manager {
namespace {
// Appends |name| to |list_of_names|, separating items with ", ".
void Append(const std::string& name, std::string* list_of_names) {
if (list_of_names->empty())
*list_of_names = name;
else
*list_of_names += ", " + name;
}
} // namespace
// static
unsigned constexpr SQLTableBuilder::kInvalidVersion;
struct SQLTableBuilder::Column {
std::string name;
std::string type;
// Whether this column is the table's PRIMARY KEY.
bool is_primary_key;
// Whether this column is part of the table's UNIQUE constraint.
bool part_of_unique_key;
// The first version this column is part of.
unsigned min_version;
// The last version this column is part of. The value of kInvalidVersion
// means that it is part of all versions since |min_version|.
unsigned max_version;
// Renaming of a column is stored as a sequence of one removed and one added
// column in |columns_|. To distinguish it from an unrelated removal and
// addition, the following bit is set to true for the added columns which
// are part of renaming. Those columns will get the data of their
// predecessors. If the bit is false, the column will be filled with the
// default value on creation.
bool gets_previous_data;
};
struct SQLTableBuilder::Index {
// The name of this index.
std::string name;
// The names of columns this index is built from.
std::vector<std::string> columns;
// The first version this index is part of.
unsigned min_version;
// The last version this index is part of. The value of kInvalidVersion
// means that it is part of all versions since |min_version|.
unsigned max_version;
};
SQLTableBuilder::SQLTableBuilder(const std::string& table_name)
: table_name_(table_name) {}
SQLTableBuilder::~SQLTableBuilder() = default;
void SQLTableBuilder::AddColumn(std::string name, std::string type) {
DCHECK(FindLastColumnByName(name) == columns_.rend());
columns_.push_back({std::move(name), std::move(type), false, false,
sealed_version_ + 1, kInvalidVersion, false});
}
void SQLTableBuilder::AddPrimaryKeyColumn(std::string name) {
for (const Column& column : columns_) {
DCHECK(!column.is_primary_key);
}
AddColumn(std::move(name), "INTEGER");
columns_.back().is_primary_key = true;
}
void SQLTableBuilder::AddColumnToUniqueKey(std::string name, std::string type) {
AddColumn(std::move(name), std::move(type));
columns_.back().part_of_unique_key = true;
}
void SQLTableBuilder::RenameColumn(const std::string& old_name,
const std::string& new_name) {
auto old_column = FindLastColumnByName(old_name);
DCHECK(old_column != columns_.rend());
if (old_name == new_name) // The easy case.
return;
DCHECK(FindLastColumnByName(new_name) == columns_.rend());
// Check there is no index in the current version that references |old_name|.
DCHECK(std::none_of(indices_.begin(), indices_.end(),
[&old_name](const Index& index) {
return index.max_version == kInvalidVersion &&
base::Contains(index.columns, old_name);
}));
if (sealed_version_ != kInvalidVersion &&
old_column->min_version <= sealed_version_) {
// This column exists in the last sealed version. Therefore it cannot be
// just replaced, it needs to be kept for generating the migration code.
Column new_column = {new_name,
old_column->type,
old_column->is_primary_key,
old_column->part_of_unique_key,
sealed_version_ + 1,
kInvalidVersion,
true};
old_column->max_version = sealed_version_;
auto past_old =
old_column.base(); // Points one element after |old_column|.
columns_.insert(past_old, std::move(new_column));
} else {
// This column was just introduced in the currently unsealed version. To
// rename it, it is enough just to modify the entry in columns_.
old_column->name = new_name;
}
}
// Removes column |name|. |name| must have been added in the past.
void SQLTableBuilder::DropColumn(const std::string& name) {
auto column = FindLastColumnByName(name);
DCHECK(column != columns_.rend());
// Check there is no index in the current version that references |old_name|.
DCHECK(std::none_of(indices_.begin(), indices_.end(),
[&name](const Index& index) {
return index.max_version == kInvalidVersion &&
base::Contains(index.columns, name);
}));
if (sealed_version_ != kInvalidVersion &&
column->min_version <= sealed_version_) {
// This column exists in the last sealed version. Therefore it cannot be
// just deleted, it needs to be kept for generating the migration code.
column->max_version = sealed_version_;
} else {
// This column was just introduced in the currently unsealed version. It
// can be just erased from |columns_|.
columns_.erase(
--(column.base())); // base() points one element after |column|.
}
}
void SQLTableBuilder::AddIndex(std::string name,
std::vector<std::string> columns) {
DCHECK(!columns.empty());
// Check if all entries of |columns| are unique.
DCHECK_EQ(std::set<std::string>(columns.begin(), columns.end()).size(),
columns.size());
// |name| must not have been added before.
DCHECK(FindLastIndexByName(name) == indices_.rend());
// Check that all referenced columns are present in the last version by making
// sure that the inner predicate applies to all columns names in |columns|.
DCHECK(std::all_of(
columns.begin(), columns.end(), [this](const std::string& column_name) {
// Check if there is any column with the required name which is also
// present in the latest version. Note that we don't require the last
// version to be sealed.
return std::any_of(columns_.begin(), columns_.end(),
[&column_name](const Column& column) {
return column.name == column_name &&
column.max_version == kInvalidVersion;
});
}));
indices_.push_back({std::move(name), std::move(columns), sealed_version_ + 1,
kInvalidVersion});
}
std::string SQLTableBuilder::ComputeConstraints(unsigned version) const {
std::string unique_key;
for (const Column& column : columns_) {
// Ignore dropped columns.
if (column.max_version < version)
continue;
// Ignore columns columns from future versions.
if (column.min_version > version)
continue;
if (column.part_of_unique_key)
Append(column.name, &unique_key);
}
std::string constraints;
if (!unique_key.empty())
Append("UNIQUE (" + unique_key + ")", &constraints);
return constraints;
}
unsigned SQLTableBuilder::SealVersion() {
return ++sealed_version_;
}
bool SQLTableBuilder::MigrateFrom(
unsigned old_version,
sql::Database* db,
const base::RepeatingCallback<bool(sql::Database*, unsigned)>&
post_migration_step_callback) const {
for (; old_version < sealed_version_; ++old_version) {
if (!MigrateToNextFrom(old_version, db))
return false;
if (post_migration_step_callback &&
!post_migration_step_callback.Run(db, old_version + 1))
return false;
}
return true;
}
bool SQLTableBuilder::CreateTable(sql::Database* db) const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
if (db->DoesTableExist(table_name_.c_str()))
return true;
std::string constraints = ComputeConstraints(sealed_version_);
DCHECK(!constraints.empty() || std::any_of(columns_.begin(), columns_.end(),
[](const Column& column) {
return column.is_primary_key;
}));
std::string names; // Names and types of the current columns.
for (const Column& column : columns_) {
if (IsColumnInLastVersion(column)) {
std::string suffix;
if (column.is_primary_key)
suffix = " PRIMARY KEY AUTOINCREMENT";
Append(column.name + " " + column.type + suffix, &names);
}
}
std::vector<std::string>
create_index_sqls; // CREATE INDEX statements for the current indices.
for (const Index& index : indices_) {
if (IsIndexInLastVersion(index)) {
create_index_sqls.push_back(base::StringPrintf(
"CREATE INDEX %s ON %s (%s)", index.name.c_str(), table_name_.c_str(),
base::JoinString(index.columns, ", ").c_str()));
}
}
std::string create_table_statement =
constraints.empty()
? base::StringPrintf("CREATE TABLE %s (%s)", table_name_.c_str(),
names.c_str())
: base::StringPrintf("CREATE TABLE %s (%s, %s)", table_name_.c_str(),
names.c_str(), constraints.c_str());
sql::Transaction transaction(db);
return transaction.Begin() && db->Execute(create_table_statement.c_str()) &&
std::all_of(create_index_sqls.begin(), create_index_sqls.end(),
[&db](const std::string& sql) {
return db->Execute(sql.c_str());
}) &&
transaction.Commit();
}
std::string SQLTableBuilder::ListAllColumnNames() const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
std::string result;
for (const Column& column : columns_) {
if (IsColumnInLastVersion(column))
Append(column.name, &result);
}
return result;
}
std::string SQLTableBuilder::ListAllNonuniqueKeyNames() const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
std::string result;
for (const Column& column : columns_) {
if (IsColumnInLastVersion(column) &&
!(column.is_primary_key || column.part_of_unique_key))
Append(column.name + "=?", &result);
}
return result;
}
std::string SQLTableBuilder::ListAllUniqueKeyNames() const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
std::string result;
for (const Column& column : columns_) {
if (IsColumnInLastVersion(column) && column.part_of_unique_key) {
if (!result.empty())
result += " AND ";
result += column.name + "=?";
}
}
return result;
}
std::vector<base::StringPiece> SQLTableBuilder::AllPrimaryKeyNames() const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
std::vector<base::StringPiece> result;
result.reserve(columns_.size());
for (const Column& column : columns_) {
if (IsColumnInLastVersion(column) && column.is_primary_key) {
result.emplace_back(column.name);
}
}
DCHECK(result.size() < 2);
return result;
}
size_t SQLTableBuilder::NumberOfColumns() const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
return base::checked_cast<size_t>(std::count_if(
columns_.begin(), columns_.end(),
[this](const Column& column) { return IsColumnInLastVersion(column); }));
}
bool SQLTableBuilder::MigrateToNextFrom(unsigned old_version,
sql::Database* db) const {
DCHECK_LT(old_version, sealed_version_);
DCHECK_GE(old_version, 0u);
DCHECK(IsVersionLastAndSealed(sealed_version_));
// Names of columns from old version, values of which are copied. This
// contains only the names without their types.
std::string old_names_of_existing_columns_without_types;
// Names of columns in new version, except for added ones.
std::string new_names_of_existing_columns;
// Names of columns in new version, except for added ones. This contains only
// the names without their types.
std::string new_names_of_existing_columns_without_types;
std::vector<std::string>
names_of_new_columns_list; // Names of added columns.
// A temporary table will be needed if some columns are dropped or renamed,
// because that is not supported by a single SQLite command.
bool needs_temp_table = false;
bool has_primary_key = false;
for (auto column = columns_.begin(); column != columns_.end(); ++column) {
if (column->max_version == old_version) {
// This column was deleted after |old_version|. It can have two reasons:
needs_temp_table = true;
auto next_column = std::next(column);
if (next_column != columns_.end() && next_column->gets_previous_data) {
// (1) The column is being renamed.
DCHECK_EQ(column->type, next_column->type);
DCHECK_NE(column->name, next_column->name);
Append(column->name, &old_names_of_existing_columns_without_types);
Append(next_column->name + " " + next_column->type,
&new_names_of_existing_columns);
Append(next_column->name, &new_names_of_existing_columns_without_types);
++column; // Avoid processing next_column in the next loop.
} else {
// (2) The column is being dropped.
}
} else if (column->min_version == old_version + 1) {
// This column was added after old_version.
if (column->is_primary_key || column->part_of_unique_key)
needs_temp_table = true;
std::string suffix;
if (column->is_primary_key) {
suffix = " PRIMARY KEY AUTOINCREMENT";
has_primary_key = true;
}
names_of_new_columns_list.push_back(column->name + " " + column->type +
suffix);
} else if (column->min_version <= old_version &&
(column->max_version == kInvalidVersion ||
column->max_version > old_version)) {
std::string suffix;
if (column->is_primary_key) {
suffix = " PRIMARY KEY AUTOINCREMENT";
has_primary_key = true;
}
// This column stays.
Append(column->name, &old_names_of_existing_columns_without_types);
Append(column->name + " " + column->type + suffix,
&new_names_of_existing_columns);
Append(column->name, &new_names_of_existing_columns_without_types);
}
}
if (old_names_of_existing_columns_without_types.empty()) {
// Table didn't exist in this version, and nothing to migrate.
return true;
}
if (needs_temp_table) {
// Following the instructions from
// https://www.sqlite.org/lang_altertable.html#otheralter, this code works
// around the fact that SQLite does not allow dropping or renaming
// columns. Instead, a new table is constructed, with the new column
// names, and data from all but dropped columns from the current table are
// copied into it. After that, the new table is renamed to the current
// one.
std::string constraints = ComputeConstraints(old_version + 1);
DCHECK(has_primary_key || !constraints.empty());
// Foreign key constraints are not enabled for the login database, so no
// PRAGMA foreign_keys=off needed.
const std::string temp_table_name = "temp_" + table_name_;
std::string names_of_all_columns = new_names_of_existing_columns;
for (const std::string& new_column : names_of_new_columns_list) {
Append(new_column, &names_of_all_columns);
}
std::string create_table_statement =
constraints.empty()
? base::StringPrintf("CREATE TABLE %s (%s)",
temp_table_name.c_str(),
names_of_all_columns.c_str())
: base::StringPrintf(
"CREATE TABLE %s (%s, %s)", temp_table_name.c_str(),
names_of_all_columns.c_str(), constraints.c_str());
sql::Transaction transaction(db);
if (!(transaction.Begin() && db->Execute(create_table_statement.c_str()) &&
db->Execute(base::StringPrintf(
"INSERT OR REPLACE INTO %s (%s) SELECT %s FROM %s",
temp_table_name.c_str(),
new_names_of_existing_columns_without_types.c_str(),
old_names_of_existing_columns_without_types.c_str(),
table_name_.c_str())
.c_str()) &&
db->Execute(base::StringPrintf("DROP TABLE %s", table_name_.c_str())
.c_str()) &&
db->Execute(base::StringPrintf("ALTER TABLE %s RENAME TO %s",
temp_table_name.c_str(),
table_name_.c_str())
.c_str()) &&
transaction.Commit())) {
return false;
}
} else if (!names_of_new_columns_list.empty()) {
// If no new table has been created, we need to add the new columns here if
// any.
sql::Transaction transaction(db);
if (!(transaction.Begin() &&
std::all_of(names_of_new_columns_list.begin(),
names_of_new_columns_list.end(),
[this, &db](const std::string& name) {
return db->Execute(
base::StringPrintf("ALTER TABLE %s ADD COLUMN %s",
table_name_.c_str(),
name.c_str())
.c_str());
}) &&
transaction.Commit())) {
return false;
}
}
return MigrateIndicesToNextFrom(old_version, db);
}
bool SQLTableBuilder::MigrateIndicesToNextFrom(unsigned old_version,
sql::Database* db) const {
DCHECK_LT(old_version, sealed_version_);
DCHECK(IsVersionLastAndSealed(sealed_version_));
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
for (const auto& index : indices_) {
std::string sql;
if (index.max_version <= old_version) {
// Index is not supposed to exist in the new version.
sql = base::StringPrintf("DROP INDEX IF EXISTS %s", index.name.c_str());
} else if (index.min_version <= old_version + 1) {
// Index is supposed to exist in the new version.
sql = base::StringPrintf("CREATE INDEX IF NOT EXISTS %s ON %s (%s)",
index.name.c_str(), table_name_.c_str(),
base::JoinString(index.columns, ", ").c_str());
} else {
continue;
}
if (!db->Execute(sql.c_str()))
return false;
}
return transaction.Commit();
}
std::vector<SQLTableBuilder::Column>::reverse_iterator
SQLTableBuilder::FindLastColumnByName(const std::string& name) {
return std::find_if(
columns_.rbegin(), columns_.rend(),
[&name](const Column& column) { return name == column.name; });
}
std::vector<SQLTableBuilder::Index>::reverse_iterator
SQLTableBuilder::FindLastIndexByName(const std::string& name) {
return std::find_if(
indices_.rbegin(), indices_.rend(),
[&name](const Index& index) { return name == index.name; });
}
bool SQLTableBuilder::IsVersionLastAndSealed(unsigned version) const {
// Is |version| the last sealed one?
if (sealed_version_ != version)
return false;
// Is the current version the last sealed one? In other words, is there
// neither a column or index added past the sealed version (min_version >
// sealed) nor deleted one version after the sealed (max_version == sealed)?
return std::none_of(columns_.begin(), columns_.end(),
[this](const Column& column) {
return column.min_version > sealed_version_ ||
column.max_version == sealed_version_;
}) &&
std::none_of(indices_.begin(), indices_.end(),
[this](const Index& index) {
return index.min_version > sealed_version_ ||
index.max_version == sealed_version_;
});
}
bool SQLTableBuilder::IsColumnInLastVersion(const Column& column) const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
return (column.min_version <= sealed_version_ &&
(column.max_version == kInvalidVersion ||
column.max_version >= sealed_version_));
}
bool SQLTableBuilder::IsIndexInLastVersion(const Index& index) const {
DCHECK(IsVersionLastAndSealed(sealed_version_));
return (index.min_version <= sealed_version_ &&
(index.max_version == kInvalidVersion ||
index.max_version >= sealed_version_));
}
} // namespace password_manager
| endlessm/chromium-browser | components/password_manager/core/browser/sql_table_builder.cc | C++ | bsd-3-clause | 21,095 |
# Copyright (c) 2017 David Sorokin <david.sorokin@gmail.com>
#
# Licensed under BSD3. See the LICENSE.txt file in the root of this distribution.
from simulation.aivika.modeler.model import *
from simulation.aivika.modeler.port import *
from simulation.aivika.modeler.stream import *
from simulation.aivika.modeler.data_type import *
from simulation.aivika.modeler.pdf import *
def uniform_random_stream(transact_type, min_delay, max_delay):
"""Return a new stream of transacts with random delays distributed uniformly."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomUniformStream ' + str(min_delay) + ' ' + str(max_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def uniform_int_random_stream(transact_type, min_delay, max_delay):
"""Return a new stream of transacts with integer random delays distributed uniformly."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomUniformIntStream ' + str(min_delay) + ' ' + str(max_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def triangular_random_stream(transact_type, min_delay, median_delay, max_delay):
"""Return a new stream of transacts with random delays having the triangular distribution."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomTriangularStream ' + str(min_delay) + ' ' + str(median_delay) + ' ' + str(max_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def normal_random_stream(transact_type, mean_delay, delay_deviation):
"""Return a new stream of transacts with random delays having the normal distribution."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomNormalStream ' + str(mean_delay) + ' ' + str(delay_deviation)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def lognormal_random_stream(transact_type, normal_mean_delay, normal_delay_deviation):
"""Return a new stream of transacts with random delays having the lognormal distribution.
The numerical parameters are related to the normal distribution that
this distribution is derived from.
"""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomLogNormalStream ' + str(normal_mean_delay) + ' ' + str(normal_delay_deviation)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def exponential_random_stream(transact_type, mean_delay):
"""Return a new stream of transacts with random delays having the exponential distribution with the specified mean (a reciprocal of the rate)."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomExponentialStream ' + str(mean_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def erlang_random_stream(transact_type, scale, shape):
"""Return a new stream of transacts with random delays having the Erlang distribution with the specified scale (a reciprocal of the rate) and shape parameters."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomErlangStream ' + str(scale) + ' ' + str(shape)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def poisson_random_stream(transact_type, mean_delay):
"""Return a new stream of transacts with random delays having the Poisson distribution with the specified mean."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomPoissonStream ' + str(mean_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def binomial_random_stream(transact_type, probability, trials):
"""Return a new stream of transacts with random delays having the binomial distribution with the specified probability and trials."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomBinomialStream ' + str(probability) + ' ' + str(trials)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def gamma_random_stream(transact_type, shape, scale):
"""Return a new stream of transacts with random delays having the Gamma distribution by the specified shape and scale."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomGammaStream ' + str(shape) + ' ' + str(scale)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def beta_random_stream(transact_type, alpha, beta):
"""Return a new stream of transacts with random delays having the Beta distribution by the specified shape parameters (alpha and beta)."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomBetaStream ' + str(alpha) + ' ' + str(beta)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def weibull_random_stream(transact_type, shape, scale):
"""Return a new stream of transacts with random delays having the Weibull distribution by the specified shape and scale."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomWeibullStream ' + str(shape) + ' ' + str(scale)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def discrete_random_stream(transact_type, pdf):
"""Return a new stream of transacts with random delays having the discrete distribution by the specified probability density function."""
expect_transact_type(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomDiscreteStream ' + encode_pdf(pdf)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
| dsorokin/aivika-modeler | simulation/aivika/modeler/stream_random.py | Python | bsd-3-clause | 7,405 |
# apis_v1/documentation_source/voter_star_on_save_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def voter_star_on_save_doc_template_values(url_root):
"""
Show documentation about voterStarOnSave
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'kind_of_ballot_item',
'value': 'string', # boolean, integer, long, string
'description': 'What is the type of ballot item for which we are saving the \'on\' status? '
'(kind_of_ballot_item is either "OFFICE", "CANDIDATE", "POLITICIAN" or "MEASURE")',
},
{
'name': 'ballot_item_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique internal identifier for this ballot_item '
'(either ballot_item_id OR ballot_item_we_vote_id required -- not both. '
'If it exists, ballot_item_id is used instead of ballot_item_we_vote_id)',
},
{
'name': 'ballot_item_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for this ballot_item across all networks '
'(either ballot_item_id OR ballot_item_we_vote_id required -- not both. '
'NOTE: In the future we might support other identifiers used in the industry.',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. Missing voter_id while trying to save.',
},
{
'code': 'STAR_ON_OFFICE CREATE/UPDATE ITEM_STARRED',
'description': '',
},
{
'code': 'STAR_ON_CANDIDATE CREATE/UPDATE ITEM_STARRED',
'description': '',
},
{
'code': 'STAR_ON_MEASURE CREATE/UPDATE ITEM_STARRED',
'description': '',
},
]
try_now_link_variables_dict = {
'kind_of_ballot_item': 'CANDIDATE',
'ballot_item_id': '5655',
}
api_response = '{\n' \
' "status": string (description of what happened),\n' \
' "success": boolean (did the save happen?),\n' \
' "ballot_item_id": integer,\n' \
' "ballot_item_we_vote_id": string,\n' \
' "kind_of_ballot_item": string (CANDIDATE, MEASURE),\n' \
'}'
template_values = {
'api_name': 'voterStarOnSave',
'api_slug': 'voterStarOnSave',
'api_introduction':
"Save or create private 'star on' state for the current voter for a measure, an office or candidate.",
'try_now_link': 'apis_v1:voterStarOnSaveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| wevote/WebAppPublic | apis_v1/documentation_source/voter_star_on_save_doc.py | Python | bsd-3-clause | 4,125 |
define(['../Property', '../Model', 'dojo/_base/declare', 'json-schema/lib/validate'],
function (Property, Model, declare, jsonSchemaValidator) {
// module:
// dstore/extensions/JsonSchema
// summary:
// This module generates a dstore schema from a JSON Schema to enabled validation of objects
// and property changes with JSON Schema
return function (jsonSchema) {
// create the schema that can be used by dstore/Model
var modelSchema = {};
var properties = jsonSchema.properties || jsonSchema;
// the validation function, this can be used for all the properties
function checkForErrors() {
var value = this.valueOf();
var key = this.name;
// get the current value and test it against the property's definition
var validation = jsonSchemaValidator.validate(value, properties[key]);
// set any errors
var errors = validation.errors;
if (errors) {
// assign the property names to the errors
for (var i = 0; i < errors.length; i++) {
errors[i].property = key;
}
}
return errors;
}
// iterate through the schema properties, creating property validators
for (var i in properties) {
var jsDefinition = properties[i];
var definition = modelSchema[i] = new Property({
checkForErrors: checkForErrors
});
if (typeof jsDefinition.type === 'string') {
// copy the type so it can be used for coercion
definition.type = jsDefinition.type;
}
if (typeof jsDefinition['default'] === 'string') {
// and copy the default
definition['default'] = jsDefinition['default'];
}
}
return declare(Model, {
schema: modelSchema
});
};
}); | ibm-js/angular-delite-example | bower_components/dstore/extensions/jsonSchema.js | JavaScript | bsd-3-clause | 1,633 |
#include "stdafx.h"
#include "CGGuildApply.h"
BOOL CGGuildApply::Read( SocketInputStream& iStream )
{
__ENTER_FUNCTION
iStream.Read( (CHAR*)(&m_GuildNameSize), sizeof(BYTE) );
if(m_GuildNameSize<MAX_GUILD_NAME_SIZE)
{
iStream.Read( (CHAR*)(m_GuildName), m_GuildNameSize );
}
iStream.Read( (CHAR*)(&m_GuildDescSize), sizeof(BYTE) );
if(m_GuildDescSize<MAX_GUILD_DESC_SIZE)
{
iStream.Read( (CHAR*)(m_GuildDesc), m_GuildDescSize);
}
return TRUE;
__LEAVE_FUNCTION
return FALSE;
}
BOOL CGGuildApply::Write( SocketOutputStream& oStream ) const
{
__ENTER_FUNCTION
oStream.Write( (CHAR*)(&m_GuildNameSize), sizeof(BYTE) );
if(m_GuildNameSize<MAX_GUILD_NAME_SIZE)
{
oStream.Write( (CHAR*)(m_GuildName), m_GuildNameSize );
}
oStream.Write( (CHAR*)(&m_GuildDescSize), sizeof(BYTE) );
if(m_GuildDescSize<MAX_GUILD_DESC_SIZE)
{
oStream.Write( (CHAR*)(m_GuildDesc), m_GuildDescSize);
}
return TRUE;
__LEAVE_FUNCTION
return FALSE;
}
UINT CGGuildApply::Execute( Player* pPlayer )
{
__ENTER_FUNCTION
return CGGuildApplyHandler::Execute( this, pPlayer );
__LEAVE_FUNCTION
return FALSE;
}
| viticm/web-pap | server/Common/Packets/CGGuildApply.cpp | C++ | bsd-3-clause | 1,209 |
<?php namespace Laravella\Ravel\Facades;
Class Facade
{
protected static $resolvedInstance;
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
throw new \RuntimeException("Facade does not implement getFacadeAccessor method.");
}
/**
* Resolve the facade root instance from the container.
*
* @param string $name
* @return mixed
*/
protected static function resolveFacadeInstance($name)
{
if (is_object($name)) return $name;
if (isset(static::$resolvedInstance[$name]))
{
return static::$resolvedInstance[$name];
}
$NP = ucfirst($name);
$classInstance = "Laravella\\Ravel\\$NP\\$NP";
return static::$resolvedInstance[$name] = new $classInstance;
}
public static function resolveMethod($method, $args)
{
$instance = static::resolveFacadeInstance(static::getFacadeAccessor());
return call_user_func_array(array($instance, $method), $args);
}
public static function __callStatic($method, $args)
{
return static::resolveMethod($method, $args);
}
public function __call($method, $args)
{
return static::resolveMethod($method, $args);
}
} | laravella/ravel | src/Laravella/Ravel/Facades/Facade.php | PHP | bsd-3-clause | 1,183 |
# License: BSD 3 clause <https://opensource.org/licenses/BSD-3-Clause>
# Copyright (c) 2016, Fabricio Vargas Matos <fabriciovargasmatos@gmail.com>
# All rights reserved.
''''
Tune the 3 most promissing algorithms and compare them
'''
# Load libraries
import os
import time
import pandas
import numpy
import matplotlib.pyplot as plt
from pandas.tools.plotting import scatter_matrix
from pandas import DataFrame
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn import cross_validation
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.pipeline import Pipeline
from sklearn.grid_search import GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.datasets import load_digits
from sklearn.model_selection import GridSearchCV
from sklearn.decomposition import PCA, NMF
from sklearn.feature_selection import SelectKBest, chi2
import lib.eda1 as eda1
import lib.eda3 as eda3
#constants
N_DIGITS = 3
NUM_FOLDS = 10
RAND_SEED = 7
SCORING = 'accuracy'
VALIDATION_SIZE = 0.20
N_JOBS = 6
#global variables
start = time.clock()
imageidx = 1
createImages = True
results = []
names = []
params = []
bestResults = []
# RandomForestClassifier
def tuneRF(X_train, Y_train, outputPath):
global results, names, params, bestResults
print 'tune LR (Random Forest Classifier)'
pipeline = Pipeline([('PCA', PCA()),('MinMaxScaler', MinMaxScaler(feature_range=(0, 1))),('Scaler', StandardScaler())])
scaler = pipeline.fit(X_train)
rescaledX = scaler.transform(X_train)
#tune para meters
# http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html
#n_estimators_values = [5, 10, 100, 1000, 3000]
n_estimators_values = [1000]
max_features_values = [0.1, 'auto', 'sqrt', 'log2', None] # (float)0.1=>10%
criterion_values = ['gini', 'entropy']
param_grid = dict(n_estimators=n_estimators_values, max_features=max_features_values, criterion=criterion_values)
model = RandomForestClassifier()
kfold = cross_validation.KFold(n=len(X_train), n_folds=NUM_FOLDS, random_state=RAND_SEED)
grid = GridSearchCV(n_jobs=N_JOBS, verbose=10, estimator=model, param_grid=param_grid, scoring=SCORING, cv=kfold)
grid_result = grid.fit(rescaledX, Y_train)
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
best_idx = grid_result.best_index_
#TODO: check it out if 'mean_test_score' is really what I want here
cv_results = grid_result.cv_results_['mean_test_score']
results.append(cv_results)
grid_scores = sorted(grid_result.grid_scores_, key=lambda x: x[2].mean(), reverse=True)
first = True
for param, mean_score, scores in grid_scores:
if first:
bestResults.append({'name':'RF', 'mean':scores.mean(), 'std':scores.std(), 'params':param})
first = False
print("%f (%f) with: %r" % (scores.mean(), scores.std(), param))
# ExtraTreesClassifier
def tuneET(X_train, Y_train, outputPath):
global results, names, params, bestResults
print 'tune ET (Extra Trees Classifier)'
pipeline = Pipeline([('PCA', PCA()),('MinMaxScaler', MinMaxScaler(feature_range=(0, 1))),('Scaler', StandardScaler())])
scaler = pipeline.fit(X_train)
rescaledX = scaler.transform(X_train)
#tune para meters
# http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.ExtraTreesClassifier.html
#n_estimators_values = [5, 10, 100, 1000, 3000]
n_estimators_values = [1000]
max_features_values = [0.1, 'auto', 'sqrt', 'log2', None] # (float)0.1=>10%
criterion_values = ['gini', 'entropy']
param_grid = dict(n_estimators=n_estimators_values, max_features=max_features_values, criterion=criterion_values)
model = ExtraTreesClassifier()
kfold = cross_validation.KFold(n=len(X_train), n_folds=NUM_FOLDS, random_state=RAND_SEED)
grid = GridSearchCV(n_jobs=N_JOBS, verbose=10, estimator=model, param_grid=param_grid, scoring=SCORING, cv=kfold)
grid_result = grid.fit(rescaledX, Y_train)
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
best_idx = grid_result.best_index_
#TODO: check it out if 'mean_test_score' is really what a want here
cv_results = grid_result.cv_results_['mean_test_score']
results.append(cv_results)
grid_scores = sorted(grid_result.grid_scores_, key=lambda x: x[2].mean(), reverse=True)
first = True
for param, mean_score, scores in grid_scores:
if first:
bestResults.append({'name':'ET', 'mean':scores.mean(), 'std':scores.std(), 'params':param})
first = False
print("%f (%f) with: %r" % (scores.mean(), scores.std(), param))
# Tune scaled SVM
def tuneSVM(X_train, Y_train, outputPath):
global results, names, params, bestResults
print 'tune SVM (Support Vector Machines Classifier)'
pipeline = Pipeline([('PCA', PCA()),('MinMaxScaler', MinMaxScaler(feature_range=(0, 1))),('Scaler', StandardScaler())])
scaler = pipeline.fit(X_train)
rescaledX = scaler.transform(X_train)
#c_values = [0.1, 1.0, 100.0, 10000.0, 100000.0]
c_values = [10000.0, 100000.0]
kernel_values = ['linear', 'poly', 'rbf', 'sigmoid']
param_grid = dict(C=c_values, kernel=kernel_values)
model = SVC()
kfold = cross_validation.KFold(n=len(X_train), n_folds=NUM_FOLDS, random_state=RAND_SEED)
grid = GridSearchCV(n_jobs=N_JOBS, verbose=10, estimator=model, param_grid=param_grid, scoring=SCORING, cv=kfold)
grid_result = grid.fit(rescaledX, Y_train)
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
best_idx = grid_result.best_index_
#TODO: check it out if 'mean_test_score' is really what a want here
cv_results = grid_result.cv_results_['mean_test_score']
results.append(cv_results)
grid_scores = sorted(grid_result.grid_scores_, key=lambda x: x[2].mean(), reverse=True)
first = True
for param, mean_score, scores in grid_scores:
if first:
bestResults.append({'name':'SVM', 'mean':scores.mean(), 'std':scores.std(), 'params':param})
first = False
print("%f (%f) with: %r" % (scores.mean(), scores.std(), param))
def drawTunedAlgorithmsComparison(results, names, outputPath):
global imageidx
print '\n === Tuned Algorithms Comparison ===\n'
#print bestResults
for x in bestResults:
print x
# Compare Algorithms
if (createImages):
fig = plt.figure()
fig.suptitle('Final Tuned-Algorithms Comparison')
ax = fig.add_subplot(111)
plt.boxplot(results)
ax.set_xticklabels(names)
#plt.show()
plt.savefig(outputPath + str(imageidx).zfill(N_DIGITS) + '-Tuned-Algorithm-Comparison.png')
imageidx += 1
plt.close('all')
def set_createImages(value):
global createImages
createImages = value
# ===================================================
# ================== main function ==================
# ===================================================
def run(inputFilePath, outputPath, createImagesFlag, dropColumns):
global start
print '####################################################################'
print '############### Running Exploratory Data Analysis #4 ###############'
print '####################################################################'
print ''
set_createImages(createImagesFlag)
start = time.clock()
eda1.reset_imageidx()
eda1.set_createImages(createImagesFlag)
if not os.path.exists(outputPath):
os.makedirs(outputPath)
# Load dataset
dataframe = eda1.loadDataframe(inputFilePath)
# drop out 'not fair' features
dataframe = eda1.dataCleansing(dataframe, dropColumns)
#Split-out train/validation dataset
X_train, X_validation, Y_train, Y_validation = eda1.splitoutValidationDataset(dataframe)
'''
# tune each algorithm
try:
tuneRF(X_train, Y_train, outputPath)
except Exception as e:
print "ERROR: couldn't tune RF"
print "Message: %s" % str(e)
try:
tuneET(X_train, Y_train, outputPath)
except Exception as e:
print "ERROR: couldn't tune ET"
print "Message: %s" % str(e)
'''
try:
tuneSVM(X_train, Y_train, outputPath)
except Exception as e:
print "ERROR: couldn't tune SVM"
print "Message: %s" % str(e)
#print the results comparing the algorithms with the best tune for each one
drawTunedAlgorithmsComparison(results, names, outputPath)
print '\n<<< THEN END - Running Exploratory Data Analysis #4 >>>'
#RF - Best: 0.853451 using {'max_features': 'log2', 'n_estimators': 1000, 'criterion': 'gini'}
#ET - Best: 0.855320 using {'max_features': None, 'n_estimators': 1000, 'criterion': 'gini'} | FabricioMatos/ifes-dropout-machine-learning | lib/eda4.py | Python | bsd-3-clause | 9,696 |