text
stringlengths 2
99.7k
| meta
dict |
|---|---|
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<_PropertySheetDisplayName>Libbitcoin Node Import Settings</_PropertySheetDisplayName>
</PropertyGroup>
<!-- User Interface -->
<ItemGroup Label="BuildOptionsExtension">
<PropertyPageSchema Include="$(MSBuildThisFileDirectory)libbitcoin-node.import.xml" />
</ItemGroup>
<!-- Linkage -->
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(ProjectDir)..\..\..\..\..\libbitcoin-node\include\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions Condition="'$(Linkage-libbitcoin-node)' == 'static' Or '$(Linkage-libbitcoin-node)' == 'ltcg'">BCN_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<AdditionalDependencies Condition="'$(Linkage-libbitcoin-node)' != ''">libbitcoin-node.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
<Link Condition="($(PlatformToolset) == 'v120') Or ($(PlatformToolset) == 'CTP_Nov2013')">
<!-- $(PlatformToolset) is hard wired to CTP_Nov2013 to allow for linkage by PlatformToolset=v120 (and CTP_Nov2013) callers. -->
<AdditionalLibraryDirectories Condition="$(Configuration.IndexOf('Debug')) != -1">$(ProjectDir)..\..\..\..\..\libbitcoin-node\bin\$(PlatformName)\Debug\CTP_Nov2013\$(Linkage-libbitcoin-node)\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalLibraryDirectories Condition="$(Configuration.IndexOf('Release')) != -1">$(ProjectDir)..\..\..\..\..\libbitcoin-node\bin\$(PlatformName)\Release\CTP_Nov2013\$(Linkage-libbitcoin-node)\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<Link Condition="($(PlatformToolset) != 'v120') And ($(PlatformToolset) != 'CTP_Nov2013')">
<AdditionalLibraryDirectories Condition="$(Configuration.IndexOf('Debug')) != -1">$(ProjectDir)..\..\..\..\..\libbitcoin-node\bin\$(PlatformName)\Debug\$(PlatformToolset)\$(Linkage-libbitcoin-node)\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalLibraryDirectories Condition="$(Configuration.IndexOf('Release')) != -1">$(ProjectDir)..\..\..\..\..\libbitcoin-node\bin\$(PlatformName)\Release\$(PlatformToolset)\$(Linkage-libbitcoin-node)\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<Link Condition="$(PlatformToolset) != 'v120'">
<!-- Need to link $(VC_CTP_Nov2013_LibraryPath_x86), $(VC_CTP_Nov2013_LibraryPath_x64), or $(VC_CTP_Nov2013_LibraryPath_ARM).-->
<AdditionalLibraryDirectories Condition="$(PlatformName) == 'ARM'">$(ProgramFiles)\Microsoft Visual C++ Compiler Nov 2013 CTP\lib\arm;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalLibraryDirectories Condition="$(PlatformName) == 'x64'">$(ProgramFiles)\Microsoft Visual C++ Compiler Nov 2013 CTP\lib\amd64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalLibraryDirectories Condition="$(PlatformName) == 'Win32'">$(ProgramFiles)\Microsoft Visual C++ Compiler Nov 2013 CTP\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<!-- Copy -->
<!-- $(PlatformToolset) is hard wired to CTP_Nov2013 to allow for linkage by PlatformToolset=v120 (and CTP_Nov2013) callers. -->
<Target Name="Linkage-libbitcoin-node-dynamic" AfterTargets="AfterBuild" Condition="('$(Linkage-libbitcoin-node)' == 'dynamic') And (($(PlatformToolset) == 'v120') Or ($(PlatformToolset) == 'CTP_Nov2013'))">
<Copy Condition="$(Configuration.IndexOf('Debug')) != -1"
SourceFiles="$(ProjectDir)..\..\..\..\..\libbitcoin-node\bin\$(PlatformName)\Debug\CTP_Nov2013\dynamic\libbitcoin-node.dll"
DestinationFiles="$(TargetDir)libbitcoin-node.dll"
SkipUnchangedFiles="true" />
<Copy Condition="$(Configuration.IndexOf('Debug')) != -1"
SourceFiles="$(ProjectDir)..\..\..\..\..\libbitcoin-node\bin\$(PlatformName)\Debug\CTP_Nov2013\dynamic\libbitcoin-node.pdb"
DestinationFiles="$(TargetDir)libbitcoin-node.pdb"
SkipUnchangedFiles="true" />
<Copy Condition="$(Configuration.IndexOf('Release')) != -1"
SourceFiles="$(ProjectDir)..\..\..\..\..\libbitcoin-node\bin\$(PlatformName)\Release\CTP_Nov2013\dynamic\libbitcoin-node.dll"
DestinationFiles="$(TargetDir)libbitcoin-node.dll"
SkipUnchangedFiles="true" />
</Target>
<Target Name="Linkage-libbitcoin-node-dynamic" AfterTargets="AfterBuild" Condition="('$(Linkage-libbitcoin-node)' == 'dynamic') And (($(PlatformToolset) != 'v120') And ($(PlatformToolset) != 'CTP_Nov2013'))">
<Copy Condition="$(Configuration.IndexOf('Debug')) != -1"
SourceFiles="$(ProjectDir)..\..\..\..\..\libbitcoin-node\bin\$(PlatformName)\Debug\$(PlatformToolset)\dynamic\libbitcoin-node.dll"
DestinationFiles="$(TargetDir)libbitcoin-node.dll"
SkipUnchangedFiles="true" />
<Copy Condition="$(Configuration.IndexOf('Debug')) != -1"
SourceFiles="$(ProjectDir)..\..\..\..\..\libbitcoin-node\bin\$(PlatformName)\Debug\$(PlatformToolset)\dynamic\libbitcoin-node.pdb"
DestinationFiles="$(TargetDir)libbitcoin-node.pdb"
SkipUnchangedFiles="true" />
<Copy Condition="$(Configuration.IndexOf('Release')) != -1"
SourceFiles="$(ProjectDir)..\..\..\..\..\libbitcoin-node\bin\$(PlatformName)\Release\$(PlatformToolset)\dynamic\libbitcoin-node.dll"
DestinationFiles="$(TargetDir)libbitcoin-node.dll"
SkipUnchangedFiles="true" />
</Target>
<!-- Messages -->
<Target Name="libbitcoin-node-info" BeforeTargets="AfterBuild" Condition="'$(Linkage-libbitcoin-node)' == 'dynamic'">
<Message Text="Copying libbitcoin-node.dll -> $(TargetDir)libbitcoin-node.dll" Importance="high"/>
<Message Text="Copying libbitcoin-node.pdb -> $(TargetDir)libbitcoin-node.pdb" Importance="high" Condition="$(Configuration.IndexOf('Debug')) != -1" />
</Target>
</Project>
|
{
"pile_set_name": "Github"
}
|
{
"from": 0,
"size": 10,
"query": {
"filtered": {
"query": {
"bool": {
"must": [
{
"range": {
"myfield._number": {
"from": 1.0,
"to": null,
"include_lower": true,
"include_upper": true
}
}
},
{
"match": {
"myfield": {
"query": "myPhrase",
"operator": "OR"
}
}
}
]
}
},
"filter": {
"exists": {
"field": "doesthisfieldexist"
}
}
}
},
"filter": {
"terms": {
"myfield": [
"myValue",
"mySecondValue"
]
}
},
"explain": false,
"sort": [
{
"_geo_distance": {
"myfield._geopoint": [
-50.0,
-70.0
]
}
},
{
"myfield._orderby": {
"order": "desc",
"ignore_unmapped": true
}
}
],
"facets": {
"myTermFacet": {
"terms": {
"field": "mytermfield",
"size": 10,
"order": "term",
"all_terms": false
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
"""auxiliary utility to get the dataset for demo"""
import numpy as np
from collections import namedtuple
from sklearn.datasets import fetch_mldata
import cPickle
import sys
import os
from subprocess import call
class ArrayPacker(object):
"""Dataset packer for iterator"""
def __init__(self, X, Y):
self.images = X
self.labels = Y
self.ptr = 0
def next_batch(self, batch_size):
if self.ptr + batch_size >= self.labels.shape[0]:
self.ptr = 0
X = self.images[self.ptr:self.ptr+batch_size]
Y = self.labels[self.ptr:self.ptr+batch_size]
self.ptr += batch_size
return X, Y
MNISTData = namedtuple("MNISTData", ["train", "test"])
def get_mnist(flatten=False, onehot=False):
mnist = fetch_mldata('MNIST original')
np.random.seed(1234) # set seed for deterministic ordering
p = np.random.permutation(mnist.data.shape[0])
X = mnist.data[p]
Y = mnist.target[p]
X = X.astype(np.float32) / 255.0
if flatten:
X = X.reshape((70000, 28 * 28))
else:
X = X.reshape((70000, 1, 28, 28))
if onehot:
onehot = np.zeros((Y.shape[0], 10))
onehot[np.arange(Y.shape[0]), Y.astype(np.int32)] = 1
Y = onehot
X_train = X[:60000]
Y_train = Y[:60000]
X_test = X[60000:]
Y_test = Y[60000:]
return MNISTData(train=ArrayPacker(X_train, Y_train),
test=ArrayPacker(X_test, Y_test))
CIFAR10Data = namedtuple("CIFAR10Data", ["train", "test"])
def load_batch(fpath, label_key='labels'):
f = open(fpath, 'rb')
if sys.version_info < (3,):
d = cPickle.load(f)
else:
d = cPickle.load(f, encoding="bytes")
# decode utf8
for k, v in d.items():
del(d[k])
d[k.decode("utf8")] = v
f.close()
data = d["data"]
labels = d[label_key]
data = data.reshape(data.shape[0], 3, 32, 32).astype(np.float32)
labels = np.array(labels, dtype="float32")
return data, labels
def get_cifar10(swap_axes=False):
path = "cifar-10-batches-py"
if not os.path.exists(path):
tar_file = "cifar-10-python.tar.gz"
origin = "http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"
if os.path.exists(tar_file):
need_download = False
else:
need_download = True
if need_download:
call(["wget", origin])
call(["tar", "-xvf", "cifar-10-python.tar.gz"])
else:
call(["tar", "-xvf", "cifar-10-python.tar.gz"])
nb_train_samples = 50000
X_train = np.zeros((nb_train_samples, 3, 32, 32), dtype="float32")
y_train = np.zeros((nb_train_samples,), dtype="float32")
for i in range(1, 6):
fpath = os.path.join(path, 'data_batch_' + str(i))
data, labels = load_batch(fpath)
X_train[(i - 1) * 10000: i * 10000, :, :, :] = data
y_train[(i - 1) * 10000: i * 10000] = labels
fpath = os.path.join(path, 'test_batch')
X_test, y_test = load_batch(fpath)
if swap_axes:
X_train = np.swapaxes(X_train, 1, 3)
X_test = np.swapaxes(X_test, 1, 3)
return CIFAR10Data(train=ArrayPacker(X_train, y_train),
test=ArrayPacker(X_test, y_test))
|
{
"pile_set_name": "Github"
}
|
<?php
use yii\helpers\Html;
use backend\modules\rbac\AdminAsset;
use yii\helpers\Json;
use yii\helpers\Url;
/* @var $this yii\web\View */
/* @var $model yii\web\IdentityInterface */
$this->title = Yii::t('rbac-admin', 'Assignments');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="assignment-index">
<?= Html::a(Yii::t('rbac-admin', 'Users'), ['index'], ['class' => 'btn btn-success']) ?>
<h1><?= Yii::t('rbac-admin', 'User') ?>: <?= Html::encode($model->{$usernameField}) ?></h1>
<div class="row">
<div class="col-lg-5">
<div class="input-group">
<span class="input-group-addon"><?= Yii::t('rbac-admin', 'Avaliable') ?>:</span>
<input type="text" class="form-control" id="search-avaliable" placeholder="Search">
</div>
<select class="form-control" id="list-avaliable" multiple size="20" style="width: 100%">
</select>
</div>
<div class="col-lg-1">
<br><br>
<a href="#" id="btn-assign" class="btn btn-success">>></a><br>
<a href="#" id="btn-revoke" class="btn btn-danger"><<</a>
</div>
<div class="col-lg-5">
<div class="input-group">
<span class="input-group-addon"><?= Yii::t('rbac-admin', 'Assigned') ?>:</span>
<input type="text" class="form-control" id="search-assigned" placeholder="Search">
</div>
<select class="form-control" id="list-assigned" multiple size="20" style="width: 100%">
</select>
</div>
</div>
</div>
<?php
AdminAsset::register($this);
$properties = Json::htmlEncode([
'userId' => $model->{$idField},
'assignUrl' => Url::to(['assign']),
'searchUrl' => Url::to(['search']),
]);
$js = <<<JS
yii.admin.initProperties({$properties});
$('#search-avaliable').keydown(function () {
yii.admin.searchAssignmet('avaliable');
});
$('#search-assigned').keydown(function () {
yii.admin.searchAssignmet('assigned');
});
$('#btn-assign').click(function () {
yii.admin.assign('assign');
return false;
});
$('#btn-revoke').click(function () {
yii.admin.assign('revoke');
return false;
});
yii.admin.searchAssignmet('avaliable', true);
yii.admin.searchAssignmet('assigned', true);
JS;
$this->registerJs($js);
|
{
"pile_set_name": "Github"
}
|
@import '../../global/_variables'; // global variables.
@import '../../global/components/_mixins'; // global mixings.
/***
Login page
***/
/* bg color */
$bg-color: #364150;
.login {
background-color: $bg-color !important;
}
.login .logo {
margin: 0 auto;
margin-top: 60px;
padding: 15px;
text-align: center;
}
.login .content {
background-color: #eceef1;
@include border-radius(7px);
width: 400px;
margin: 40px auto 10px auto;
padding: 30px;
padding-top: 10px;
overflow: hidden;
position: relative;
}
.login .content h3 {
color: #4db3a5;
text-align: center;
font-size: 28px;
font-weight: 400 !important;
}
.login .content h4 {
color: #555;
}
.login .content .hint {
color: #999;
padding: 0;
margin: 15px 0 7px 0;
}
.login .content .login-form,
.login .content .forget-form {
padding: 0px;
margin:0px;
}
.login .content .form-control {
border: none;
background-color: #dde3ec;
height: 43px;
color: #8290a3;
border: 1px solid #dde3ec;
&:focus,
&:active {
border: 1px solid #c3ccda;
}
@include placeholder(#8290a3);
}
.login .content select.form-control {
padding-left: 9px;
padding-right: 9px;
}
.login .content .forget-form {
display: none;
}
.login .content .register-form {
display: none;
}
.login .content .form-title {
font-weight: 300;
margin-bottom: 25px;
}
.login .content .form-actions {
clear: both;
border: 0px;
border-bottom: 1px solid #eee;
padding: 0px 30px 25px 30px;
margin-left: -30px;
margin-right: -30px;
}
.login-options {
margin-bottom: 30px;
overflow: hidden;
}
.login-options h4 {
float: left;
font-weight: 600;
font-size: 15px;
color: #7d91aa !important;
}
.login-options .social-icons {
float: right;
padding-top: 3px;
}
.login-options .social-icons li a {
border-radius: 15px 15px 15px 15px !important;
-moz-border-radius: 15px 15px 15px 15px !important;
-webkit-border-radius: 15px 15px 15px 15px !important;
}
.login .content .form-actions .checkbox {
margin-left: 0;
padding-left: 0;
}
.login .content .forget-form .form-actions {
border: 0;
margin-bottom: 0;
padding-bottom: 20px;
}
.login .content .register-form .form-actions {
border: 0;
margin-bottom: 0;
padding-bottom: 0px;
}
.login .content .form-actions .btn {
margin-top: 1px;
}
.login .content .form-actions .btn-success {
font-weight: 600;
padding: 10px 20px !important;
}
.login .content .form-actions .btn-default {
font-weight: 600;
padding: 10px 25px !important;
color: #6c7a8d;
background-color: #ffffff;
border: none;
}
.login .content .form-actions .btn-default:hover {
background-color: #fafaff;
color: #45b6af;
}
.login .content .forget-password {
font-size: 14px;
float: right;
display: inline-block;
margin-top: 10px;
}
.login .content .check {
color: #8290a3;
}
.login .content .rememberme {
margin-left: 8px;
margin-top: 10px;
}
.login .content .create-account {
margin: 0 -40px -40px -40px;
padding: 15px 0 17px 0;
text-align: center;
background-color: #6c7a8d;
@include border-radius(0 0 7px 7px);
}
.login .content .create-account p a {
font-weight: 600;
font-size: 14px;
color: #c3cedd;
}
.login .content .create-account a {
display: inline-block;
margin-top: 5px;
}
/* footer copyright */
.login .copyright {
text-align: center;
margin: 0 auto 30px 0;
padding: 10px;
color: lighten($bg-color, 30%);
font-size: 13px;
}
@media (max-width: 440px) {
/***
Login page
***/
.login .logo {
margin-top: 10px;
}
.login .content {
width: 280px;
margin-top: 10px;
}
.login .content h3 {
font-size: 22px;
}
.forget-password {
display: inline-block;
margin-top: 20px;
}
.login-options .social-icons {
float: left;
padding-top: 3px;
}
.login .checkbox {
font-size: 13px;
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14313.18" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14283.14"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Yaw Rotation View Controller-->
<scene sceneID="eXj-bo-KtG">
<objects>
<viewController storyboardIdentifier="YawRotationViewController" automaticallyAdjustsScrollViewInsets="NO" id="rNN-gu-otp" customClass="YawRotationViewController" customModule="Gemini_Example" customModuleProvider="target" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="jRJ-f8-www"/>
<viewControllerLayoutGuide type="bottom" id="a10-ZX-fNm"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="dZg-b1-Trc">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<collectionView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" showsHorizontalScrollIndicator="NO" showsVerticalScrollIndicator="NO" dataMode="prototypes" translatesAutoresizingMaskIntoConstraints="NO" id="pUf-XH-av4" customClass="GeminiCollectionView" customModule="Gemini">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<collectionViewFlowLayout key="collectionViewLayout" minimumLineSpacing="10" minimumInteritemSpacing="10" id="QSA-Xk-bG7">
<size key="itemSize" width="50" height="50"/>
<size key="headerReferenceSize" width="0.0" height="0.0"/>
<size key="footerReferenceSize" width="0.0" height="0.0"/>
<inset key="sectionInset" minX="0.0" minY="0.0" maxX="0.0" maxY="0.0"/>
</collectionViewFlowLayout>
<cells>
<collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="ImageCollectionViewCell" id="AWO-MI-MkR">
<rect key="frame" x="0.0" y="0.0" width="50" height="50"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center">
<rect key="frame" x="0.0" y="0.0" width="50" height="50"/>
<autoresizingMask key="autoresizingMask"/>
</view>
</collectionViewCell>
</cells>
</collectionView>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstAttribute="trailing" secondItem="pUf-XH-av4" secondAttribute="trailing" id="8S8-hD-SYm"/>
<constraint firstAttribute="bottom" secondItem="pUf-XH-av4" secondAttribute="bottom" id="LN8-vM-NfU"/>
<constraint firstItem="pUf-XH-av4" firstAttribute="leading" secondItem="dZg-b1-Trc" secondAttribute="leading" id="h6l-og-Lee"/>
<constraint firstItem="pUf-XH-av4" firstAttribute="top" secondItem="dZg-b1-Trc" secondAttribute="top" id="kY2-MI-B2N"/>
</constraints>
</view>
<connections>
<outlet property="collectionView" destination="pUf-XH-av4" id="anj-b8-uzT"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="0OI-xU-Caf" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-276" y="107"/>
</scene>
</scenes>
</document>
|
{
"pile_set_name": "Github"
}
|
import {
api,
Process,
Task,
utils,
config,
task,
specHelper,
} from "../../../src/index";
const actionhero = new Process();
let taskOutput = [];
const queue = "testQueue";
describe("Core: Tasks", () => {
beforeAll(async () => {
await actionhero.start();
api.resque.multiWorker.options.minTaskProcessors = 1;
api.resque.multiWorker.options.maxTaskProcessors = 1;
api.resque.multiWorker.options.connection.redis.setMaxListeners(100);
class RegularTask extends Task {
constructor() {
super();
this.name = "regular";
this.description = "task: regular";
this.queue = queue;
this.frequency = 0;
}
run(params) {
taskOutput.push(params.word);
return params.word;
}
}
class PeriodicTask extends Task {
constructor() {
super();
this.name = "periodicTask";
this.description = "task: periodicTask";
this.queue = queue;
this.frequency = 100;
}
async run(params) {
taskOutput.push("periodicTask");
return "periodicTask";
}
}
class SlowTask extends Task {
constructor() {
super();
this.name = "slowTask";
this.description = "task: slowTask";
this.queue = queue;
this.frequency = 0;
}
async run(params) {
await utils.sleep(5000);
taskOutput.push("slowTask");
return "slowTask";
}
}
class TaskWithInputs extends Task {
constructor() {
super();
this.name = "taskWithInputs";
this.description = "task: taskWithInputs";
this.queue = queue;
this.frequency = 0;
this.inputs = {
a: { required: true, default: 1 },
b: {
required: true,
default: () => {
return 2;
},
},
c: {
required: true,
validator: (p) => {
if (p !== 3) {
throw new Error("nope");
}
},
},
d: {
required: true,
validator: (p) => {
if (p !== 4) {
return false;
}
},
},
};
}
async run(params) {
taskOutput.push("taskWithInputs");
return "taskWithInputs";
}
}
api.tasks.tasks.regularTask = new RegularTask();
api.tasks.tasks.periodicTask = new PeriodicTask();
api.tasks.tasks.slowTask = new SlowTask();
api.tasks.tasks.taskWithInputs = new TaskWithInputs();
api.tasks.jobs.regularTask = api.tasks.jobWrapper("regularTask");
api.tasks.jobs.periodicTask = api.tasks.jobWrapper("periodicTask");
api.tasks.jobs.slowTask = api.tasks.jobWrapper("slowTask");
api.tasks.jobs.taskWithInputs = api.tasks.jobWrapper("taskWithInputs");
});
afterAll(async () => {
delete api.tasks.tasks.regularTask;
delete api.tasks.tasks.periodicTask;
delete api.tasks.tasks.slowTask;
delete api.tasks.tasks.taskWithInputs;
delete api.tasks.jobs.regularTask;
delete api.tasks.jobs.periodicTask;
delete api.tasks.jobs.slowTask;
delete api.tasks.jobs.taskWithInputs;
config.tasks.queues = [];
api.resque.multiWorker.options.minTaskProcessors = 0;
api.resque.multiWorker.options.maxTaskProcessors = 0;
await actionhero.stop();
});
beforeEach(async () => {
taskOutput = [];
await api.resque.queue.connection.redis.flushdb();
});
afterEach(async () => {
await api.resque.stopScheduler();
await api.resque.stopMultiWorker();
});
test("validates tasks", () => {
api.tasks.tasks.regularTask.validate();
});
test("a bad task definition causes an exception", () => {
class BadTask extends Task {
constructor() {
super();
// this.name = 'noName'
this.description = "no name";
this.queue = queue;
this.frequency = 0;
}
async run(params) {}
}
const task = new BadTask();
try {
task.validate();
throw new Error("should not get here");
} catch (error) {
expect(error.toString()).toMatch(/name is required for this task/);
}
});
test("setup worked", () => {
expect(Object.keys(api.tasks.tasks)).toHaveLength(4 + 1);
});
test("all queues should start empty", async () => {
const length = await api.resque.queue.length("default");
expect(length).toEqual(0);
});
test("can run a task manually", async () => {
const response = await specHelper.runTask("regularTask", {
word: "theWord",
});
expect(response).toEqual("theWord");
expect(taskOutput[0]).toEqual("theWord");
});
test("can run a task fully", async () => {
const response = await specHelper.runFullTask("regularTask", {
word: "theWord",
});
expect(response).toEqual("theWord");
expect(taskOutput[0]).toEqual("theWord");
});
test("it can detect that a task was enqueued to run now", async () => {
await task.enqueue("regularTask", { word: "testing" });
const found = await specHelper.findEnqueuedTasks("regularTask");
expect(found.length).toEqual(1);
expect(found[0].args[0].word).toEqual("testing");
expect(found[0].timestamp).toBeNull();
});
test("it can detect that a task was enqueued to run in the future", async () => {
await task.enqueueIn(1000, "regularTask", { word: "testing" });
const found = await specHelper.findEnqueuedTasks("regularTask");
expect(found.length).toEqual(1);
expect(found[0].args[0].word).toEqual("testing");
expect(found[0].timestamp).toBeGreaterThan(1);
});
test("can call task methods inside the run", async () => {
class TaskWithMethod extends Task {
constructor() {
super();
this.name = "taskWithMethod";
this.description = "task with additional methods to execute in run";
this.queue = queue;
}
async stepOne() {
await utils.sleep(100);
taskOutput.push("one");
}
stepTwo() {
taskOutput.push("two");
}
async run() {
await this.stepOne();
this.stepTwo();
taskOutput.push("tree");
}
}
api.tasks.tasks.taskWithMethod = new TaskWithMethod();
api.tasks.jobs.taskWithMethod = api.tasks.jobWrapper("taskWithMethod");
await specHelper.runFullTask("taskWithMethod", {});
expect(taskOutput).toHaveLength(3);
expect(taskOutput[0]).toEqual("one");
expect(taskOutput[1]).toEqual("two");
expect(taskOutput[2]).toEqual("tree");
});
test("no delayed tasks should be scheduled", async () => {
const timestamps = await api.resque.queue.scheduledAt(
queue,
"periodicTask"
);
expect(timestamps).toHaveLength(0);
});
test("all periodic tasks can be enqueued at boot", async () => {
await task.enqueueAllRecurrentTasks();
const length = await api.resque.queue.length(queue);
expect(length).toEqual(1);
});
test("re-enquing a recurring task will not throw", async () => {
await task.enqueueAllRecurrentTasks();
await task.enqueueAllRecurrentTasks(); // does not throw
const length = await api.resque.queue.length(queue);
expect(length).toEqual(1);
});
test("re-enqueuing a periodic task should not enqueue it again", async () => {
const tryOne = await task.enqueue("periodicTask", null);
const tryTwo = await task.enqueue("periodicTask", null);
const length = await api.resque.queue.length(queue);
expect(tryOne).toEqual(true);
expect(tryTwo).toEqual(false);
expect(length).toEqual(1);
});
test("can add a normal job", async () => {
await task.enqueue("regularTask", { word: "first" });
const length = await api.resque.queue.length(queue);
expect(length).toEqual(1);
});
test("can add a delayed job", async () => {
const time = new Date().getTime() + 1000;
await task.enqueueAt(time, "regularTask", { word: "first" });
const timestamps = await api.resque.queue.scheduledAt(
queue,
"regularTask",
[{ word: "first" }]
);
expect(timestamps).toHaveLength(1);
const completeTime = Math.floor(time / 1000);
expect(Number(timestamps[0])).toBeGreaterThanOrEqual(completeTime);
expect(Number(timestamps[0])).toBeLessThan(completeTime + 2);
});
test("can see enqueued timestamps & see jobs within those timestamps (single + batch)", async () => {
const time = new Date().getTime() + 1000;
const roundedTime = Math.round(time / 1000) * 1000;
await task.enqueueAt(time, "regularTask", { word: "first" });
const timestamps = await task.timestamps();
expect(timestamps).toHaveLength(1);
expect(timestamps[0]).toEqual(roundedTime);
const { tasks } = await task.delayedAt(roundedTime);
expect(tasks).toHaveLength(1);
expect(tasks[0].class).toEqual("regularTask");
const allTasks = await task.allDelayed();
expect(Object.keys(allTasks)).toHaveLength(1);
expect(Object.keys(allTasks)[0]).toEqual(String(roundedTime));
expect(allTasks[roundedTime][0].class).toEqual("regularTask");
});
test("I can remove an enqueued job", async () => {
await task.enqueue("regularTask", { word: "first" });
const length = await api.resque.queue.length(queue);
expect(length).toEqual(1);
const count = await task.del(queue, "regularTask", { word: "first" });
expect(count).toEqual(1);
const lengthAgain = await api.resque.queue.length(queue);
expect(lengthAgain).toEqual(0);
});
test("I can remove a delayed job", async () => {
await task.enqueueIn(1000, "regularTask", { word: "first" });
const timestamps = await api.resque.queue.scheduledAt(
queue,
"regularTask",
[{ word: "first" }]
);
expect(timestamps).toHaveLength(1);
const timestampsDeleted = await task.delDelayed(queue, "regularTask", {
word: "first",
});
expect(timestampsDeleted).toHaveLength(1);
expect(timestampsDeleted).toEqual(timestamps);
const timestampsDeletedAgain = await task.delDelayed(queue, "regularTask", {
word: "first",
});
expect(timestampsDeletedAgain).toHaveLength(0);
});
test("I can remove and stop a recurring task", async () => {
// enqueue the delayed job 2x, one in each type of queue
await task.enqueue("periodicTask", null);
await task.enqueueIn(1000, "periodicTask", null);
const count = await task.stopRecurrentTask("periodicTask");
expect(count).toEqual(2);
});
describe("input validation", () => {
test("tasks which provide input can be enqueued", async () => {
await expect(task.enqueue("taskWithInputs", {})).rejects.toThrow(
/input for task/
);
await task.enqueue("taskWithInputs", { a: 1, b: 2, c: 3, d: 4 }); // does not throw
});
test("tasks which provide input can be enqueuedAt", async () => {
await expect(task.enqueueIn(1, "taskWithInputs", {})).rejects.toThrow(
/input for task/
);
await task.enqueueIn(1, "taskWithInputs", { a: 1, b: 2, c: 3, d: 4 }); // does not throw
});
test("tasks which provide input can be enqueuedIn", async () => {
await expect(task.enqueueAt(1, "taskWithInputs", {})).rejects.toThrow(
/input for task/
);
await task.enqueueAt(1, "taskWithInputs", { a: 1, b: 2, c: 3, d: 4 }); // does not throw
});
test("defaults can be provided (via literal)", async () => {
await task.enqueue("taskWithInputs", { b: 2, c: 3, d: 4 });
const enqueuedTask = await specHelper.findEnqueuedTasks("taskWithInputs");
expect(enqueuedTask[0].args[0]).toEqual({ a: 1, b: 2, c: 3, d: 4 });
});
test("defaults can be provided (via function)", async () => {
await task.enqueue("taskWithInputs", { a: 1, c: 3, d: 4 });
const enqueuedTask = await specHelper.findEnqueuedTasks("taskWithInputs");
expect(enqueuedTask[0].args[0]).toEqual({ a: 1, b: 2, c: 3, d: 4 });
});
test("validation will fail with input that does not match the validation method (via throw)", async () => {
await expect(
task.enqueue("taskWithInputs", { a: 1, b: 2, c: -1, d: 4 })
).rejects.toThrow(/nope/);
});
test("validation will fail with input that does not match the validation method (via false)", async () => {
await expect(
task.enqueue("taskWithInputs", { a: 1, b: 2, c: 3, d: -1 })
).rejects.toThrow(/-1 is not a valid value for d in task taskWithInputs/);
});
});
describe("middleware", () => {
describe("enqueue modification", () => {
beforeAll(async () => {
const middleware = {
name: "test-middleware",
priority: 1000,
global: false,
preEnqueue: () => {
throw new Error("You cannot enqueue me!");
},
};
task.addMiddleware(middleware);
api.tasks.tasks.middlewareTask = {
name: "middlewareTask",
description: "middlewaretask",
queue: "default",
frequency: 0,
middleware: ["test-middleware"],
run: (params, worker) => {
throw new Error("Should never get here");
},
};
api.tasks.jobs.middlewareTask = api.tasks.jobWrapper("middlewareTask");
});
afterAll(async () => {
api.tasks.globalMiddleware = [];
delete api.tasks.jobs.middlewareTask;
});
test("can modify the behavior of enqueue with middleware.preEnqueue", async () => {
try {
await task.enqueue("middlewareTask", {});
} catch (error) {
expect(error.toString()).toEqual("Error: You cannot enqueue me!");
}
});
});
describe("Pre and Post processing", () => {
beforeAll(() => {
const middleware = {
name: "test-middleware",
priority: 1000,
global: false,
preProcessor: function () {
const params = this.args[0];
if (params.stop === true) {
return false;
}
if (params.throw === true) {
throw new Error("thown!");
}
params.test = true;
if (!this.worker.result) {
this.worker.result = {};
}
this.worker.result.pre = true;
return true;
},
postProcessor: function () {
this.worker.result.post = true;
return true;
},
};
task.addMiddleware(middleware);
api.tasks.tasks.middlewareTask = {
name: "middlewareTask",
description: "middlewaretask",
queue: "default",
frequency: 0,
middleware: ["test-middleware"],
run: function (params, worker) {
expect(params.test).toEqual(true);
const result = worker.result;
result.run = true;
return result;
},
};
api.tasks.jobs.middlewareTask = api.tasks.jobWrapper("middlewareTask");
});
afterAll(() => {
api.tasks.globalMiddleware = [];
delete api.tasks.jobs.middlewareTask;
});
test("can modify parameters before a task and modify result after task completion", async () => {
const result = await specHelper.runFullTask("middlewareTask", {
foo: "bar",
});
expect(result.run).toEqual(true);
expect(result.pre).toEqual(true);
expect(result.post).toEqual(true);
});
test("can prevent the running of a task with error", async () => {
try {
await specHelper.runFullTask("middlewareTask", { throw: true });
} catch (error) {
expect(error.toString()).toEqual("Error: thown!");
}
});
test("can prevent the running of a task with return value", async () => {
const result = await specHelper.runFullTask("middlewareTask", {
stop: true,
});
expect(result).toBeUndefined();
});
});
});
describe("details view in a working system", () => {
test("can use api.tasks.details to learn about the system", async () => {
config.tasks.queues = ["*"];
await task.enqueue("slowTask", { a: 1 });
api.resque.multiWorker.start();
await utils.sleep(2000);
const details = await task.details();
expect(Object.keys(details.queues)).toEqual(["testQueue"]);
expect(details.queues.testQueue).toHaveLength(0);
expect(Object.keys(details.workers)).toHaveLength(1);
const workerName = Object.keys(details.workers)[0];
expect(details.workers[workerName].queue).toEqual("testQueue");
expect(details.workers[workerName].payload.args).toEqual([{ a: 1 }]);
expect(details.workers[workerName].payload.class).toEqual("slowTask");
await api.resque.multiWorker.stop();
}, 10000);
});
});
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* The MenuItemsController
*
* @copyright Copyright (c) 2010 Carl Sutton ( dogmatic69 )
* @link http://www.infinitas-cms.org
* @package Infinitas.Menus.Controller
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @since 0.8a
*
* @author Carl Sutton <dogmatic69@infinitas-cms.org>
*/
/**
* The MenuItemsController
*
* @package Infinitas.Menus.Controller
*/
class MenuItemsController extends MenusAppController {
/**
* List all menu items
*
* @return void
*/
public function admin_index() {
$this->Paginator->settings = array(
'contain' => array(
'Menu',
'Group'
)
);
$menuItems = $this->Paginator->paginate(
null,
array_merge(array($this->modelClass . '.parent_id !=' => 0), $this->Filter->filter)
);
$filterOptions = $this->Filter->filterOptions;
$filterOptions['fields'] = array(
'name',
'menu_id' => array(null => __d('menus', 'All')) + $this->{$this->modelClass}->Menu->find('list'),
'group_id' => array(null => __d('menus', 'Public')) + $this->{$this->modelClass}->Group->find('list'),
'active' => (array)Configure::read('CORE.active_options')
);
$this->set(compact('menuItems', 'filterOptions'));
}
/**
* Add menu items
*
* @return void
*/
public function admin_add() {
parent::admin_add();
if (isset($this->request->params['named']['parent_id'])) {
$this->request->data[$this->modelClass]['parent_id'] = $this->request->params['named']['parent_id'];
}
$menus = $this->{$this->modelClass}->Menu->find('list');
if (empty($menus)) {
$this->notice(__d('menus', 'Please add a menu before adding items'), array(
'level' => 'notice',
'redirect' => array(
'controller' => 'menus'
)
));
}
$groups = array(0 => __d('menus', 'Public')) + $this->{$this->modelClass}->Group->find('list');
if (!empty($this->request->data[$this->modelClass]['parent_id'])) {
$parents = array(0 => __d('menus', 'Root')) + $this->{$this->modelClass}->generateTreeList(array(
$this->modelClass . '.parent_id !=' => 0,
$this->modelClass . '.menu_id' => reset(array_keys($menus))
));
}
$plugins = $this->{$this->modelClass}->getPlugins();
$this->set(compact('menus', 'groups', 'parents', 'plugins'));
}
/**
* Edit menu items
*
* @param string $id the id of the menu item
*
* @return void
*/
public function admin_edit($id = null) {
parent::admin_edit($id);
$menus = $this->{$this->modelClass}->Menu->find('list');
$groups = array(0 => __d('menus', 'Public')) + $this->{$this->modelClass}->Group->find('list');
$parents = $this->{$this->modelClass}->getParents($this->request->data[$this->modelClass]['menu_id']);
$plugins = $this->{$this->modelClass}->getPlugins();
$controllers = $this->{$this->modelClass}->getControllers($this->request->data[$this->modelClass]['plugin']);
$actions = $this->{$this->modelClass}->getActions($this->request->data[$this->modelClass]['plugin'], $this->request->data[$this->modelClass]['controller']);
$this->set(compact('menus', 'groups', 'parents', 'plugins', 'controllers', 'actions'));
}
/**
* Get parent menus
*
* Used for the ajax getting of parent menus items to populate the ajax
* dropdown menus when building and editing menu items.
*
* @return void
*/
public function admin_getParents() {
if (empty($this->request->data[$this->modelClass]['menu_id'])) {
return false;
}
$this->set('json', $this->{$this->modelClass}->getParents($this->request->data[$this->modelClass]['menu_id']));
}
}
|
{
"pile_set_name": "Github"
}
|
.chat-container {
.chat-box {
position: absolute;
top: 20px;
left: 25%;
display: flex;
flex-direction: column;
width: 780px;
height: 520px;
border-radius: 5px;
border: 1px solid #d1d1d1;
background: #fff;
box-shadow: 0 15px 40px rgba(0, 0, 0, .2);
.chat-header {
position: relative;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 60px;
background: #e6e6e6;
flex-shrink: 0;
.header-left {
position: absolute;
left: 0;
height: 80%;
img {
height: 100%;
}
}
.header-center {
height: 80%;
img {
height: 100%;
}
}
.header-right {
position: absolute;
right: 30px;
}
}
.chat-body {
display: flex;
flex-grow: 1;
display: flex;
.left {
flex-shrink: 0;
width: 200px;
height: 100%;
border-right: 1px solid #f3f3f3;
}
.main {
flex-grow: 1;
height: 100%;
.chat-list {
height: 328px;
overflow: auto;
}
.chat-editor-wrapper {
height: 130px;
flex-shrink: 0;
border-top: 1px solid #f3f3f3;
}
}
.right {
display: flex;
flex-direction: column;
flex-shrink: 0;
width: 135px;
height: 100%;
background: #f6f7f9;
border-left: 1px solid #f3f3f3;
.member {
padding: 8px 10px 3px;
}
.user-item {
display: flex;
align-items: center;
color: #787677;
font-size: 12px;
padding: 5px 10px;
.avatar-box {
position: relative;
flex-shrink: 0;
width: 24px;
height: 24px;
border-radius: 50%;
overflow: hidden;
&.mask {
img {
opacity: .7;
}
div {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.2);
}
}
}
}
}
}
}
}
//避免css嵌套太深就从上面的提出来了,css没有模块化,所以要注意此样式会影响其他页面相同样式名的样式
.left-item {
display: flex;
align-items: center;
padding: 10px;
&:hover {
background: #f3f3f3;
}
.left-item-text {
flex-grow: 1;
overflow: hidden;
margin-left: 10px;
.group-name {
display: flex;
justify-content: space-between;
align-items: center;
span:first-child {
color: rgba(0, 0, 0, 0.75);
font-size: 15px;
line-height: 1.5;
}
span:last-child {
font-size: 12px;
color: #abaaab;
}
}
.group-message {
display: flex;
color: #777777;
font-size: 13px;
height: 21px;
overflow: hidden;
&:last-child {
flex-grow: 1;
overflow: hidden;
}
p {
margin-bottom: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
}
}
.chat-item {
padding: 15px;
.time {
margin: 10px 0;
text-align: center;
font-size: 12px;
color: #d0cfcf;
}
.chat-item-info {
display: flex;
justify-content: flex-start;
&.chat-right {
flex-direction: row-reverse;
.chat-main {
text-align: right;
margin-right: 12px;
.username {
color: #9f9f9f;
}
.chat-content {
background: #d9f4fe;
text-align: left;
&::before{
display: none;
}
&::after {
content: '';
position: absolute;
top: 8px;
left: 100%;
width: 0;
height: 0;
border-top: 3px solid transparent;
border-bottom: 6px solid transparent;
border-left: 6px solid #d9f4fe;
}
}
}
}
.chat-main {
flex-grow: 1;
margin-left: 12px;
.username {
color: #a0abca;
font-size: 14px;
}
.chat-content {
position: relative;
display: inline-block;
max-width: 80%;
padding: 12px;
border-radius: 5px;
background: #f3f3f3;
word-wrap: break-word;
word-break: break-all;
&::before {
content: '';
position: absolute;
top: 8px;
right: 100%;
width: 0;
height: 0;
border-top: 3px solid transparent;
border-bottom: 6px solid transparent;
border-right: 6px solid #f3f3f3;
}
img {
max-width: 100%;
height: 200px;
}
p {
margin-bottom: 0;
}
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
libtcmalloc_minimal_la-internal_logging.lo \
libtcmalloc_minimal_la-internal_logging.o: src/internal_logging.cc \
/usr/include/stdio.h /usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h \
/usr/local/lib/gcc/i686-pc-linux-gnu/4.0.2/include/stddef.h \
/usr/include/bits/types.h /usr/include/bits/wordsize.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/local/lib/gcc/i686-pc-linux-gnu/4.0.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/include/bits/stdio.h /usr/include/string.h /usr/include/xlocale.h \
src/internal_logging.h src/config.h /usr/include/stdlib.h \
/usr/include/bits/waitflags.h /usr/include/bits/waitstatus.h \
/usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sys/types.h /usr/include/time.h /usr/include/sys/select.h \
/usr/include/bits/select.h /usr/include/bits/sigset.h \
/usr/include/bits/time.h /usr/include/sys/sysmacros.h \
/usr/include/bits/pthreadtypes.h /usr/include/bits/sched.h \
/usr/include/alloca.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h
/usr/include/stdio.h:
/usr/include/features.h:
/usr/include/sys/cdefs.h:
/usr/include/gnu/stubs.h:
/usr/local/lib/gcc/i686-pc-linux-gnu/4.0.2/include/stddef.h:
/usr/include/bits/types.h:
/usr/include/bits/wordsize.h:
/usr/include/bits/typesizes.h:
/usr/include/libio.h:
/usr/include/_G_config.h:
/usr/include/wchar.h:
/usr/include/bits/wchar.h:
/usr/include/gconv.h:
/usr/local/lib/gcc/i686-pc-linux-gnu/4.0.2/include/stdarg.h:
/usr/include/bits/stdio_lim.h:
/usr/include/bits/sys_errlist.h:
/usr/include/bits/stdio.h:
/usr/include/string.h:
/usr/include/xlocale.h:
src/internal_logging.h:
src/config.h:
/usr/include/stdlib.h:
/usr/include/bits/waitflags.h:
/usr/include/bits/waitstatus.h:
/usr/include/endian.h:
/usr/include/bits/endian.h:
/usr/include/sys/types.h:
/usr/include/time.h:
/usr/include/sys/select.h:
/usr/include/bits/select.h:
/usr/include/bits/sigset.h:
/usr/include/bits/time.h:
/usr/include/sys/sysmacros.h:
/usr/include/bits/pthreadtypes.h:
/usr/include/bits/sched.h:
/usr/include/alloca.h:
/usr/include/unistd.h:
/usr/include/bits/posix_opt.h:
/usr/include/bits/environments.h:
/usr/include/bits/confname.h:
/usr/include/getopt.h:
|
{
"pile_set_name": "Github"
}
|
define([], function () {
return {
sepia(imageData) {
const width = imageData.width, height = imageData.height;
const inputData = imageData.data;
let amount = 10;
amount *= 255 / 100;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const pixel = (y * width + x) * 4;
const luma = inputData[pixel] * 0.3 + inputData[pixel + 1] * 0.59 + inputData[pixel + 2] * 0.11;
let r, g, b;
r = g = b = luma;
r += 20;
g += 10;
b -= amount;
inputData[pixel] = r;
inputData[pixel + 1] = g;
inputData[pixel + 2] = b;
}
}
return imageData;
},
desaturate(imageData) {
for (let y = 0; y < imageData.height; y++) {
for (let x = 0; x < imageData.width; x++) {
const i = (y * 4) * imageData.width + x * 4;
const red = imageData.data[i];
const green = imageData.data[i + 1];
const blue = imageData.data[i + 2];
const avg = (Math.max(red, green, blue) + Math.min(red, green, blue)) / 2;
imageData.data[i] = avg;
imageData.data[i + 1] = avg;
imageData.data[i + 2] = avg;
}
}
return imageData;
},
oil(imageData) {
const width = imageData.width, height = imageData.height;
let outputData = [];
range = 1;
const rHistogram = [];
const gHistogram = [];
const bHistogram = [];
const rTotal = [];
const gTotal = [];
const bTotal = [];
const levels = 256;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let pixel = (y * width + x) * 4;
for (let i = 0; i < levels; i++) {
rHistogram[i] = gHistogram[i] = bHistogram[i] = rTotal[i] = gTotal[i] = bTotal[i] = 0;
}
for (let row = -range; row <= range; row++) {
let iy = y + row;
let ioffset;
if (0 <= iy && iy < height) {
ioffset = iy * width;
for (let col = -range; col <= range; col++) {
let ix = x + col;
if (0 <= ix && ix < width) {
let r = imageData.data[(ioffset + ix) * 4]
let g = imageData.data[(ioffset + ix) * 4 + 1]
let b = imageData.data[(ioffset + ix) * 4 + 2]
let ri = r * levels / 256;
let gi = g * levels / 256;
let bi = b * levels / 256;
rTotal[ri] += r;
gTotal[gi] += g;
bTotal[bi] += b;
rHistogram[ri]++;
gHistogram[gi]++;
bHistogram[bi]++;
}
}
}
}
let r = 0, g = 0, b = 0;
for (let i = 1; i < levels; i++) {
if (rHistogram[i] > rHistogram[r]) {
r = i;
}
if (gHistogram[i] > gHistogram[g]) {
g = i;
}
if (bHistogram[i] > bHistogram[b]) {
b = i;
}
}
r = rTotal[r] / rHistogram[r];
g = gTotal[g] / gHistogram[g];
b = bTotal[b] / bHistogram[b];
outputData[pixel] = r;
outputData[pixel + 1] = g;
outputData[pixel + 2] = b;
outputData[pixel + 3] = imageData.data[pixel + 3];
}
}
for (let k = 0; k < outputData.length; k++) {
imageData.data[k] = outputData[k];
}
return imageData;
},
pixel(imageData) {
var width = imageData.width, height = imageData.height;
size = 4;
for (var y = 0; y < height; y += size) {
for (var x = 0; x < width; x += size) {
var pixel = (y * width + x) * 4;
var w = Math.min(size, width - x);
var h = Math.min(size, height - y);
var t = w * h;
var r = 0, g = 0, b = 0;
for (var by = y; by < y + h; by++) {
for (var bx = x; bx < x + w; bx++) {
var bPixel = (by * width + bx) * 4;
r += imageData.data[bPixel];
g += imageData.data[bPixel + 1];
b += imageData.data[bPixel + 2];
}
}
for (var by = y; by < y + h; by++) {
for (var bx = x; bx < x + w; bx++) {
var bPixel = (by * width + bx) * 4;
imageData.data[bPixel] = r / t;
imageData.data[bPixel + 1] = g / t;
imageData.data[bPixel + 2] = b / t;
}
}
}
}
return imageData;
},
stars(imageData) {
var img = new Image();
img.src = './assets/bokeh-stars.png';
img.onload = function () {
const canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
starsImageData = ctx.getImageData(0, 0, this.width, this.height);
for (let y = 0; y < imageData.height; y++) {
for (let x = 0; x < imageData.width; x++) {
const i = (y * 4) * imageData.width + x * 4;
imageData.data[i] += starsImageData.data[i];
imageData.data[i + 1] += starsImageData.data[i + 1];
imageData.data[i + 2] += starsImageData.data[i + 2];
}
}
console.log(imageData);
};
},
edges(imageData) {
var width = imageData.width, height = imageData.height;
var outputData = [];
var matrixH = [-1, -2, -1,
0, 0, 0,
1, 2, 1];
var matrixV = [-1, 0, 1,
-2, 0, 2,
-1, 0, 1];
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var pixel = (y * width + x) * 4;
var rh = 0; gh = 0; bh = 0;
var rv = 0; gv = 0; bv = 0;
for (var row = -1; row <= 1; row++) {
var iy = y + row;
var ioffset;
if (iy >= 0 && iy < height) {
ioffset = iy * width * 4;
} else {
ioffset = y * width * 4;
}
var moffset = 3 * (row + 1) + 1;
for (var col = -1; col <= 1; col++) {
var ix = x + col;
if (!(ix >= 0 && ix < width)) {
ix = x;
}
ix *= 4;
var r = imageData.data[ioffset + ix];
var g = imageData.data[ioffset + ix + 1];
var b = imageData.data[ioffset + ix + 2];
var h = matrixH[moffset + col];
var v = matrixV[moffset + col];
rh += parseInt(h * r);
bh += parseInt(h * g);
gh += parseInt(h * b);
rv += parseInt(v * r);
gv += parseInt(v * g);
bv += parseInt(v * b);
}
}
r = parseInt(Math.sqrt(rh * rh + rv * rv) / 1.8);
g = parseInt(Math.sqrt(gh * gh + gv * gv) / 1.8);
b = parseInt(Math.sqrt(bh * bh + bv * bv) / 1.8);
outputData[pixel] = r;
outputData[pixel + 1] = g;
outputData[pixel + 2] = b;
outputData[pixel + 3] = imageData.data[pixel + 3];
}
}
for (var k = 0; k < outputData.length; k++) {
imageData.data[k] = outputData[k];
}
return imageData;
},
solarize(imageData) {
const width = imageData.width, height = imageData.height;
const inputData = imageData.data;
const table = [];
for (let i = 0; i < 256; i++) {
const val = (i / 255 > 0.5) ? 2 * (i / 255 - 0.5) : 2 * (0.5 - i / 255)
table[i] = parseInt(255 * val);
}
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let pixel = (y * width + x) * 4;
for (let i = 0; i < 3; i++) {
inputData[pixel + i] = table[inputData[pixel + i]];
}
}
}
return imageData;
},
diffuse(imageData) {
const width = imageData.width, height = imageData.height;
const inputData = imageData.data;
const scale = 2;
const sinTable = [];
const cosTable = [];
for (let i = 0; i < 256; i++) {
const angle = Math.PI * 2 * i / 256;
sinTable[i] = scale * Math.sin(angle);
cosTable[i] = scale * Math.cos(angle);
}
transInverse = function (x, y, out) {
const angle = parseInt(Math.random() * 255);
const distance = Math.random();
out[0] = x + distance * sinTable[angle];
out[1] = y + distance * cosTable[angle];
}
const out = [];
const outputData = [];
for (let j = 0; j < inputData.length; j++) {
outputData[j] = inputData[j];
}
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const pixel = (y * width + x) * 4;
transInverse(x, y, out);
var srcX = Math.floor(out[0]);
var srcY = Math.floor(out[1]);
var xWeight = out[0] - srcX;
var yWeight = out[1] - srcY;
var nw, ne, sw, se;
if (srcX >= 0 && srcX < width - 1 && srcY >= 0 && srcY < height - 1) {
const i = (width * srcY + srcX) * 4;
nw = [inputData[i], inputData[i + 1], inputData[i + 2], inputData[i + 3]];
ne = [inputData[i + 4], inputData[i + 5], inputData[i + 6], inputData[i + 7]];
sw = [inputData[i + width * 4], inputData[i + width * 4 + 1], inputData[i + width * 4 + 2], inputData[i + width * 4 + 3]];
se = [inputData[i + (width + 1) * 4], inputData[i + (width + 1) * 4 + 1], inputData[i + (width + 1) * 4 + 2], inputData[i + (width + 1) * 4 + 3]];
} else {
nw = getPixel(inputData, srcX, srcY, width, height);
ne = getPixel(inputData, srcX + 1, srcY, width, height);
sw = getPixel(inputData, srcX, srcY + 1, width, height);
se = getPixel(inputData, srcX + 1, srcY + 1, width, height);
}
var rgba = bilinearInterpolate(xWeight, yWeight, nw, ne, sw, se);
outputData[pixel] = rgba[0];
outputData[pixel + 1] = rgba[1];
outputData[pixel + 2] = rgba[2];
outputData[pixel + 3] = rgba[3];
}
}
for (var k = 0; k < outputData.length; k++) {
inputData[k] = outputData[k];
}
return imageData;
}
}
});
function getPixel(pixels, x, y, width, height) {
const pix = (y * width + x) * 4;
if (x < 0 || x >= width || y < 0 || y >= height) {
return [pixels[((clampPixel(y, 0, height - 1) * width) + clampPixel(x, 0, width - 1)) * 4],
pixels[((clampPixel(y, 0, height - 1) * width) + clampPixel(x, 0, width - 1)) * 4 + 1],
pixels[((clampPixel(y, 0, height - 1) * width) + clampPixel(x, 0, width - 1)) * 4 + 2],
pixels[((clampPixel(y, 0, height - 1) * width) + clampPixel(x, 0, width - 1)) * 4 + 3]];
}
return [pixels[pix], pixels[pix + 1], pixels[pix + 2], pixels[pix + 3]]
}
function clampPixel(x, a, b) {
return (x < a) ? a : (x > b) ? b : x;
}
function bilinearInterpolate(x, y, nw, ne, sw, se) {
let m0, m1;
const r0 = nw[0]; const g0 = nw[1]; const b0 = nw[2]; const a0 = nw[3];
const r1 = ne[0]; const g1 = ne[1]; const b1 = ne[2]; const a1 = ne[3];
const r2 = sw[0]; const g2 = sw[1]; const b2 = sw[2]; const a2 = sw[3];
const r3 = se[0]; const g3 = se[1]; const b3 = se[2]; const a3 = se[3];
const cx = 1.0 - x; const cy = 1.0 - y;
m0 = cx * a0 + x * a1;
m1 = cx * a2 + x * a3;
const a = cy * m0 + y * m1;
m0 = cx * r0 + x * r1;
m1 = cx * r2 + x * r3;
const r = cy * m0 + y * m1;
m0 = cx * g0 + x * g1;
m1 = cx * g2 + x * g3;
const g = cy * m0 + y * m1;
m0 = cx * b0 + x * b1;
m1 = cx * b2 + x * b3;
const b = cy * m0 + y * m1;
return [r, g, b, a];
}
|
{
"pile_set_name": "Github"
}
|
*** Settings ***
Library OperatingSystem
Library String
Resource ../../../variables/${VARIABLES}_variables.robot
Resource ../../../libraries/all_libs.robot
Resource ../../../libraries/pretty_keywords.robot
Suite Setup Testsuite Setup
Suite Teardown Testsuite Teardown
Test Setup TestSetup
Test Teardown TestTeardown
*** Variables ***
${VARIABLES}= common
${ENV}= common
${WAIT_TIMEOUT}= 20s
${SYNC_SLEEP}= 3s
${TRACE_WAIT_TIMEOUT}= 6s
${TRACE_SYNC_SLEEP}= 1s
${PING_WAIT_TIMEOUT}= 15s
${PING_SLEEP}= 1s
@{segments} b:: c::
@{segmentsweight} 1 @{segments} # segment list's weight and segments
@{segmentList} ${segmentsweight}
${vpp1_tap_ipv6}= a::a
${linux_vpp1_tap_ipv6}= a::1
${linux_vpp1_tap_ipv6_subnet}= a::
${vpp3_tap_ipv6}= c::c
${linux_vpp3_tap_ipv6}= c::1
${linux_vpp3_tap_ipv6_subnet}= c::
${linux_vpp1_tap_ipv4_subnet} 10.1.1.0 # 24-bit netmask, IPv4 pattern: 10.<vpp number>.x.x
${linux_vpp1_tap_ipv4}= 10.1.1.1
${vpp1_tap_ipv4}= 10.1.1.2
${vpp1_memif2_ipv4}= 10.1.3.1
${srproxy_out_memif_ipv4}= 10.2.1.1
${srproxy_in_memif_ipv4}= 10.2.2.2
${linux_vpp3_tap_ipv4_subnet}= 10.3.1.0 # 24-bit netmask
${linux_vpp3_tap_ipv4}= 10.3.1.1
${vpp3_tap_ipv4}= 10.3.1.2
${vpp3_memif2_ipv4}= 10.3.3.1
${service_out_memif_ipv4}= 10.4.1.2
${service_in_memif_ipv4}= 10.4.2.1
${vpp1_tap_mac}= 11:11:11:11:11:11
${linux_vpp1_tap_mac}= 22:22:22:22:22:22
${vpp3_tap_mac}= 33:33:33:33:33:33
${linux_vpp3_tap_mac}= 44:44:44:44:44:44
${vpp1_memif1_mac}= 02:f1:be:90:00:01
${vpp2_memif1_mac}= 02:f1:be:90:00:02
${vpp2_memif2_mac}= 02:f1:be:90:02:02
${vpp3_memif1_mac}= 02:f1:be:90:00:03
${vpp3_memif2_mac}= 02:f1:be:90:02:03
${vpp1_memif2_mac}= 02:f1:be:90:02:01
${srproxy_out_memif_mac}= 02:f1:be:90:03:02
${service_in_memif_mac}= 02:f1:be:90:00:04
${service_out_memif_mac}= 02:f1:be:90:02:04
${srproxy_in_memif_mac}= 02:f1:be:90:04:02
# ethernet frame sending variables (used as values in sending python script or in validation)
${out_interface}= linux_vpp1_tap
${source_mac_address}= 01:02:03:04:05:06
${destination_mac_address}= 01:02:03:04:05:06
${ethernet_type} 88b5 # using public ethernet type for prototype and vendor-specific protocol development to not explicitly say what to expect in payload (=general frame) (http://standards-oui.ieee.org/ethertype/eth.txt)
${payload} "["*30)+"PAYLOAD"+("]"*30 # custom payload (= general frame) (inserted directly "as is" in python script)
${payload_hex_prefix}= 5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b # partial prefix of payload in hexadecimal form (used for validation)
${checksum} 1a2b3c4d # checksum is not controlled anywhere, but needed for correct construction of frame structure
${srproxy_out_memif_vpp_name}= memif3/3 # used for validation
${srproxy_in_memif_vpp_index}= 4 # used for validation
*** Test Cases ***
Common Setup Used Across All Tests
[Tags] setup
# create nodes
Add Agent VPP Node agent_vpp_1
Add Agent VPP Node agent_vpp_2
Add Agent VPP Node agent_vpp_3
Add Agent VPP Node agent_vpp_4
# creating TAP tunnels between linux and VPP (in containers)
Put TAPv2 Interface With 2 IPs node=agent_vpp_1 name=vpp1_tap ip=${vpp1_tap_ipv6} prefix=64 second_ip=${vpp1_tap_ipv4} second_prefix=24 host_if_name=linux_vpp1_tap mac=${vpp1_tap_mac}
Wait Until Keyword Succeeds ${WAIT_TIMEOUT} ${SYNC_SLEEP} vpp_term: Interface Is Created node=agent_vpp_1 mac=${vpp1_tap_mac}
linux: Set Host TAP Interface node=agent_vpp_1 host_if_name=linux_vpp1_tap ip=${linux_vpp1_tap_ipv6} prefix=64 mac=${linux_vpp1_tap_mac} second_ip=${linux_vpp1_tap_ipv4} second_prefix=24
Put TAPv2 Interface With 2 IPs node=agent_vpp_3 name=vpp3_tap ip=${vpp3_tap_ipv6} prefix=64 second_ip=${vpp3_tap_ipv4} second_prefix=24 host_if_name=linux_vpp3_tap mac=${vpp3_tap_mac}
Wait Until Keyword Succeeds ${WAIT_TIMEOUT} ${SYNC_SLEEP} vpp_term: Interface Is Created node=agent_vpp_3 mac=${vpp3_tap_mac}
linux: Set Host TAP Interface node=agent_vpp_3 host_if_name=linux_vpp3_tap ip=${linux_vpp3_tap_ipv6} prefix=64 mac=${linux_vpp3_tap_mac} second_ip=${linux_vpp3_tap_ipv4} second_prefix=24
# creating VPP (memif) tunnels between nodes (for IPv6 address purposes: agent_vpp_1 = node A, agent_vpp_2 = node B (SR proxy), agent_vpp_3 = node C, agent_vpp_4 = node D (SR-unaware service))
Create Master vpp1_memif1 on agent_vpp_1 with IP ab::a, MAC ${vpp1_memif1_mac}, key 1 and m1.sock socket
Create Slave vpp2_memif1 on agent_vpp_2 with IP ab::b, MAC ${vpp2_memif1_mac}, key 1 and m1.sock socket
Create Master vpp2_memif2 on agent_vpp_2 with IP bc::b, MAC ${vpp2_memif2_mac}, key 2 and m2.sock socket
Create Slave vpp3_memif1 on agent_vpp_3 with IP bc::c, MAC ${vpp3_memif1_mac}, key 2 and m2.sock socket
# creating routes between nodes (using memifs)
Create Route On agent_vpp_1 With IP b::/64 With Vrf Id 0 With Interface vpp1_memif1 And Next Hop ab::b
Create Route On agent_vpp_2 With IP c::/64 With Vrf Id 0 With Interface vpp2_memif2 And Next Hop bc::c
# configure segment routing that is common for all tests
Put SRv6 Policy node=agent_vpp_1 bsid=a::c installationVrfId=0 srhEncapsulation=true sprayBehaviour=false segmentlists=${segmentList}
# preventing packet drops due to unresolved ipv6 neighbor discovery
vpp_term: Set IPv6 neighbor agent_vpp_1 memif1/1 ab::b ${vpp2_memif1_mac}
vpp_term: Set IPv6 neighbor agent_vpp_2 memif1/1 ab::a ${vpp1_memif1_mac}
vpp_term: Set IPv6 neighbor agent_vpp_2 memif2/2 bc::c ${vpp3_memif1_mac}
vpp_term: Set IPv6 neighbor agent_vpp_3 memif1/2 bc::b ${vpp2_memif2_mac}
Dynamic SR Proxy with L3-IPv6 SR-unaware service
# Testing IPv6 traffic(ping packet) going through SR-proxy (IPv6 segment routing) connected to IPv6 SR-unaware service.
# Desired ping packet path:
## Container agent_vpp_1: linux environment -> linux_vpp1_tap interface -(tap tunnel to VPP1)-> vpp1_tap interface
## -> steering to segment routing (segment list="b::, c::") -(segment routing to b::)
## -> vpp1_memif1 interface (memif tunnel to VPP2)
## Container agent_vpp_2 (SR proxy node): vpp2_memif1 interface -(SR-proxy functionality)-> srproxy_out_memif interface
## Container agent_vpp_4 (SR-unware service node): service_in_memif interface -(just forwarding incomming packet)-> service_out_memif interface
## Container agent_vpp_2 (SR proxy node): srproxy_in_memif interface -(segment routing to c::)-> vpp2_memif2 interface
## Container agent_vpp_3: vpp3_memif1 interface -(DX6 decapsulation from segment routing)-> vpp3_tap interface
## -> linux_vpp3_tap(ping reached destination) -(ping reply)-> vpp3_tap interface
## -> vpp3_memif2 interface (memif tunnel to VPP1)
## Container agent_vpp_1: vpp1_memif2 interface -> vpp1_tap interface -> linux_vpp1_tap interface -> linux environment
# creating path for ping packet (path is already partially done in common setup)
## steering trafic from linux to TAPs tunnel leading to VPP
linux: Add Route node=agent_vpp_1 destination_ip=${linux_vpp3_tap_ipv6} prefix=64 next_hop_ip=${vpp1_tap_ipv6}
## steering traffic to segment routing
Put SRv6 L3 Steering node=agent_vpp_1 name=toC bsid=a::c installationVrfId=0 prefixAddress=c::/64
## creating sr-proxy in and out interfaces (using memifs)
Create Master srproxy_out_memif on agent_vpp_2 with Prefixed IP bd:1::b/32, MAC ${srproxy_out_memif_mac}, key 3 and m3.sock socket
Create Slave service_in_memif on agent_vpp_4 with Prefixed IP bd:1::d/32, MAC ${service_in_memif_mac}, key 3 and m3.sock socket
Create Master service_out_memif on agent_vpp_4 with Prefixed IP bd:2::d/32, MAC ${service_out_memif_mac}, key 4 and m4.sock socket
Create Slave srproxy_in_memif on agent_vpp_2 with Prefixed IP bd:2::b/32, MAC ${srproxy_in_memif_mac}, key 4 and m4.sock socket
## configure SR-proxy
Put Local SID With End.AD function node=agent_vpp_2 sidAddress=b:: l3serviceaddress=bd:1::d outinterface=srproxy_out_memif ininterface=srproxy_in_memif
## creating service routes (Service just sends received packets back)
Create Route On agent_vpp_4 With IP ${linux_vpp3_tap_ipv6_subnet}/64 With Vrf Id 0 With Interface service_out_memif And Next Hop bd:2::b
## configure exit from segment routing
Put Local SID With End.DX6 function node=agent_vpp_3 sidAddress=c:: installationVrfId=0 outinterface=vpp3_tap nexthop=${linux_vpp3_tap_ipv6}
## path for ping packet returning back to source (no segment routing, but just plain IPv6 route):
## create route for ping echo to get back to vpp3 from linux enviroment in agent_vpp_3 container
linux: Add Route node=agent_vpp_3 destination_ip=${linux_vpp1_tap_ipv6} prefix=64 next_hop_ip=${vpp3_tap_ipv6}
## creating path for ping echo from vpp3 to vpp1
Create Master vpp3_memif2 on agent_vpp_3 with IP ac::c, MAC ${vpp3_memif2_mac}, key 5 and m5.sock socket
Create Slave vpp1_memif2 on agent_vpp_1 with IP ac::a, MAC ${vpp1_memif2_mac}, key 5 and m5.sock socket
Create Route On agent_vpp_3 With IP ${linux_vpp1_tap_ipv6_subnet}/64 With Vrf Id 0 With Interface vpp3_memif2 And Next Hop ac::a
# preventing packet drops due to unresolved ipv6 neighbor discovery
vpp_term: Set IPv6 neighbor agent_vpp_1 memif2/5 ac::c ${vpp3_memif2_mac}
vpp_term: Set IPv6 neighbor agent_vpp_1 tap0 ${linux_vpp1_tap_ipv6} ${linux_vpp1_tap_mac}
vpp_term: Set IPv6 neighbor agent_vpp_2 memif3/3 bd:1::d ${service_in_memif_mac}
vpp_term: Set IPv6 neighbor agent_vpp_2 memif4/4 bd:2::d ${service_out_memif_mac}
vpp_term: Set IPv6 neighbor agent_vpp_3 memif2/5 ac::a ${vpp1_memif2_mac}
vpp_term: Set IPv6 neighbor agent_vpp_3 tap0 ${linux_vpp3_tap_ipv6} ${linux_vpp3_tap_mac}
vpp_term: Set IPv6 neighbor agent_vpp_4 memif1/3 bd:1::b ${srproxy_out_memif_mac}
vpp_term: Set IPv6 neighbor agent_vpp_4 memif2/4 bd:2::b ${srproxy_in_memif_mac}
# add packet tracing
vpp_term: Add Trace Memif agent_vpp_2 100
# ping from agent_vpp_1 to agent_vpp_3's tap interface (despite efforts to eliminite first packet drop by setting ipv6 neighbor, sometimes it is still happening -> timeoutable pinging repeat until first ping success)
Wait Until Keyword Succeeds ${PING_WAIT_TIMEOUT} .${PING_SLEEP} linux: Check Ping6 node=agent_vpp_1 ip=${linux_vpp3_tap_ipv6} count=1
# check that packet is processed by SR-proxy, send to SR-unware service using correct interface and in the process decapsulated(checked only source and destination address and not if SR header extension is missing because that is not visible in trace)
${vpp2trace}= vpp_term: Show Trace agent_vpp_2
Packet Trace ${vpp2trace} Should Contain One Packet Trace That Contains These Ordered Substrings srv6-ad-localsid, IP6: ${srproxy_out_memif_mac} -> ${service_in_memif_mac}, ICMP6: ${linux_vpp1_tap_ipv6} -> ${linux_vpp3_tap_ipv6}, ., . # using only 3 substrings to match packet trace
# check that packet has returned from SR-unware service, gets rewritten by proxy (SR encapsulation) and send to another SR segment (correct interface and correct source and destination address)
Packet Trace ${vpp2trace} Should Contain One Packet Trace That Contains These Ordered Substrings ${linux_vpp1_tap_ipv6} -> ${linux_vpp3_tap_ipv6}, SRv6-AD-rewrite: src :: dst c::, IP6: ${vpp2_memif2_mac} -> ${vpp3_memif1_mac}, IPV6_ROUTE: :: -> c::, . # using only 4 substrings to match packet trace
# cleanup (for next test)
Delete VPP Interface agent_vpp_2 srproxy_in_memif
Delete VPP Interface agent_vpp_2 srproxy_out_memif
Delete VPP Interface agent_vpp_4 service_in_memif
Delete VPP Interface agent_vpp_4 service_out_memif
Delete VPP Interface agent_vpp_3 vpp3_memif2
Delete VPP Interface agent_vpp_1 vpp1_memif2
Delete Local SID node=agent_vpp_2 sidAddress=b::
Delete Local SID node=agent_vpp_3 sidAddress=c::
vpp_term: Clear Trace agent_vpp_2
Dynamic SR Proxy with L3-IPv4 SR-unaware service
# Testing IPv4 traffic(ping packet) going through SR-proxy (IPv6 segment routing) connected to IPv4 SR-unaware service.
# Desired ping packet path is basically the same as in test for IPv6 SR-unaware service. The difference is that we
# use IPv4 addresses and IPv4 routes everywhere except of IPv6 segment routing.
# creating path for ping packet (path is already partially done in common setup)
## steering trafic from linux to TAPs tunnel leading to VPP
linux: Add Route node=agent_vpp_1 destination_ip=${linux_vpp3_tap_ipv4_subnet} prefix=24 next_hop_ip=${vpp1_tap_ipv4}
## steering traffic to segment routing
Put SRv6 L3 Steering node=agent_vpp_1 name=toC bsid=a::c installationVrfId=0 prefixAddress=${linux_vpp3_tap_ipv4_subnet}/24
## creating sr-proxy in and out interfaces (using memifs)
Create Master srproxy_out_memif on agent_vpp_2 with Prefixed IP ${srproxy_out_memif_ipv4}/24, MAC ${srproxy_out_memif_mac}, key 3 and m3.sock socket
Create Slave service_in_memif on agent_vpp_4 with Prefixed IP ${service_in_memif_ipv4}/24, MAC ${service_in_memif_mac}, key 3 and m3.sock socket
Create Master service_out_memif on agent_vpp_4 with Prefixed IP ${service_out_memif_ipv4}/24, MAC ${service_out_memif_mac}, key 4 and m4.sock socket
Create Slave srproxy_in_memif on agent_vpp_2 with Prefixed IP ${srproxy_in_memif_ipv4}/24, MAC ${srproxy_in_memif_mac}, key 4 and m4.sock socket
## configure SR-proxy
Put Local SID With End.AD function node=agent_vpp_2 sidAddress=b:: l3serviceaddress=${service_in_memif_ipv4} outinterface=srproxy_out_memif ininterface=srproxy_in_memif
## creating service routes (Service just sends received packets back)
Create Route On agent_vpp_4 With IP ${linux_vpp3_tap_ipv4_subnet}/24 With Vrf Id 0 With Interface service_out_memif And Next Hop ${srproxy_in_memif_ipv4}
## configure exit from segment routing
Put Local SID With End.DX4 function node=agent_vpp_3 sidAddress=c:: installationVrfId=0 outinterface=vpp3_tap nexthop=${linux_vpp3_tap_ipv4}
## path for ping packet returning back to source (no segment routing, but just plain IPv4 route):
## create route for ping echo to get back to vpp3 from linux enviroment in agent_vpp_3 container
linux: Add Route node=agent_vpp_3 destination_ip=${linux_vpp1_tap_ipv4_subnet} prefix=24 next_hop_ip=${vpp3_tap_ipv4}
## creating path for ping echo from vpp3 to vpp1
Create Master vpp3_memif2 on agent_vpp_3 with IP ${vpp3_memif2_ipv4}, MAC ${vpp3_memif2_mac}, key 5 and m5.sock socket
Create Slave vpp1_memif2 on agent_vpp_1 with IP ${vpp1_memif2_ipv4}, MAC ${vpp1_memif2_mac}, key 5 and m5.sock socket
Create Route On agent_vpp_3 With IP ${linux_vpp1_tap_ipv4_subnet}/24 With Vrf Id 0 With Interface vpp3_memif2 And Next Hop ${vpp1_memif2_ipv4}
# preventing packet drops due to unresolved ipv6 neighbor discovery (some won't resolve properly, so it is not only about good traffic from first ping)
vpp_term: Set ARP agent_vpp_2 memif3/3 ${service_in_memif_ipv4} ${service_in_memif_mac}
vpp_term: Set ARP agent_vpp_3 memif2/5 ${vpp1_memif2_ipv4} ${vpp1_memif2_mac}
vpp_term: Set ARP agent_vpp_4 memif2/4 ${srproxy_in_memif_ipv4} ${srproxy_in_memif_mac}
# add packet tracing
vpp_term: Add Trace Memif agent_vpp_2 100
# ping from agent_vpp_1 to agent_vpp_3's tap interface (despite efforts to eliminite first packet drop by setting arp, sometimes it is still happening -> timeoutable pinging repeat until first ping success)
Wait Until Keyword Succeeds ${PING_WAIT_TIMEOUT} .${PING_SLEEP} linux: Check Ping node=agent_vpp_1 ip=${linux_vpp3_tap_ipv4} count=1
# check that packet is processed by SR-proxy, send to SR-unware service using correct interface and in the process decapsulated(checked only source and destination address and not if SR header extension is missing because that is not visible in trace)
${vpp2trace}= vpp_term: Show Trace agent_vpp_2
Packet Trace ${vpp2trace} Should Contain One Packet Trace That Contains These Ordered Substrings srv6-ad-localsid, IP4: ${srproxy_out_memif_mac} -> ${service_in_memif_mac}, ICMP: ${linux_vpp1_tap_ipv4} -> ${linux_vpp3_tap_ipv4}, ., . # using only 3 substrings to match packet trace
# check that packet has returned from SR-unware service, gets rewritten by proxy (SR encapsulation) and send to another SR segment (correct interface and correct source and destination address)
Packet Trace ${vpp2trace} Should Contain One Packet Trace That Contains These Ordered Substrings ${linux_vpp1_tap_ipv4} -> ${linux_vpp3_tap_ipv4}, SRv6-AD-rewrite: src :: dst c::, IP6: ${vpp2_memif2_mac} -> ${vpp3_memif1_mac}, IPV6_ROUTE: :: -> c::, . # using only 4 substrings to match packet trace
# cleanup (for next test)
Delete Local SID node=agent_vpp_2 sidAddress=b::
vpp_term: Clear Trace agent_vpp_2
Dynamic SR Proxy with L2 SR-unaware service
# Testing L2 traffic(sending custom Ethernet frame) going through SR-proxy (IPv6 segment routing) connected to
# L2 SR-unaware service. Desired frame path starts identically to the path in IPv6 SR-unaware service test, but
# ends right after SR-proxy (at least it is not further checked). We don't do the full packet/frame path as for
# IPv4/IPv6 SR-unaware services, because sending ethernet frame is not like ping that has echo and nice ping tool
# in linux that tells you whether echo was received or not. For doing the same for ethernet frame, there have to be
# some traffic catching tool and that is too complicated for something that is basically not the aim of test.
# The aim is to check SR-proxy functionality.
# creating path for frame (path is already partially done in common setup+using memifs between sr-proxy and service from ipv4 test)
## steering traffic to segment routing
Put SRv6 L2 Steering node=agent_vpp_1 name=toC bsid=a::c interfaceName=vpp1_tap
## configure SR-proxy
Put Local SID With End.AD function node=agent_vpp_2 sidAddress=b:: outinterface=srproxy_out_memif ininterface=srproxy_in_memif # L2 SR-unware service
## creating service paths (Service just sends received frame back)
Create Bridge Domain bd1 Without Autolearn On agent_vpp_4 With Interfaces service_in_memif, service_out_memif
Add fib entry for 01:02:03:04:05:06 in bd1 over service_out_memif on agent_vpp_4
# add packet tracing
vpp_term: Add Trace Memif agent_vpp_2 100
# sending ethernet frame
linux: Send Ethernet Frame agent_vpp_1 ${out_interface} ${source_mac_address} ${destination_mac_address} ${ethernet_type} ${payload} ${checksum}
Wait Until Keyword Succeeds ${TRACE_WAIT_TIMEOUT} ${TRACE_SYNC_SLEEP} Trace on agent_vpp_2 has at least 2 packets
# check that packet is processed by SR-proxy, send to SR-unware service using correct interface and in the process decapsulated(checked only ethernet frame
# type and source/destination address and not if SR header extension is missing because that is not visible in trace)
${vpp2trace}= vpp_term: Show Trace agent_vpp_2
Packet Trace ${vpp2trace} Should Contain One Packet Trace That Contains These Ordered Substrings srv6-ad-localsid, ${srproxy_out_memif_vpp_name}, 0x${ethernet_type}: ${source_mac_address} -> ${destination_mac_address}, ., . # using only 3 substrings to match packet trace
# check that packet has returned from SR-unware service (something received from correct interface and later checked its rewritten payload to be sure it is
# the right frame), gets rewritten by proxy (SR encapsulation) and send to another SR segment (correct interface and correct source and destination address)
Packet Trace ${vpp2trace} Should Contain One Packet Trace That Contains These Ordered Substrings memif: hw_if_index ${srproxy_in_memif_vpp_index}, SRv6-AD-rewrite: src :: dst c::, ${ethernet_type}${payload_hex_prefix}, IP6: ${vpp2_memif2_mac} -> ${vpp3_memif1_mac}, IPV6_ROUTE: :: -> c::
*** Keywords ***
Packet Trace ${packettrace} Should Contain One Packet Trace That Contains These Ordered Substrings ${substr1}, ${substr2}, ${substr3}, ${substr4}, ${substr5}
${packetsplit}= String.Split String ${packettrace} Packet
Should Contain Match ${packetsplit} regexp=.*${substr1}.*${substr2}.*${substr3}.*${substr4}.*${substr5}.* case_insensitive=True
Trace on ${node} has at least 2 packets
${trace}= vpp_term: Show Trace ${node}
Should Contain ${trace} Packet 2
TestSetup
Make Datastore Snapshots ${TEST_NAME}_test_setup
TestTeardown
Make Datastore Snapshots ${TEST_NAME}_test_teardown
|
{
"pile_set_name": "Github"
}
|
package com.lzhpo.rabbitmq.model5.workqueues.gongping;
import com.lzhpo.rabbitmq.ConnectionUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
/**
* <p> Author:lzhpo </p>
* <p> Title:</p>
* <p> Description:
* Message acknowledgment(消息应答):
*
* boolean autoAck = false;
* channel.basicConsume(QUEUE_NAME, autoAck, consumer);
*
* boolean autoAck = true;(自动确认模式)一旦 RabbitMQ 将消息分发给了消费者,就会从内存中删除。
* 在这种情况下,如果杀死正在执行任务的消费者,会丢失正在处理的消息,也会丢失已经分发给这个消
* 费者但尚未处理的消息。
*
* boolean autoAck = false; (手动确认模式) 我们不想丢失任何任务,如果有一个消费者挂掉了,那么
* 我们应该将分发给它的任务交付给另一个消费者去处理。 为了确保消息不会丢失,RabbitMQ 支持消
* 息应答。消费者发送一个消息应答,告诉 RabbitMQ 这个消息已经接收并且处理完毕了。RabbitMQ 可
* 以删除它了。
*
* 消息应答是默认打开的。也就是 boolean autoAck =false;
*
* </p>
*/
public class Recv2 {
private final static String QUEUE_NAME = "test_queue_work";
public static void main(String[] args) throws Exception {
// 获取到连接以及mq通道
Connection connection = ConnectionUtils.getConnection();
final Channel channel = connection.createChannel();
// 声明队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
channel.basicQos(1);//保证一次只分发一个
//定义一个消息的消费者
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//super.handleDelivery(consumerTag, envelope, properties, body);
String message = new String(body, "UTF-8");
System.out.println(" [2] Received '" + message + "'");
try {
doWork(message);
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println(" [x] Done");
channel.basicAck(envelope.getDeliveryTag(), false);/**关闭自动确认应答,手动应答**/
}
}
};
/**关闭自动应答**/
boolean autoAck = false; //关闭自动确认
channel.basicConsume(QUEUE_NAME, autoAck, consumer);
}
private static void doWork(String task) throws InterruptedException {
Thread.sleep(2000);
}
public static void oldAPi() throws Exception {
// 获取到连接以及mq通道
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
// 声明队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
// 同一时刻服务器只会发一条消息给消费者
channel.basicQos(1);
// 定义队列的消费者
QueueingConsumer consumer = new QueueingConsumer(channel);
// 监听队列,手动返回完成状态
channel.basicConsume(QUEUE_NAME, false, consumer);
// 获取消息
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
// 休眠1秒
Thread.sleep(1000);
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);/**关闭自动确认应答,手动应答**/
}
}
}
|
{
"pile_set_name": "Github"
}
|
#region Copyright notice and license
// Copyright 2018 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal.Tests
{
// Creates instances of fake IBufferReader. All created instances will become invalid once Dispose is called.
internal class FakeBufferReaderManager : IDisposable
{
List<GCHandle> pinnedHandles = new List<GCHandle>();
bool disposed = false;
public IBufferReader CreateSingleSegmentBufferReader(byte[] data)
{
return CreateMultiSegmentBufferReader(new List<byte[]> { data });
}
public IBufferReader CreateMultiSegmentBufferReader(IEnumerable<byte[]> dataSegments)
{
GrpcPreconditions.CheckState(!disposed);
GrpcPreconditions.CheckNotNull(dataSegments);
var segments = new List<GCHandle>();
foreach (var data in dataSegments)
{
GrpcPreconditions.CheckNotNull(data);
segments.Add(GCHandle.Alloc(data, GCHandleType.Pinned));
}
pinnedHandles.AddRange(segments); // all the allocated GCHandles will be freed on Dispose()
return new FakeBufferReader(segments);
}
public IBufferReader CreateNullPayloadBufferReader()
{
GrpcPreconditions.CheckState(!disposed);
return new FakeBufferReader(null);
}
public void Dispose()
{
if (!disposed)
{
disposed = true;
for (int i = 0; i < pinnedHandles.Count; i++)
{
pinnedHandles[i].Free();
}
}
}
private class FakeBufferReader : IBufferReader
{
readonly List<GCHandle> bufferSegments;
readonly int? totalLength;
readonly IEnumerator<GCHandle> segmentEnumerator;
public FakeBufferReader(List<GCHandle> bufferSegments)
{
this.bufferSegments = bufferSegments;
this.totalLength = ComputeTotalLength(bufferSegments);
this.segmentEnumerator = bufferSegments?.GetEnumerator();
}
public int? TotalLength => totalLength;
public bool TryGetNextSlice(out Slice slice)
{
GrpcPreconditions.CheckNotNull(bufferSegments);
if (!segmentEnumerator.MoveNext())
{
slice = default(Slice);
return false;
}
var segment = segmentEnumerator.Current;
int sliceLen = ((byte[]) segment.Target).Length;
slice = new Slice(segment.AddrOfPinnedObject(), sliceLen);
return true;
}
static int? ComputeTotalLength(List<GCHandle> bufferSegments)
{
if (bufferSegments == null)
{
return null;
}
int sum = 0;
foreach (var segment in bufferSegments)
{
var data = (byte[]) segment.Target;
sum += data.Length;
}
return sum;
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
//------------------------------------------------------------------------------
// <copyright file="RegexRunner.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
// This RegexRunner class is a base class for compiled regex code.
// Implementation notes:
//
// RegexRunner provides a common calling convention and a common
// runtime environment for the interpreter and the compiled code.
//
// It provides the driver code that call's the subclass's Go()
// method for either scanning or direct execution.
//
// It also maintains memory allocation for the backtracking stack,
// the grouping stack and the longjump crawlstack, and provides
// methods to push new subpattern match results into (or remove
// backtracked results from) the Match instance.
namespace MonoDevelop.Ide.Editor.Highlighting.RegexEngine {
using System;
using System.Text;
using System.Collections;
using System.Diagnostics;
using System.ComponentModel;
using System.Globalization;
using MonoDevelop.Core.Text;
/// <internalonly/>
//
#if !SILVERLIGHT
[EditorBrowsable(EditorBrowsableState.Never)]
#endif
#if !SILVERLIGHT
[Obsolete ("Old editor")]
abstract class RegexRunner
{
#else
abstract internal class RegexRunner {
#endif
protected internal int runtextbeg; // beginning of text to search
protected internal int runtextend; // end of text to search
protected internal int runtextstart; // starting point for search
protected internal string runtext; // text to search
protected internal int runtextpos; // current position in text
protected internal int [] runtrack; // The backtracking stack. Opcodes use this to store data regarding
protected internal int runtrackpos; // what they have matched and where to backtrack to. Each "frame" on
// the stack takes the form of [CodePosition Data1 Data2...], where
// CodePosition is the position of the current opcode and
// the data values are all optional. The CodePosition can be negative, and
// these values (also called "back2") are used by the BranchMark family of opcodes
// to indicate whether they are backtracking after a successful or failed
// match.
// When we backtrack, we pop the CodePosition off the stack, set the current
// instruction pointer to that code position, and mark the opcode
// with a backtracking flag ("Back"). Each opcode then knows how to
// handle its own data.
protected internal int [] runstack; // This stack is used to track text positions across different opcodes.
protected internal int runstackpos; // For example, in /(a*b)+/, the parentheses result in a SetMark/CaptureMark
// pair. SetMark records the text position before we match a*b. Then
// CaptureMark uses that position to figure out where the capture starts.
// Opcodes which push onto this stack are always paired with other opcodes
// which will pop the value from it later. A successful match should mean
// that this stack is empty.
protected internal int [] runcrawl; // The crawl stack is used to keep track of captures. Every time a group
protected internal int runcrawlpos; // has a capture, we push its group number onto the runcrawl stack. In
// the case of a balanced match, we push BOTH groups onto the stack.
protected internal int runtrackcount; // count of states that may do backtracking
protected internal Match runmatch; // result object
protected internal Regex runregex; // regex object
private Int32 timeout; // timeout in millisecs (needed for actual)
private bool ignoreTimeout;
private Int32 timeoutOccursAt;
// GPaperin: We have determined this value in a series of experiments where x86 retail
// builds (ono-lab-optimised) were run on different pattern/input pairs. Larger values
// of TimeoutCheckFrequency did not tend to increase performance; smaller values
// of TimeoutCheckFrequency tended to slow down the execution.
private const int TimeoutCheckFrequency = 1000;
private int timeoutChecksToSkip;
protected internal RegexRunner() { }
/*
* Scans the string to find the first match. Uses the Match object
* both to feed text in and as a place to store matches that come out.
*
* All the action is in the abstract Go() method defined by subclasses. Our
* responsibility is to load up the class members (as done here) before
* calling Go.
*
* <
*/
protected internal Match Scan(Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick) {
return Scan(regex, text, textbeg, textend, textstart, prevlen, quick, regex.MatchTimeout);
}
#if !SILVERLIGHT
protected internal
#else
internal
#endif
Match Scan(Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick, TimeSpan timeout) {
int bump;
int stoppos;
bool initted = false;
// We need to re-validate timeout here because Scan is historically protected and
// thus there is a possibility it is called from user code:
Regex.ValidateMatchTimeout(timeout);
this.ignoreTimeout = (Regex.InfiniteMatchTimeout == timeout);
this.timeout = this.ignoreTimeout
? (Int32) Regex.InfiniteMatchTimeout.TotalMilliseconds
: (Int32) (timeout.TotalMilliseconds + 0.5); // Round
runregex = regex;
runtext = text;
runtextbeg = textbeg;
runtextend = textend;
runtextstart = textstart;
bump = runregex.RightToLeft ? -1 : 1;
stoppos = runregex.RightToLeft ? runtextbeg : runtextend;
runtextpos = textstart;
// If previous match was empty or failed, advance by one before matching
if (prevlen == 0) {
if (runtextpos == stoppos)
return Match.Empty;
runtextpos += bump;
}
StartTimeoutWatch();
for (; ; ) {
#if DBG
if (runregex.Debug) {
Debug.WriteLine("");
Debug.WriteLine("Search range: from " + runtextbeg.ToString(CultureInfo.InvariantCulture) + " to " + runtextend.ToString(CultureInfo.InvariantCulture));
Debug.WriteLine("Firstchar search starting at " + runtextpos.ToString(CultureInfo.InvariantCulture) + " stopping at " + stoppos.ToString(CultureInfo.InvariantCulture));
}
#endif
if (FindFirstChar()) {
CheckTimeout();
if (!initted) {
InitMatch();
initted = true;
}
#if DBG
if (runregex.Debug) {
Debug.WriteLine("Executing engine starting at " + runtextpos.ToString(CultureInfo.InvariantCulture));
Debug.WriteLine("");
}
#endif
Go();
if (runmatch._matchcount [0] > 0) {
// <
return TidyMatch(quick);
}
// reset state for another go
runtrackpos = runtrack.Length;
runstackpos = runstack.Length;
runcrawlpos = runcrawl.Length;
}
// failure!
if (runtextpos == stoppos) {
TidyMatch(true);
return Match.Empty;
}
// <
// Bump by one and start again
runtextpos += bump;
}
// We never get here
}
private void StartTimeoutWatch() {
if (ignoreTimeout)
return;
timeoutChecksToSkip = TimeoutCheckFrequency;
// We are using Environment.TickCount and not Timewatch for performance reasons.
// Environment.TickCount is an int that cycles. We intentionally let timeoutOccursAt
// overflow it will still stay ahead of Environment.TickCount for comparisons made
// in DoCheckTimeout():
unchecked {
timeoutOccursAt = Environment.TickCount + timeout;
}
}
#if !SILVERLIGHT
protected
#else
internal
#endif
void CheckTimeout() {
if (ignoreTimeout)
return;
if (--timeoutChecksToSkip != 0)
return;
timeoutChecksToSkip = TimeoutCheckFrequency;
DoCheckTimeout();
}
private void DoCheckTimeout() {
// Note that both, Environment.TickCount and timeoutOccursAt are ints and can overflow and become negative.
// See the comment in StartTimeoutWatch().
int currentMillis = Environment.TickCount;
if (currentMillis < timeoutOccursAt)
return;
if (0 > timeoutOccursAt && 0 < currentMillis)
return;
#if DBG
if (runregex.Debug) {
Debug.WriteLine("");
Debug.WriteLine("RegEx match timeout occurred!");
Debug.WriteLine("Specified timeout: " + TimeSpan.FromMilliseconds(timeout).ToString());
Debug.WriteLine("Timeout check frequency: " + TimeoutCheckFrequency);
Debug.WriteLine("Search pattern: " + runregex.pattern);
Debug.WriteLine("Input: " + runtext);
Debug.WriteLine("About to throw RegexMatchTimeoutException.");
}
#endif
throw new RegexMatchTimeoutException(runtext, runregex.pattern, TimeSpan.FromMilliseconds(timeout));
}
/*
* The responsibility of Go() is to run the regular expression at
* runtextpos and call Capture() on all the captured subexpressions,
* then to leave runtextpos at the ending position. It should leave
* runtextpos where it started if there was no match.
*/
protected abstract void Go();
/*
* The responsibility of FindFirstChar() is to advance runtextpos
* until it is at the next position which is a candidate for the
* beginning of a successful match.
*/
protected abstract bool FindFirstChar();
/*
* InitTrackCount must initialize the runtrackcount field; this is
* used to know how large the initial runtrack and runstack arrays
* must be.
*/
protected abstract void InitTrackCount();
/*
* Initializes all the data members that are used by Go()
*/
private void InitMatch() {
// Use a hashtable'ed Match object if the capture numbers are sparse
if (runmatch == null) {
if (runregex.caps != null)
runmatch = new MatchSparse(runregex, runregex.caps, runregex.capsize, runtext, runtextbeg, runtextend - runtextbeg, runtextstart);
else
runmatch = new Match (runregex, runregex.capsize, runtext, runtextbeg, runtextend - runtextbeg, runtextstart);
} else {
runmatch.Reset(runregex, runtext, runtextbeg, runtextend, runtextstart);
}
// note we test runcrawl, because it is the last one to be allocated
// If there is an alloc failure in the middle of the three allocations,
// we may still return to reuse this instance, and we want to behave
// as if the allocations didn't occur. (we used to test _trackcount != 0)
if (runcrawl != null) {
runtrackpos = runtrack.Length;
runstackpos = runstack.Length;
runcrawlpos = runcrawl.Length;
return;
}
InitTrackCount();
int tracksize = runtrackcount * 8;
int stacksize = runtrackcount * 8;
if (tracksize < 32)
tracksize = 32;
if (stacksize < 16)
stacksize = 16;
runtrack = new int [tracksize];
runtrackpos = tracksize;
runstack = new int [stacksize];
runstackpos = stacksize;
runcrawl = new int [32];
runcrawlpos = 32;
}
/*
* Put match in its canonical form before returning it.
*/
private Match TidyMatch(bool quick) {
if (!quick) {
Match match = runmatch;
runmatch = null;
match.Tidy(runtextpos);
return match;
} else {
// in quick mode, a successful match returns null, and
// the allocated match object is left in the cache
return null;
}
}
/*
* Called by the implemenation of Go() to increase the size of storage
*/
protected void EnsureStorage() {
if (runstackpos < runtrackcount * 4)
DoubleStack();
if (runtrackpos < runtrackcount * 4)
DoubleTrack();
}
/*
* Called by the implemenation of Go() to decide whether the pos
* at the specified index is a boundary or not. It's just not worth
* emitting inline code for this logic.
*/
protected bool IsBoundary(int index, int startpos, int endpos) {
return (index > startpos && RegexCharClass.IsWordChar(runtext [index - 1])) !=
(index < endpos && RegexCharClass.IsWordChar(runtext [index]));
}
protected bool IsECMABoundary(int index, int startpos, int endpos) {
return (index > startpos && RegexCharClass.IsECMAWordChar(runtext [index - 1])) !=
(index < endpos && RegexCharClass.IsECMAWordChar(runtext [index]));
}
protected static bool CharInSet(char ch, String set, String category) {
string charClass = RegexCharClass.ConvertOldStringsToClass(set, category);
return RegexCharClass.CharInClass(ch, charClass);
}
protected static bool CharInClass(char ch, String charClass) {
return RegexCharClass.CharInClass(ch, charClass);
}
/*
* Called by the implemenation of Go() to increase the size of the
* backtracking stack.
*/
protected void DoubleTrack() {
int [] newtrack;
newtrack = new int [runtrack.Length * 2];
System.Array.Copy(runtrack, 0, newtrack, runtrack.Length, runtrack.Length);
runtrackpos += runtrack.Length;
runtrack = newtrack;
}
/*
* Called by the implemenation of Go() to increase the size of the
* grouping stack.
*/
protected void DoubleStack() {
int [] newstack;
newstack = new int [runstack.Length * 2];
System.Array.Copy(runstack, 0, newstack, runstack.Length, runstack.Length);
runstackpos += runstack.Length;
runstack = newstack;
}
/*
* Increases the size of the longjump unrolling stack.
*/
protected void DoubleCrawl() {
int [] newcrawl;
newcrawl = new int [runcrawl.Length * 2];
System.Array.Copy(runcrawl, 0, newcrawl, runcrawl.Length, runcrawl.Length);
runcrawlpos += runcrawl.Length;
runcrawl = newcrawl;
}
/*
* Save a number on the longjump unrolling stack
*/
protected void Crawl(int i) {
if (runcrawlpos == 0)
DoubleCrawl();
runcrawl [--runcrawlpos] = i;
}
/*
* Remove a number from the longjump unrolling stack
*/
protected int Popcrawl() {
return runcrawl [runcrawlpos++];
}
/*
* Get the height of the stack
*/
protected int Crawlpos() {
return runcrawl.Length - runcrawlpos;
}
/*
* Called by Go() to capture a subexpression. Note that the
* capnum used here has already been mapped to a non-sparse
* index (by the code generator RegexWriter).
*/
protected void Capture(int capnum, int start, int end) {
if (end < start) {
int T;
T = end;
end = start;
start = T;
}
Crawl(capnum);
runmatch.AddMatch(capnum, start, end - start);
}
/*
* Called by Go() to capture a subexpression. Note that the
* capnum used here has already been mapped to a non-sparse
* index (by the code generator RegexWriter).
*/
protected void TransferCapture(int capnum, int uncapnum, int start, int end) {
int start2;
int end2;
// these are the two intervals that are cancelling each other
if (end < start) {
int T;
T = end;
end = start;
start = T;
}
start2 = MatchIndex(uncapnum);
end2 = start2 + MatchLength(uncapnum);
// The new capture gets the innermost defined interval
if (start >= end2) {
end = start;
start = end2;
} else if (end <= start2) {
start = start2;
} else {
if (end > end2)
end = end2;
if (start2 > start)
start = start2;
}
Crawl(uncapnum);
runmatch.BalanceMatch(uncapnum);
if (capnum != -1) {
Crawl(capnum);
runmatch.AddMatch(capnum, start, end - start);
}
}
/*
* Called by Go() to revert the last capture
*/
protected void Uncapture() {
int capnum = Popcrawl();
runmatch.RemoveMatch(capnum);
}
/*
* Call out to runmatch to get around visibility issues
*/
protected bool IsMatched(int cap) {
return runmatch.IsMatched(cap);
}
/*
* Call out to runmatch to get around visibility issues
*/
protected int MatchIndex(int cap) {
return runmatch.MatchIndex(cap);
}
/*
* Call out to runmatch to get around visibility issues
*/
protected int MatchLength(int cap) {
return runmatch.MatchLength(cap);
}
#if DBG
/*
* Dump the current state
*/
internal virtual void DumpState() {
Debug.WriteLine("Text: " + TextposDescription());
Debug.WriteLine("Track: " + StackDescription(runtrack, runtrackpos));
Debug.WriteLine("Stack: " + StackDescription(runstack, runstackpos));
}
internal static String StackDescription(int [] A, int Index) {
StringBuilder Sb = new StringBuilder();
Sb.Append(A.Length - Index);
Sb.Append('/');
Sb.Append(A.Length);
if (Sb.Length < 8)
Sb.Append(' ', 8 - Sb.Length);
Sb.Append("(");
for (int i = Index; i < A.Length; i++) {
if (i > Index)
Sb.Append(' ');
Sb.Append(A [i]);
}
Sb.Append(')');
return Sb.ToString();
}
internal virtual String TextposDescription() {
StringBuilder Sb = new StringBuilder();
int remaining;
Sb.Append(runtextpos);
if (Sb.Length < 8)
Sb.Append(' ', 8 - Sb.Length);
if (runtextpos > runtextbeg)
Sb.Append(RegexCharClass.CharDescription(runtext [runtextpos - 1]));
else
Sb.Append('^');
Sb.Append('>');
remaining = runtextend - runtextpos;
for (int i = runtextpos; i < runtextend; i++) {
Sb.Append(RegexCharClass.CharDescription(runtext [i]));
}
if (Sb.Length >= 64) {
Sb.Length = 61;
Sb.Append("...");
} else {
Sb.Append('$');
}
return Sb.ToString();
}
#endif
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2015-2016, Freescale Semiconductor, Inc.
* Copyright 2016-2017 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "fsl_lpuart.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/* LPUART transfer state. */
enum _lpuart_transfer_states
{
kLPUART_TxIdle, /*!< TX idle. */
kLPUART_TxBusy, /*!< TX busy. */
kLPUART_RxIdle, /*!< RX idle. */
kLPUART_RxBusy /*!< RX busy. */
};
/* Typedef for interrupt handler. */
typedef void (*lpuart_isr_t)(LPUART_Type *base, lpuart_handle_t *handle);
/*******************************************************************************
* Prototypes
******************************************************************************/
/*!
* @brief Get the LPUART instance from peripheral base address.
*
* @param base LPUART peripheral base address.
* @return LPUART instance.
*/
uint32_t LPUART_GetInstance(LPUART_Type *base);
/*!
* @brief Get the length of received data in RX ring buffer.
*
* @userData handle LPUART handle pointer.
* @return Length of received data in RX ring buffer.
*/
static size_t LPUART_TransferGetRxRingBufferLength(LPUART_Type *base, lpuart_handle_t *handle);
/*!
* @brief Check whether the RX ring buffer is full.
*
* @userData handle LPUART handle pointer.
* @retval true RX ring buffer is full.
* @retval false RX ring buffer is not full.
*/
static bool LPUART_TransferIsRxRingBufferFull(LPUART_Type *base, lpuart_handle_t *handle);
/*!
* @brief Write to TX register using non-blocking method.
*
* This function writes data to the TX register directly, upper layer must make
* sure the TX register is empty or TX FIFO has empty room before calling this function.
*
* @note This function does not check whether all the data has been sent out to bus,
* so before disable TX, check kLPUART_TransmissionCompleteFlag to ensure the TX is
* finished.
*
* @param base LPUART peripheral base address.
* @param data Start addresss of the data to write.
* @param length Size of the buffer to be sent.
*/
static void LPUART_WriteNonBlocking(LPUART_Type *base, const uint8_t *data, size_t length);
/*!
* @brief Read RX register using non-blocking method.
*
* This function reads data from the TX register directly, upper layer must make
* sure the RX register is full or TX FIFO has data before calling this function.
*
* @param base LPUART peripheral base address.
* @param data Start addresss of the buffer to store the received data.
* @param length Size of the buffer.
*/
static void LPUART_ReadNonBlocking(LPUART_Type *base, uint8_t *data, size_t length);
/*******************************************************************************
* Variables
******************************************************************************/
/* Array of LPUART handle. */
static lpuart_handle_t *s_lpuartHandle[FSL_FEATURE_SOC_LPUART_COUNT];
/* Array of LPUART peripheral base address. */
static LPUART_Type *const s_lpuartBases[] = LPUART_BASE_PTRS;
/* Array of LPUART IRQ number. */
#if defined(FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ) && FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ
static const IRQn_Type s_lpuartRxIRQ[] = LPUART_RX_IRQS;
static const IRQn_Type s_lpuartTxIRQ[] = LPUART_TX_IRQS;
#else
static const IRQn_Type s_lpuartIRQ[] = LPUART_RX_TX_IRQS;
#endif
#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
/* Array of LPUART clock name. */
static const clock_ip_name_t s_lpuartClock[] = LPUART_CLOCKS;
#if defined(LPUART_PERIPH_CLOCKS)
/* Array of LPUART functional clock name. */
static const clock_ip_name_t s_lpuartPeriphClocks[] = LPUART_PERIPH_CLOCKS;
#endif
#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
/* LPUART ISR for transactional APIs. */
static lpuart_isr_t s_lpuartIsr;
/*******************************************************************************
* Code
******************************************************************************/
uint32_t LPUART_GetInstance(LPUART_Type *base)
{
uint32_t instance;
/* Find the instance index from base address mappings. */
for (instance = 0; instance < ARRAY_SIZE(s_lpuartBases); instance++)
{
if (s_lpuartBases[instance] == base)
{
break;
}
}
assert(instance < ARRAY_SIZE(s_lpuartBases));
return instance;
}
static size_t LPUART_TransferGetRxRingBufferLength(LPUART_Type *base, lpuart_handle_t *handle)
{
assert(handle);
size_t size;
if (handle->rxRingBufferTail > handle->rxRingBufferHead)
{
size = (size_t)(handle->rxRingBufferHead + handle->rxRingBufferSize - handle->rxRingBufferTail);
}
else
{
size = (size_t)(handle->rxRingBufferHead - handle->rxRingBufferTail);
}
return size;
}
static bool LPUART_TransferIsRxRingBufferFull(LPUART_Type *base, lpuart_handle_t *handle)
{
assert(handle);
bool full;
if (LPUART_TransferGetRxRingBufferLength(base, handle) == (handle->rxRingBufferSize - 1U))
{
full = true;
}
else
{
full = false;
}
return full;
}
static void LPUART_WriteNonBlocking(LPUART_Type *base, const uint8_t *data, size_t length)
{
assert(data);
size_t i;
/* The Non Blocking write data API assume user have ensured there is enough space in
peripheral to write. */
for (i = 0; i < length; i++)
{
base->DATA = data[i];
}
}
static void LPUART_ReadNonBlocking(LPUART_Type *base, uint8_t *data, size_t length)
{
assert(data);
size_t i;
#if defined(FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT) && FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT
uint32_t ctrl = base->CTRL;
bool isSevenDataBits =
((ctrl & LPUART_CTRL_M7_MASK) ||
((!(ctrl & LPUART_CTRL_M7_MASK)) && (!(ctrl & LPUART_CTRL_M_MASK)) && (ctrl & LPUART_CTRL_PE_MASK)));
#endif
/* The Non Blocking read data API assume user have ensured there is enough space in
peripheral to write. */
for (i = 0; i < length; i++)
{
#if defined(FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT) && FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT
if (isSevenDataBits)
{
data[i] = (base->DATA & 0x7F);
}
else
{
data[i] = base->DATA;
}
#else
data[i] = base->DATA;
#endif
}
}
status_t LPUART_Init(LPUART_Type *base, const lpuart_config_t *config, uint32_t srcClock_Hz)
{
assert(config);
assert(config->baudRate_Bps);
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
assert(FSL_FEATURE_LPUART_FIFO_SIZEn(base) >= config->txFifoWatermark);
assert(FSL_FEATURE_LPUART_FIFO_SIZEn(base) >= config->rxFifoWatermark);
#endif
uint32_t temp;
uint16_t sbr, sbrTemp;
uint32_t osr, osrTemp, tempDiff, calculatedBaud, baudDiff;
/* This LPUART instantiation uses a slightly different baud rate calculation
* The idea is to use the best OSR (over-sampling rate) possible
* Note, OSR is typically hard-set to 16 in other LPUART instantiations
* loop to find the best OSR value possible, one that generates minimum baudDiff
* iterate through the rest of the supported values of OSR */
baudDiff = config->baudRate_Bps;
osr = 0;
sbr = 0;
for (osrTemp = 4; osrTemp <= 32; osrTemp++)
{
/* calculate the temporary sbr value */
sbrTemp = (srcClock_Hz / (config->baudRate_Bps * osrTemp));
/*set sbrTemp to 1 if the sourceClockInHz can not satisfy the desired baud rate*/
if (sbrTemp == 0)
{
sbrTemp = 1;
}
/* Calculate the baud rate based on the temporary OSR and SBR values */
calculatedBaud = (srcClock_Hz / (osrTemp * sbrTemp));
tempDiff = calculatedBaud - config->baudRate_Bps;
/* Select the better value between srb and (sbr + 1) */
if (tempDiff > (config->baudRate_Bps - (srcClock_Hz / (osrTemp * (sbrTemp + 1)))))
{
tempDiff = config->baudRate_Bps - (srcClock_Hz / (osrTemp * (sbrTemp + 1)));
sbrTemp++;
}
if (tempDiff <= baudDiff)
{
baudDiff = tempDiff;
osr = osrTemp; /* update and store the best OSR value calculated */
sbr = sbrTemp; /* update store the best SBR value calculated */
}
}
/* Check to see if actual baud rate is within 3% of desired baud rate
* based on the best calculate OSR value */
if (baudDiff > ((config->baudRate_Bps / 100) * 3))
{
/* Unacceptable baud rate difference of more than 3%*/
return kStatus_LPUART_BaudrateNotSupport;
}
#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
uint32_t instance = LPUART_GetInstance(base);
/* Enable lpuart clock */
CLOCK_EnableClock(s_lpuartClock[instance]);
#if defined(LPUART_PERIPH_CLOCKS)
CLOCK_EnableClock(s_lpuartPeriphClocks[instance]);
#endif
#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
#if defined(FSL_FEATURE_LPUART_HAS_GLOBAL) && FSL_FEATURE_LPUART_HAS_GLOBAL
/*Reset all internal logic and registers, except the Global Register */
LPUART_SoftwareReset(base);
#else
/* Disable LPUART TX RX before setting. */
base->CTRL &= ~(LPUART_CTRL_TE_MASK | LPUART_CTRL_RE_MASK);
#endif
temp = base->BAUD;
/* Acceptable baud rate, check if OSR is between 4x and 7x oversampling.
* If so, then "BOTHEDGE" sampling must be turned on */
if ((osr > 3) && (osr < 8))
{
temp |= LPUART_BAUD_BOTHEDGE_MASK;
}
/* program the osr value (bit value is one less than actual value) */
temp &= ~LPUART_BAUD_OSR_MASK;
temp |= LPUART_BAUD_OSR(osr - 1);
/* write the sbr value to the BAUD registers */
temp &= ~LPUART_BAUD_SBR_MASK;
base->BAUD = temp | LPUART_BAUD_SBR(sbr);
/* Set bit count and parity mode. */
base->BAUD &= ~LPUART_BAUD_M10_MASK;
temp = base->CTRL &
~(LPUART_CTRL_PE_MASK | LPUART_CTRL_PT_MASK | LPUART_CTRL_M_MASK | LPUART_CTRL_ILT_MASK |
LPUART_CTRL_IDLECFG_MASK);
temp |=
(uint8_t)config->parityMode | LPUART_CTRL_IDLECFG(config->rxIdleConfig) | LPUART_CTRL_ILT(config->rxIdleType);
#if defined(FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT) && FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT
if (kLPUART_SevenDataBits == config->dataBitsCount)
{
if (kLPUART_ParityDisabled != config->parityMode)
{
temp &= ~LPUART_CTRL_M7_MASK; /* Seven data bits and one parity bit */
}
else
{
temp |= LPUART_CTRL_M7_MASK;
}
}
else
#endif
{
if (kLPUART_ParityDisabled != config->parityMode)
{
temp |= LPUART_CTRL_M_MASK; /* Eight data bits and one parity bit */
}
}
base->CTRL = temp;
#if defined(FSL_FEATURE_LPUART_HAS_STOP_BIT_CONFIG_SUPPORT) && FSL_FEATURE_LPUART_HAS_STOP_BIT_CONFIG_SUPPORT
/* set stop bit per char */
temp = base->BAUD & ~LPUART_BAUD_SBNS_MASK;
base->BAUD = temp | LPUART_BAUD_SBNS((uint8_t)config->stopBitCount);
#endif
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
/* Set tx/rx WATER watermark
Note:
Take care of the RX FIFO, RX interrupt request only assert when received bytes
equal or more than RX water mark, there is potential issue if RX water
mark larger than 1.
For example, if RX FIFO water mark is 2, upper layer needs 5 bytes and
5 bytes are received. the last byte will be saved in FIFO but not trigger
RX interrupt because the water mark is 2.
*/
base->WATER = (((uint32_t)(config->rxFifoWatermark) << 16) | config->txFifoWatermark);
/* Enable tx/rx FIFO */
base->FIFO |= (LPUART_FIFO_TXFE_MASK | LPUART_FIFO_RXFE_MASK);
/* Flush FIFO */
base->FIFO |= (LPUART_FIFO_TXFLUSH_MASK | LPUART_FIFO_RXFLUSH_MASK);
#endif
/* Clear all status flags */
temp = (LPUART_STAT_RXEDGIF_MASK | LPUART_STAT_IDLE_MASK | LPUART_STAT_OR_MASK | LPUART_STAT_NF_MASK |
LPUART_STAT_FE_MASK | LPUART_STAT_PF_MASK);
#if defined(FSL_FEATURE_LPUART_HAS_LIN_BREAK_DETECT) && FSL_FEATURE_LPUART_HAS_LIN_BREAK_DETECT
temp |= LPUART_STAT_LBKDIF_MASK;
#endif
#if defined(FSL_FEATURE_LPUART_HAS_ADDRESS_MATCHING) && FSL_FEATURE_LPUART_HAS_ADDRESS_MATCHING
temp |= (LPUART_STAT_MA1F_MASK | LPUART_STAT_MA2F_MASK);
#endif
#if defined(FSL_FEATURE_LPUART_HAS_MODEM_SUPPORT) && FSL_FEATURE_LPUART_HAS_MODEM_SUPPORT
/* Set the CTS configuration/TX CTS source. */
base->MODIR |= LPUART_MODIR_TXCTSC(config->txCtsConfig) | LPUART_MODIR_TXCTSSRC(config->txCtsSource);
if (config->enableRxRTS)
{
/* Enable the receiver RTS(request-to-send) function. */
base->MODIR |= LPUART_MODIR_RXRTSE_MASK;
}
if (config->enableTxCTS)
{
/* Enable the CTS(clear-to-send) function. */
base->MODIR |= LPUART_MODIR_TXCTSE_MASK;
}
#endif
/* Set data bits order. */
if (config->isMsb)
{
temp |= LPUART_STAT_MSBF_MASK;
}
else
{
temp &= ~LPUART_STAT_MSBF_MASK;
}
base->STAT |= temp;
/* Enable TX/RX base on configure structure. */
temp = base->CTRL;
if (config->enableTx)
{
temp |= LPUART_CTRL_TE_MASK;
}
if (config->enableRx)
{
temp |= LPUART_CTRL_RE_MASK;
}
base->CTRL = temp;
return kStatus_Success;
}
void LPUART_Deinit(LPUART_Type *base)
{
uint32_t temp;
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
/* Wait tx FIFO send out*/
while (0 != ((base->WATER & LPUART_WATER_TXCOUNT_MASK) >> LPUART_WATER_TXWATER_SHIFT))
{
}
#endif
/* Wait last char shoft out */
while (0 == (base->STAT & LPUART_STAT_TC_MASK))
{
}
/* Clear all status flags */
temp = (LPUART_STAT_RXEDGIF_MASK | LPUART_STAT_IDLE_MASK | LPUART_STAT_OR_MASK | LPUART_STAT_NF_MASK |
LPUART_STAT_FE_MASK | LPUART_STAT_PF_MASK);
#if defined(FSL_FEATURE_LPUART_HAS_LIN_BREAK_DETECT) && FSL_FEATURE_LPUART_HAS_LIN_BREAK_DETECT
temp |= LPUART_STAT_LBKDIF_MASK;
#endif
#if defined(FSL_FEATURE_LPUART_HAS_ADDRESS_MATCHING) && FSL_FEATURE_LPUART_HAS_ADDRESS_MATCHING
temp |= (LPUART_STAT_MA1F_MASK | LPUART_STAT_MA2F_MASK);
#endif
base->STAT |= temp;
/* Disable the module. */
base->CTRL = 0;
#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
uint32_t instance = LPUART_GetInstance(base);
/* Disable lpuart clock */
CLOCK_DisableClock(s_lpuartClock[instance]);
#if defined(LPUART_PERIPH_CLOCKS)
CLOCK_DisableClock(s_lpuartPeriphClocks[instance]);
#endif
#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
}
void LPUART_GetDefaultConfig(lpuart_config_t *config)
{
assert(config);
config->baudRate_Bps = 115200U;
config->parityMode = kLPUART_ParityDisabled;
config->dataBitsCount = kLPUART_EightDataBits;
config->isMsb = false;
#if defined(FSL_FEATURE_LPUART_HAS_STOP_BIT_CONFIG_SUPPORT) && FSL_FEATURE_LPUART_HAS_STOP_BIT_CONFIG_SUPPORT
config->stopBitCount = kLPUART_OneStopBit;
#endif
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
config->txFifoWatermark = 0;
config->rxFifoWatermark = 0;
#endif
#if defined(FSL_FEATURE_LPUART_HAS_MODEM_SUPPORT) && FSL_FEATURE_LPUART_HAS_MODEM_SUPPORT
config->enableRxRTS = false;
config->enableTxCTS = false;
config->txCtsConfig = kLPUART_CtsSampleAtStart;
config->txCtsSource = kLPUART_CtsSourcePin;
#endif
config->rxIdleType = kLPUART_IdleTypeStartBit;
config->rxIdleConfig = kLPUART_IdleCharacter1;
config->enableTx = false;
config->enableRx = false;
}
status_t LPUART_SetBaudRate(LPUART_Type *base, uint32_t baudRate_Bps, uint32_t srcClock_Hz)
{
assert(baudRate_Bps);
uint32_t temp, oldCtrl;
uint16_t sbr, sbrTemp;
uint32_t osr, osrTemp, tempDiff, calculatedBaud, baudDiff;
/* This LPUART instantiation uses a slightly different baud rate calculation
* The idea is to use the best OSR (over-sampling rate) possible
* Note, OSR is typically hard-set to 16 in other LPUART instantiations
* loop to find the best OSR value possible, one that generates minimum baudDiff
* iterate through the rest of the supported values of OSR */
baudDiff = baudRate_Bps;
osr = 0;
sbr = 0;
for (osrTemp = 4; osrTemp <= 32; osrTemp++)
{
/* calculate the temporary sbr value */
sbrTemp = (srcClock_Hz / (baudRate_Bps * osrTemp));
/*set sbrTemp to 1 if the sourceClockInHz can not satisfy the desired baud rate*/
if (sbrTemp == 0)
{
sbrTemp = 1;
}
/* Calculate the baud rate based on the temporary OSR and SBR values */
calculatedBaud = (srcClock_Hz / (osrTemp * sbrTemp));
tempDiff = calculatedBaud - baudRate_Bps;
/* Select the better value between srb and (sbr + 1) */
if (tempDiff > (baudRate_Bps - (srcClock_Hz / (osrTemp * (sbrTemp + 1)))))
{
tempDiff = baudRate_Bps - (srcClock_Hz / (osrTemp * (sbrTemp + 1)));
sbrTemp++;
}
if (tempDiff <= baudDiff)
{
baudDiff = tempDiff;
osr = osrTemp; /* update and store the best OSR value calculated */
sbr = sbrTemp; /* update store the best SBR value calculated */
}
}
/* Check to see if actual baud rate is within 3% of desired baud rate
* based on the best calculate OSR value */
if (baudDiff < ((baudRate_Bps / 100) * 3))
{
/* Store CTRL before disable Tx and Rx */
oldCtrl = base->CTRL;
/* Disable LPUART TX RX before setting. */
base->CTRL &= ~(LPUART_CTRL_TE_MASK | LPUART_CTRL_RE_MASK);
temp = base->BAUD;
/* Acceptable baud rate, check if OSR is between 4x and 7x oversampling.
* If so, then "BOTHEDGE" sampling must be turned on */
if ((osr > 3) && (osr < 8))
{
temp |= LPUART_BAUD_BOTHEDGE_MASK;
}
/* program the osr value (bit value is one less than actual value) */
temp &= ~LPUART_BAUD_OSR_MASK;
temp |= LPUART_BAUD_OSR(osr - 1);
/* write the sbr value to the BAUD registers */
temp &= ~LPUART_BAUD_SBR_MASK;
base->BAUD = temp | LPUART_BAUD_SBR(sbr);
/* Restore CTRL. */
base->CTRL = oldCtrl;
return kStatus_Success;
}
else
{
/* Unacceptable baud rate difference of more than 3%*/
return kStatus_LPUART_BaudrateNotSupport;
}
}
void LPUART_EnableInterrupts(LPUART_Type *base, uint32_t mask)
{
base->BAUD |= ((mask << 8) & (LPUART_BAUD_LBKDIE_MASK | LPUART_BAUD_RXEDGIE_MASK));
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
base->FIFO = (base->FIFO & ~(LPUART_FIFO_TXOF_MASK | LPUART_FIFO_RXUF_MASK)) |
((mask << 8) & (LPUART_FIFO_TXOFE_MASK | LPUART_FIFO_RXUFE_MASK));
#endif
mask &= 0xFFFFFF00U;
base->CTRL |= mask;
}
void LPUART_DisableInterrupts(LPUART_Type *base, uint32_t mask)
{
base->BAUD &= ~((mask << 8) & (LPUART_BAUD_LBKDIE_MASK | LPUART_BAUD_RXEDGIE_MASK));
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
base->FIFO = (base->FIFO & ~(LPUART_FIFO_TXOF_MASK | LPUART_FIFO_RXUF_MASK)) &
~((mask << 8) & (LPUART_FIFO_TXOFE_MASK | LPUART_FIFO_RXUFE_MASK));
#endif
mask &= 0xFFFFFF00U;
base->CTRL &= ~mask;
}
uint32_t LPUART_GetEnabledInterrupts(LPUART_Type *base)
{
uint32_t temp;
temp = (base->BAUD & (LPUART_BAUD_LBKDIE_MASK | LPUART_BAUD_RXEDGIE_MASK)) >> 8;
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
temp |= (base->FIFO & (LPUART_FIFO_TXOFE_MASK | LPUART_FIFO_RXUFE_MASK)) >> 8;
#endif
temp |= (base->CTRL & 0xFF0C000);
return temp;
}
uint32_t LPUART_GetStatusFlags(LPUART_Type *base)
{
uint32_t temp;
temp = base->STAT;
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
temp |= (base->FIFO &
(LPUART_FIFO_TXEMPT_MASK | LPUART_FIFO_RXEMPT_MASK | LPUART_FIFO_TXOF_MASK | LPUART_FIFO_RXUF_MASK)) >>
16;
#endif
return temp;
}
status_t LPUART_ClearStatusFlags(LPUART_Type *base, uint32_t mask)
{
uint32_t temp;
status_t status;
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
temp = (uint32_t)base->FIFO;
temp &= (uint32_t)(~(LPUART_FIFO_TXOF_MASK | LPUART_FIFO_RXUF_MASK));
temp |= (mask << 16) & (LPUART_FIFO_TXOF_MASK | LPUART_FIFO_RXUF_MASK);
base->FIFO = temp;
#endif
temp = (uint32_t)base->STAT;
#if defined(FSL_FEATURE_LPUART_HAS_LIN_BREAK_DETECT) && FSL_FEATURE_LPUART_HAS_LIN_BREAK_DETECT
temp &= (uint32_t)(~(LPUART_STAT_LBKDIF_MASK));
temp |= mask & LPUART_STAT_LBKDIF_MASK;
#endif
temp &= (uint32_t)(~(LPUART_STAT_RXEDGIF_MASK | LPUART_STAT_IDLE_MASK | LPUART_STAT_OR_MASK | LPUART_STAT_NF_MASK |
LPUART_STAT_FE_MASK | LPUART_STAT_PF_MASK));
temp |= mask & (LPUART_STAT_RXEDGIF_MASK | LPUART_STAT_IDLE_MASK | LPUART_STAT_OR_MASK | LPUART_STAT_NF_MASK |
LPUART_STAT_FE_MASK | LPUART_STAT_PF_MASK);
#if defined(FSL_FEATURE_LPUART_HAS_ADDRESS_MATCHING) && FSL_FEATURE_LPUART_HAS_ADDRESS_MATCHING
temp &= (uint32_t)(~(LPUART_STAT_MA2F_MASK | LPUART_STAT_MA1F_MASK));
temp |= mask & (LPUART_STAT_MA2F_MASK | LPUART_STAT_MA1F_MASK);
#endif
base->STAT = temp;
/* If some flags still pending. */
if (mask & LPUART_GetStatusFlags(base))
{
/* Some flags can only clear or set by the hardware itself, these flags are: kLPUART_TxDataRegEmptyFlag,
kLPUART_TransmissionCompleteFlag, kLPUART_RxDataRegFullFlag, kLPUART_RxActiveFlag,
kLPUART_NoiseErrorInRxDataRegFlag, kLPUART_ParityErrorInRxDataRegFlag,
kLPUART_TxFifoEmptyFlag, kLPUART_RxFifoEmptyFlag. */
status = kStatus_LPUART_FlagCannotClearManually; /* flags can not clear manually */
}
else
{
status = kStatus_Success;
}
return status;
}
void LPUART_WriteBlocking(LPUART_Type *base, const uint8_t *data, size_t length)
{
assert(data);
/* This API can only ensure that the data is written into the data buffer but can't
ensure all data in the data buffer are sent into the transmit shift buffer. */
while (length--)
{
while (!(base->STAT & LPUART_STAT_TDRE_MASK))
{
}
base->DATA = *(data++);
}
}
status_t LPUART_ReadBlocking(LPUART_Type *base, uint8_t *data, size_t length)
{
assert(data);
uint32_t statusFlag;
#if defined(FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT) && FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT
uint32_t ctrl = base->CTRL;
bool isSevenDataBits =
((ctrl & LPUART_CTRL_M7_MASK) ||
((!(ctrl & LPUART_CTRL_M7_MASK)) && (!(ctrl & LPUART_CTRL_M_MASK)) && (ctrl & LPUART_CTRL_PE_MASK)));
#endif
while (length--)
{
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
while (0 == ((base->WATER & LPUART_WATER_RXCOUNT_MASK) >> LPUART_WATER_RXCOUNT_SHIFT))
#else
while (!(base->STAT & LPUART_STAT_RDRF_MASK))
#endif
{
statusFlag = LPUART_GetStatusFlags(base);
if (statusFlag & kLPUART_RxOverrunFlag)
{
LPUART_ClearStatusFlags(base, kLPUART_RxOverrunFlag);
return kStatus_LPUART_RxHardwareOverrun;
}
if (statusFlag & kLPUART_NoiseErrorFlag)
{
LPUART_ClearStatusFlags(base, kLPUART_NoiseErrorFlag);
return kStatus_LPUART_NoiseError;
}
if (statusFlag & kLPUART_FramingErrorFlag)
{
LPUART_ClearStatusFlags(base, kLPUART_FramingErrorFlag);
return kStatus_LPUART_FramingError;
}
if (statusFlag & kLPUART_ParityErrorFlag)
{
LPUART_ClearStatusFlags(base, kLPUART_ParityErrorFlag);
return kStatus_LPUART_ParityError;
}
}
#if defined(FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT) && FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT
if (isSevenDataBits)
{
*(data++) = (base->DATA & 0x7F);
}
else
{
*(data++) = base->DATA;
}
#else
*(data++) = base->DATA;
#endif
}
return kStatus_Success;
}
void LPUART_TransferCreateHandle(LPUART_Type *base,
lpuart_handle_t *handle,
lpuart_transfer_callback_t callback,
void *userData)
{
assert(handle);
uint32_t instance;
#if defined(FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT) && FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT
uint32_t ctrl = base->CTRL;
bool isSevenDataBits =
((ctrl & LPUART_CTRL_M7_MASK) ||
((!(ctrl & LPUART_CTRL_M7_MASK)) && (!(ctrl & LPUART_CTRL_M_MASK)) && (ctrl & LPUART_CTRL_PE_MASK)));
#endif
/* Zero the handle. */
memset(handle, 0, sizeof(lpuart_handle_t));
/* Set the TX/RX state. */
handle->rxState = kLPUART_RxIdle;
handle->txState = kLPUART_TxIdle;
/* Set the callback and user data. */
handle->callback = callback;
handle->userData = userData;
#if defined(FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT) && FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT
/* Initial seven data bits flag */
handle->isSevenDataBits = isSevenDataBits;
#endif
/* Get instance from peripheral base address. */
instance = LPUART_GetInstance(base);
/* Save the handle in global variables to support the double weak mechanism. */
s_lpuartHandle[instance] = handle;
s_lpuartIsr = LPUART_TransferHandleIRQ;
/* Enable interrupt in NVIC. */
#if defined(FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ) && FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ
EnableIRQ(s_lpuartRxIRQ[instance]);
EnableIRQ(s_lpuartTxIRQ[instance]);
#else
EnableIRQ(s_lpuartIRQ[instance]);
#endif
}
void LPUART_TransferStartRingBuffer(LPUART_Type *base,
lpuart_handle_t *handle,
uint8_t *ringBuffer,
size_t ringBufferSize)
{
assert(handle);
assert(ringBuffer);
/* Setup the ring buffer address */
handle->rxRingBuffer = ringBuffer;
handle->rxRingBufferSize = ringBufferSize;
handle->rxRingBufferHead = 0U;
handle->rxRingBufferTail = 0U;
/* Enable the interrupt to accept the data when user need the ring buffer. */
LPUART_EnableInterrupts(base, kLPUART_RxDataRegFullInterruptEnable | kLPUART_RxOverrunInterruptEnable);
}
void LPUART_TransferStopRingBuffer(LPUART_Type *base, lpuart_handle_t *handle)
{
assert(handle);
if (handle->rxState == kLPUART_RxIdle)
{
LPUART_DisableInterrupts(base, kLPUART_RxDataRegFullInterruptEnable | kLPUART_RxOverrunInterruptEnable);
}
handle->rxRingBuffer = NULL;
handle->rxRingBufferSize = 0U;
handle->rxRingBufferHead = 0U;
handle->rxRingBufferTail = 0U;
}
status_t LPUART_TransferSendNonBlocking(LPUART_Type *base, lpuart_handle_t *handle, lpuart_transfer_t *xfer)
{
assert(handle);
assert(xfer);
assert(xfer->data);
assert(xfer->dataSize);
status_t status;
/* Return error if current TX busy. */
if (kLPUART_TxBusy == handle->txState)
{
status = kStatus_LPUART_TxBusy;
}
else
{
handle->txData = xfer->data;
handle->txDataSize = xfer->dataSize;
handle->txDataSizeAll = xfer->dataSize;
handle->txState = kLPUART_TxBusy;
/* Enable transmiter interrupt. */
LPUART_EnableInterrupts(base, kLPUART_TxDataRegEmptyInterruptEnable);
status = kStatus_Success;
}
return status;
}
void LPUART_TransferAbortSend(LPUART_Type *base, lpuart_handle_t *handle)
{
assert(handle);
LPUART_DisableInterrupts(base, kLPUART_TxDataRegEmptyInterruptEnable | kLPUART_TransmissionCompleteInterruptEnable);
handle->txDataSize = 0;
handle->txState = kLPUART_TxIdle;
}
status_t LPUART_TransferGetSendCount(LPUART_Type *base, lpuart_handle_t *handle, uint32_t *count)
{
assert(handle);
assert(count);
if (kLPUART_TxIdle == handle->txState)
{
return kStatus_NoTransferInProgress;
}
*count = handle->txDataSizeAll - handle->txDataSize;
return kStatus_Success;
}
status_t LPUART_TransferReceiveNonBlocking(LPUART_Type *base,
lpuart_handle_t *handle,
lpuart_transfer_t *xfer,
size_t *receivedBytes)
{
assert(handle);
assert(xfer);
assert(xfer->data);
assert(xfer->dataSize);
uint32_t i;
status_t status;
/* How many bytes to copy from ring buffer to user memory. */
size_t bytesToCopy = 0U;
/* How many bytes to receive. */
size_t bytesToReceive;
/* How many bytes currently have received. */
size_t bytesCurrentReceived;
/* How to get data:
1. If RX ring buffer is not enabled, then save xfer->data and xfer->dataSize
to lpuart handle, enable interrupt to store received data to xfer->data. When
all data received, trigger callback.
2. If RX ring buffer is enabled and not empty, get data from ring buffer first.
If there are enough data in ring buffer, copy them to xfer->data and return.
If there are not enough data in ring buffer, copy all of them to xfer->data,
save the xfer->data remained empty space to lpuart handle, receive data
to this empty space and trigger callback when finished. */
if (kLPUART_RxBusy == handle->rxState)
{
status = kStatus_LPUART_RxBusy;
}
else
{
bytesToReceive = xfer->dataSize;
bytesCurrentReceived = 0;
/* If RX ring buffer is used. */
if (handle->rxRingBuffer)
{
/* Disable LPUART RX IRQ, protect ring buffer. */
LPUART_DisableInterrupts(base, kLPUART_RxDataRegFullInterruptEnable);
/* How many bytes in RX ring buffer currently. */
bytesToCopy = LPUART_TransferGetRxRingBufferLength(base, handle);
if (bytesToCopy)
{
bytesToCopy = MIN(bytesToReceive, bytesToCopy);
bytesToReceive -= bytesToCopy;
/* Copy data from ring buffer to user memory. */
for (i = 0U; i < bytesToCopy; i++)
{
xfer->data[bytesCurrentReceived++] = handle->rxRingBuffer[handle->rxRingBufferTail];
/* Wrap to 0. Not use modulo (%) because it might be large and slow. */
if (handle->rxRingBufferTail + 1U == handle->rxRingBufferSize)
{
handle->rxRingBufferTail = 0U;
}
else
{
handle->rxRingBufferTail++;
}
}
}
/* If ring buffer does not have enough data, still need to read more data. */
if (bytesToReceive)
{
/* No data in ring buffer, save the request to LPUART handle. */
handle->rxData = xfer->data + bytesCurrentReceived;
handle->rxDataSize = bytesToReceive;
handle->rxDataSizeAll = bytesToReceive;
handle->rxState = kLPUART_RxBusy;
}
/* Enable LPUART RX IRQ if previously enabled. */
LPUART_EnableInterrupts(base, kLPUART_RxDataRegFullInterruptEnable);
/* Call user callback since all data are received. */
if (0 == bytesToReceive)
{
if (handle->callback)
{
handle->callback(base, handle, kStatus_LPUART_RxIdle, handle->userData);
}
}
}
/* Ring buffer not used. */
else
{
handle->rxData = xfer->data + bytesCurrentReceived;
handle->rxDataSize = bytesToReceive;
handle->rxDataSizeAll = bytesToReceive;
handle->rxState = kLPUART_RxBusy;
/* Enable RX interrupt. */
LPUART_EnableInterrupts(base, kLPUART_RxDataRegFullInterruptEnable | kLPUART_RxOverrunInterruptEnable |
kLPUART_IdleLineInterruptEnable);
}
/* Return the how many bytes have read. */
if (receivedBytes)
{
*receivedBytes = bytesCurrentReceived;
}
status = kStatus_Success;
}
return status;
}
void LPUART_TransferAbortReceive(LPUART_Type *base, lpuart_handle_t *handle)
{
assert(handle);
/* Only abort the receive to handle->rxData, the RX ring buffer is still working. */
if (!handle->rxRingBuffer)
{
/* Disable RX interrupt. */
LPUART_DisableInterrupts(base, kLPUART_RxDataRegFullInterruptEnable | kLPUART_RxOverrunInterruptEnable |
kLPUART_IdleLineInterruptEnable);
}
handle->rxDataSize = 0U;
handle->rxState = kLPUART_RxIdle;
}
status_t LPUART_TransferGetReceiveCount(LPUART_Type *base, lpuart_handle_t *handle, uint32_t *count)
{
assert(handle);
assert(count);
if (kLPUART_RxIdle == handle->rxState)
{
return kStatus_NoTransferInProgress;
}
*count = handle->rxDataSizeAll - handle->rxDataSize;
return kStatus_Success;
}
void LPUART_TransferHandleIRQ(LPUART_Type *base, lpuart_handle_t *handle)
{
assert(handle);
uint8_t count;
uint8_t tempCount;
/* If RX overrun. */
if (LPUART_STAT_OR_MASK & base->STAT)
{
/* Clear overrun flag, otherwise the RX does not work. */
base->STAT = ((base->STAT & 0x3FE00000U) | LPUART_STAT_OR_MASK);
/* Trigger callback. */
if (handle->callback)
{
handle->callback(base, handle, kStatus_LPUART_RxHardwareOverrun, handle->userData);
}
}
/* If IDLE flag is set and the IDLE interrupt is enabled. */
if ((LPUART_STAT_IDLE_MASK & base->STAT) && (LPUART_CTRL_ILIE_MASK & base->CTRL))
{
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
count = ((uint8_t)((base->WATER & LPUART_WATER_RXCOUNT_MASK) >> LPUART_WATER_RXCOUNT_SHIFT));
while ((count) && (handle->rxDataSize))
{
tempCount = MIN(handle->rxDataSize, count);
/* Using non block API to read the data from the registers. */
LPUART_ReadNonBlocking(base, handle->rxData, tempCount);
handle->rxData += tempCount;
handle->rxDataSize -= tempCount;
count -= tempCount;
/* If rxDataSize is 0, disable idle line interrupt.*/
if (!(handle->rxDataSize))
{
handle->rxState = kLPUART_RxIdle;
LPUART_DisableInterrupts(base, kLPUART_RxDataRegFullInterruptEnable | kLPUART_RxOverrunInterruptEnable);
if (handle->callback)
{
handle->callback(base, handle, kStatus_LPUART_RxIdle, handle->userData);
}
}
}
#endif
/* Clear IDLE flag.*/
base->STAT |= LPUART_STAT_IDLE_MASK;
/* If rxDataSize is 0, disable idle line interrupt.*/
if (!(handle->rxDataSize))
{
LPUART_DisableInterrupts(base, kLPUART_IdleLineInterruptEnable);
}
/* If callback is not NULL and rxDataSize is not 0. */
if ((handle->callback) && (handle->rxDataSize))
{
handle->callback(base, handle, kStatus_LPUART_IdleLineDetected, handle->userData);
}
}
/* Receive data register full */
if ((LPUART_STAT_RDRF_MASK & base->STAT) && (LPUART_CTRL_RIE_MASK & base->CTRL))
{
/* Get the size that can be stored into buffer for this interrupt. */
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
count = ((uint8_t)((base->WATER & LPUART_WATER_RXCOUNT_MASK) >> LPUART_WATER_RXCOUNT_SHIFT));
#else
count = 1;
#endif
/* If handle->rxDataSize is not 0, first save data to handle->rxData. */
while ((count) && (handle->rxDataSize))
{
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
tempCount = MIN(handle->rxDataSize, count);
#else
tempCount = 1;
#endif
/* Using non block API to read the data from the registers. */
LPUART_ReadNonBlocking(base, handle->rxData, tempCount);
handle->rxData += tempCount;
handle->rxDataSize -= tempCount;
count -= tempCount;
/* If all the data required for upper layer is ready, trigger callback. */
if (!handle->rxDataSize)
{
handle->rxState = kLPUART_RxIdle;
if (handle->callback)
{
handle->callback(base, handle, kStatus_LPUART_RxIdle, handle->userData);
}
}
}
/* If use RX ring buffer, receive data to ring buffer. */
if (handle->rxRingBuffer)
{
while (count--)
{
/* If RX ring buffer is full, trigger callback to notify over run. */
if (LPUART_TransferIsRxRingBufferFull(base, handle))
{
if (handle->callback)
{
handle->callback(base, handle, kStatus_LPUART_RxRingBufferOverrun, handle->userData);
}
}
/* If ring buffer is still full after callback function, the oldest data is overrided. */
if (LPUART_TransferIsRxRingBufferFull(base, handle))
{
/* Increase handle->rxRingBufferTail to make room for new data. */
if (handle->rxRingBufferTail + 1U == handle->rxRingBufferSize)
{
handle->rxRingBufferTail = 0U;
}
else
{
handle->rxRingBufferTail++;
}
}
/* Read data. */
#if defined(FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT) && FSL_FEATURE_LPUART_HAS_7BIT_DATA_SUPPORT
if (handle->isSevenDataBits)
{
handle->rxRingBuffer[handle->rxRingBufferHead] = (base->DATA & 0x7F);
}
else
{
handle->rxRingBuffer[handle->rxRingBufferHead] = base->DATA;
}
#else
handle->rxRingBuffer[handle->rxRingBufferHead] = base->DATA;
#endif
/* Increase handle->rxRingBufferHead. */
if (handle->rxRingBufferHead + 1U == handle->rxRingBufferSize)
{
handle->rxRingBufferHead = 0U;
}
else
{
handle->rxRingBufferHead++;
}
}
}
/* If no receive requst pending, stop RX interrupt. */
else if (!handle->rxDataSize)
{
LPUART_DisableInterrupts(base, kLPUART_RxDataRegFullInterruptEnable | kLPUART_RxOverrunInterruptEnable);
}
else
{
}
}
/* Send data register empty and the interrupt is enabled. */
if ((base->STAT & LPUART_STAT_TDRE_MASK) && (base->CTRL & LPUART_CTRL_TIE_MASK))
{
/* Get the bytes that available at this moment. */
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
count = FSL_FEATURE_LPUART_FIFO_SIZEn(base) -
((base->WATER & LPUART_WATER_TXCOUNT_MASK) >> LPUART_WATER_TXCOUNT_SHIFT);
#else
count = 1;
#endif
while ((count) && (handle->txDataSize))
{
#if defined(FSL_FEATURE_LPUART_HAS_FIFO) && FSL_FEATURE_LPUART_HAS_FIFO
tempCount = MIN(handle->txDataSize, count);
#else
tempCount = 1;
#endif
/* Using non block API to write the data to the registers. */
LPUART_WriteNonBlocking(base, handle->txData, tempCount);
handle->txData += tempCount;
handle->txDataSize -= tempCount;
count -= tempCount;
/* If all the data are written to data register, notify user with the callback, then TX finished. */
if (!handle->txDataSize)
{
handle->txState = kLPUART_TxIdle;
/* Disable TX register empty interrupt. */
base->CTRL = (base->CTRL & ~LPUART_CTRL_TIE_MASK);
/* Trigger callback. */
if (handle->callback)
{
handle->callback(base, handle, kStatus_LPUART_TxIdle, handle->userData);
}
}
}
}
}
void LPUART_TransferHandleErrorIRQ(LPUART_Type *base, lpuart_handle_t *handle)
{
/* To be implemented by User. */
}
#if defined(FSL_FEATURE_LPUART_HAS_SHARED_IRQ0_IRQ1) && FSL_FEATURE_LPUART_HAS_SHARED_IRQ0_IRQ1
#if defined(FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ) && FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ
void LPUART0_LPUART1_RX_DriverIRQHandler(void)
{
if (CLOCK_isEnabledClock(s_lpuartClock[0]))
{
if ((LPUART_STAT_OR_MASK & LPUART0->STAT) ||
((LPUART_STAT_RDRF_MASK & LPUART0->STAT) && (LPUART_CTRL_RIE_MASK & LPUART0->CTRL)))
{
s_lpuartIsr(LPUART0, s_lpuartHandle[0]);
}
}
if (CLOCK_isEnabledClock(s_lpuartClock[1]))
{
if ((LPUART_STAT_OR_MASK & LPUART1->STAT) ||
((LPUART_STAT_RDRF_MASK & LPUART1->STAT) && (LPUART_CTRL_RIE_MASK & LPUART1->CTRL)))
{
s_lpuartIsr(LPUART1, s_lpuartHandle[1]);
}
}
}
void LPUART0_LPUART1_TX_DriverIRQHandler(void)
{
if (CLOCK_isEnabledClock(s_lpuartClock[0]))
{
if ((LPUART_STAT_OR_MASK & LPUART0->STAT) ||
((LPUART0->STAT & LPUART_STAT_TDRE_MASK) && (LPUART0->CTRL & LPUART_CTRL_TIE_MASK)))
{
s_lpuartIsr(LPUART0, s_lpuartHandle[0]);
}
}
if (CLOCK_isEnabledClock(s_lpuartClock[1]))
{
if ((LPUART_STAT_OR_MASK & LPUART1->STAT) ||
((LPUART1->STAT & LPUART_STAT_TDRE_MASK) && (LPUART1->CTRL & LPUART_CTRL_TIE_MASK)))
{
s_lpuartIsr(LPUART1, s_lpuartHandle[1]);
}
}
}
#else
void LPUART0_LPUART1_DriverIRQHandler(void)
{
if (CLOCK_isEnabledClock(s_lpuartClock[0]))
{
if ((LPUART_STAT_OR_MASK & LPUART0->STAT) ||
((LPUART_STAT_RDRF_MASK & LPUART0->STAT) && (LPUART_CTRL_RIE_MASK & LPUART0->CTRL)) ||
((LPUART0->STAT & LPUART_STAT_TDRE_MASK) && (LPUART0->CTRL & LPUART_CTRL_TIE_MASK)))
{
s_lpuartIsr(LPUART0, s_lpuartHandle[0]);
}
}
if (CLOCK_isEnabledClock(s_lpuartClock[1]))
{
if ((LPUART_STAT_OR_MASK & LPUART1->STAT) ||
((LPUART_STAT_RDRF_MASK & LPUART1->STAT) && (LPUART_CTRL_RIE_MASK & LPUART1->CTRL)) ||
((LPUART1->STAT & LPUART_STAT_TDRE_MASK) && (LPUART1->CTRL & LPUART_CTRL_TIE_MASK)))
{
s_lpuartIsr(LPUART1, s_lpuartHandle[1]);
}
}
}
#endif
#endif
#if defined(LPUART0)
#if !(defined(FSL_FEATURE_LPUART_HAS_SHARED_IRQ0_IRQ1) && FSL_FEATURE_LPUART_HAS_SHARED_IRQ0_IRQ1)
#if defined(FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ) && FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ
void LPUART0_TX_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART0, s_lpuartHandle[0]);
}
void LPUART0_RX_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART0, s_lpuartHandle[0]);
}
#else
void LPUART0_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART0, s_lpuartHandle[0]);
}
#endif
#endif
#endif
#if defined(LPUART1)
#if !(defined(FSL_FEATURE_LPUART_HAS_SHARED_IRQ0_IRQ1) && FSL_FEATURE_LPUART_HAS_SHARED_IRQ0_IRQ1)
#if defined(FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ) && FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ
void LPUART1_TX_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART1, s_lpuartHandle[1]);
}
void LPUART1_RX_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART1, s_lpuartHandle[1]);
}
#else
void LPUART1_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART1, s_lpuartHandle[1]);
}
#endif
#endif
#endif
#if defined(LPUART2)
#if defined(FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ) && FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ
void LPUART2_TX_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART2, s_lpuartHandle[2]);
}
void LPUART2_RX_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART2, s_lpuartHandle[2]);
}
#else
void LPUART2_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART2, s_lpuartHandle[2]);
}
#endif
#endif
#if defined(LPUART3)
#if defined(FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ) && FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ
void LPUART3_TX_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART3, s_lpuartHandle[3]);
}
void LPUART3_RX_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART3, s_lpuartHandle[3]);
}
#else
void LPUART3_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART3, s_lpuartHandle[3]);
}
#endif
#endif
#if defined(LPUART4)
#if defined(FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ) && FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ
void LPUART4_TX_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART4, s_lpuartHandle[4]);
}
void LPUART4_RX_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART4, s_lpuartHandle[4]);
}
#else
void LPUART4_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART4, s_lpuartHandle[4]);
}
#endif
#endif
#if defined(LPUART5)
#if defined(FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ) && FSL_FEATURE_LPUART_HAS_SEPARATE_RX_TX_IRQ
void LPUART5_TX_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART5, s_lpuartHandle[5]);
}
void LPUART5_RX_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART5, s_lpuartHandle[5]);
}
#else
void LPUART5_DriverIRQHandler(void)
{
s_lpuartIsr(LPUART5, s_lpuartHandle[5]);
}
#endif
#endif
#if defined(CM4_0_LPUART)
void M4_0_LPUART_DriverIRQHandler(void)
{
s_lpuartIsr(CM4_0_LPUART, s_lpuartHandle[LPUART_GetInstance(CM4_0_LPUART)]);
}
#endif
#if defined(CM4_1_LPUART)
void M4_1_LPUART_DriverIRQHandler(void)
{
s_lpuartIsr(CM4_1_LPUART, s_lpuartHandle[LPUART_GetInstance(CM4_1_LPUART)]);
}
#endif
#if defined(DMA_LPUART0)
void DMA_UART0_INT_IRQHandler(void)
{
s_lpuartIsr(DMA_LPUART0, s_lpuartHandle[LPUART_GetInstance(DMA_LPUART0)]);
}
#endif
#if defined(DMA_LPUART1)
void DMA_UART1_INT_IRQHandler(void)
{
s_lpuartIsr(DMA_LPUART1, s_lpuartHandle[LPUART_GetInstance(DMA_LPUART1)]);
}
#endif
#if defined(DMA_LPUART2)
void DMA_UART2_INT_IRQHandler(void)
{
s_lpuartIsr(DMA_LPUART2, s_lpuartHandle[LPUART_GetInstance(DMA_LPUART2)]);
}
#endif
#if defined(DMA_LPUART3)
void DMA_UART3_INT_IRQHandler(void)
{
s_lpuartIsr(DMA_LPUART3, s_lpuartHandle[LPUART_GetInstance(DMA_LPUART3)]);
}
#endif
#if defined(DMA_LPUART4)
void DMA_UART4_INT_IRQHandler(void)
{
s_lpuartIsr(DMA_LPUART4, s_lpuartHandle[LPUART_GetInstance(DMA_LPUART4)]);
}
#endif
|
{
"pile_set_name": "Github"
}
|
/*****************************************************************************
*
* PROJECT: Multi Theft Auto v1.0
* LICENSE: See LICENSE in the top level directory
* FILE: mods/deathmatch/logic/CWeaponNames.cpp
* PURPOSE: GTA weapon name definitions class
*
* Multi Theft Auto is available from http://www.multitheftauto.com/
*
*****************************************************************************/
#include "StdInc.h"
using namespace std;
char szWeaponNameEmpty[] = "";
struct SWeaponName
{
char szName[32];
};
struct SWeaponSlot
{
char cSlot;
};
SWeaponName WeaponNames[] = {{"Fist"},
{"Brassknuckle"},
{"Golfclub"},
{"Nightstick"},
{"Knife"},
{"Bat"},
{"Shovel"},
{"Poolstick"},
{"Katana"},
{"Chainsaw"},
{"Dildo"},
{"Dildo"},
{"Vibrator"},
{"Vibrator"},
{"Flower"},
{"Cane"},
{"Grenade"},
{"Teargas"},
{"Molotov"},
{"Rocket"},
{"Rocket"},
{"Freefall Bomb"},
{"Colt 45"},
{"Silenced"},
{"Deagle"},
{"Shotgun"},
{"Sawed-off"},
{"Combat Shotgun"},
{"Uzi"},
{"MP5"},
{"AK-47"},
{"M4"},
{"Tec-9"},
{"Rifle"},
{"Sniper"},
{"Rocket Launcher"},
{"Rocket Launcher HS"},
{"Flamethrower"},
{"Minigun"},
{"Satchel"},
{"Bomb"},
{"Spraycan"},
{"Fire Extinguisher"},
{"Camera"},
{"Nightvision"},
{"Infrared"},
{"Parachute"},
{"Last Weapon"},
{"Armour"},
{"Rammed"},
{"Ranover"},
{"Explosion"},
{"Driveby"},
{"Drowned"},
{"Fall"},
{"Unknown"},
{"Melee"},
{"Weapon"},
{"Flare"},
{"Tank Grenade"}};
SWeaponSlot WeaponIDs[] = {{0}, {0}, {1}, {1}, {1}, {1}, {1}, {1}, {1}, {1}, {10}, {10}, {10}, {-1}, {10}, {10}, {8}, {8}, {8}, {-1}, {-1}, {-1}, {2}, {2},
{2}, {3}, {3}, {3}, {4}, {4}, {5}, {5}, {4}, {6}, {6}, {7}, {7}, {7}, {7}, {8}, {12}, {9}, {9}, {9}, {11}, {11}, {11}, {-1}};
bool CWeaponNames::IsWeaponIDAkimbo(unsigned char ucID)
{
return (ucID == 22 || ucID == 26 || ucID == 28 || ucID == 32);
}
bool CWeaponNames::IsDriveByWeapon(unsigned char ucID)
{
return ((ucID >= 22 && ucID <= 33) || ucID == 38);
}
unsigned char CWeaponNames::GetWeaponID(const char* szName)
{
// If the specified string was empty, return 0
if (szName[0] == 0)
return 0xFF;
// Look for it in our table
for (unsigned int i = 0; i < NUMELMS(WeaponNames); i++)
{
if (stricmp(szName, WeaponNames[i].szName) == 0)
{
return i;
}
}
return 0xFF;
}
const char* CWeaponNames::GetWeaponName(unsigned char ucID)
{
if (ucID < NUMELMS(WeaponNames))
{
return WeaponNames[ucID].szName;
}
return szWeaponNameEmpty;
}
char CWeaponNames::GetSlotFromWeapon(unsigned char ucID)
{
if (ucID < NUMELMS(WeaponIDs))
{
return WeaponIDs[ucID].cSlot;
}
return -1;
}
|
{
"pile_set_name": "Github"
}
|
#-*- coding:etf-8 -*-
"""
数学表达式计算
Contributed by izanbf1803.
Example:
-------------------------------------------------------------------------------------------------
Code:
| exp = "2452 * (3 * 6.5 + 1) * 6 / 235"
| print("Expression:", exp)
| print("Parsed expression:", mp.parse(exp))
| print("Evaluation result:", mp.evaluate(exp))
Output:
| Expression: 2452 * (3 * 6 + 1) * 6 / 235
| Parsed expression: ['2452', '*', '(', '3', '*', '6', '+', '1', ')', '*', '6', '/', '235']
| Evaluation result: 1189.4808510638297
-------------------------------------------------------------------------------------------------
"""
from collections import deque
import re
numeric_value = re.compile('\d+(\.\d+)?')
__operators__ = "+-/*"
__parenthesis__ = "()"
__priority__ = {
'+': 0,
'-': 0,
'*': 1,
'/': 1,
}
def is_operator(token):
"""
Check if token it's a operator
token Char: Token
"""
return token in __operators__
def higher_priority(op1, op2):
"""
Check if op1 have higher priority than op2
op1 Char: Operation Token 1
op2 Char: Operation Token 2
"""
return __priority__[op1] >= __priority__[op2]
def calc(n2, n1, operator):
"""
Calculate operation result
n2 Number: Number 2
n1 Number: Number 1
operator Char: Operation to calculate
"""
if operator == '-': return n1 - n2
elif operator == '+': return n1 + n2
elif operator == '*': return n1 * n2
elif operator == '/': return n1 / n2
return 0
def apply_operation(op_stack, out_stack):
"""
Apply operation to the first 2 items of the output queue
op_stack Deque (reference)
out_stack Deque (reference)
"""
out_stack.append(calc(out_stack.pop(), out_stack.pop(), op_stack.pop()))
def parse(expression):
"""
Return array of parsed tokens in the expression
expression String: Math expression to parse in infix notation
"""
result = []
current = ""
for i in expression:
if i.isdigit() or i == '.':
current += i
else:
if len(current) > 0:
result.append(current)
current = ""
if i != ' ':
result.append(i)
if len(current) > 0:
result.append(current)
return result
def evaluate(expression):
"""
Calculate result of expression
expression String: The expression
type Type (optional): Number type [int, float]
"""
op_stack = deque() # operator stack
out_stack = deque() # output stack (values)
for token in parse(expression):
if numeric_value.match(token):
out_stack.append(float(token))
elif token == '(':
op_stack.append(token)
elif token == ')':
while len(op_stack) > 0 and op_stack[-1] != '(':
apply_operation(op_stack, out_stack)
op_stack.pop() # Remove remaining '('
else: # is_operator(token)
while len(op_stack) > 0 and is_operator(op_stack[-1]) and higher_priority(op_stack[-1], token):
apply_operation(op_stack, out_stack)
op_stack.append(token)
while len(op_stack) > 0:
apply_operation(op_stack, out_stack)
return out_stack[-1]
|
{
"pile_set_name": "Github"
}
|
###############################################################################
# ilastik: interactive learning and segmentation toolkit
#
# Copyright (C) 2011-2014, the ilastik developers
# <team@ilastik.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# In addition, as a special exception, the copyright holders of
# ilastik give you permission to combine ilastik with applets,
# workflows and plugins which are not covered under the GNU
# General Public License.
#
# See the LICENSE file for details. License information is also available
# on the ilastik web site at:
# http://ilastik.org/license.html
###############################################################################
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtGui import QColor
from volumina.api import createDataSource, ColortableLayer, AlphaModulatedLayer
from volumina import colortables
from ilastik.applets.dataExport.dataExportGui import DataExportGui, DataExportLayerViewerGui
from lazyflow.operators import OpMultiArraySlicer2
from ilastik.utility.exportingOperator import ExportingGui
class ObjectClassificationDataExportGui(DataExportGui, ExportingGui):
"""
A subclass of the generic data export gui that creates custom layer viewers.
"""
def __init__(self, *args, **kwargs):
super(ObjectClassificationDataExportGui, self).__init__(*args, **kwargs)
self._exporting_operator = None
def set_exporting_operator(self, op):
self._exporting_operator = op
def get_exporting_operator(self):
return self._exporting_operator
def createLayerViewer(self, opLane):
return ObjectClassificationResultsViewer(self.parentApplet, opLane)
def get_export_dialog_title(self):
return "Export Object Information"
@property
def gui_applet(self):
return self.parentApplet
def get_table_export_settings(self):
return self._exporting_operator.get_table_export_settings()
def get_raw_shape(self):
return self._exporting_operator.get_raw_shape()
def get_feature_names(self):
return self._exporting_operator.get_feature_names()
def _initAppletDrawerUic(self):
super(ObjectClassificationDataExportGui, self)._initAppletDrawerUic()
btn = QPushButton("Configure Feature Table Export", clicked=self.configure_table_export)
self.drawer.exportSettingsGroupBox.layout().addWidget(btn)
class ObjectClassificationResultsViewer(DataExportLayerViewerGui):
_colorTable16 = colortables.default16_new
def setupLayers(self):
layers = []
opLane = self.topLevelOperatorView
selection_names = opLane.SelectionNames.value
selection = selection_names[opLane.InputSelection.value]
# This code is written to handle the specific output cases we know about.
# If those change, update this function!
assert selection in [
"Object Predictions",
"Object Probabilities",
"Blockwise Object Predictions",
"Blockwise Object Probabilities",
"Object Identities",
"Pixel Probabilities",
]
if selection in ("Object Predictions", "Blockwise Object Predictions"):
previewSlot = self.topLevelOperatorView.ImageToExport
if previewSlot.ready():
previewLayer = ColortableLayer(createDataSource(previewSlot), colorTable=self._colorTable16)
previewLayer.name = "Prediction - Preview"
previewLayer.visible = False
layers.append(previewLayer)
elif selection in ("Object Probabilities", "Blockwise Object Probabilities"):
previewLayers = self._initPredictionLayers(opLane.ImageToExport)
for layer in previewLayers:
layer.visible = False
layer.name = layer.name + "- Preview"
layers += previewLayers
elif selection == "Pixel Probabilities":
previewLayers = self._initPredictionLayers(opLane.ImageToExport)
for layer in previewLayers:
layer.visible = False
layer.name = layer.name + "- Preview"
layers += previewLayers
elif selection == "Object Identities":
previewSlot = self.topLevelOperatorView.ImageToExport
layer = self._initColortableLayer(previewSlot)
layers.append(layer)
else:
assert False, "Unknown selection."
rawSlot = self.topLevelOperatorView.RawData
if rawSlot.ready():
rawLayer = self.createStandardLayerFromSlot(rawSlot)
rawLayer.name = "Raw Data"
rawLayer.opacity = 1.0
layers.append(rawLayer)
return layers
def _initPredictionLayers(self, predictionSlot):
layers = []
opLane = self.topLevelOperatorView
# Use a slicer to provide a separate slot for each channel layer
opSlicer = OpMultiArraySlicer2(parent=opLane.viewed_operator().parent)
opSlicer.Input.connect(predictionSlot)
opSlicer.AxisFlag.setValue("c")
for channel, channelSlot in enumerate(opSlicer.Slices):
if channelSlot.ready():
drange = channelSlot.meta.drange or (0.0, 1.0)
predictsrc = createDataSource(channelSlot)
predictLayer = AlphaModulatedLayer(
predictsrc,
tintColor=QColor.fromRgba(self._colorTable16[channel + 1]),
normalize=drange,
)
predictLayer.opacity = 1.0
predictLayer.visible = True
predictLayer.name = "Probability Channel #{}".format(channel + 1)
layers.append(predictLayer)
return layers
def _initColortableLayer(self, labelSlot):
objectssrc = createDataSource(labelSlot)
objectssrc.setObjectName("LabelImage LazyflowSrc")
ct = colortables.create_default_16bit()
ct[0] = QColor(0, 0, 0, 0).rgba() # make 0 transparent
layer = ColortableLayer(objectssrc, ct)
layer.name = "Object Identities - Preview"
layer.setToolTip("Segmented objects, shown in different colors")
layer.visible = False
layer.opacity = 0.5
layer.colortableIsRandom = True
return layer
|
{
"pile_set_name": "Github"
}
|
# 20181204 Github 前端趋势榜
[Github 前端开发日报](http://caibaojian.com/c/news)栏目数据来自[Github热榜](http://news.caibaojian.com/)(我开发的爬虫),每日分享HTML、CSS、JavaScript、Vue等开源项目,为开发者提供动力,点击Star按钮来关注这个项目,点击Watch来收听每日的更新[Github主页](https://github.com/kujian/githubTrending)
## JavaScript
* [gaearon/overreacted.io](https://github.com/gaearon/overreacted.io) (ignore me)
* [pim-book/programmers-introduction-to-mathematics](https://github.com/pim-book/programmers-introduction-to-mathematics) (Code for A Programmer's Introduction to Mathematics)
* [ithinco/i-am-chinese-the-dragonfly-must-go-on](https://github.com/ithinco/i-am-chinese-the-dragonfly-must-go-on) (A response to “We are Google employees, Google must drop DragonFly”)
* [oussamahamdaoui/forgJs](https://github.com/oussamahamdaoui/forgJs) (ForgJs is a javascript lightweight object validator. Go check the Quick start section and start coding with love)
* [pcottle/learnGitBranching](https://github.com/pcottle/learnGitBranching) (An interactive git visualization to challenge and educate!)
* [vuejs/vue](https://github.com/vuejs/vue) (
A progressive, incrementally-adoptable JavaScript framework for building UI on the web.
)
* [olifolkerd/tabulator](https://github.com/olifolkerd/tabulator) (Interactive Tables and Data Grids for JavaScript)
* [facebook/react](https://github.com/facebook/react) (A declarative, efficient, and flexible JavaScript library for building user interfaces.)
* [GitSquared/edex-ui](https://github.com/GitSquared/edex-ui) (A science fiction desktop running everywhere. Awesome.)
* [leonardomso/33-js-concepts](https://github.com/leonardomso/33-js-concepts) (? 33 concepts every JavaScript developer should know.)
* [Tencent/omi](https://github.com/Tencent/omi) (Omi === Preact + Scoped CSS + Store System + Native Support in 3kb javascript.)
* [zhoushaw/Instagram](https://github.com/zhoushaw/Instagram) (A web-app with some feature like Instagram!!😉📸😊)
* [withspectrum/spectrum](https://github.com/withspectrum/spectrum) (Simple, powerful online communities.)
* [bvaughn/progress-estimator](https://github.com/bvaughn/progress-estimator) (Logs a progress bar and estimation for how long a Promise will take to complete)
* [GoogleChrome/puppeteer](https://github.com/GoogleChrome/puppeteer) (Headless Chrome Node API)
* [facebook/create-react-app](https://github.com/facebook/create-react-app) (Create React apps with no build configuration.)
* [algorithm-visualizer/algorithm-visualizer](https://github.com/algorithm-visualizer/algorithm-visualizer) (🎆Interactive Online Platform that Visualizes Algorithms from Code)
* [zeit/next.js](https://github.com/zeit/next.js) (
Framework for server-rendered React apps
)
* [30-seconds/30-seconds-of-code](https://github.com/30-seconds/30-seconds-of-code) (Curated collection of useful Javascript snippets that you can understand in 30 seconds or less.)
* [axios/axios](https://github.com/axios/axios) (Promise based HTTP client for the browser and node.js)
* [airbnb/javascript](https://github.com/airbnb/javascript) (
JavaScript Style Guide
)
* [NervJS/taro](https://github.com/NervJS/taro) (京东多端统一开发框架,支持用 React 的开发方式编写一次代码,生成能运行在微信小程序、H5、React Native 等的应用。)
* [nodejs/node](https://github.com/nodejs/node) (
Node.js JavaScript runtime ✨??✨
)
* [kaola-fed/megalo](https://github.com/kaola-fed/megalo) (基于 Vue 的小程序开发框架)
* [gatsbyjs/gatsby](https://github.com/gatsbyjs/gatsby) (⚛️?? Blazing fast static site generator for React)
* [iview/iview-admin](https://github.com/iview/iview-admin) (Vue 2.0 admin management system template based on iView)
* [youzan/vant](https://github.com/youzan/vant) (A Vue.js 2.0 Mobile UI at YouZan)
* [Molunerfinn/PicGo](https://github.com/Molunerfinn/PicGo) (A simple & beautiful tool for pictures uploading built by electron-vue)
## Vue
* [a54552239/projectManage](https://github.com/a54552239/projectManage) (基于Vue.js实现的项目管理系统)
* [PanJiaChen/vue-element-admin](https://github.com/PanJiaChen/vue-element-admin) (
vue2 admin / a management system template
)
* [ElemeFE/element](https://github.com/ElemeFE/element) (
A Vue.js 2.0 UI Toolkit for Web
)
* [dcloudio/uni-app](https://github.com/dcloudio/uni-app) (使用 Vue.js 开发跨平台应用的前端框架)
* [kaola-fed/megalo-demo](https://github.com/kaola-fed/megalo-demo) (megalo-demo)
* [iview/iview](https://github.com/iview/iview) (
A high quality UI Toolkit with both Vue.js 2.0 and 1.0
)
* [LanceGin/Mockman](https://github.com/LanceGin/Mockman) (Manage and start the mock servers on your local platform easily)
* [lin-xin/vue-manage-system](https://github.com/lin-xin/vue-manage-system) (
The web management system solution based on Vue2 and Element-UI.
)
* [DivanteLtd/vue-storefront](https://github.com/DivanteLtd/vue-storefront) (Vue.js Storefront - PWA for eCommerce. 100% offline, platform agnostic, headless, Magento2 supported. Always Open Source, MIT license. Join us as contributor (contributors@vuestorefront.io).)
* [putianxi/putianxi.github.io](https://github.com/putianxi/putianxi.github.io) (滚蛋吧!莆田系)
* [bailicangdu/vue2-manage](https://github.com/bailicangdu/vue2-manage) (
基于 vue + element-ui 的后台管理系统
)
* [airyland/vux](https://github.com/airyland/vux) (
Mobile web UI Components based on Vue and WeUI (Vue@2.x)
)
* [hinesboy/mavonEditor](https://github.com/hinesboy/mavonEditor) (mavonEditor - A markdown editor based on Vue that supports a variety of personalized features)
* [vueComponent/ant-design-vue](https://github.com/vueComponent/ant-design-vue) (An enterprise-class UI components based on Ant Design and Vue. ?)
* [LeCoupa/vuedarkmode](https://github.com/LeCoupa/vuedarkmode) (Vue Dark Mode | A minimalist dark design system designed for the insomniacs who enjoy dark interfaces as much as we do. ?)
* [salomonelli/best-resume-ever](https://github.com/salomonelli/best-resume-ever) (? ? Build fast ? and easy multiple beautiful resumes and create your best CV ever! Made with Vue and LESS.)
* [YTU94/meedu-wxapp](https://github.com/YTU94/meedu-wxapp) (📜meEdu微信小程序。(wxapp for meedu)❗️)
## HTML
* [gorhill/uBlock](https://github.com/gorhill/uBlock) (uBlock Origin - An efficient blocker for Chromium and Firefox. Fast and lean.)
* [valentinxxx/nginxconfig.io](https://github.com/valentinxxx/nginxconfig.io) (nginx config generator)
* [rampatra/wedding-website](https://github.com/rampatra/wedding-website) (Our Wedding Website 👫)
* [google/styleguide](https://github.com/google/styleguide) (
Style guides for Google-originated open-source projects
)
* [OWASP/owasp-mstg](https://github.com/OWASP/owasp-mstg) (
The Mobile Security Testing Guide (MSTG) is the ultimate guide for mobile app security testing and reverse engineering.
)
* [almasaeed2010/AdminLTE](https://github.com/almasaeed2010/AdminLTE) (
AdminLTE - Free Premium Admin control Panel Theme Based On Bootstrap 3.x
)
* [portainer/portainer](https://github.com/portainer/portainer) (
Simple management UI for Docker
)
* [wesbos/JavaScript30](https://github.com/wesbos/JavaScript30) (
30 Day Vanilla JS Challenge
)
* [facebookresearch/fastText](https://github.com/facebookresearch/fastText) (Library for fast text representation and classification.)
* [OpenAPITools/openapi-generator](https://github.com/OpenAPITools/openapi-generator) (OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3))
* [google/fonts](https://github.com/google/fonts) (Font files available from Google Fonts)
* [Huxpro/huxpro.github.io](https://github.com/Huxpro/huxpro.github.io) (
My Blog / Jekyll Themes / PWA
)
* [fengdu78/Coursera-ML-AndrewNg-Notes](https://github.com/fengdu78/Coursera-ML-AndrewNg-Notes) (吴恩达老师的机器学习课程个人笔记)
* [coreui/coreui-free-bootstrap-admin-template](https://github.com/coreui/coreui-free-bootstrap-admin-template) (CoreUI is free bootstrap admin template with Angular2, AngularJS, React.js & Vue.js support.)
* [fossasia/gci18.fossasia.org](https://github.com/fossasia/gci18.fossasia.org) (FOSSASIA Google Code-In Website 2018 <a href="https://gci18.fossasia.org" rel="nofollow">https://gci18.fossasia.org</a>)
* [tc39/proposal-optional-chaining](https://github.com/tc39/proposal-optional-chaining) (Base OTP behaviors presented as schemas)
* [electron/electron-api-demos](https://github.com/electron/electron-api-demos) (
Explore the Electron APIs
)
## CSS
* [BcRikko/NES.css](https://github.com/BcRikko/NES.css) (NES-style CSS Framework | ファミコン風CSSフレームワーク[WIP])
* [cssanimation/css-animation-101](https://github.com/cssanimation/css-animation-101) (Learn how to bring animation to your web projects)
* [twbs/bootstrap](https://github.com/twbs/bootstrap) (The most popular HTML, CSS, and JavaScript framework for developing responsive, mobile first projects on the web.
)
* [jgthms/bulma](https://github.com/jgthms/bulma) (
Modern CSS framework based on Flexbox
)
* [daneden/animate.css](https://github.com/daneden/animate.css) (
A cross-browser library of CSS animations. As easy to use as an easy thing.
)
* [nakov/practical-cryptography-for-developers-book](https://github.com/nakov/practical-cryptography-for-developers-book) (Practical Cryptography for Developers: Hashes, MAC, Key Derivation, DHKE, Symmetric and Asymmetric Ciphers, Elliptic Curves, Digital Signatures)
* [98mprice/PSone.css](https://github.com/98mprice/PSone.css) (🎮 Playstation 1 style CSS Framework, inspired by NES.css)
* [TalkingData/iview-weapp](https://github.com/TalkingData/iview-weapp) (一套高质量的微信小程序 UI 组件库)
* [StylishThemes/GitHub-Dark](https://github.com/StylishThemes/GitHub-Dark) (
<img class="emoji" title=":octocat:" alt=":octocat:" src="https://assets-cdn.github.com/images/icons/emoji/octocat.png" height="20" width="20" align="absmiddle"> Dark GitHub style
)
* [IanLunn/Hover](https://github.com/IanLunn/Hover) (
A collection of CSS3 powered hover effects to be applied to links, buttons, logos, SVG, featured images and so on. Easily apply to your own elements, modify or just use for inspiration. Available in CSS, Sass, and LESS.
)
* [udacity/course-collaboration-travel-plans](https://github.com/udacity/course-collaboration-travel-plans) (?Jalpc -- A flexible Jekyll theme, 3 steps to build your website.)
* [Microsoft/TypeScript-Node-Starter](https://github.com/Microsoft/TypeScript-Node-Starter) (
A starter template for TypeScript and Node with a detailed README describing how to use the two together.
)
* [theme-next/hexo-theme-next](https://github.com/theme-next/hexo-theme-next) (Elegant and powerful theme for Hexo.)
* [Requarks/wiki](https://github.com/Requarks/wiki) (Wiki.js | A modern, lightweight and powerful wiki app built on NodeJS, Git and Markdown)
* [l-hammer/You-need-to-know-css](https://github.com/l-hammer/You-need-to-know-css) (CSS Tricks for web developer)
* [handong1587/handong1587.github.io](https://github.com/handong1587/handong1587.github.io) (
A Jekyll-based theme designed for documentation and help systems. See the link for detailed instructions on setting up and configuring everything.
)
* [fossasia/fossasia.org](https://github.com/fossasia/fossasia.org) (FOSSASIA Website <a href="http://fossasia.org" rel="nofollow">http://fossasia.org</a>)
* [sahat/hackathon-starter](https://github.com/sahat/hackathon-starter) (
A boilerplate for Node.js web applications
)
* [rstacruz/cheatsheets](https://github.com/rstacruz/cheatsheets) (My cheatsheets)
## TypeScript
* [ionic-team/ionic](https://github.com/ionic-team/ionic) (Build amazing native and progressive web apps with open web technologies. One app running on everything ?)
## Unknow
* [h5bp/Front-end-Developer-Interview-Questions](https://github.com/h5bp/Front-end-Developer-Interview-Questions) (
A list of helpful front-end related questions you can use to interview potential candidates, test yourself or completely ignore.
)
日报维护作者:[前端博客](http://caibaojian.com/) 和 [微博](http://caibaojian.com/go/weibo)

|
{
"pile_set_name": "Github"
}
|
(* Copyright 2001, 2002, 2003 Maxence Guesdon, b52_simon INRIA *)
(*
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Printf2
open GtkBase
open Gtk
type content =
| String of string
| Pixmap of GDraw.pixmap
| Pixtext of string * GDraw.pixmap
type line = content list * GDraw.optcolor option
type 'a ptree =
{
data : 'a;
mutable children : 'a ptree list
}
let dummy_line = [], None
class virtual ['a] filtered_plist
sel_mode titles titles_show get_key =
let wscroll = GBin.scrolled_window
~hpolicy: `AUTOMATIC
~vpolicy: `AUTOMATIC
()
in
let (wlist : 'a GList.clist) = GList.clist_poly
~titles_show: titles_show
~titles: titles
~selection_mode: sel_mode
~packing: wscroll#add
()
in
let tooltips = GData.tooltips () in
object (self)
val mutable items = ([||] : 'a array)
val mutable contents = ([||] : line array)
val mutable nitems = 0
val mutable current_sort = 0
val mutable selection = ([] : 'a list)
val mutable wlist = wlist
val mutable filtered = Intmap.empty
val mutable nfiltered = 0
val mutable columns_width = ([] : (int * int) list)
val mutable first_click_done = false;
method box = wscroll#coerce
method wlist = wlist
method virtual content : 'a -> line
method compare = Pervasives.compare
method selection = selection
method on_select (d:'a) = ()
method on_deselect (d:'a) = ()
method on_double_click (d:'a) = ()
method private sort =
Array.fill contents 0 nitems dummy_line;
let array = Array.init nitems (fun i ->
(items.(i),i)) in
Array.sort (fun (v1,n1) (v2,n2) ->
let cmp = self#compare v1 v2 in
if cmp = 0 then compare n1 n2 else cmp
) array;
for i = 0 to nitems - 1 do
let item, _ = array.(i) in
items.(i) <- item
done
method set_titles l =
wscroll#remove wlist#coerce;
let (w : 'a GList.clist) = GList.clist_poly
~titles_show: titles_show
~titles: l
~selection_mode: sel_mode
~packing: wscroll#add
()
in
wlist <- w;
self#connect_events
method update_row d row =
if row >= 0 then begin
try
let line = self#content d in
if line <> contents.(row) then begin
contents.(row) <- line;
let (l, col_opt) = line in
let rec iter n l =
match l with
[] -> ()
| (String s) :: q ->
wlist#set_cell ~text: s row n;
iter (n+1) q
| (Pixmap p) :: q ->
wlist#set_cell ~pixmap: p row n;
iter (n+1) q
| (Pixtext (s, p)) :: q ->
wlist#set_cell ~text:s ~pixmap:p ~spacing:5 row n;
iter (n+1) q
in
iter 0 l;
(* tooltips#set_tip ((wlist:int)#get_row row)#coerce ~text: "Tooltip";*)
match col_opt with
None -> ()
| Some c ->
wlist#set_row ~foreground: c row;
end
with e ->
lprintf "Exception %s in update_row\n" (Printexc2.to_string e);
end else begin
lprintf "update_row < 0\n"
end
method insert ?row d =
let r =
match row with
None ->
ignore (wlist#append []) ; wlist#rows - 1
| Some p ->
ignore (wlist#insert ~row: p []) ; p
in
self#update_row d r
method update =
wlist#freeze ();
wlist#clear ();
self#sort;
selection <- [];
for i = 0 to nitems - 1 do
self#insert items.(i);
done;
(* self#wlist#columns_autosize (); *)
wlist#thaw ()
method clear =
wlist#clear ();
nitems <- 0;
items <- [||];
contents <- [||];
filtered <- Intmap.empty;
selection <- []
method menu = ([] : GToolbox.menu_entry list)
method private connect_events =
let check_double_click event d =
(
match event with
None -> ()
| Some ev ->
let t = GdkEvent.get_type ev in
match t with
`TWO_BUTTON_PRESS -> self#on_double_click d
| _ -> ()
)
in
let f_select_table ~row ~column ~event =
try
let d = items.(row) in
selection <- d ::
(List.filter (fun d2 -> d <> d2) selection);
self#on_select d;
check_double_click event d
with Failure _ -> ()
in
let f_unselect_table ~row ~column ~event =
try
let d = items.(row) in
selection <-
(List.filter (fun d2 -> d <> d2) selection);
self#on_deselect d;
check_double_click event d
with Failure _ -> ()
in
ignore (wlist#connect#select_row f_select_table);
ignore (wlist#connect#unselect_row f_unselect_table);
ignore (wlist#connect#click_column
(fun c ->
if not first_click_done then begin
wlist#columns_autosize ();
first_click_done <- true
end;
(* GToolbox.autosize_clist self#wlist; *)
self#resort_column c ()
)
);
(* connect the press on button 3 for contextual menu *)
ignore (wlist#event#connect#button_press ~callback:
(
fun ev ->
GdkEvent.Button.button ev = 3 &&
GdkEvent.get_type ev = `BUTTON_PRESS &&
(
GAutoconf.popup_menu
~button: 1
~time: 0
~entries: self#menu;
true
)
)
);
(* connect the press on button 3 for title contextual menu *)
for col = 0 to wlist#columns - 1 do
let w = wlist#column_widget col in
let b = Widget.get_ancestor w#as_widget (Type.from_name "GtkButton") in
let button = new GButton.button (Object.unsafe_cast b) in
ignore (button#event#connect#button_press ~callback:
(
fun ev ->
GdkEvent.Button.button ev = 3 &&
GdkEvent.get_type ev = `BUTTON_PRESS &&
(
GAutoconf.popup_menu
~button: 1
~time: 0
~entries: (self#column_menu col);
true
)
)
);
(* connect the columns resizing to draw what could need a column width *)
ignore (w#misc#connect#size_allocate ~callback:
(fun rect ->
let width = rect.width in
if col < (wlist#columns - 1)
then columns_width <- List.append columns_width [(col, width)]
else begin
columns_width <- List.append columns_width [(col, width)];
self#has_changed_width columns_width;
columns_width <- []
end
));
done;
initializer
self#connect_events;
self#wlist#columns_autosize ()
method resort_column i () =
let n = i + 1 in
if current_sort = n or (- current_sort) = n then
current_sort <- (- current_sort)
else
current_sort <- n;
self#update
method column_menu i =
[
`I ("sort", self#resort_column i);
]
method has_changed_width l = ()
method find key =
let rec iter i len =
if i = len then (-1, Intmap.find key filtered) else
if get_key items.(i) = key then (i, items.(i)) else
iter (i+1) len
in
iter 0 nitems
method get_data n =
if (n > nitems) || (n < 0) then
raise Not_found
else items.(n)
method get_all_items =
let l = ref [] in
l := Intmap.to_list filtered;
for n = 0 to (nitems - 1) do
l := items.(n)::!l
done;
!l
method add_item i =
if self#filter i then
self#add_filtered_item i
else begin
let pos = nitems in
self#add_hidden_item i;
self#insert ~row: pos i;
end
method size = nitems + nfiltered
method private add_hidden_item i =
if nitems = Array.length items then begin
let nis = nitems * 2 + 8 in
let is = Array.make nis i in
Array.blit items 0 is 0 nitems;
contents <- Array.make nis dummy_line;
items <- is
end else begin
items.(nitems) <- i;
contents.(nitems) <- dummy_line;
end;
nitems <- nitems+1
method private add_filtered_item i =
let key = get_key i in
filtered <- Intmap.add key i filtered;
nfiltered <- nfiltered + 1
method refresh_filter =
let filter = self#filter in
let add_filtered_item = self#add_filtered_item in
let add_hidden_item = self#add_hidden_item in
let old_items = Array.sub items 0 nitems in
let old_map = filtered in
(* freeze & clear reverted to show the user that
something appened if it takes too long time *)
wlist#clear ();
wlist#freeze ();
nitems <- 0;
filtered <- Intmap.empty;
selection <- [];
nfiltered <- 0;
items <- [||];
contents <- [||];
Array.iter (fun i ->
if filter i then
add_filtered_item i
else
add_hidden_item i
) old_items;
Intmap.iter (fun _ i ->
if filter i then
add_filtered_item i
else
add_hidden_item i
) old_map;
self#sort;
for i = 0 to nitems - 1 do
self#insert items.(i);
done;
self#wlist#columns_autosize ();
wlist#thaw ()
method reset_data data =
let filter = self#filter in
let add_filtered_item = self#add_filtered_item in
let add_hidden_item = self#add_hidden_item in
(* freeze & clear reverted to show the user that
something appened if it takes too long time *)
wlist#clear ();
wlist#freeze ();
nitems <- 0;
filtered <- Intmap.empty;
selection <- [];
nfiltered <- 0;
items <- [||];
contents <- [||];
List.iter (fun i ->
if filter i then
add_filtered_item i
else
add_hidden_item i
) data;
self#sort;
for i = 0 to nitems - 1 do
self#insert items.(i);
done;
self#wlist#columns_autosize ();
wlist#thaw ()
method virtual filter : 'a -> bool
method refresh_item old_pos i =
let old_filtered = old_pos < 0 in
let new_filtered = self#filter i in
match old_filtered, new_filtered with
true, false ->
filtered <- Intmap.remove (get_key i) filtered;
nfiltered <- nfiltered - 1;
let pos = nitems in
self#add_hidden_item i;
self#insert ~row: pos i;
| false, true ->
Array.blit items (old_pos+1) items old_pos (nitems - old_pos - 1);
Array.blit contents (old_pos+1) contents old_pos (nitems - old_pos - 1);
nitems <- nitems - 1;
items <- Array.sub items 0 nitems;
contents <- Array.sub contents 0 nitems;
self#wlist#remove old_pos;
selection <- List.filter (fun fi -> get_key fi <> get_key i) selection;
self#add_filtered_item i
| false, _ ->
self#update_row i old_pos
| _ -> ()
method remove_item pos i =
if pos < 0 then begin
filtered <- Intmap.remove (get_key i) filtered;
nfiltered <- nfiltered - 1
end else begin
self#wlist#remove pos;
Array.blit items (pos+1) items pos (nitems - pos - 1);
Array.blit contents (pos+1) contents pos (nitems - pos - 1);
nitems <- nitems - 1;
items <- Array.sub items 0 nitems;
contents <- Array.sub contents 0 nitems;
selection <- List.filter (fun fi -> get_key fi <> get_key i) selection
end
method iter (f : 'a -> unit) =
for i = 0 to nitems - 1 do
f items.(i)
done
end
class virtual ['a] plist
sel_mode titles titles_show get_key =
object
inherit ['a] filtered_plist sel_mode titles titles_show get_key
method filter i = false
end
class virtual ['a] filtered_ptree
sel_mode titles titles_show get_key =
let wscroll = GBin.scrolled_window
~hpolicy: `AUTOMATIC
~vpolicy: `AUTOMATIC
()
in
let (wlist : 'a GList.clist) = GList.clist_poly
~titles_show: titles_show
~titles: titles
~selection_mode: sel_mode
~packing: wscroll#add
()
in
let tooltips = GData.tooltips () in
object (self)
constraint 'a = 'b ptree
val mutable items = ([||] : 'a array)
val mutable contents = ([||] : line array)
val mutable nitems = 0
val mutable current_sort = 0
val mutable selection = ([] : 'a list)
val mutable wlist = wlist
val mutable filtered = Intmap.empty
val mutable nfiltered = 0
val mutable columns_width = ([] : (int * int) list)
val mutable is_expanded = ([] : (int list * int ) list)
method is_expanded = is_expanded
method box = wscroll#coerce
method wlist = wlist
method virtual content : 'a -> line
method compare = Pervasives.compare
method selection = selection
method on_select (d : 'a ) = ()
method on_deselect (d : 'a ) = ()
method on_double_click (d : 'a ) = ()
method private sort =
Array.fill contents 0 nitems dummy_line;
let depth =
let d = ref 0 in
for i = 0 to nitems - 1 do
let l = List.length (get_key (items.(i))) - 1 in
if l > !d then
d := l
done;
!d
in
let array = Array.init nitems (fun i ->
(items.(i),i)) in
(* we sort only items belonging to the max depth *)
Array.sort (fun (v1,n1) (v2,n2) ->
if (List.length (get_key (v1)) - 1) = depth &&
(List.length (get_key (v2)) - 1) = depth
then
if depth >= 1 then
if List.nth (get_key (v1)) (depth - 1) = List.nth (get_key (v2)) (depth - 1) then
begin
let cmp = self#compare v1 v2 in
if cmp = 0 then compare n1 n2 else cmp
end
else compare n1 n2
else
begin
let cmp = self#compare v1 v2 in
if cmp = 0 then compare n1 n2 else cmp
end
else compare n1 n2
) array;
for i = 0 to nitems - 1 do
let item, _ = array.(i) in
items.(i) <- item
done
method set_titles l =
wscroll#remove wlist#coerce;
let (w : 'a GList.clist) = GList.clist_poly
~titles_show: titles_show
~titles: l
~selection_mode: sel_mode
~packing: wscroll#add
()
in
wlist <- w;
self#connect_events
method update_row d row =
if row >= 0 then begin
try
let line = self#content d in
if line <> contents.(row) then begin
contents.(row) <- line;
let (l, col_opt) = line in
let rec iter n l =
match l with
[] -> ()
| (String s) :: q ->
wlist#set_cell ~text:s row n;
iter (n+1) q
| (Pixmap p) :: q ->
wlist#set_cell ~pixmap:p row n;
iter (n+1) q
| (Pixtext (s, p)) :: q ->
wlist#set_cell ~text:s ~pixmap:p ~spacing:5 row n;
iter (n+1) q
in
iter 0 l;
(* tooltips#set_tip ((wlist:int)#get_row row)#coerce ~text: "Tooltip";*)
match col_opt with
None -> ()
| Some c ->
wlist#set_row ~foreground: c row;
end
with e ->
lprintf "Exception %s in update_row\n" (Printexc2.to_string e);
end else begin
lprintf "update_row < 0\n"
end
method insert ?row d =
let r =
match row with
None ->
ignore (wlist#append []) ; wlist#rows - 1
| Some p ->
ignore (wlist#insert ~row: p []) ; p
in
self#update_row d r
method expand i =
if not (List.mem_assoc (get_key i) is_expanded) then
begin
let (row, _) = self#find (get_key i) in
match i.children with
[] -> true
| l ->
begin
wlist#freeze ();
let array_of_children = ref [||] in
List.iter (fun c ->
(* we will just not display children that
match the filter rules *)
if not (self#filter c) then
array_of_children := Array.append !array_of_children [|c|]
) l;
let length = Array.length !array_of_children in
let new_nitems = nitems + length in
let new_items = Array.make new_nitems {data = i.data; children = []} in
Array.blit items 0 new_items 0 (row + 1);
Array.blit !array_of_children 0 new_items (row + 1) length;
Array.blit items (row + 1) new_items (row + length + 1) (nitems - row - 1);
let new_contents = Array.make new_nitems dummy_line in
Array.blit contents 0 new_contents 0 (row + 1);
Array.blit contents row new_contents (row + length + 1) (nitems - row - 1);
nitems <- new_nitems;
items <- new_items;
contents <- new_contents;
for r = 0 to length - 1 do
self#insert ~row:(row + r + 1) items.(row + r + 1)
done;
is_expanded <- ((get_key i), length)::is_expanded;
wlist#thaw ();
true
end
end
else true
method collapse i =
if (List.mem_assoc (get_key i) is_expanded) then
begin
wlist#freeze ();
let (row, _) = self#find (get_key i) in
let length = List.assoc (get_key i) is_expanded in
let new_nitems = nitems - length in
let new_items = Array.make new_nitems {data = i.data; children = []} in
Array.blit items 0 new_items 0 (row + 1);
Array.blit items (row + length + 1) new_items (row + 1) (nitems - row - length - 1);
let new_contents = Array.make new_nitems dummy_line in
Array.blit contents 0 new_contents 0 (row + 1);
Array.blit contents (row + length + 1) new_contents (row + 1) (nitems - row - length - 1);
nitems <- new_nitems;
items <- new_items;
contents <- new_contents;
for r = 0 to (length - 1) do
self#wlist#remove (row + 1)
done;
is_expanded <- List.remove_assoc (get_key i) is_expanded;
wlist#thaw ();
true
end
else true
method update =
wlist#freeze ();
wlist#clear ();
self#sort;
selection <- [];
for i = 0 to nitems - 1 do
self#insert items.(i);
done;
(* the autosize function increases tremendeously
the time to display the items with pixmaps depending
on the column size. So I suppressed it *)
(* self#wlist#columns_autosize ();*)
wlist#thaw ()
method clear =
wlist#clear ();
nitems <- 0;
items <- [||];
contents <- [||];
filtered <- Intmap.empty;
selection <- []
method menu = ([] : GToolbox.menu_entry list)
method private connect_events =
let check_double_click event d =
(
match event with
None -> ()
| Some ev ->
let t = GdkEvent.get_type ev in
match t with
`TWO_BUTTON_PRESS -> self#on_double_click d
| _ -> ()
)
in
let f_select_table ~row ~column ~event =
try
let d = items.(row) in
selection <- d ::
(List.filter (fun d2 -> d <> d2) selection);
self#on_select d;
check_double_click event d
with Failure _ -> ()
in
let f_unselect_table ~row ~column ~event =
try
let d = items.(row) in
selection <-
(List.filter (fun d2 -> d <> d2) selection);
self#on_deselect d;
check_double_click event d
with Failure _ -> ()
in
ignore (wlist#connect#select_row f_select_table);
ignore (wlist#connect#unselect_row f_unselect_table);
ignore (wlist#connect#click_column
(fun c ->
(* GToolbox.autosize_clist self#wlist; *)
self#resort_column c ()
)
);
(* connect the press on button 3 for contextual menu *)
ignore (wlist#event#connect#button_press ~callback:
(
fun ev ->
GdkEvent.Button.button ev = 3 &&
GdkEvent.get_type ev = `BUTTON_PRESS &&
(
GAutoconf.popup_menu
~button: 1
~time: 0
~entries: self#menu;
true
)
)
);
(* connect the press on button 3 for title contextual menu *)
for col = 0 to wlist#columns - 1 do
let w = wlist#column_widget col in
let b = Widget.get_ancestor w#as_widget (Type.from_name "GtkButton") in
let button = new GButton.button (Object.unsafe_cast b) in
ignore (button#event#connect#button_press ~callback:
(
fun ev ->
GdkEvent.Button.button ev = 3 &&
GdkEvent.get_type ev = `BUTTON_PRESS &&
(
GAutoconf.popup_menu
~button: 1
~time: 0
~entries: (self#column_menu col);
true
)
)
);
(* connect the columns resizing to draw what could need a column width *)
ignore (w#misc#connect#size_allocate ~callback:
(fun rect ->
let width = rect.width in
if col < (wlist#columns - 1)
then columns_width <- List.append columns_width [(col, width)]
else begin
columns_width <- List.append columns_width [(col, width)];
self#has_changed_width columns_width;
columns_width <- []
end
));
done;
initializer
self#connect_events;
self#wlist#columns_autosize ()
method resort_column i () =
let n = i + 1 in
if current_sort = n or (- current_sort) = n then
current_sort <- (- current_sort)
else
current_sort <- n;
self#update
method column_menu i =
[
`I ("sort", self#resort_column i);
]
method has_changed_width l = ()
method find key =
let rec iter i len =
if i = len then
if (List.length key) = 1 then
(-1, Intmap.find (List.hd key) filtered)
else raise Not_found
else
if get_key items.(i) = key then (i, items.(i)) else
iter (i+1) len
in
iter 0 nitems
method get_data n =
if (n > nitems) || (n < 0) then
raise Not_found
else items.(n)
method get_all_items =
let l = ref [] in
l := Intmap.to_list filtered;
for n = 0 to (nitems - 1) do
l := items.(n)::!l
done;
!l
method add_item i =
if self#filter i then
self#add_filtered_item i
else begin
let pos = nitems in
self#add_hidden_item i;
self#insert ~row: pos i;
end
method size = nitems + nfiltered
method private add_hidden_item i =
if nitems = Array.length items then begin
let nis = nitems * 2 + 8 in
let is = Array.make nis i in
Array.blit items 0 is 0 nitems;
contents <- Array.make nis dummy_line;
items <- is
end else begin
items.(nitems) <- i;
contents.(nitems) <- dummy_line;
end;
nitems <- nitems+1
method private add_filtered_item i =
if (List.length (get_key i)) = 1 then
begin
let key = List.hd (get_key i) in
filtered <- Intmap.add key i filtered;
nfiltered <- nfiltered + 1
end
method refresh_filter =
let filter = self#filter in
let add_filtered_item = self#add_filtered_item in
let add_hidden_item = self#add_hidden_item in
let old_items = Array.sub items 0 nitems in
let old_map = filtered in
(* freeze & clear reverted to show the user that
something appened if it takes too long time *)
wlist#clear ();
wlist#freeze ();
nitems <- 0;
filtered <- Intmap.empty;
selection <- [];
nfiltered <- 0;
items <- [||];
contents <- [||];
Array.iter (fun i ->
if filter i then
add_filtered_item i
else
add_hidden_item i
) old_items;
Intmap.iter (fun _ i ->
if filter i then
add_filtered_item i
else
add_hidden_item i
) old_map;
self#sort;
for i = 0 to nitems - 1 do
self#insert items.(i)
done;
self#wlist#columns_autosize ();
wlist#thaw ()
method reset_data data =
let filter = self#filter in
let add_filtered_item = self#add_filtered_item in
let add_hidden_item = self#add_hidden_item in
(* freeze & clear reverted to show the user that
something appened if it takes too long time *)
wlist#clear ();
wlist#freeze ();
nitems <- 0;
filtered <- Intmap.empty;
nfiltered <- 0;
selection <- [];
items <- [||];
contents <- [||];
List.iter (fun i ->
if filter i then
add_filtered_item i
else
add_hidden_item i
) data;
self#sort;
for i = 0 to nitems - 1 do
self#insert items.(i)
done;
self#wlist#columns_autosize ();
wlist#thaw ()
method virtual filter : 'a -> bool
method refresh_item old_pos i =
let old_filtered = old_pos < 0 in
let new_filtered = self#filter i in
match old_filtered, new_filtered with
true, false ->
if (List.length (get_key i)) = 1 then
begin
let key = List.hd (get_key i) in
filtered <- Intmap.remove key filtered;
nfiltered <- nfiltered - 1;
let pos = nitems in
self#add_hidden_item i;
self#insert ~row:pos i;
end
| false, true ->
Array.blit items (old_pos+1) items old_pos (nitems - old_pos - 1);
Array.blit contents (old_pos+1) contents old_pos (nitems - old_pos - 1);
nitems <- nitems - 1;
items <- Array.sub items 0 nitems;
contents <- Array.sub contents 0 nitems;
self#wlist#remove old_pos;
selection <- List.filter (fun fi -> get_key fi <> get_key i) selection;
if (List.length (get_key i)) = 1 then
self#add_filtered_item i
| false, _ ->
self#update_row i old_pos
| _ -> ()
method remove_item pos i =
if pos < 0 then
begin
if (List.length (get_key i)) = 1 then
begin
let key = List.hd (get_key i) in
filtered <- Intmap.remove key filtered;
nfiltered <- nfiltered - 1
end
end else
begin
let b = if (List.mem_assoc (get_key i) is_expanded) then
self#collapse i
else false
in
self#wlist#remove pos;
Array.blit items (pos+1) items pos (nitems - pos - 1);
Array.blit contents (pos+1) contents pos (nitems - pos - 1);
nitems <- nitems - 1;
items <- Array.sub items 0 nitems;
contents <- Array.sub contents 0 nitems;
selection <- List.filter (fun fi -> get_key fi <> get_key i) selection
end
method iter (f : 'a -> unit) =
for i = 0 to nitems - 1 do
f items.(i)
done
end
|
{
"pile_set_name": "Github"
}
|
<?php
namespace Illuminate\Contracts\Cache;
interface Store
{
/**
* Retrieve an item from the cache by key.
*
* @param string|array $key
* @return mixed
*/
public function get($key);
/**
* Retrieve multiple items from the cache by key.
*
* Items not found in the cache will have a null value.
*
* @param array $keys
* @return array
*/
public function many(array $keys);
/**
* Store an item in the cache for a given number of seconds.
*
* @param string $key
* @param mixed $value
* @param int $seconds
* @return bool
*/
public function put($key, $value, $seconds);
/**
* Store multiple items in the cache for a given number of seconds.
*
* @param array $values
* @param int $seconds
* @return bool
*/
public function putMany(array $values, $seconds);
/**
* Increment the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return int|bool
*/
public function increment($key, $value = 1);
/**
* Decrement the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return int|bool
*/
public function decrement($key, $value = 1);
/**
* Store an item in the cache indefinitely.
*
* @param string $key
* @param mixed $value
* @return bool
*/
public function forever($key, $value);
/**
* Remove an item from the cache.
*
* @param string $key
* @return bool
*/
public function forget($key);
/**
* Remove all items from the cache.
*
* @return bool
*/
public function flush();
/**
* Get the cache key prefix.
*
* @return string
*/
public function getPrefix();
}
|
{
"pile_set_name": "Github"
}
|
{"1179": 0.23512073149405358}
{"1106": 0.228654571409621}
{"652": 0.26706320871106765}
{"617": 0.25888070620540204}
{"529": 0.23796719398186578}
{"1336": 0.22708931518452144}
{"560": 0.2612410483304467}
{"569": 0.25344843499981895, "556": 0.24737922264439613}
{"864": 0.22093242105651731, "1369": 0.21443143954958546, "76": 0.40886685944828904, "1239": 0.21973134129865812}
{"578": 0.24341360801328762}
{"565": 0.22537008065000699}
{"565": 0.22537008065000699}
{"852": 0.24665007174833561}
{"585": 0.20568709444011163, "593": 0.2111648504919568}
{"798": 0.23752138082151483}
{"1146": 0.26372473331822505}
{"970": 0.49241241628743165}
{"565": 0.22537008065000699}
{"1179": 0.23512073149405358}
{"1434": 0.24199816170253058}
{"137": 0.2303888589730046}
{"1310": 0.23764658131335351}
{"1430": 0.25725355551917889}
{"631": 0.22755810285217448}
{"694": 0.23557849339442957}
{"64": 0.24006964581180151}
{"1006": 0.41449628448151665}
{"674": 0.24046207318157189}
{"523": 0.2326400032896663}
{"523": 0.2326400032896663}
{"293": 0.25487102517929688}
{"745": 0.25646022913234029}
{"964": 0.24960912218491935}
{"899": 0.23962299579755325}
{"678": 0.47617484462379728}
{"1409": 0.22876936141504556}
{"500": 0.25316108127895848}
{"935": 0.25024624638360504}
{"694": 0.23557849339442957}
{"930": 0.24397712364164292}
{"842": 0.24971400597247123}
{"41": 0.23893312924561128}
{"500": 0.25316108127895848}
{"10": 0.23406045565083938}
{"938": 0.24081849542597181}
{"849": 0.21599952923357182, "1042": 0.21691626531835001, "1449": 0.22383080563615174, "1141": 0.21833538294901292, "247": 0.22693284763697358}
{"560": 0.2612410483304467}
{"567": 0.23239051559499777}
{"44": 0.25088912095966992}
{"578": 0.24341360801328762}
{"925": 0.24438902348815275}
{"685": 0.2407830851122072, "678": 0.22537824222837052}
{"1012": 0.25750021664711448, "678": 0.22537824222837052}
{"852": 0.24665007174833561}
{"151": 0.26128454362670561}
{"527": 0.24300391288770593}
{"1347": 0.22790454872534552, "1175": 0.22357866579787608}
{"942": 0.23721967139914463}
{"141": 0.25581976709249948}
{"788": 0.23779520229913709}
{"578": 0.24341360801328762}
{"969": 0.24555643831723051}
{"930": 0.24397712364164292}
{"578": 0.24341360801328762}
{"593": 0.22307253104567326}
{"565": 0.22537008065000699}
{"36": 0.23543685280498811}
{"952": 0.26686593300373918}
{"738": 0.45426349478116546}
{"44": 0.25088912095966992}
{"694": 0.23557849339442957}
{"915": 0.26148178514411891}
{"694": 0.23557849339442957}
{"576": 0.18564556757965958, "548": 0.18541124832192993, "581": 0.18863738882564113, "519": 0.18882982873769058, "1143": 0.17801192740093244, "492": 0.19238649675442196, "525": 0.18378408000683025, "498": 0.18214579951657511, "633": 0.1897550190960772, "535": 0.1838247094663058, "185": 0.18795764874691565, "603": 0.18373198921238931, "540": 0.19083171449275435, "574": 0.1789275813611691}
{"1123": 0.24285689571356381}
{"1347": 0.24075618836441365}
{"1457": 0.23949186744617962}
{"631": 0.22755810285217448}
{"1007": 0.2437537198484607}
{"1313": 0.25105740996079901}
{"137": 0.2303888589730046}
{"585": 0.43457176375036721}
{"496": 0.24591901488043832, "619": 0.2407540709168863}
{"1325": 0.2637374022414995}
{"44": 0.25088912095966992}
{"560": 0.2612410483304467}
{"529": 0.23796719398186578}
{"798": 0.23752138082151483}
{"509": 0.25746384133671257}
{"631": 0.22755810285217448}
{"336": 0.23998904711335559}
{"857": 0.24721943813444125}
{"1123": 0.24285689571356381}
{"102": 0.39871020965426923}
{"921": 0.23885438399743503, "692": 0.2692890122309623}
{"1061": 0.23418589807881479}
{"513": 0.2421764047236647}
{"1019": 0.46394596718371534}
{"951": 0.23480360996586586}
{"1000": 0.40487795347937966, "988": 0.43438296548875571}
|
{
"pile_set_name": "Github"
}
|
// 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.
import 'package:flutter_web/gestures.dart';
import 'package:test/test.dart';
typedef void GestureArenaCallback(Object key);
const int primaryKey = 4;
class TestGestureArenaMember extends GestureArenaMember {
bool acceptRan = false;
@override
void acceptGesture(int key) {
expect(key, equals(primaryKey));
acceptRan = true;
}
bool rejectRan = false;
@override
void rejectGesture(int key) {
expect(key, equals(primaryKey));
rejectRan = true;
}
}
class GestureTester {
GestureArenaManager arena = new GestureArenaManager();
TestGestureArenaMember first = new TestGestureArenaMember();
TestGestureArenaMember second = new TestGestureArenaMember();
GestureArenaEntry firstEntry;
void addFirst() {
firstEntry = arena.add(primaryKey, first);
}
GestureArenaEntry secondEntry;
void addSecond() {
secondEntry = arena.add(primaryKey, second);
}
void expectNothing() {
expect(first.acceptRan, isFalse);
expect(first.rejectRan, isFalse);
expect(second.acceptRan, isFalse);
expect(second.rejectRan, isFalse);
}
void expectFirstWin() {
expect(first.acceptRan, isTrue);
expect(first.rejectRan, isFalse);
expect(second.acceptRan, isFalse);
expect(second.rejectRan, isTrue);
}
void expectSecondWin() {
expect(first.acceptRan, isFalse);
expect(first.rejectRan, isTrue);
expect(second.acceptRan, isTrue);
expect(second.rejectRan, isFalse);
}
}
void main() {
test('Should win by accepting', () {
final GestureTester tester = new GestureTester();
tester.addFirst();
tester.addSecond();
tester.arena.close(primaryKey);
tester.expectNothing();
tester.firstEntry.resolve(GestureDisposition.accepted);
tester.expectFirstWin();
});
test('Should win by sweep', () {
final GestureTester tester = new GestureTester();
tester.addFirst();
tester.addSecond();
tester.arena.close(primaryKey);
tester.expectNothing();
tester.arena.sweep(primaryKey);
tester.expectFirstWin();
});
test('Should win on release after hold sweep release', () {
final GestureTester tester = new GestureTester();
tester.addFirst();
tester.addSecond();
tester.arena.close(primaryKey);
tester.expectNothing();
tester.arena.hold(primaryKey);
tester.expectNothing();
tester.arena.sweep(primaryKey);
tester.expectNothing();
tester.arena.release(primaryKey);
tester.expectFirstWin();
});
test('Should win on sweep after hold release sweep', () {
final GestureTester tester = new GestureTester();
tester.addFirst();
tester.addSecond();
tester.arena.close(primaryKey);
tester.expectNothing();
tester.arena.hold(primaryKey);
tester.expectNothing();
tester.arena.release(primaryKey);
tester.expectNothing();
tester.arena.sweep(primaryKey);
tester.expectFirstWin();
});
test('Only first winner should win', () {
final GestureTester tester = new GestureTester();
tester.addFirst();
tester.addSecond();
tester.arena.close(primaryKey);
tester.expectNothing();
tester.firstEntry.resolve(GestureDisposition.accepted);
tester.secondEntry.resolve(GestureDisposition.accepted);
tester.expectFirstWin();
});
test('Only first winner should win, regardless of order', () {
final GestureTester tester = new GestureTester();
tester.addFirst();
tester.addSecond();
tester.arena.close(primaryKey);
tester.expectNothing();
tester.secondEntry.resolve(GestureDisposition.accepted);
tester.firstEntry.resolve(GestureDisposition.accepted);
tester.expectSecondWin();
});
test('Win before close is delayed to close', () {
final GestureTester tester = new GestureTester();
tester.addFirst();
tester.addSecond();
tester.expectNothing();
tester.firstEntry.resolve(GestureDisposition.accepted);
tester.expectNothing();
tester.arena.close(primaryKey);
tester.expectFirstWin();
});
test('Win before close is delayed to close, and only first winner should win',
() {
final GestureTester tester = new GestureTester();
tester.addFirst();
tester.addSecond();
tester.expectNothing();
tester.firstEntry.resolve(GestureDisposition.accepted);
tester.secondEntry.resolve(GestureDisposition.accepted);
tester.expectNothing();
tester.arena.close(primaryKey);
tester.expectFirstWin();
});
test(
'Win before close is delayed to close, and only first winner should '
'win, regardless of order', () {
final GestureTester tester = new GestureTester();
tester.addFirst();
tester.addSecond();
tester.expectNothing();
tester.secondEntry.resolve(GestureDisposition.accepted);
tester.firstEntry.resolve(GestureDisposition.accepted);
tester.expectNothing();
tester.arena.close(primaryKey);
tester.expectSecondWin();
});
}
|
{
"pile_set_name": "Github"
}
|
(ns search-relevancy-test.top-n
"Functions for running search relevancy tests of the form - I expect collection X to be in the
top N collections returned when searching for Z."
(:require
[clj-http.client :as client]
[clojure.data.xml :as xml]
[cmr.common.config :refer [defconfig]]
[search-relevancy-test.core :as core]
[search-relevancy-test.reporter :as reporter]))
(defconfig cmr-search-url
"Base URL for performing CMR searches."
{:default "https://cmr.earthdata.nasa.gov/search"})
(def standard-params-string
"Query parameters to use for every query"
"page_size=2000")
(defn get-concept-id-from-reference
"Returns a concept-id from a reference XML element."
[reference]
(->> reference
(filter #(= :id (:tag %)))
first
:content
first))
(defn get-position-in-references
"Returns the position that the concept-id is found in within the references results. If not found
in the results at all return nil."
[test-concept-id references]
(first
(keep-indexed (fn [idx reference]
(let [concept-id (get-concept-id-from-reference reference)]
(when (= test-concept-id concept-id)
(inc idx))))
references)))
(defn get-xml-references
"Returns the XML references for the given request URL."
[request-url]
(->> (client/get request-url)
:body
xml/parse-str
:content
(filter #(= :references (:tag %)))
first
:content
(map :content)))
(defn perform-subtest
"Performs a subtest for an anomaly test."
[test]
(let [url (format "%s/collections?%s&%s" (cmr-search-url) standard-params-string (:search test))
references (get-xml-references url)
position (get-position-in-references (:concept-id test) references)
desired-position (Integer/parseInt (:position test))
passed? (and (not (nil? position))
(<= position desired-position))
result {:pass passed?
:anomaly (:anomaly test)
:test (:test test)
:actual position
:desired desired-position}]
(reporter/print-top-n-test-result test result)
result))
(defn perform-anomaly-test
"Performs all of the subtests for a top N anomaly test."
[anomaly->subtests]
(let [subtests (val anomaly->subtests)]
(reporter/print-start-of-anomaly-tests (key anomaly->subtests) (count subtests))
(mapv perform-subtest subtests)))
(defn get-tests-from-filename
"Returns a map of anomaly number to tests for that anomaly by parsing the CSV file for the passed
in filename."
[filename]
(sort core/string-key-to-int-sort
(group-by :anomaly (core/read-anomaly-test-csv filename))))
(defn run-top-n-tests
"Run all of the top N tests from the CSV file"
[filename]
(let [top-n-tests (get-tests-from-filename filename)
results (doall (mapcat perform-anomaly-test top-n-tests))]
(reporter/print-top-n-results-summary results)
results))
(comment
(run-top-n-tests "top_n_tests.csv"))
|
{
"pile_set_name": "Github"
}
|
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class ServiceTestCase(IntegrationTestCase):
def test_list_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.serverless.v1.services.list()
self.holodeck.assert_has_request(Request(
'get',
'https://serverless.twilio.com/v1/Services',
))
def test_read_empty_response(self):
self.holodeck.mock(Response(
200,
'''
{
"services": [],
"meta": {
"first_page_url": "https://serverless.twilio.com/v1/Services?PageSize=50&Page=0",
"key": "services",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
"url": "https://serverless.twilio.com/v1/Services?PageSize=50&Page=0"
}
}
'''
))
actual = self.client.serverless.v1.services.list()
self.assertIsNotNone(actual)
def test_fetch_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.holodeck.assert_has_request(Request(
'get',
'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
))
def test_fetch_response(self):
self.holodeck.mock(Response(
200,
'''
{
"sid": "ZS00000000000000000000000000000000",
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"friendly_name": "test-service",
"unique_name": "test-service-1",
"include_credentials": true,
"ui_editable": false,
"date_created": "2018-11-10T20:00:00Z",
"date_updated": "2018-11-10T20:00:00Z",
"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000",
"links": {
"environments": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments",
"functions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions",
"assets": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets",
"builds": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds"
}
}
'''
))
actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.assertIsNotNone(actual)
def test_delete_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
self.holodeck.assert_has_request(Request(
'delete',
'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
))
def test_delete_response(self):
self.holodeck.mock(Response(
204,
None,
))
actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").delete()
self.assertTrue(actual)
def test_create_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.serverless.v1.services.create(unique_name="unique_name", friendly_name="friendly_name")
values = {'UniqueName': "unique_name", 'FriendlyName': "friendly_name", }
self.holodeck.assert_has_request(Request(
'post',
'https://serverless.twilio.com/v1/Services',
data=values,
))
def test_create_response(self):
self.holodeck.mock(Response(
201,
'''
{
"sid": "ZS00000000000000000000000000000000",
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"friendly_name": "service-friendly",
"unique_name": "service-unique",
"include_credentials": true,
"ui_editable": false,
"date_created": "2018-11-10T20:00:00Z",
"date_updated": "2018-11-10T20:00:00Z",
"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000",
"links": {
"environments": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments",
"functions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions",
"assets": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets",
"builds": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds"
}
}
'''
))
actual = self.client.serverless.v1.services.create(unique_name="unique_name", friendly_name="friendly_name")
self.assertIsNotNone(actual)
def test_update_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update()
self.holodeck.assert_has_request(Request(
'post',
'https://serverless.twilio.com/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
))
def test_update_response(self):
self.holodeck.mock(Response(
200,
'''
{
"sid": "ZS00000000000000000000000000000000",
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"friendly_name": "service-friendly-update",
"unique_name": "service-unique-update",
"include_credentials": true,
"ui_editable": true,
"date_created": "2018-11-10T20:00:00Z",
"date_updated": "2018-11-10T20:00:00Z",
"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000",
"links": {
"environments": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments",
"functions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions",
"assets": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets",
"builds": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds"
}
}
'''
))
actual = self.client.serverless.v1.services("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update()
self.assertIsNotNone(actual)
|
{
"pile_set_name": "Github"
}
|
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core/auxiliary/brocade'
class MetasploitModule < Msf::Post
include Msf::Auxiliary::Brocade
include Msf::Exploit::Deprecated
moved_from 'post/brocade/gather/enum_brocade'
def initialize(info = {})
super(
update_info(
info,
'Name' => 'Brocade Gather Device General Information',
'Description' => %q{
This module collects Brocade device information and configuration.
This module has been tested against an icx6430 running 08.0.20T311.
},
'License' => MSF_LICENSE,
'Author' => [ 'h00die'],
'Platform' => [ 'brocade'],
'SessionTypes' => [ 'shell' ]
)
)
end
def run
# Get device prompt
prompt = session.shell_command("\n")
if prompt.end_with?('(config)#') # config shell
vprint_status('In a config cli')
session.shell_write("skip-page-display\n")
session.shell_write("terminal length 0\n")
elsif prompt.end_with?('#') # regular cli shell (non-config)
vprint_status('In an enabled cli')
session.shell_write("skip-page-display\n")
session.shell_write("terminal length 0\n")
elsif prompt.end_with?('>') # cli not enabled
vprint_status('In a non-enabled cli')
end
# attempt to disable paging, cli not enabled this will fail anyways
session.shell_write("skip-page-display\n")
session.shell_write("terminal length 0\n")
# Get version info
print_status('Getting version information')
version_out = session.shell_command("show version\n")
if /^, Version: (?<ver>.+) | SW: Version (?<ver>.+) /i =~ version_out
vprint_status("OS: #{ver}")
end
ver_loc = store_loot('brocade.version',
'text/plain',
session,
version_out.strip,
'version.txt',
'Brocade Version')
# Print the version of VERBOSE set to true.
vprint_good("Version information stored in to loot #{ver_loc}")
# run additional information gathering
enum_configs(prompt)
end
# run commands found in exec mode under privilege 1
def enum_configs(prompt)
host = session.session_host
port = session.session_port
exec_commands = [
{
'cmd' => 'show configuration',
'fn' => 'get_config',
'desc' => 'Get Device Config on Brocade Device'
},
]
exec_commands.each do |ec|
command = ec['cmd']
cmd_out = session.shell_command(command).gsub(/#{command}|#{prompt}/, '')
print_status("Gathering info from #{command}")
# detect if we're in pagination and get as much data as possible
if cmd_out.include?('--More--')
cmd_out += session.shell_command(" \n" * 20) # 20 pages *should* be enough
end
if ec['fn'] == 'get_config'
brocade_config_eater(host, port, cmd_out.strip)
else
cmd_loc = store_loot("brocade.#{ec['fn']}",
'text/plain',
session,
cmd_out.strip,
"#{ec['fn']}.txt",
ec['desc'])
vprint_good("Saving to #{cmd_loc}")
end
end
end
end
|
{
"pile_set_name": "Github"
}
|
<?php namespace Illuminate\Queue;
use Illuminate\Redis\Database;
use Illuminate\Queue\Jobs\RedisJob;
class RedisQueue extends Queue implements QueueInterface {
/**
* The Redis database instance.
*
* @var \Illuminate\Redis\Database
*/
protected $redis;
/**
* The connection name.
*
* @var string
*/
protected $connection;
/**
* The name of the default queue.
*
* @var string
*/
protected $default;
/**
* Create a new Redis queue instance.
*
* @param \Illuminate\Redis\Database $redis
* @param string $default
* @param string $connection
* @return void
*/
public function __construct(Database $redis, $default = 'default', $connection = null)
{
$this->redis = $redis;
$this->default = $default;
$this->connection = $connection;
}
/**
* Push a new job onto the queue.
*
* @param string $job
* @param mixed $data
* @param string $queue
* @return void
*/
public function push($job, $data = '', $queue = null)
{
return $this->pushRaw($this->createPayload($job, $data), $queue);
}
/**
* Push a raw payload onto the queue.
*
* @param string $payload
* @param string $queue
* @param array $options
* @return mixed
*/
public function pushRaw($payload, $queue = null, array $options = array())
{
$this->redis->rpush($this->getQueue($queue), $payload);
return array_get(json_decode($payload, true), 'id');
}
/**
* Push a new job onto the queue after a delay.
*
* @param \DateTime|int $delay
* @param string $job
* @param mixed $data
* @param string $queue
* @return void
*/
public function later($delay, $job, $data = '', $queue = null)
{
$payload = $this->createPayload($job, $data);
$delay = $this->getSeconds($delay);
$this->redis->zadd($this->getQueue($queue).':delayed', $this->getTime() + $delay, $payload);
return array_get(json_decode($payload, true), 'id');
}
/**
* Release a reserved job back onto the queue.
*
* @param string $queue
* @param string $payload
* @param int $delay
* @param int $attempts
* @return void
*/
public function release($queue, $payload, $delay, $attempts)
{
$payload = $this->setMeta($payload, 'attempts', $attempts);
$this->redis->zadd($this->getQueue($queue).':delayed', $this->getTime() + $delay, $payload);
}
/**
* Pop the next job off of the queue.
*
* @param string $queue
* @return \Illuminate\Queue\Jobs\Job|null
*/
public function pop($queue = null)
{
$original = $queue ?: $this->default;
$this->migrateAllExpiredJobs($queue = $this->getQueue($queue));
$job = $this->redis->lpop($queue);
if ( ! is_null($job))
{
$this->redis->zadd($queue.':reserved', $this->getTime() + 60, $job);
return new RedisJob($this->container, $this, $job, $original);
}
}
/**
* Delete a reserved job from the queue.
*
* @param string $queue
* @param string $job
* @return void
*/
public function deleteReserved($queue, $job)
{
$this->redis->zrem($this->getQueue($queue).':reserved', $job);
}
/**
* Migrate all of the waiting jobs in the queue.
*
* @param string $queue
* @return void
*/
protected function migrateAllExpiredJobs($queue)
{
$this->migrateExpiredJobs($queue.':delayed', $queue);
$this->migrateExpiredJobs($queue.':reserved', $queue);
}
/**
* Migrate the delayed jobs that are ready to the regular queue.
*
* @param string $from
* @param string $to
* @return void
*/
public function migrateExpiredJobs($from, $to)
{
$options = ['cas' => true, 'watch' => $from, 'retry' => 10];
$this->redis->transaction($options, function ($transaction) use ($from, $to)
{
// First we need to get all of jobs that have expired based on the current time
// so that we can push them onto the main queue. After we get them we simply
// remove them from this "delay" queues. All of this within a transaction.
$jobs = $this->getExpiredJobs(
$transaction, $from, $time = $this->getTime()
);
// If we actually found any jobs, we will remove them from the old queue and we
// will insert them onto the new (ready) "queue". This means they will stand
// ready to be processed by the queue worker whenever their turn comes up.
if (count($jobs) > 0)
{
$this->removeExpiredJobs($transaction, $from, $time);
$this->pushExpiredJobsOntoNewQueue($transaction, $to, $jobs);
}
});
}
/**
* Get the expired jobs from a given queue.
*
* @param \Predis\Transaction\MultiExec $transaction
* @param string $from
* @param int $time
* @return array
*/
protected function getExpiredJobs($transaction, $from, $time)
{
return $transaction->zrangebyscore($from, '-inf', $time);
}
/**
* Remove the expired jobs from a given queue.
*
* @param \Predis\Transaction\MultiExec $transaction
* @param string $from
* @param int $time
* @return void
*/
protected function removeExpiredJobs($transaction, $from, $time)
{
$transaction->multi();
$transaction->zremrangebyscore($from, '-inf', $time);
}
/**
* Push all of the given jobs onto another queue.
*
* @param \Predis\Transaction\MultiExec $transaction
* @param string $to
* @param array $jobs
* @return void
*/
protected function pushExpiredJobsOntoNewQueue($transaction, $to, $jobs)
{
call_user_func_array([$transaction, 'rpush'], array_merge([$to], $jobs));
}
/**
* Create a payload string from the given job and data.
*
* @param string $job
* @param mixed $data
* @param string $queue
* @return string
*/
protected function createPayload($job, $data = '', $queue = null)
{
$payload = parent::createPayload($job, $data);
$payload = $this->setMeta($payload, 'id', $this->getRandomId());
return $this->setMeta($payload, 'attempts', 1);
}
/**
* Get a random ID string.
*
* @return string
*/
protected function getRandomId()
{
return str_random(32);
}
/**
* Get the queue or return the default.
*
* @param string|null $queue
* @return string
*/
protected function getQueue($queue)
{
return 'queues:'.($queue ?: $this->default);
}
/**
* Get the underlying Redis instance.
*
* @return \Illuminate\Redis\Database
*/
public function getRedis()
{
return $this->redis;
}
}
|
{
"pile_set_name": "Github"
}
|
'use strict';
var expect = require('expect.js'),
KdbxUuid = require('../../lib/format/kdbx-uuid');
describe('KdbxUuid', function () {
it('creates uuid from 16 bytes ArrayBuffer', function () {
var uuid = new KdbxUuid(
new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6]).buffer
);
expect(uuid.id).to.be('AQIDBAUGBwgJCgECAwQFBg==');
});
it('creates uuid from 16 bytes array', function () {
var uuid = new KdbxUuid(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6]));
expect(uuid.id).to.be('AQIDBAUGBwgJCgECAwQFBg==');
});
it('creates uuid base64 string', function () {
var uuid = new KdbxUuid('AQIDBAUGBwgJCgECAwQFBg==');
expect(uuid.id).to.be('AQIDBAUGBwgJCgECAwQFBg==');
});
it('creates undefined uuid from less than 16 bytes', function () {
var uuid = new KdbxUuid(new Uint16Array([123]).buffer);
expect(uuid.id).to.be(undefined);
});
it('creates undefined uuid from falsy', function () {
var uuid = new KdbxUuid(0);
expect(uuid.id).to.be(undefined);
});
it('returns uuid in toString method', function () {
var uuid = new KdbxUuid(
new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6]).buffer
);
expect(uuid.toString()).to.be('AQIDBAUGBwgJCgECAwQFBg==');
});
it('returns uuid in valueOf method', function () {
var uuid = new KdbxUuid(
new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6]).buffer
);
expect(uuid.valueOf()).to.be('AQIDBAUGBwgJCgECAwQFBg==');
});
it('allows to be used as hash key', function () {
var uuid1 = new KdbxUuid(
new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6]).buffer
);
var uuid2 = new KdbxUuid(
new Uint8Array([2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6]).buffer
);
var hashTable = {};
hashTable[uuid1] = 1;
hashTable[uuid2] = 2;
expect(hashTable[uuid1]).to.be(1);
expect(hashTable[uuid2]).to.be(2);
});
it('creates empty uuid from no arg', function () {
var uuid = new KdbxUuid();
expect(uuid.toString()).to.be('AAAAAAAAAAAAAAAAAAAAAA==');
expect(uuid.empty).to.be(true);
});
it('sets empty property for empty uuid', function () {
var uuid = new KdbxUuid(new Uint8Array(16).buffer);
expect(uuid.toString()).to.be('AAAAAAAAAAAAAAAAAAAAAA==');
expect(uuid.empty).to.be(true);
});
it('returns bytes in toBytes method', function () {
var bytes = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6]);
var uuid = new KdbxUuid(bytes.buffer);
expect(uuid.toBytes()).to.be.eql(bytes);
});
it('returns bytes in bytes property', function () {
var bytes = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6]);
var uuid = new KdbxUuid(bytes.buffer);
expect(uuid.bytes).to.be.eql(bytes);
});
it('returns bytes in toBytes method for empty value', function () {
var uuid = new KdbxUuid();
expect(uuid.toBytes()).to.be.eql([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
});
it('returns undefined in toBytes method for vad value', function () {
var bytes = new Uint8Array([1, 2, 3, 4, 5]);
var uuid = new KdbxUuid(bytes.buffer);
expect(uuid.toBytes()).to.be(undefined);
});
it('generates random uuid', function () {
var uuid = KdbxUuid.random();
expect(uuid).to.be.a(KdbxUuid);
expect(uuid.toString()).not.to.be('AAAAAAAAAAAAAAAAAAAAAA==');
});
it('checks equality', function () {
var uuid = new KdbxUuid(
new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6]).buffer
);
expect(uuid.equals('AQIDBAUGBwgJCgECAwQFBg==')).to.be(true);
expect(uuid.equals(new KdbxUuid('AQIDBAUGBwgJCgECAwQFBg=='))).to.be(true);
expect(uuid.equals(null)).to.be(false);
expect(uuid.equals(undefined)).to.be(false);
expect(uuid.equals('???')).to.be(false);
expect(uuid.equals(new KdbxUuid())).to.be(false);
});
});
|
{
"pile_set_name": "Github"
}
|
using UnityEngine;
using System.Collections;
using LuaInterface;
public class TestLuaThread : MonoBehaviour
{
string script =
@"
function fib(n)
local a, b = 0, 1
while n > 0 do
a, b = b, a + b
n = n - 1
end
return a
end
function CoFunc(len)
print('Coroutine started')
local i = 0
for i = 0, len, 1 do
local flag = coroutine.yield(fib(i))
if not flag then
break
end
end
print('Coroutine ended')
end
function Test()
local co = coroutine.create(CoFunc)
return co
end
";
LuaState state = null;
LuaThread thread = null;
string tips = null;
void Start ()
{
#if UNITY_5 || UNITY_2017 || UNITY_2018
Application.logMessageReceived += ShowTips;
#else
Application.RegisterLogCallback(ShowTips);
#endif
new LuaResLoader();
state = new LuaState();
state.Start();
state.LogGC = true;
state.DoString(script);
LuaFunction func = state.GetFunction("Test");
func.BeginPCall();
func.PCall();
thread = func.CheckLuaThread();
thread.name = "LuaThread";
func.EndPCall();
func.Dispose();
func = null;
thread.Resume(10);
}
void OnApplicationQuit()
{
if (thread != null)
{
thread.Dispose();
thread = null;
}
state.Dispose();
state = null;
#if UNITY_5 || UNITY_2017 || UNITY_2018
Application.logMessageReceived -= ShowTips;
#else
Application.RegisterLogCallback(null);
#endif
}
void ShowTips(string msg, string stackTrace, LogType type)
{
tips += msg;
tips += "\r\n";
}
void Update()
{
state.CheckTop();
state.Collect();
}
void OnGUI()
{
GUI.Label(new Rect(Screen.width / 2 - 300, Screen.height / 2 - 200, 600, 400), tips);
if (GUI.Button(new Rect(10, 50, 120, 40), "Resume Thead"))
{
int ret = -1;
if (thread != null && thread.Resume(true, out ret) == (int)LuaThreadStatus.LUA_YIELD)
{
Debugger.Log("lua yield: " + ret);
}
}
else if (GUI.Button(new Rect(10, 150, 120, 40), "Close Thread"))
{
if (thread != null)
{
thread.Dispose();
thread = null;
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
jasmine.TrivialReporter = function(doc) {
this.document = doc || document;
this.suiteDivs = {};
this.logRunningSpecs = false;
};
jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) {
var el = document.createElement(type);
for (var i = 2; i < arguments.length; i++) {
var child = arguments[i];
if (typeof child === 'string') {
el.appendChild(document.createTextNode(child));
} else {
if (child) { el.appendChild(child); }
}
}
for (var attr in attrs) {
if (attr == "className") {
el[attr] = attrs[attr];
} else {
el.setAttribute(attr, attrs[attr]);
}
}
return el;
};
jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) {
var showPassed, showSkipped;
this.outerDiv = this.createDom('div', { className: 'jasmine_reporter' },
this.createDom('div', { className: 'banner' },
this.createDom('div', { className: 'logo' },
this.createDom('a', { href: 'http://pivotal.github.com/jasmine/', target: "_blank" }, "Jasmine"),
this.createDom('span', { className: 'version' }, runner.env.versionString())),
this.createDom('div', { className: 'options' },
"Show ",
showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }),
this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "),
showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }),
this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped")
)
),
this.runnerDiv = this.createDom('div', { className: 'runner running' },
this.createDom('a', { className: 'run_spec', href: '?' }, "run all"),
this.runnerMessageSpan = this.createDom('span', {}, "Running..."),
this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, ""))
);
this.document.body.appendChild(this.outerDiv);
var suites = runner.suites();
for (var i = 0; i < suites.length; i++) {
var suite = suites[i];
var suiteDiv = this.createDom('div', { className: 'suite' },
this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"),
this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description));
this.suiteDivs[suite.id] = suiteDiv;
var parentDiv = this.outerDiv;
if (suite.parentSuite) {
parentDiv = this.suiteDivs[suite.parentSuite.id];
}
parentDiv.appendChild(suiteDiv);
}
this.startedAt = new Date();
var self = this;
showPassed.onclick = function(evt) {
if (showPassed.checked) {
self.outerDiv.className += ' show-passed';
} else {
self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, '');
}
};
showSkipped.onclick = function(evt) {
if (showSkipped.checked) {
self.outerDiv.className += ' show-skipped';
} else {
self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, '');
}
};
};
jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) {
var results = runner.results();
var className = (results.failedCount > 0) ? "runner failed" : "runner passed";
this.runnerDiv.setAttribute("class", className);
//do it twice for IE
this.runnerDiv.setAttribute("className", className);
var specs = runner.specs();
var specCount = 0;
for (var i = 0; i < specs.length; i++) {
if (this.specFilter(specs[i])) {
specCount++;
}
}
var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s");
message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s";
this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild);
this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString()));
};
jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) {
var results = suite.results();
var status = results.passed() ? 'passed' : 'failed';
if (results.totalCount == 0) { // todo: change this to check results.skipped
status = 'skipped';
}
this.suiteDivs[suite.id].className += " " + status;
};
jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) {
if (this.logRunningSpecs) {
this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
}
};
jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) {
var results = spec.results();
var status = results.passed() ? 'passed' : 'failed';
if (results.skipped) {
status = 'skipped';
}
var specDiv = this.createDom('div', { className: 'spec ' + status },
this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"),
this.createDom('a', {
className: 'description',
href: '?spec=' + encodeURIComponent(spec.getFullName()),
title: spec.getFullName()
}, spec.description));
var resultItems = results.getItems();
var messagesDiv = this.createDom('div', { className: 'messages' });
for (var i = 0; i < resultItems.length; i++) {
var result = resultItems[i];
if (result.type == 'log') {
messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString()));
} else if (result.type == 'expect' && result.passed && !result.passed()) {
messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message));
if (result.trace.stack) {
messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
}
}
}
if (messagesDiv.childNodes.length > 0) {
specDiv.appendChild(messagesDiv);
}
this.suiteDivs[spec.suite.id].appendChild(specDiv);
};
jasmine.TrivialReporter.prototype.log = function() {
var console = jasmine.getGlobal().console;
if (console && console.log) {
if (console.log.apply) {
console.log.apply(console, arguments);
} else {
console.log(arguments); // ie fix: console.log.apply doesn't exist on ie
}
}
};
jasmine.TrivialReporter.prototype.getLocation = function() {
return this.document.location;
};
jasmine.TrivialReporter.prototype.specFilter = function(spec) {
var paramMap = {};
var params = this.getLocation().search.substring(1).split('&');
for (var i = 0; i < params.length; i++) {
var p = params[i].split('=');
paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
}
if (!paramMap["spec"]) return true;
return spec.getFullName().indexOf(paramMap["spec"]) == 0;
};
|
{
"pile_set_name": "Github"
}
|
import Vue, { PluginObject } from 'vue';
import { TableType } from './table-type';
/**
* Registers Vuejs-Datatable components globally in VueJS.
*
* @example
* import { DatatableFactory } from 'vuejs-datatable';
* const myDatatableFactory = new DatatableFactory()
* .registerTableType( new TableType( 'my-table', {}) )
* Vue.use( myDatatableFactory );
*/
export declare class DatatableFactory implements PluginObject<void> {
/** A reference to the Vue instance the plugin is installed in. It may be used to check if the factory was already installed */
private vueInstance?;
/** Registry of declared table types. */
private readonly tableTypes;
/** The default table type to use if no other configuration was provided. */
private readonly defaultTableType;
/**
* Initialize the default factory
*/
constructor();
/**
* Get a table type by its identifier.
*
* @param id - The identifier of the table type. If not provided, it will default to the default table type.
* @returns the table type registered with that identifier.
*/
getTableType(id?: string): TableType<any> | undefined;
/**
* Controls the use of the default table type.
*
* @param use - `true` to use the default type, `false` otherwise.
* @returns `this` for chaining.
*/
useDefaultType(use: boolean): this;
/**
* Check if the factory uses the default table type.
*
* @returns a boolean indicating if the factory uses the default table type.
*/
useDefaultType(): boolean;
/**
* Creates a new table type with a specified prefix, that you can customize using a callback.
*
* @param nameOrTableType - The name of the component to register, or a [[TableType]] object.
* @param callback - An optional function to execute, that configures the newly created [[TableType]]. It takes a single parameter: the newly created [[TableType]], and should
* return the transformed table type.
* @returns `this` for chaining.
*/
registerTableType<TRow extends {} = {}, TSource = TRow[], TFiltered = TRow[], TSorted = TRow[], TPaged = TRow[]>(nameOrTableType: string | TableType<TRow, TSource, TFiltered, TSorted, TPaged>, callback?: (tableType: TableType<TRow, TSource, TFiltered, TSorted, TPaged>) => TableType<TRow, TSource, TFiltered, TSorted, TPaged> | undefined): this;
/**
* Creates a new table type with a specified prefix, that you can customize using a callback.
*
* @param nameOrTableType - The name of the component to register, or a [[TableType]] object.
* @returns `this` for chaining.
*/
deregisterTableType(nameOrTableType: string | TableType<any>): this;
/**
* Declares global components exported by vuejs-datatable, & load configs.
*
* @param Vue - The Vue instance to configure.
* @returns nothing.
*/
install(vue: typeof Vue): void;
/**
* Declares a pair of components (a Datatable & a Datatable-Pager) sharing a config.
*
* @param id - The base name of the datatable type.
* @param tableType - The configuration object that describes both datatable & the related pager.
* @returns `this` for chaining.
*/
private installTableType;
/**
* Remove a table type definition from vue (the datatable & its associated pager).
* This should be used carefully, because Vue won't be able to instanciate new instances of this table type.
*
* @param id - The base name of the datatable type to forget.
* @returns `this` for chaining.
*/
private uninstallTableType;
}
|
{
"pile_set_name": "Github"
}
|
package api
import (
"encoding/json"
"net/http"
"strconv"
"github.com/passwall/passwall-server/internal/app"
"github.com/passwall/passwall-server/internal/storage"
"github.com/passwall/passwall-server/model"
"github.com/gorilla/mux"
)
// FindAllEmails ...
func FindAllEmails(s storage.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var err error
emails := []model.Email{}
fields := []string{"id", "created_at", "updated_at", "email"}
argsStr, argsInt := SetArgs(r, fields)
schema := r.Context().Value("schema").(string)
emails, err = s.Emails().FindAll(argsStr, argsInt, schema)
if err != nil {
RespondWithError(w, http.StatusNotFound, err.Error())
return
}
// Encrypt payload
var payload model.Payload
key := r.Context().Value("transmissionKey").(string)
encrypted, err := app.EncryptJSON(key, emails)
if err != nil {
RespondWithError(w, http.StatusInternalServerError, err.Error())
return
}
payload.Data = string(encrypted)
RespondWithJSON(w, http.StatusOK, payload)
}
}
// FindEmailByID ...
func FindEmailByID(s storage.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
RespondWithError(w, http.StatusBadRequest, err.Error())
return
}
schema := r.Context().Value("schema").(string)
email, err := s.Emails().FindByID(uint(id), schema)
if err != nil {
RespondWithError(w, http.StatusNotFound, err.Error())
return
}
// Decrypt server side encrypted fields
decEmail, err := app.DecryptModel(email)
if err != nil {
RespondWithError(w, http.StatusInternalServerError, err.Error())
return
}
emailDTO := model.ToEmailDTO(decEmail.(*model.Email))
// Encrypt payload
var payload model.Payload
key := r.Context().Value("transmissionKey").(string)
encrypted, err := app.EncryptJSON(key, emailDTO)
if err != nil {
RespondWithError(w, http.StatusInternalServerError, err.Error())
return
}
payload.Data = string(encrypted)
RespondWithJSON(w, http.StatusOK, payload)
}
}
// CreateEmail ...
func CreateEmail(s storage.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
payload, err := ToPayload(r)
if err != nil {
RespondWithError(w, http.StatusBadRequest, InvalidRequestPayload)
return
}
defer r.Body.Close()
// Decrypt payload
var emailDTO model.EmailDTO
key := r.Context().Value("transmissionKey").(string)
err = app.DecryptJSON(key, []byte(payload.Data), &emailDTO)
if err != nil {
RespondWithError(w, http.StatusInternalServerError, err.Error())
return
}
schema := r.Context().Value("schema").(string)
createdEmail, err := app.CreateEmail(s, &emailDTO, schema)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
createdEmailDTO := model.ToEmailDTO(createdEmail)
// Encrypt payload
encrypted, err := app.EncryptJSON(key, createdEmailDTO)
if err != nil {
RespondWithError(w, http.StatusInternalServerError, err.Error())
return
}
payload.Data = string(encrypted)
RespondWithJSON(w, http.StatusOK, payload)
}
}
// UpdateEmail ...
func UpdateEmail(s storage.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
RespondWithError(w, http.StatusBadRequest, err.Error())
return
}
// Unmarshal request body to payload
var payload model.Payload
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&payload); err != nil {
RespondWithError(w, http.StatusBadRequest, InvalidRequestPayload)
return
}
defer r.Body.Close()
// Decrypt payload
var emailDTO model.EmailDTO
key := r.Context().Value("transmissionKey").(string)
err = app.DecryptJSON(key, []byte(payload.Data), &emailDTO)
if err != nil {
RespondWithError(w, http.StatusInternalServerError, err.Error())
return
}
schema := r.Context().Value("schema").(string)
email, err := s.Emails().FindByID(uint(id), schema)
if err != nil {
RespondWithError(w, http.StatusNotFound, err.Error())
return
}
updatedEmail, err := app.UpdateEmail(s, email, &emailDTO, schema)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
updatedEmailDTO := model.ToEmailDTO(updatedEmail)
// Encrypt payload
encrypted, err := app.EncryptJSON(key, updatedEmailDTO)
if err != nil {
RespondWithError(w, http.StatusInternalServerError, err.Error())
return
}
payload.Data = string(encrypted)
RespondWithJSON(w, http.StatusOK, payload)
}
}
// DeleteEmail ...
func DeleteEmail(s storage.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
RespondWithError(w, http.StatusBadRequest, err.Error())
return
}
schema := r.Context().Value("schema").(string)
email, err := s.Emails().FindByID(uint(id), schema)
if err != nil {
RespondWithError(w, http.StatusNotFound, err.Error())
return
}
err = s.Emails().Delete(email.ID, schema)
if err != nil {
RespondWithError(w, http.StatusNotFound, err.Error())
return
}
response := model.Response{
Code: http.StatusOK,
Status: "Success",
Message: "Email deleted successfully!",
}
RespondWithJSON(w, http.StatusOK, response)
}
}
|
{
"pile_set_name": "Github"
}
|
Gui class extend [
test: selector [
<category: 'testing'>
| win |
win := BWindow new: 'test'.
win width: 100 height: 100.
(self perform: selector) value: win.
win map.
Blox dispatchEvents: win
]
callbackTest [
<category: 'testing single controls'>
^
[:win |
| cont dlg sure |
win callback:
[cont := BTransientWindow new: 'BLOX test' in: win.
cont width: 250 height: 130.
dlg := BDialog new: cont label: 'Are you sure?'.
dlg
addButton: 'Yes'
receiver: [sure := true]
message: #value.
dlg
addButton: 'No'
receiver: [sure := false]
message: #value.
dlg loop.
sure]
message: #value]
]
canvasTest [
<category: 'testing single controls'>
^
[:win |
| ctl |
ctl := BScrolledCanvas new: win.
ctl width: 100 height: 100.
ctl backgroundColor: 'gray35'.
ctl extraSpace: 10 @ 0.
win width: 220 height: 220.
win map.
"p := ctl widthAbsolute @ ctl heightAbsolute. p printNl."
self drawInCanvas: ctl width: 200 @ 200]
]
drawInCanvas: ctl width: p [
<category: 'testing single controls'>
| status rect poly |
poly := (BPolyline new: ctl)
closed: true;
color: 'blue';
outlineColor: 'LemonChiffon';
points: (self points: p
coords: #(#(0.1 0.1) #(0.5 0.2) #(0.9000000000000001 0.9000000000000001) #(0.5 0.8000000000000001)));
create.
(BLine new: ctl)
origin: p * 0.1 corner: p * 0.9000000000000001;
color: 'Magenta';
cap: #round;
width: 8;
create.
rect := (BRectangle new: ctl)
origin: p * 0.45 extent: p * 0.1;
color: 'yellow';
outlineColor: 'Magenta';
width: 2;
create.
(BSpline new: ctl)
closed: false;
points: (self points: p
coords: #(#(0.05 0.05) #(0.05 0.05) #(0.05 0.9500000000000001) #(0.9500000000000001 0.9500000000000001) #(0.9500000000000001 0.9500000000000001) #(0.9500000000000001 0.05) #(0.05 0.05) #(0.05 0.05) #(0.05 0.25) #(0.05 0.25)));
join: #bevel;
color: 'ForestGreen';
width: 8;
create. "Trick to get the bevel-styled join" "at the top-left corner too"
(BArc new: ctl)
origin: p * (0.2 @ 0.8000000000000001) corner: p * (0.8000000000000001 @ 1);
outlineColor: 'gray75';
from: p * (0.2 @ 0.9000000000000001);
to: p * (0.5 @ 0.8000000000000001);
create.
(BArc new: ctl)
origin: p * (0.2 @ 0) corner: p * (0.8000000000000001 @ 0.2);
outlineColor: 'gray75';
startAngle: 270;
endAngle: 360;
create.
status := 0.
poly
onMouseDoubleEvent: 1
send: #value:
to:
[:pnt |
status := status + 1.
status = 1 ifTrue: [poly raise].
status = 2 ifTrue: [poly lower].
status = 3
ifTrue:
[(BEmbeddedText new: ctl)
color: 'Cyan';
text: 'Smalltalk is great';
font: 'Helvetica 12';
center: p / 2 extent: p x @ (p y / 10);
create.
rect remove]]
]
points: p coords: coords [
<category: 'testing single controls'>
^coords collect: [:each | p * ((each at: 1) @ (each at: 2))]
]
dropdownTest [
<category: 'testing single controls'>
^
[:win |
| cb name size label |
cb :=
[[label font: '{%1} %2' %
{name text.
size text}] on: Error
do: [:sig | sig return]].
win width: 300 height: 300.
name := BDropDownList new: win.
size := BDropDownEdit new: win.
label := BLabel new: win.
name
width: 250;
contents: Blox fonts;
callback: cb message: #value;
index: 1.
size
x: 252;
width: 48;
elements: #(6 8 10 12 14 18 24 36 48 72);
callback: cb message: #value;
index: 4.
label
effect: #groove;
width: 300 height: 300;
posVert: name;
alignment: #center;
label: 'The quick brown fox jumps over the lazy dog. 0123456789']
]
vContainerTest [
<category: 'testing single controls'>
^
[:win |
| vertical ctl cont |
cont := BContainer new: win.
cont setVerticalLayout: true.
ctl := BLabel new: cont label: 'label'.
ctl := BButton new: cont label: 'button'.
win backgroundColor: 'navyblue']
]
hContainerTest [
<category: 'testing single controls'>
^
[:win |
| vertical ctl cont |
cont := BContainer new: win.
cont setVerticalLayout: false.
ctl := BLabel new: cont label: 'label'.
ctl := BButton new: cont label: 'button'.
win backgroundColor: 'navyblue']
]
dialogTest1 [
<category: 'testing single controls'>
^
[:win |
| cont dlg |
cont := BTransientWindow new: 'transient' in: win.
cont width: 250 height: 130.
dlg := BDialog new: cont label: 'dialog test'.
dlg
addButton: 'OK'
receiver: self
message: #itemChosen.
dlg
addButton: 'Cancel'
receiver: self
message: #yourself.
win map.
dlg loop]
]
dialogTest2 [
<category: 'testing single controls'>
^
[:win |
| cont dlg |
cont := BTransientWindow new: 'transient' in: win.
cont width: 250 height: 130.
dlg := BDialog
new: cont
label: 'dialog test'
prompt: 'default'.
dlg
addButton: 'OK'
receiver: self
message: #pickMeHarder.
dlg
addButton: 'Cancel'
receiver: self
message: #yourself.
win map.
dlg loop]
]
editTest [
<category: 'testing single controls'>
^
[:win |
(BLabel new: win) label: 'Enter whatever you want:'.
(BEdit new: win)
x: 0 y: 50;
width: 100;
callback: Blox message: 'beep'.
win width: 200 height: 80]
]
eventTest [
<category: 'testing single controls'>
^
[:win |
| event events x y key ascii mouse |
mouse :=
[:pnt |
x label: pnt x printString.
y label: pnt y printString].
win width: 400 height: 200.
(event := BLabel new: win label: '')
x: 0 y: 0;
width: 200.
(x := BLabel new: win label: '')
x: 200 y: 0;
width: 50.
(y := BLabel new: win label: '')
x: 250 y: 0;
width: 50.
(key := BLabel new: win label: '')
x: 300 y: 0;
width: 50.
(ascii := BLabel new: win label: '')
x: 350 y: 0;
width: 50.
(BText new: win)
posVert: event;
onAsciiKeyEventSend: #value:
to:
[:char |
"This is a test, so to save space I'm using blocks. This is not
good programming practice, as it leads to huge methods."
event label: 'key'.
ascii label: (String with: char)];
onKeyEventSend: #value:
to:
[:keyPressed |
event label: 'ascii'.
key label: keyPressed];
onKeyEvent: 'Return'
send: #beep
to: Blox;
onMouseDownEvent: 1
send: #value:
to:
[:pnt |
mouse value: pnt.
event label: 'down'];
onMouseMoveEvent: 1
send: #value:
to:
[:pnt |
mouse value: pnt.
event label: 'move'];
onMouseUpEvent: 1
send: #value:
to:
[:pnt |
mouse value: pnt.
event label: 'up'];
onMouseDoubleEvent: 1
send: #value:
to:
[:pnt |
mouse value: pnt.
event label: 'double'];
onMouseTripleEvent: 1
send: #value:
to:
[:pnt |
mouse value: pnt.
event label: 'triple'];
onMouseEnterEventSend: #value to: [event label: 'enter'];
onMouseLeaveEventSend: #value to: [event label: 'leave']]
]
formTest [
<category: 'testing single controls'>
^
[:win |
| cont |
cont := BForm new: win.
(BLabel new: cont label: 'label') width: 100 height: 50.
(BButton new: cont label: 'button')
y: 50;
width: 100 height: 50]
]
formattingTest [
<category: 'testing single controls'>
^
[:win |
(BText new: win)
insertAtEnd: 'Trying edit box widgets' attribute: BTextAttributes red;
insertAtEnd: ' strikeout ' attribute: BTextAttributes strikeout;
insertAtEnd: ' red again ' attribute: BTextAttributes red;
insertAtEnd: ' now cyan '
attribute: (BTextAttributes new foregroundColor: 'DarkCyan');
insertAtEnd: ' now background '
attribute: (BTextAttributes yellow backgroundColor: 'DarkSlateBlue');
insertAtEnd: ' font '
attribute: (BTextAttributes underline font: 'Helvetica 24')]
]
textEventsTest [
<category: 'testing single controls'>
^
[:win |
| attrs bindings dlg cont text |
win width: win width * 2.
(bindings := BTextBindings new)
onMouseEnterEventSend: #value to: [text cursor: #hand2];
onMouseLeaveEventSend: #value to: [text cursor: #arrow];
onMouseUpEvent: 1
send: #value:
to:
[:pnt |
cont := BTransientWindow new: 'BLOX test' in: win.
cont height: 100.
dlg := BDialog new: cont label: 'You clicked on me'.
dlg
addButton: 'ok'
receiver: self
message: #yourself.
dlg loop].
attrs := (BTextAttributes new)
underline;
center;
blue;
font: 'Helvetica 18';
events: bindings.
(text := BText new: win)
cursor: #arrow;
insertAtEnd: 'Click on me!' attribute: attrs;
nl;
insertAtEnd: 'and not on me' attribute: BTextAttributes center]
]
imageTest [
<category: 'testing single controls'>
^
[:win |
| image |
image := BImage new: win image: self validImageFile.
image
onMouseMoveEvent: 1
send: #value:
to: [:pnt | image gamma: (0.2 max: pnt x / 100)].
win width: image imageWidth height: image imageHeight]
]
validImageFile [
<category: 'testing single controls'>
^(Directory kernel / '../blox/bear.gif') readStream
]
labelTest [
<category: 'testing single controls'>
^
[:win |
win width: 400.
(BLabel new: win label: '*** a ''ridge'' blue label ***')
effect: #ridge;
x: 40;
width: 320 height: 100;
inset: 20;
backgroundColor: 'LightSkyBlue';
font: 'Helvetica 18']
]
listboxTest [
<category: 'testing single controls'>
^
[:win |
(BList new: win)
width: 100 height: 100;
inset: 2;
contents: #('test 1' 'test 2' 'test 3' 'test 4' 'test 5' 'test 6')]
]
textTest [
<category: 'testing single controls'>
^
[:win |
| text |
win width: 300.
text := BText new: win.
text
contents: 'Trying edit box widgets
this line is long - this line is long - this line is long - '.
BButton new: text label: 'and has a button in it']
]
fileDialogTest [
<category: 'testing prompters'>
^
[:win |
| text file fileName |
win width: 500.
text := (BText new: win) font: 'Courier 9'.
fileName := BDialog
chooseFileToOpen: win
label: 'Open a file'
default: nil
defaultExtension: 'st'
types: #(#('Smalltalk files' '.st') #('Text files' '.txt' '.diz') #('C source files' '.c' '.h')).
fileName isNil
ifFalse:
[file := FileStream
open: fileName
mode: 'r'
ifFail: [ReadStream on: '***FILE COULD NOT BE OPENED' copy].
text contents: file contents.
file close]]
]
colorDialogTest [
<category: 'testing prompters'>
^
[:win |
| label color |
win width: 400.
label := (BLabel new: win label: '*** this is gray (for now) ***')
effect: #groove;
x: 40;
width: 320 height: 100;
inset: 20;
font: 'Helvetica 18'.
color := BDialog
chooseColor: win
label: 'Choose a color!'
default: 'SteelBlue'.
color isNil
ifFalse:
[label
label: 'but now it isn''t anymore';
backgroundColor: color printNl]]
]
menuTest [
<category: 'testing menus'>
^[:win | self createTestMenuBar: win]
]
popupMenuTest [
<category: 'testing menus'>
^
[:win |
| list menu menuItem |
list := self listboxTest value: win.
menu := BPopupMenu new: list.
menuItem := BMenuItem new: menu label: 'a one'.
menuItem callback: Gui message: 'itemChosen'.
menuItem := BMenuItem new: menu label: 'and a two'.
menuItem := BMenuItem new: menu label: 'and away'.
menuItem := BMenuItem new: menu label: 'we go']
]
createTestMenuBar: win [
<category: 'testing menus'>
| bar |
bar := BMenuBar new: win.
self createFirstMenu: bar.
self createSecondMenu: bar
]
createFirstMenu: bar [
<category: 'testing menus'>
| menu menuItem |
menu := BMenu new: bar label: 'foo'.
menuItem := BMenuItem new: menu label: 'a one'.
menuItem callback: Gui message: 'itemChosen'.
menuItem := BMenuItem new: menu label: 'and a two'.
menuItem := BMenuItem new: menu label: 'and away'.
menuItem := BMenuItem new: menu label: 'we go'.
bar add: menu
]
createSecondMenu: bar [
<category: 'testing menus'>
| menu menuItem |
menu := BMenu new: bar label: 'bar'.
menuItem := BMenuItem new: menu label: 'testme '.
menuItem callback: Gui message: 'pickMeHarder'.
menuItem := BMenuItem new: menu.
menuItem := BCheckMenuItem new: menu label: 'don''t try me'.
menuItem := BCheckMenuItem new: menu label: 'i do nothing'.
menuItem := BMenuItem new: menu.
menuItem := BCheckMenuItem new: menu label: 'abc'.
menuItem value: true.
bar add: menu.
menuItem label: 'cba - changed my mind'.
menuItem := BCheckMenuItem new: menu label: 'added on the fly'.
menuItem value: true
]
itemChosen [
<category: 'testing menus'>
'Picked me!!!' printNl
]
pickMeHarder [
<category: 'testing menus'>
'Pick me harder' printNl
]
iconTest [
<category: 'testing extended widgets'>
^
[:win |
(self icon: BImage exclaim in: win) x: 30 y: 30.
(self icon: BImage stop in: win) x: 70 y: 30.
(self icon: BImage info in: win) x: 30 y: 70.
(self icon: BImage question in: win) x: 70 y: 70.
win width: 120 height: 120.
win map]
]
icon: data in: win [
<category: 'testing extended widgets'>
^(BImage new: win data: data)
inset: -16;
borderWidth: 0;
yourself
]
progressTest [
<category: 'testing extended widgets'>
^
[:win |
| ctl |
win width: 150 height: 70.
(ctl := BProgress new: win)
x: 5
y: 5
width: 140
height: 60;
effect: #sunken;
borderWidth: 2;
value: 0.009000000000000002.
Blox debug: false.
[[win exists] whileTrue:
[(Delay forMilliseconds: 50) wait.
[ctl value: (ctl value + 0.01) fractionPart] on: Error
do: [:sig | sig return]]]
forkAt: Processor userInterruptPriority]
]
colorButtonTest [
<category: 'testing extended widgets'>
^
[:win |
| btn |
btn := BColorButton new: win.
btn inset: 15]
]
balloonTest [
<category: 'testing extended widgets'>
^
[:win |
| eventSet btn |
btn := BButton new: win label: 'Move here!'.
btn
inset: 15;
width: 100 height: 100.
(btn addEventSet: BBalloon) text: 'Sample balloon help']
]
]
Eval [
Transcript
nextPutAll: 'Available tests';
nl.
tests := OrderedCollection new.
BLOX.Gui class selectors
do: [:sel | ('*Test*' match: sel) & (sel numArgs = 0) ifTrue: [tests add: sel]].
tests asSortedCollection do:
[:each |
Transcript
nextPutAll: ' ';
print: each;
nl]
]
|
{
"pile_set_name": "Github"
}
|
"""
Definition of views.
"""
from django.shortcuts import render
from django.http import HttpRequest
from django.template import RequestContext
from datetime import datetime
def home(request):
"""Renders the home page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/index.html',
{
'title':'Home Page',
'year':datetime.now().year,
}
)
def contact(request):
"""Renders the contact page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/contact.html',
{
'title':'Contact',
'message':'Your contact page.',
'year':datetime.now().year,
}
)
def about(request):
"""Renders the about page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/about.html',
{
'title':'About',
'message':'Your application description page.',
'year':datetime.now().year,
}
)
|
{
"pile_set_name": "Github"
}
|
.calendar_date_select {
color:white;
border:#777 1px solid;
display:block;
width:195px;
z-index: 1000;
}
/* this is a fun ie6 hack to get drop downs to stay behind the popup window. This should always be just underneath .calendar_date_select */
iframe.ie6_blocker {
position: absolute;
z-index: 999;
}
.calendar_date_select thead th {
font-weight:bold;
background-color: #aaa;
border-top:1px solid #777;
border-bottom:1px solid #777;
color: white !important;
}
.calendar_date_select .cds_buttons {
text-align:center;
padding:5px 0px;
background-color: #555;
}
.calendar_date_select .cds_footer {
background-color: black;
padding:3px;
font-size:12px;
text-align:center;
}
.calendar_date_select table {
margin: 0px;
padding: 0px;
}
.calendar_date_select .cds_header {
background-color: #ccc;
border-bottom: 2px solid #aaa;
text-align:center;
}
.calendar_date_select .cds_header span {
font-size:15px;
color: black;
font-weight: bold;
}
.calendar_date_select select { font-size:11px;}
.calendar_date_select .cds_header a:hover {
color: white;
}
.calendar_date_select .cds_header a {
width:22px;
height:20px;
text-decoration: none;
font-size:14px;
color:black !important;
}
.calendar_date_select .cds_header a.prev {
float:right;
}
.calendar_date_select .cds_header a.next {
float:left;
}
.calendar_date_select .cds_header a.close {
float:left;
display:none;
}
.calendar_date_select .cds_header select.month {
width:90px;
}
.calendar_date_select .cds_header select.year {
width:61px;
}
.calendar_date_select .cds_buttons a {
color: white;
font-size: 9px;
}
.calendar_date_select td {
font-size:12px;
width: 24px;
height: 21px;
text-align:center;
vertical-align: middle;
background-color: #fff;
}
.calendar_date_select td.weekend {
background-color: #eee;
border-right:1px solid #ddd;
border-left:1px solid #ddd;
}
.calendar_date_select td div {
color: #000;
}
.calendar_date_select td div.other {
color: #ccc;
}
.calendar_date_select td.selected div {
color:white;
}
.calendar_date_select tbody td {
border-bottom: 1px solid #ddd;
}
.calendar_date_select td.selected {
background-color:#777;
}
.calendar_date_select td:hover {
background-color:#ccc;
}
.calendar_date_select td.today {
border: 1px dashed #999;
}
.calendar_date_select td.disabled div {
color: #e6e6e6;
}
.fieldWithErrors .calendar_date_select {
border: 2px solid red;
}
|
{
"pile_set_name": "Github"
}
|
---
title: チュートリアル:Azure Active Directory と Percolate の統合 | Microsoft Docs
description: このチュートリアルでは、Azure Active Directory と Percolate の間でシングル サインオンを構成する方法について説明します。
services: active-directory
author: jeevansd
manager: CelesteDG
ms.reviewer: celested
ms.service: active-directory
ms.subservice: saas-app-tutorial
ms.workload: identity
ms.topic: tutorial
ms.date: 04/01/2019
ms.author: jeedes
ms.openlocfilehash: deb64aa0c344e818b5fd85ca1a161293fd35d6f6
ms.sourcegitcommit: 023d10b4127f50f301995d44f2b4499cbcffb8fc
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 08/18/2020
ms.locfileid: "88553996"
---
# <a name="tutorial-azure-active-directory-integration-with-percolate"></a>チュートリアル:Azure Active Directory と Percolate との統合
このチュートリアルでは、Percolate と Azure Active Directory (Azure AD) を統合する方法について説明します。
この統合には、次の利点があります。
* Azure AD を使用して、Percolate にアクセスするユーザーを管理できます。
* ユーザーが自分の Azure AD アカウントを使用して自動的に Percolate にサインイン (シングル サインオン) できるようにすることができます。
* 1 つの中央サイト (Azure ポータル) でアカウントを管理できます。
SaaS アプリと Azure AD の統合の詳細については、「[Azure Active Directory でのアプリケーションへのシングル サインオン](https://docs.microsoft.com/azure/active-directory/active-directory-appssoaccess-whatis)」を参照してください。
Azure サブスクリプションをお持ちでない場合は、開始する前に[無料アカウントを作成](https://azure.microsoft.com/free/)してください。
## <a name="prerequisites"></a>前提条件
Percolate と Azure AD の統合を構成するには、次のものが必要です。
* Azure AD サブスクリプション。 Azure AD の環境がない場合は、[無料アカウント](https://azure.microsoft.com/free/)を取得できます。
* シングル サインオンが有効な Percolate サブスクリプション。
## <a name="scenario-description"></a>シナリオの説明
このチュートリアルでは、テスト環境で Azure AD のシングル サインオンを構成してテストします。
* Percolate では、SP-initiated SSO と IdP-initiated SSO がサポートされます。
## <a name="add-percolate-from-the-gallery"></a>ギャラリーから Percolate を追加する
Azure AD への Percolate の統合を構成するには、ギャラリーからマネージド SaaS アプリの一覧に Percolate を追加する必要があります。
1. [Azure portal](https://portal.azure.com) の左側のウィンドウで、 **[Azure Active Directory]** を選択します。
![[Azure Active Directory] を選択します。](common/select-azuread.png)
2. **[エンタープライズ アプリケーション]** > **[すべてのアプリケーション]** の順に移動します。
![[エンタープライズ アプリケーション] ブレード](common/enterprise-applications.png)
3. アプリケーションを追加するには、ウィンドウの上部の **[新しいアプリケーション]** を選択します。
![[新しいアプリケーション] を選択する](common/add-new-app.png)
4. 検索ボックスに「**Percolate**」と入力します。 検索結果で **[Percolate]** を選択し、 **[追加]** を選択します。
![[検索結果]](common/search-new-app.png)
## <a name="configure-and-test-azure-ad-single-sign-on"></a>Azure AD シングル サインオンの構成とテスト
このセクションでは、Britta Simon という名前のテスト ユーザーを使用して、Percolate で Azure AD のシングル サインオンを構成およびテストします。
シングル サインオンを有効にするには、Azure AD ユーザーと Percolate の対応するユーザーの間で、関係を確立する必要があります。
Percolate で Azure AD のシングル サインオンを構成およびテストするには、以下の手順を完了する必要があります。
1. **[Azure AD のシングル サインオンを構成](#configure-azure-ad-single-sign-on)** して、この機能をユーザーに対して有効にします。
2. アプリケーション側で **[Percolate シングル サインオンを構成](#configure-percolate-single-sign-on)** します。
3. Azure AD のシングル サインオンをテストするための **[Azure AD テスト ユーザーを作成](#create-an-azure-ad-test-user)** します。
4. **[Azure AD テスト ユーザーを割り当て](#assign-the-azure-ad-test-user)** て、Azure AD のシングル サインオンをそのユーザーに対して有効にします。
5. ユーザーの Azure AD 表現にリンクされた **[Percolate テスト ユーザーを作成](#create-a-percolate-test-user)** します。
6. **[シングル サインオンをテスト](#test-single-sign-on)** して、この構成が機能することを確認します。
### <a name="configure-azure-ad-single-sign-on"></a>Azure AD シングル サインオンの構成
このセクションでは、Azure portal で Azure AD のシングル サインオンを有効にします。
Percolate で Azure AD シングル サインオンを構成するには、次の手順を実行します。
1. [Azure portal](https://portal.azure.com/) の **Percolate** アプリケーション統合ページで、 **[シングル サインオン]** を選択します。
![[シングル サインオン] の選択](common/select-sso.png)
2. **[シングル サインオン方式の選択]** ダイアログ ボックスで、 **[SAML/WS-Fed]** モードを選択して、シングル サインオンを有効にします。

3. **[SAML でシングル サインオンをセットアップします]** ページで、**編集**アイコンを選択して **[基本的な SAML 構成]** ダイアログ ボックスを開きます。
![[編集] アイコン](common/edit-urls.png)
4. **[基本的な SAML 構成]** ダイアログ ボックスでは、IdP-initiated モードでアプリケーションを構成するためのアクションは必要ありません。 アプリは既に Azure と統合されています。
![[Percolate のドメインと URL] のシングル サインオン情報](common/preintegrated.png)
5. SP-initiated モードでアプリケーションを構成する場合は、 **[追加の URL を設定します]** を選択し、 **[サインオン URL]** ボックスに **https://percolate.com/app/login** と入力します。
![[Percolate のドメインと URL] のシングル サインオン情報](common/metadata-upload-additional-signon.png)
6. **[SAML でシングル サインオンをセットアップします]** ページの **[SAML 署名証明書]** セクションで、**コピー** アイコンを選択して **[アプリのフェデレーション メタデータ URL]** をコピーします。 この URL を保存します。

7. **[Percolate のセットアップ]** セクションで、要件に基づいて適切な URL をコピーします。

1. **[ログイン URL]** 。
1. **[Azure AD 識別子]** 。
1. **[ログアウト URL]** 。
### <a name="configure-percolate-single-sign-on"></a>Percolate シングル サインオンの構成
1. 新しい Web ブラウザー ウィンドウで、管理者として Percolate にサインインします。
2. ホーム ページの左側で、 **[設定]** を選択します。
![[設定] を選択する](./media/percolate-tutorial/configure01.png)
3. 左側のウィンドウで、 **[組織]** の下にある **[SSO]** を選択します。
![[組織] の下にある [SSO] の選択](./media/percolate-tutorial/configure02.png)
1. **[ログイン URL]** ボックスに、Azure portal からコピーした **[ログイン URL]** の値を貼り付けます。
1. **[エンティティ ID]** ボックスに、Azure portal からコピーした **[Azure AD 識別子]** の値を貼り付けます。
1. メモ帳で、Azure portal からダウンロードした base 64 エンコード証明書を開きます。 その内容をコピーして、 **[x509 certificates]\(x509 証明書\)** ボックスに貼り付けます。
1. **[Email attribute]\(電子メール属性\)** ボックスに、「**emailaddress**」と入力します。
1. **[Identity provider metadata URL]\(ID プロバイダー メタデータ URL\)** ボックスはオプションのフィールドです。 **[アプリのフェデレーション メタデータ URL]** を Azure portal からコピーした場合、それをこのボックスに貼り付けることができます。
1. **[Should AuthNRequests be signed?]\(AuthNRequests には署名が必要ですか?\)** リストで、 **[いいえ]** を選択します。
1. **[Enable SSO auto-provisioning]\(SSO の自動プロビジョニングを有効にする\)** リストで、 **[いいえ]** を選択します。
1. **[保存]** を選択します。
### <a name="create-an-azure-ad-test-user"></a>Azure AD のテスト ユーザーの作成
このセクションでは、Azure portal で Britta Simon という名前のテスト ユーザーを作成します。
1. Azure portal で、左側のウィンドウの **[Azure Active Directory]** を選択し、 **[ユーザー]** 、 **[すべてのユーザー]** の順に選択します。
![[すべてのユーザー] を選択する](common/users.png)
2. 画面の上部にある **[新しいユーザー]** を選択します。
![[新しいユーザー] を選択する](common/new-user.png)
3. **[ユーザー]** ダイアログ ボックスで、次の手順を実行します。
![[ユーザー] ダイアログ ボックス](common/user-properties.png)
1. **[名前]** ボックスに「**BrittaSimon**」と入力します。
1. **[ユーザー名]** ボックスに「**BrittaSimon@\<yourcompanydomain>.\<extension>** 」と入力します (例: BrittaSimon@contoso.com)。
1. **[パスワードを表示]** を選択し、 **[パスワード]** ボックス内の値を書き留めます。
1. **[作成]** を選択します
### <a name="assign-the-azure-ad-test-user"></a>Azure AD テスト ユーザーの割り当て
このセクションでは、Britta Simon に Percolate へのアクセスを許可することで、このユーザーが Azure AD シングル サインオンを使用できるようにします。
1. Azure portal で **[エンタープライズ アプリケーション]** を選択し、 **[すべてのアプリケーション]** を選択してから、 **[Percolate]** を選択します。
![[エンタープライズ アプリケーション] ブレード](common/enterprise-applications.png)
2. アプリケーションの一覧で、 **[Percolate]** を選択します。

3. 左側のウィンドウで **[ユーザーとグループ]** を選択します。
![[ユーザーとグループ] の選択](common/users-groups-blade.png)
4. **[ユーザーの追加]** を選択し、 **[割り当ての追加]** ダイアログ ボックスで **[ユーザーとグループ]** を選択します。
![[ユーザーとグループ] の選択](common/add-assign-user.png)
5. **[ユーザーとグループ]** ダイアログ ボックスで、ユーザーの一覧で **[Britta Simon]** を選択し、画面の下部にある **[選択]** ボタンをクリックします。
6. SAML アサーション内にロール値が必要な場合、 **[ロールの選択]** ダイアログ ボックスで、一覧からユーザーに適したロールを選択します。 画面の下部にある **[選択]** ボタンをクリックします。
7. **[割り当ての追加]** ダイアログ ボックスで **[割り当て]** を選びます。
### <a name="create-a-percolate-test-user"></a>Percolate テスト ユーザーの作成
Azure AD ユーザーが Percolate にサインインできるようにするには、それらを Percolate に追加する必要があります。 手動で追加する必要があります。
ユーザー アカウントを作成するには、以下の手順に従います。
1. 管理者として Percolate にサインインします。
2. 左側のウィンドウで、 **[組織]** の下にある **[ユーザー]** を選択します。 **[新しいユーザー]** を選択します。
![[新しいユーザー] の選択](./media/percolate-tutorial/configure03.png)
3. **[ユーザーの作成]** ページで、以下の手順を実行します。
![[ユーザーの作成] ページ](./media/percolate-tutorial/configure04.png)
1. **[電子メール]** ボックスに、ユーザーの電子メール アドレスを入力します。 たとえば、「 brittasimon@contoso.com 」のように入力します。
1. **[フル ネーム]** ボックスに、ユーザーの名前を入力します。 たとえば、「**Brittasimon**」と入力します。
1. **[ユーザーの作成]** を選択します。
### <a name="test-single-sign-on"></a>シングル サインオンのテスト
ここで、アクセス パネルを使用して Azure AD のシングル サインオン構成をテストする必要があります。
アクセス パネルで [Percolate] タイルを選択すると、SSO を設定した Percolate インスタンスに自動的にサインインします。 詳細については、「[マイ アプリ ポータルでアプリにアクセスして使用する](https://docs.microsoft.com/azure/active-directory/active-directory-saas-access-panel-introduction)」を参照してください。
## <a name="additional-resources"></a>その他のリソース
- [SaaS アプリケーションと Azure Active Directory との統合に関するチュートリアル](https://docs.microsoft.com/azure/active-directory/active-directory-saas-tutorial-list)
- [Azure Active Directory のアプリケーション アクセスとシングル サインオンとは](https://docs.microsoft.com/azure/active-directory/active-directory-appssoaccess-whatis)
- [Azure Active Directory の条件付きアクセスとは](https://docs.microsoft.com/azure/active-directory/conditional-access/overview)
|
{
"pile_set_name": "Github"
}
|
package ru.qatools.gridrouter.caps;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.DesiredCapabilities;
import ru.qatools.gridrouter.json.JsonCapabilities;
import ru.qatools.gridrouter.utils.JsonUtils;
import java.io.IOException;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class AppiumCapabilityProcessorTest {
private CapabilityProcessor processor;
@Before
public void setUp() throws Exception {
processor = new AppiumCapabilityProcessor();
}
@Test
public void accept() throws Exception {
assertThat(processor.accept(createCapabilities("", "iOS")), is(true));
assertThat(processor.accept(createCapabilities("blabla", "iOS")), is(false));
assertThat(processor.accept(createCapabilities("", "bla")), is(false));
assertThat(processor.accept(createCapabilities("bla", "iOS")), is(false));
}
private JsonCapabilities createCapabilities(String browserName, String platformName) throws IOException {
DesiredCapabilities desiredCapabilities = new DesiredCapabilities(browserName, "test", Platform.ANY);
desiredCapabilities.setCapability("platformName", platformName);
return JsonUtils.buildJsonCapabilities(desiredCapabilities);
}
@Test
public void process() throws Exception {
JsonCapabilities jsonCapabilities = new JsonCapabilities();
processor.process(jsonCapabilities);
assertThat(jsonCapabilities.any().keySet(), contains("keepKeyChains"));
assertThat(jsonCapabilities.any().get("keepKeyChains"), equalTo(true));
}
}
|
{
"pile_set_name": "Github"
}
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>gae</artifactId>
<version>2.0.3-SNAPSHOT</version>
</parent>
<artifactId>fr.opensagres.xdocreport.itext.extension-gae</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>unpack</id>
<phase>generate-sources</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.itext.extension</artifactId>
<version>${project.version}</version>
<type>jar</type>
<classifier>sources</classifier>
<outputDirectory>${unpackDir}</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of the License "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
// Implements a Session of a Symbian OS server for the RUsbMassStorage API
//
//
/**
@file
@internalTechnology
*/
#ifndef CUSBOTGSESSION_H
#define CUSBOTGSESSION_H
_LIT(KUsbOtgClientPncCat, "UsbOtgServer");
class CUsbOtgServer;
enum TMsManPanicClient
{
EUsbOtgPanicIllegalIPC
};
class CUsbOtgSession : public CSession2
{
public:
static CUsbOtgSession* NewL();
virtual void CreateL();
protected:
CUsbOtgSession();
void ConstructL();
private:
~CUsbOtgSession();
public:
// CSession2
void ServiceL(const RMessage2& aMessage);
void DispatchMessageL(const RMessage2& aMessage);
private:
// Services
void DeviceInsertedL(const RMessage2& aMessage);
void NotifyChange(const RMessage2& aMessage);
void NotifyChangeCancel();
TInt BusDrop();
protected:
// panic the client
void PanicClient(const RMessage2& aMessage,TInt aPanic) const;
private:
CUsbOtgServer& Server();
};
inline CUsbOtgServer& CUsbOtgSession::Server()
{
return *static_cast<CUsbOtgServer*>(const_cast<CServer2*>(CSession2::Server()));
}
#endif // CUSBOTGSESSION_H
|
{
"pile_set_name": "Github"
}
|
{
"smithy": "1.0",
"metadata": {
"suppressions": [
{
"id": "HttpMethodSemantics",
"namespace": "*"
},
{
"id": "HttpResponseCodeSemantics",
"namespace": "*"
},
{
"id": "PaginatedTrait",
"namespace": "*"
},
{
"id": "HttpHeaderTrait",
"namespace": "*"
},
{
"id": "HttpUriConflict",
"namespace": "*"
},
{
"id": "Service",
"namespace": "*"
}
]
},
"shapes": {
"com.amazonaws.sso#AccessKeyType": {
"type": "string"
},
"com.amazonaws.sso#AccessTokenType": {
"type": "string",
"traits": {
"smithy.api#sensitive": {}
}
},
"com.amazonaws.sso#AccountIdType": {
"type": "string"
},
"com.amazonaws.sso#AccountInfo": {
"type": "structure",
"members": {
"accountId": {
"target": "com.amazonaws.sso#AccountIdType",
"traits": {
"smithy.api#documentation": "<p>The identifier of the AWS account that is assigned to the user.</p>"
}
},
"emailAddress": {
"target": "com.amazonaws.sso#EmailAddressType",
"traits": {
"smithy.api#documentation": "<p>The email address of the AWS account that is assigned to the user.</p>"
}
},
"accountName": {
"target": "com.amazonaws.sso#AccountNameType",
"traits": {
"smithy.api#documentation": "<p>The display name of the AWS account that is assigned to the user.</p>"
}
}
},
"traits": {
"smithy.api#documentation": "<p>Provides information about your AWS account.</p>"
}
},
"com.amazonaws.sso#AccountListType": {
"type": "list",
"member": {
"target": "com.amazonaws.sso#AccountInfo"
}
},
"com.amazonaws.sso#AccountNameType": {
"type": "string"
},
"com.amazonaws.sso#EmailAddressType": {
"type": "string",
"traits": {
"smithy.api#length": {
"min": 1,
"max": 254
}
}
},
"com.amazonaws.sso#ErrorDescription": {
"type": "string"
},
"com.amazonaws.sso#ExpirationTimestampType": {
"type": "long"
},
"com.amazonaws.sso#GetRoleCredentials": {
"type": "operation",
"input": {
"target": "com.amazonaws.sso#GetRoleCredentialsRequest"
},
"output": {
"target": "com.amazonaws.sso#GetRoleCredentialsResponse"
},
"errors": [
{
"target": "com.amazonaws.sso#InvalidRequestException"
},
{
"target": "com.amazonaws.sso#ResourceNotFoundException"
},
{
"target": "com.amazonaws.sso#TooManyRequestsException"
},
{
"target": "com.amazonaws.sso#UnauthorizedException"
}
],
"traits": {
"smithy.api#auth": [],
"smithy.api#documentation": "<p>Returns the STS short-term credentials for a given role name that is assigned to the\n user.</p>",
"smithy.api#http": {
"method": "GET",
"uri": "/federation/credentials",
"code": 200
},
"smithy.api#optionalAuth": {}
}
},
"com.amazonaws.sso#GetRoleCredentialsRequest": {
"type": "structure",
"members": {
"accountId": {
"target": "com.amazonaws.sso#AccountIdType",
"traits": {
"smithy.api#documentation": "<p>The identifier for the AWS account that is assigned to the user.</p>",
"smithy.api#httpQuery": "account_id",
"smithy.api#required": {}
}
},
"accessToken": {
"target": "com.amazonaws.sso#AccessTokenType",
"traits": {
"smithy.api#documentation": "<p>The token issued by the <code>CreateToken</code> API call. For more information, see\n <a href=\"https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html\">CreateToken</a> in the <i>AWS SSO OIDC API Reference Guide</i>.</p>",
"smithy.api#httpHeader": "x-amz-sso_bearer_token",
"smithy.api#required": {}
}
},
"roleName": {
"target": "com.amazonaws.sso#RoleNameType",
"traits": {
"smithy.api#documentation": "<p>The friendly name of the role that is assigned to the user.</p>",
"smithy.api#httpQuery": "role_name",
"smithy.api#required": {}
}
}
}
},
"com.amazonaws.sso#GetRoleCredentialsResponse": {
"type": "structure",
"members": {
"roleCredentials": {
"target": "com.amazonaws.sso#RoleCredentials",
"traits": {
"smithy.api#documentation": "<p>The credentials for the role that is assigned to the user.</p>"
}
}
}
},
"com.amazonaws.sso#InvalidRequestException": {
"type": "structure",
"members": {
"message": {
"target": "com.amazonaws.sso#ErrorDescription"
}
},
"traits": {
"smithy.api#documentation": "<p>Indicates that a problem occurred with the input to the request. For example, a required\n parameter might be missing or out of range.</p>",
"smithy.api#error": "client",
"smithy.api#httpError": 400
}
},
"com.amazonaws.sso#ListAccountRoles": {
"type": "operation",
"input": {
"target": "com.amazonaws.sso#ListAccountRolesRequest"
},
"output": {
"target": "com.amazonaws.sso#ListAccountRolesResponse"
},
"errors": [
{
"target": "com.amazonaws.sso#InvalidRequestException"
},
{
"target": "com.amazonaws.sso#ResourceNotFoundException"
},
{
"target": "com.amazonaws.sso#TooManyRequestsException"
},
{
"target": "com.amazonaws.sso#UnauthorizedException"
}
],
"traits": {
"smithy.api#auth": [],
"smithy.api#documentation": "<p>Lists all roles that are assigned to the user for a given AWS account.</p>",
"smithy.api#http": {
"method": "GET",
"uri": "/assignment/roles",
"code": 200
},
"smithy.api#optionalAuth": {},
"smithy.api#paginated": {
"inputToken": "nextToken",
"outputToken": "nextToken",
"pageSize": "maxResults"
}
}
},
"com.amazonaws.sso#ListAccountRolesRequest": {
"type": "structure",
"members": {
"nextToken": {
"target": "com.amazonaws.sso#NextTokenType",
"traits": {
"smithy.api#documentation": "<p>The page token from the previous response output when you request subsequent pages.</p>",
"smithy.api#httpQuery": "next_token"
}
},
"accessToken": {
"target": "com.amazonaws.sso#AccessTokenType",
"traits": {
"smithy.api#documentation": "<p>The token issued by the <code>CreateToken</code> API call. For more information, see\n <a href=\"https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html\">CreateToken</a> in the <i>AWS SSO OIDC API Reference Guide</i>.</p>",
"smithy.api#httpHeader": "x-amz-sso_bearer_token",
"smithy.api#required": {}
}
},
"accountId": {
"target": "com.amazonaws.sso#AccountIdType",
"traits": {
"smithy.api#documentation": "<p>The identifier for the AWS account that is assigned to the user.</p>",
"smithy.api#httpQuery": "account_id",
"smithy.api#required": {}
}
},
"maxResults": {
"target": "com.amazonaws.sso#MaxResultType",
"traits": {
"smithy.api#documentation": "<p>The number of items that clients can request per page.</p>",
"smithy.api#httpQuery": "max_result"
}
}
}
},
"com.amazonaws.sso#ListAccountRolesResponse": {
"type": "structure",
"members": {
"nextToken": {
"target": "com.amazonaws.sso#NextTokenType",
"traits": {
"smithy.api#documentation": "<p>The page token client that is used to retrieve the list of accounts.</p>"
}
},
"roleList": {
"target": "com.amazonaws.sso#RoleListType",
"traits": {
"smithy.api#documentation": "<p>A paginated response with the list of roles and the next token if more results are available.</p>"
}
}
}
},
"com.amazonaws.sso#ListAccounts": {
"type": "operation",
"input": {
"target": "com.amazonaws.sso#ListAccountsRequest"
},
"output": {
"target": "com.amazonaws.sso#ListAccountsResponse"
},
"errors": [
{
"target": "com.amazonaws.sso#InvalidRequestException"
},
{
"target": "com.amazonaws.sso#ResourceNotFoundException"
},
{
"target": "com.amazonaws.sso#TooManyRequestsException"
},
{
"target": "com.amazonaws.sso#UnauthorizedException"
}
],
"traits": {
"smithy.api#auth": [],
"smithy.api#documentation": "<p>Lists all AWS accounts assigned to the user. These AWS accounts are assigned by the\n administrator of the account. For more information, see <a href=\"https://docs.aws.amazon.com/singlesignon/latest/userguide/useraccess.html#assignusers\">Assign User Access</a> in the <i>AWS SSO User Guide</i>. This operation\n returns a paginated response.</p>",
"smithy.api#http": {
"method": "GET",
"uri": "/assignment/accounts",
"code": 200
},
"smithy.api#optionalAuth": {},
"smithy.api#paginated": {
"inputToken": "nextToken",
"outputToken": "nextToken",
"pageSize": "maxResults"
}
}
},
"com.amazonaws.sso#ListAccountsRequest": {
"type": "structure",
"members": {
"accessToken": {
"target": "com.amazonaws.sso#AccessTokenType",
"traits": {
"smithy.api#documentation": "<p>The token issued by the <code>CreateToken</code> API call. For more information, see\n <a href=\"https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html\">CreateToken</a> in the <i>AWS SSO OIDC API Reference Guide</i>.</p>",
"smithy.api#httpHeader": "x-amz-sso_bearer_token",
"smithy.api#required": {}
}
},
"maxResults": {
"target": "com.amazonaws.sso#MaxResultType",
"traits": {
"smithy.api#documentation": "<p>This is the number of items clients can request per page.</p>",
"smithy.api#httpQuery": "max_result"
}
},
"nextToken": {
"target": "com.amazonaws.sso#NextTokenType",
"traits": {
"smithy.api#documentation": "<p>(Optional) When requesting subsequent pages, this is the page token from the previous response output.</p>",
"smithy.api#httpQuery": "next_token"
}
}
}
},
"com.amazonaws.sso#ListAccountsResponse": {
"type": "structure",
"members": {
"accountList": {
"target": "com.amazonaws.sso#AccountListType",
"traits": {
"smithy.api#documentation": "<p>A paginated response with the list of account information and the next token if more results are available.</p>"
}
},
"nextToken": {
"target": "com.amazonaws.sso#NextTokenType",
"traits": {
"smithy.api#documentation": "<p>The page token client that is used to retrieve the list of accounts.</p>"
}
}
}
},
"com.amazonaws.sso#Logout": {
"type": "operation",
"input": {
"target": "com.amazonaws.sso#LogoutRequest"
},
"errors": [
{
"target": "com.amazonaws.sso#InvalidRequestException"
},
{
"target": "com.amazonaws.sso#TooManyRequestsException"
},
{
"target": "com.amazonaws.sso#UnauthorizedException"
}
],
"traits": {
"smithy.api#auth": [],
"smithy.api#documentation": "<p>Removes the client- and server-side session that is associated with the user.</p>",
"smithy.api#http": {
"method": "POST",
"uri": "/logout",
"code": 200
},
"smithy.api#optionalAuth": {}
}
},
"com.amazonaws.sso#LogoutRequest": {
"type": "structure",
"members": {
"accessToken": {
"target": "com.amazonaws.sso#AccessTokenType",
"traits": {
"smithy.api#documentation": "<p>The token issued by the <code>CreateToken</code> API call. For more information, see\n <a href=\"https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html\">CreateToken</a> in the <i>AWS SSO OIDC API Reference Guide</i>.</p>",
"smithy.api#httpHeader": "x-amz-sso_bearer_token",
"smithy.api#required": {}
}
}
}
},
"com.amazonaws.sso#MaxResultType": {
"type": "integer",
"traits": {
"smithy.api#box": {},
"smithy.api#range": {
"min": 1,
"max": 100
}
}
},
"com.amazonaws.sso#NextTokenType": {
"type": "string"
},
"com.amazonaws.sso#ResourceNotFoundException": {
"type": "structure",
"members": {
"message": {
"target": "com.amazonaws.sso#ErrorDescription"
}
},
"traits": {
"smithy.api#documentation": "<p>The specified resource doesn't exist.</p>",
"smithy.api#error": "client",
"smithy.api#httpError": 404
}
},
"com.amazonaws.sso#RoleCredentials": {
"type": "structure",
"members": {
"secretAccessKey": {
"target": "com.amazonaws.sso#SecretAccessKeyType",
"traits": {
"smithy.api#documentation": "<p>The key that is used to sign the request. For more information, see <a href=\"https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html\">Using Temporary Security Credentials to Request Access to AWS Resources</a> in the\n <i>AWS IAM User Guide</i>.</p>"
}
},
"accessKeyId": {
"target": "com.amazonaws.sso#AccessKeyType",
"traits": {
"smithy.api#documentation": "<p>The identifier used for the temporary security credentials. For more information, see\n <a href=\"https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html\">Using Temporary Security Credentials to Request Access to AWS Resources</a> in the\n <i>AWS IAM User Guide</i>.</p>"
}
},
"expiration": {
"target": "com.amazonaws.sso#ExpirationTimestampType",
"traits": {
"smithy.api#documentation": "<p>The date on which temporary security credentials expire.</p>"
}
},
"sessionToken": {
"target": "com.amazonaws.sso#SessionTokenType",
"traits": {
"smithy.api#documentation": "<p>The token used for temporary credentials. For more information, see <a href=\"https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html\">Using Temporary Security Credentials to Request Access to AWS Resources</a> in the\n <i>AWS IAM User Guide</i>.</p>"
}
}
},
"traits": {
"smithy.api#documentation": "<p>Provides information about the role credentials that are assigned to the user.</p>"
}
},
"com.amazonaws.sso#RoleInfo": {
"type": "structure",
"members": {
"roleName": {
"target": "com.amazonaws.sso#RoleNameType",
"traits": {
"smithy.api#documentation": "<p>The friendly name of the role that is assigned to the user.</p>"
}
},
"accountId": {
"target": "com.amazonaws.sso#AccountIdType",
"traits": {
"smithy.api#documentation": "<p>The identifier of the AWS account assigned to the user.</p>"
}
}
},
"traits": {
"smithy.api#documentation": "<p>Provides information about the role that is assigned to the user.</p>"
}
},
"com.amazonaws.sso#RoleListType": {
"type": "list",
"member": {
"target": "com.amazonaws.sso#RoleInfo"
}
},
"com.amazonaws.sso#RoleNameType": {
"type": "string"
},
"com.amazonaws.sso#SWBPortalService": {
"type": "service",
"version": "2019-06-10",
"operations": [
{
"target": "com.amazonaws.sso#GetRoleCredentials"
},
{
"target": "com.amazonaws.sso#ListAccountRoles"
},
{
"target": "com.amazonaws.sso#ListAccounts"
},
{
"target": "com.amazonaws.sso#Logout"
}
],
"traits": {
"aws.api#service": {
"sdkId": "SSO",
"arnNamespace": "awsssoportal",
"cloudFormationName": "SSO",
"cloudTrailEventSource": "portal.switchboard.amazonaws.com"
},
"aws.auth#sigv4": {
"name": "awsssoportal"
},
"aws.protocols#restJson1": {},
"smithy.api#documentation": "<p>AWS Single Sign-On Portal is a web service that makes it easy for you to assign user\n access to AWS SSO resources such as the user portal. Users can get AWS account applications\n and roles assigned to them and get federated into the application.</p>\n \n <p>For general information about AWS SSO, see <a href=\"https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html\">What is AWS\n Single Sign-On?</a> in the <i>AWS SSO User Guide</i>.</p>\n \n <p>This API reference guide describes the AWS SSO Portal operations that you can call\n programatically and includes detailed information on data types and errors.</p>\n \n <note>\n <p>AWS provides SDKs that consist of libraries and sample code for various programming\n languages and platforms, such as Java, Ruby, .Net, iOS, or Android. The SDKs provide a\n convenient way to create programmatic access to AWS SSO and other AWS services. For more\n information about the AWS SDKs, including how to download and install them, see <a href=\"http://aws.amazon.com/tools/\">Tools for Amazon Web Services</a>.</p>\n </note>",
"smithy.api#title": "AWS Single Sign-On"
}
},
"com.amazonaws.sso#SecretAccessKeyType": {
"type": "string",
"traits": {
"smithy.api#sensitive": {}
}
},
"com.amazonaws.sso#SessionTokenType": {
"type": "string",
"traits": {
"smithy.api#sensitive": {}
}
},
"com.amazonaws.sso#TooManyRequestsException": {
"type": "structure",
"members": {
"message": {
"target": "com.amazonaws.sso#ErrorDescription"
}
},
"traits": {
"smithy.api#documentation": "<p>Indicates that the request is being made too frequently and is more than what the server can handle.</p>",
"smithy.api#error": "client",
"smithy.api#httpError": 429
}
},
"com.amazonaws.sso#UnauthorizedException": {
"type": "structure",
"members": {
"message": {
"target": "com.amazonaws.sso#ErrorDescription"
}
},
"traits": {
"smithy.api#documentation": "<p>Indicates that the request is not authorized. This can happen due to an invalid access token in the request.</p>",
"smithy.api#error": "client",
"smithy.api#httpError": 401
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageIOCoder.h"
#import "SDImageCoderHelper.h"
#import "NSImage+Compatibility.h"
#import <ImageIO/ImageIO.h>
#import "UIImage+Metadata.h"
@implementation SDImageIOCoder {
size_t _width, _height;
CGImagePropertyOrientation _orientation;
CGImageSourceRef _imageSource;
CGFloat _scale;
BOOL _finished;
}
- (void)dealloc {
if (_imageSource) {
CFRelease(_imageSource);
_imageSource = NULL;
}
#if SD_UIKIT
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
#endif
}
- (void)didReceiveMemoryWarning:(NSNotification *)notification
{
if (_imageSource) {
CGImageSourceRemoveCacheAtIndex(_imageSource, 0);
}
}
+ (instancetype)sharedCoder {
static SDImageIOCoder *coder;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
coder = [[SDImageIOCoder alloc] init];
});
return coder;
}
#pragma mark - Decode
- (BOOL)canDecodeFromData:(nullable NSData *)data {
switch ([NSData sd_imageFormatForImageData:data]) {
case SDImageFormatWebP:
// Do not support WebP decoding
return NO;
case SDImageFormatHEIC:
// Check HEIC decoding compatibility
return [[self class] canDecodeFromHEICFormat];
case SDImageFormatHEIF:
// Check HEIF decoding compatibility
return [[self class] canDecodeFromHEIFFormat];
default:
return YES;
}
}
- (UIImage *)decodedImageWithData:(NSData *)data options:(nullable SDImageCoderOptions *)options {
if (!data) {
return nil;
}
CGFloat scale = 1;
NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor];
if (scaleFactor != nil) {
scale = [scaleFactor doubleValue];
if (scale < 1) {
scale = 1;
}
}
UIImage *image = [[UIImage alloc] initWithData:data scale:scale];
image.sd_imageFormat = [NSData sd_imageFormatForImageData:data];
return image;
}
#pragma mark - Progressive Decode
- (BOOL)canIncrementalDecodeFromData:(NSData *)data {
return [self canDecodeFromData:data];
}
- (instancetype)initIncrementalWithOptions:(nullable SDImageCoderOptions *)options {
self = [super init];
if (self) {
_imageSource = CGImageSourceCreateIncremental(NULL);
CGFloat scale = 1;
NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor];
if (scaleFactor != nil) {
scale = [scaleFactor doubleValue];
if (scale < 1) {
scale = 1;
}
}
_scale = scale;
#if SD_UIKIT
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
#endif
}
return self;
}
- (void)updateIncrementalData:(NSData *)data finished:(BOOL)finished {
if (_finished) {
return;
}
_finished = finished;
// The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/
// Thanks to the author @Nyx0uf
// Update the data source, we must pass ALL the data, not just the new bytes
CGImageSourceUpdateData(_imageSource, (__bridge CFDataRef)data, finished);
if (_width + _height == 0) {
CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(_imageSource, 0, NULL);
if (properties) {
NSInteger orientationValue = 1;
CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight);
if (val) CFNumberGetValue(val, kCFNumberLongType, &_height);
val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth);
if (val) CFNumberGetValue(val, kCFNumberLongType, &_width);
val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation);
if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue);
CFRelease(properties);
// When we draw to Core Graphics, we lose orientation information,
// which means the image below born of initWithCGIImage will be
// oriented incorrectly sometimes. (Unlike the image born of initWithData
// in didCompleteWithError.) So save it here and pass it on later.
_orientation = (CGImagePropertyOrientation)orientationValue;
}
}
}
- (UIImage *)incrementalDecodedImageWithOptions:(SDImageCoderOptions *)options {
UIImage *image;
if (_width + _height > 0) {
// Create the image
CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(_imageSource, 0, NULL);
if (partialImageRef) {
CGFloat scale = _scale;
NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor];
if (scaleFactor != nil) {
scale = [scaleFactor doubleValue];
if (scale < 1) {
scale = 1;
}
}
#if SD_UIKIT || SD_WATCH
UIImageOrientation imageOrientation = [SDImageCoderHelper imageOrientationFromEXIFOrientation:_orientation];
image = [[UIImage alloc] initWithCGImage:partialImageRef scale:scale orientation:imageOrientation];
#else
image = [[UIImage alloc] initWithCGImage:partialImageRef scale:scale orientation:_orientation];
#endif
CGImageRelease(partialImageRef);
CFStringRef uttype = CGImageSourceGetType(_imageSource);
image.sd_imageFormat = [NSData sd_imageFormatFromUTType:uttype];
}
}
return image;
}
#pragma mark - Encode
- (BOOL)canEncodeToFormat:(SDImageFormat)format {
switch (format) {
case SDImageFormatWebP:
// Do not support WebP encoding
return NO;
case SDImageFormatHEIC:
// Check HEIC encoding compatibility
return [[self class] canEncodeToHEICFormat];
case SDImageFormatHEIF:
// Check HEIF encoding compatibility
return [[self class] canEncodeToHEIFFormat];
default:
return YES;
}
}
- (NSData *)encodedDataWithImage:(UIImage *)image format:(SDImageFormat)format options:(nullable SDImageCoderOptions *)options {
if (!image) {
return nil;
}
if (format == SDImageFormatUndefined) {
BOOL hasAlpha = [SDImageCoderHelper CGImageContainsAlpha:image.CGImage];
if (hasAlpha) {
format = SDImageFormatPNG;
} else {
format = SDImageFormatJPEG;
}
}
NSMutableData *imageData = [NSMutableData data];
CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:format];
// Create an image destination.
CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, 1, NULL);
if (!imageDestination) {
// Handle failure.
return nil;
}
NSMutableDictionary *properties = [NSMutableDictionary dictionary];
#if SD_UIKIT || SD_WATCH
CGImagePropertyOrientation exifOrientation = [SDImageCoderHelper exifOrientationFromImageOrientation:image.imageOrientation];
#else
CGImagePropertyOrientation exifOrientation = kCGImagePropertyOrientationUp;
#endif
properties[(__bridge NSString *)kCGImagePropertyOrientation] = @(exifOrientation);
double compressionQuality = 1;
if (options[SDImageCoderEncodeCompressionQuality]) {
compressionQuality = [options[SDImageCoderEncodeCompressionQuality] doubleValue];
}
properties[(__bridge NSString *)kCGImageDestinationLossyCompressionQuality] = @(compressionQuality);
// Add your image to the destination.
CGImageDestinationAddImage(imageDestination, image.CGImage, (__bridge CFDictionaryRef)properties);
// Finalize the destination.
if (CGImageDestinationFinalize(imageDestination) == NO) {
// Handle failure.
imageData = nil;
}
CFRelease(imageDestination);
return [imageData copy];
}
+ (BOOL)canDecodeFromFormat:(SDImageFormat)format {
CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:format];
NSArray *imageUTTypes = (__bridge_transfer NSArray *)CGImageSourceCopyTypeIdentifiers();
if ([imageUTTypes containsObject:(__bridge NSString *)(imageUTType)]) {
return YES;
}
return NO;
}
+ (BOOL)canDecodeFromHEICFormat {
static BOOL canDecode = NO;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
canDecode = [self canDecodeFromFormat:SDImageFormatHEIC];
});
return canDecode;
}
+ (BOOL)canDecodeFromHEIFFormat {
static BOOL canDecode = NO;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
canDecode = [self canDecodeFromFormat:SDImageFormatHEIF];
});
return canDecode;
}
+ (BOOL)canEncodeToFormat:(SDImageFormat)format {
NSMutableData *imageData = [NSMutableData data];
CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:format];
// Create an image destination.
CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, 1, NULL);
if (!imageDestination) {
// Can't encode to HEIC
return NO;
} else {
// Can encode to HEIC
CFRelease(imageDestination);
return YES;
}
}
+ (BOOL)canEncodeToHEICFormat {
static BOOL canEncode = NO;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
canEncode = [self canEncodeToFormat:SDImageFormatHEIC];
});
return canEncode;
}
+ (BOOL)canEncodeToHEIFFormat {
static BOOL canEncode = NO;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
canEncode = [self canEncodeToFormat:SDImageFormatHEIF];
});
return canEncode;
}
@end
|
{
"pile_set_name": "Github"
}
|
"support_item_gold_ranked"
{
"challengetype" "148"
"desc" "#DOTA_ChallengeDesc_Support_Item_Gold"
"status_text" "#DOTA_ChallengeStatusText_Support_Item_Gold"
"events"
{
"matching_type" "game_state"
"query"
{
"state_values"
{
"1"
{
"key" "support_gold_spent"
"aggregator" "count"
}
}
}
"progress_stored_in" "1"
"post_tests"
{
"test_value"
{
"storage" "1"
"compare" ">="
"amount" "<support_gold_spent>"
}
}
}
"variables"
{
"<support_gold_spent>"
{
"format" "int"
"index" "0"
}
}
}
|
{
"pile_set_name": "Github"
}
|
BT=${BT-../../bin/bedtools}
check()
{
if diff $1 $2; then
echo ok
else
echo fail
fi
}
###########################################################
###########################################################
# BAM files #
###########################################################
###########################################################
samtools view -Sb one_block.sam > one_block.bam 2>/dev/null
samtools view -Sb two_blocks.sam > two_blocks.bam 2>/dev/null
samtools view -Sb three_blocks.sam > three_blocks.bam 2>/dev/null
samtools view -Sb sam-w-del.sam > sam-w-del.bam 2>/dev/null
##################################################################
# Test three blocks without -split
##################################################################
echo " genomecov.t1...\c"
echo \
"chr1 0 50 1" > exp
$BT genomecov -ibam three_blocks.bam -bg > obs
check obs exp
rm obs exp
##################################################################
# Test three blocks with -split
##################################################################
echo " genomecov.t2...\c"
echo \
"chr1 0 10 1
chr1 20 30 1
chr1 40 50 1" > exp
$BT genomecov -ibam three_blocks.bam -bg -split > obs
check obs exp
rm obs exp
##################################################################
# Test three blocks with -split and -bga
##################################################################
echo " genomecov.t3...\c"
echo \
"chr1 0 10 1
chr1 10 20 0
chr1 20 30 1
chr1 30 40 0
chr1 40 50 1
chr1 50 1000 0" > exp
$BT genomecov -ibam three_blocks.bam -bga -split > obs
check obs exp
rm obs exp
##################################################################
# Test blocked BAM from multiple files w/ -bga and w/o -split
##################################################################
echo " genomecov.t4...\c"
echo \
"chr1 0 30 3
chr1 30 40 2
chr1 40 50 1
chr1 50 1000 0" > exp
samtools merge -f /dev/stdout *block*.bam | $BT genomecov -ibam - -bga > obs
check obs exp
rm obs exp
##################################################################
# Test blocked BAM from multiple files w/ -bga and w -split
##################################################################
echo " genomecov.t5...\c"
echo \
"chr1 0 10 3
chr1 10 15 2
chr1 15 20 1
chr1 20 25 2
chr1 25 30 3
chr1 30 50 1
chr1 50 1000 0" > exp
samtools merge -f /dev/stdout *block*.bam | $BT genomecov -ibam - -bga -split > obs
check obs exp
rm obs exp
##################################################################
# Test three blocks with -split and -dz
##################################################################
echo " genomecov.t6...\c"
echo \
"chr1 0 1
chr1 1 1
chr1 2 1
chr1 3 1
chr1 4 1
chr1 5 1
chr1 6 1
chr1 7 1
chr1 8 1
chr1 9 1
chr1 20 1
chr1 21 1
chr1 22 1
chr1 23 1
chr1 24 1
chr1 25 1
chr1 26 1
chr1 27 1
chr1 28 1
chr1 29 1
chr1 40 1
chr1 41 1
chr1 42 1
chr1 43 1
chr1 44 1
chr1 45 1
chr1 46 1
chr1 47 1
chr1 48 1
chr1 49 1" > exp
$BT genomecov -ibam three_blocks.bam -dz -split > obs
check obs exp
rm obs exp
##################################################################
# Test SAM with 1bp D operator
##################################################################
echo " genomecov.t7...\c"
echo \
"chr1 0 10 1
chr1 11 21 1" > exp
$BT genomecov -ibam sam-w-del.bam -bg > obs
check obs exp
rm obs exp
rm *.bam
|
{
"pile_set_name": "Github"
}
|
# created by tools/tclZIC.tcl - do not edit
set TZData(:America/Monterrey) {
{-9223372036854775808 -24076 0 LMT}
{-1514743200 -21600 0 CST}
{568015200 -21600 0 CST}
{576057600 -18000 1 CDT}
{594198000 -21600 0 CST}
{599637600 -21600 0 CST}
{828864000 -18000 1 CDT}
{846399600 -21600 0 CST}
{860313600 -18000 1 CDT}
{877849200 -21600 0 CST}
{891763200 -18000 1 CDT}
{909298800 -21600 0 CST}
{923212800 -18000 1 CDT}
{941353200 -21600 0 CST}
{954662400 -18000 1 CDT}
{972802800 -21600 0 CST}
{989136000 -18000 1 CDT}
{1001833200 -21600 0 CST}
{1018166400 -18000 1 CDT}
{1035702000 -21600 0 CST}
{1049616000 -18000 1 CDT}
{1067151600 -21600 0 CST}
{1081065600 -18000 1 CDT}
{1099206000 -21600 0 CST}
{1112515200 -18000 1 CDT}
{1130655600 -21600 0 CST}
{1143964800 -18000 1 CDT}
{1162105200 -21600 0 CST}
{1175414400 -18000 1 CDT}
{1193554800 -21600 0 CST}
{1207468800 -18000 1 CDT}
{1225004400 -21600 0 CST}
{1238918400 -18000 1 CDT}
{1256454000 -21600 0 CST}
{1270368000 -18000 1 CDT}
{1288508400 -21600 0 CST}
{1301817600 -18000 1 CDT}
{1319958000 -21600 0 CST}
{1333267200 -18000 1 CDT}
{1351407600 -21600 0 CST}
{1365321600 -18000 1 CDT}
{1382857200 -21600 0 CST}
{1396771200 -18000 1 CDT}
{1414306800 -21600 0 CST}
{1428220800 -18000 1 CDT}
{1445756400 -21600 0 CST}
{1459670400 -18000 1 CDT}
{1477810800 -21600 0 CST}
{1491120000 -18000 1 CDT}
{1509260400 -21600 0 CST}
{1522569600 -18000 1 CDT}
{1540710000 -21600 0 CST}
{1554624000 -18000 1 CDT}
{1572159600 -21600 0 CST}
{1586073600 -18000 1 CDT}
{1603609200 -21600 0 CST}
{1617523200 -18000 1 CDT}
{1635663600 -21600 0 CST}
{1648972800 -18000 1 CDT}
{1667113200 -21600 0 CST}
{1680422400 -18000 1 CDT}
{1698562800 -21600 0 CST}
{1712476800 -18000 1 CDT}
{1730012400 -21600 0 CST}
{1743926400 -18000 1 CDT}
{1761462000 -21600 0 CST}
{1775376000 -18000 1 CDT}
{1792911600 -21600 0 CST}
{1806825600 -18000 1 CDT}
{1824966000 -21600 0 CST}
{1838275200 -18000 1 CDT}
{1856415600 -21600 0 CST}
{1869724800 -18000 1 CDT}
{1887865200 -21600 0 CST}
{1901779200 -18000 1 CDT}
{1919314800 -21600 0 CST}
{1933228800 -18000 1 CDT}
{1950764400 -21600 0 CST}
{1964678400 -18000 1 CDT}
{1982818800 -21600 0 CST}
{1996128000 -18000 1 CDT}
{2014268400 -21600 0 CST}
{2027577600 -18000 1 CDT}
{2045718000 -21600 0 CST}
{2059027200 -18000 1 CDT}
{2077167600 -21600 0 CST}
{2091081600 -18000 1 CDT}
{2108617200 -21600 0 CST}
{2122531200 -18000 1 CDT}
{2140066800 -21600 0 CST}
{2153980800 -18000 1 CDT}
{2172121200 -21600 0 CST}
{2185430400 -18000 1 CDT}
{2203570800 -21600 0 CST}
{2216880000 -18000 1 CDT}
{2235020400 -21600 0 CST}
{2248934400 -18000 1 CDT}
{2266470000 -21600 0 CST}
{2280384000 -18000 1 CDT}
{2297919600 -21600 0 CST}
{2311833600 -18000 1 CDT}
{2329369200 -21600 0 CST}
{2343283200 -18000 1 CDT}
{2361423600 -21600 0 CST}
{2374732800 -18000 1 CDT}
{2392873200 -21600 0 CST}
{2406182400 -18000 1 CDT}
{2424322800 -21600 0 CST}
{2438236800 -18000 1 CDT}
{2455772400 -21600 0 CST}
{2469686400 -18000 1 CDT}
{2487222000 -21600 0 CST}
{2501136000 -18000 1 CDT}
{2519276400 -21600 0 CST}
{2532585600 -18000 1 CDT}
{2550726000 -21600 0 CST}
{2564035200 -18000 1 CDT}
{2582175600 -21600 0 CST}
{2596089600 -18000 1 CDT}
{2613625200 -21600 0 CST}
{2627539200 -18000 1 CDT}
{2645074800 -21600 0 CST}
{2658988800 -18000 1 CDT}
{2676524400 -21600 0 CST}
{2690438400 -18000 1 CDT}
{2708578800 -21600 0 CST}
{2721888000 -18000 1 CDT}
{2740028400 -21600 0 CST}
{2753337600 -18000 1 CDT}
{2771478000 -21600 0 CST}
{2785392000 -18000 1 CDT}
{2802927600 -21600 0 CST}
{2816841600 -18000 1 CDT}
{2834377200 -21600 0 CST}
{2848291200 -18000 1 CDT}
{2866431600 -21600 0 CST}
{2879740800 -18000 1 CDT}
{2897881200 -21600 0 CST}
{2911190400 -18000 1 CDT}
{2929330800 -21600 0 CST}
{2942640000 -18000 1 CDT}
{2960780400 -21600 0 CST}
{2974694400 -18000 1 CDT}
{2992230000 -21600 0 CST}
{3006144000 -18000 1 CDT}
{3023679600 -21600 0 CST}
{3037593600 -18000 1 CDT}
{3055734000 -21600 0 CST}
{3069043200 -18000 1 CDT}
{3087183600 -21600 0 CST}
{3100492800 -18000 1 CDT}
{3118633200 -21600 0 CST}
{3132547200 -18000 1 CDT}
{3150082800 -21600 0 CST}
{3163996800 -18000 1 CDT}
{3181532400 -21600 0 CST}
{3195446400 -18000 1 CDT}
{3212982000 -21600 0 CST}
{3226896000 -18000 1 CDT}
{3245036400 -21600 0 CST}
{3258345600 -18000 1 CDT}
{3276486000 -21600 0 CST}
{3289795200 -18000 1 CDT}
{3307935600 -21600 0 CST}
{3321849600 -18000 1 CDT}
{3339385200 -21600 0 CST}
{3353299200 -18000 1 CDT}
{3370834800 -21600 0 CST}
{3384748800 -18000 1 CDT}
{3402889200 -21600 0 CST}
{3416198400 -18000 1 CDT}
{3434338800 -21600 0 CST}
{3447648000 -18000 1 CDT}
{3465788400 -21600 0 CST}
{3479702400 -18000 1 CDT}
{3497238000 -21600 0 CST}
{3511152000 -18000 1 CDT}
{3528687600 -21600 0 CST}
{3542601600 -18000 1 CDT}
{3560137200 -21600 0 CST}
{3574051200 -18000 1 CDT}
{3592191600 -21600 0 CST}
{3605500800 -18000 1 CDT}
{3623641200 -21600 0 CST}
{3636950400 -18000 1 CDT}
{3655090800 -21600 0 CST}
{3669004800 -18000 1 CDT}
{3686540400 -21600 0 CST}
{3700454400 -18000 1 CDT}
{3717990000 -21600 0 CST}
{3731904000 -18000 1 CDT}
{3750044400 -21600 0 CST}
{3763353600 -18000 1 CDT}
{3781494000 -21600 0 CST}
{3794803200 -18000 1 CDT}
{3812943600 -21600 0 CST}
{3826252800 -18000 1 CDT}
{3844393200 -21600 0 CST}
{3858307200 -18000 1 CDT}
{3875842800 -21600 0 CST}
{3889756800 -18000 1 CDT}
{3907292400 -21600 0 CST}
{3921206400 -18000 1 CDT}
{3939346800 -21600 0 CST}
{3952656000 -18000 1 CDT}
{3970796400 -21600 0 CST}
{3984105600 -18000 1 CDT}
{4002246000 -21600 0 CST}
{4016160000 -18000 1 CDT}
{4033695600 -21600 0 CST}
{4047609600 -18000 1 CDT}
{4065145200 -21600 0 CST}
{4079059200 -18000 1 CDT}
{4096594800 -21600 0 CST}
}
|
{
"pile_set_name": "Github"
}
|
# created by tools/tclZIC.tcl - do not edit
set TZData(:America/Monterrey) {
{-9223372036854775808 -24076 0 LMT}
{-1514743200 -21600 0 CST}
{568015200 -21600 0 CST}
{576057600 -18000 1 CDT}
{594198000 -21600 0 CST}
{599637600 -21600 0 CST}
{828864000 -18000 1 CDT}
{846399600 -21600 0 CST}
{860313600 -18000 1 CDT}
{877849200 -21600 0 CST}
{891763200 -18000 1 CDT}
{909298800 -21600 0 CST}
{923212800 -18000 1 CDT}
{941353200 -21600 0 CST}
{954662400 -18000 1 CDT}
{972802800 -21600 0 CST}
{989136000 -18000 1 CDT}
{1001833200 -21600 0 CST}
{1018166400 -18000 1 CDT}
{1035702000 -21600 0 CST}
{1049616000 -18000 1 CDT}
{1067151600 -21600 0 CST}
{1081065600 -18000 1 CDT}
{1099206000 -21600 0 CST}
{1112515200 -18000 1 CDT}
{1130655600 -21600 0 CST}
{1143964800 -18000 1 CDT}
{1162105200 -21600 0 CST}
{1175414400 -18000 1 CDT}
{1193554800 -21600 0 CST}
{1207468800 -18000 1 CDT}
{1225004400 -21600 0 CST}
{1238918400 -18000 1 CDT}
{1256454000 -21600 0 CST}
{1270368000 -18000 1 CDT}
{1288508400 -21600 0 CST}
{1301817600 -18000 1 CDT}
{1319958000 -21600 0 CST}
{1333267200 -18000 1 CDT}
{1351407600 -21600 0 CST}
{1365321600 -18000 1 CDT}
{1382857200 -21600 0 CST}
{1396771200 -18000 1 CDT}
{1414306800 -21600 0 CST}
{1428220800 -18000 1 CDT}
{1445756400 -21600 0 CST}
{1459670400 -18000 1 CDT}
{1477810800 -21600 0 CST}
{1491120000 -18000 1 CDT}
{1509260400 -21600 0 CST}
{1522569600 -18000 1 CDT}
{1540710000 -21600 0 CST}
{1554624000 -18000 1 CDT}
{1572159600 -21600 0 CST}
{1586073600 -18000 1 CDT}
{1603609200 -21600 0 CST}
{1617523200 -18000 1 CDT}
{1635663600 -21600 0 CST}
{1648972800 -18000 1 CDT}
{1667113200 -21600 0 CST}
{1680422400 -18000 1 CDT}
{1698562800 -21600 0 CST}
{1712476800 -18000 1 CDT}
{1730012400 -21600 0 CST}
{1743926400 -18000 1 CDT}
{1761462000 -21600 0 CST}
{1775376000 -18000 1 CDT}
{1792911600 -21600 0 CST}
{1806825600 -18000 1 CDT}
{1824966000 -21600 0 CST}
{1838275200 -18000 1 CDT}
{1856415600 -21600 0 CST}
{1869724800 -18000 1 CDT}
{1887865200 -21600 0 CST}
{1901779200 -18000 1 CDT}
{1919314800 -21600 0 CST}
{1933228800 -18000 1 CDT}
{1950764400 -21600 0 CST}
{1964678400 -18000 1 CDT}
{1982818800 -21600 0 CST}
{1996128000 -18000 1 CDT}
{2014268400 -21600 0 CST}
{2027577600 -18000 1 CDT}
{2045718000 -21600 0 CST}
{2059027200 -18000 1 CDT}
{2077167600 -21600 0 CST}
{2091081600 -18000 1 CDT}
{2108617200 -21600 0 CST}
{2122531200 -18000 1 CDT}
{2140066800 -21600 0 CST}
{2153980800 -18000 1 CDT}
{2172121200 -21600 0 CST}
{2185430400 -18000 1 CDT}
{2203570800 -21600 0 CST}
{2216880000 -18000 1 CDT}
{2235020400 -21600 0 CST}
{2248934400 -18000 1 CDT}
{2266470000 -21600 0 CST}
{2280384000 -18000 1 CDT}
{2297919600 -21600 0 CST}
{2311833600 -18000 1 CDT}
{2329369200 -21600 0 CST}
{2343283200 -18000 1 CDT}
{2361423600 -21600 0 CST}
{2374732800 -18000 1 CDT}
{2392873200 -21600 0 CST}
{2406182400 -18000 1 CDT}
{2424322800 -21600 0 CST}
{2438236800 -18000 1 CDT}
{2455772400 -21600 0 CST}
{2469686400 -18000 1 CDT}
{2487222000 -21600 0 CST}
{2501136000 -18000 1 CDT}
{2519276400 -21600 0 CST}
{2532585600 -18000 1 CDT}
{2550726000 -21600 0 CST}
{2564035200 -18000 1 CDT}
{2582175600 -21600 0 CST}
{2596089600 -18000 1 CDT}
{2613625200 -21600 0 CST}
{2627539200 -18000 1 CDT}
{2645074800 -21600 0 CST}
{2658988800 -18000 1 CDT}
{2676524400 -21600 0 CST}
{2690438400 -18000 1 CDT}
{2708578800 -21600 0 CST}
{2721888000 -18000 1 CDT}
{2740028400 -21600 0 CST}
{2753337600 -18000 1 CDT}
{2771478000 -21600 0 CST}
{2785392000 -18000 1 CDT}
{2802927600 -21600 0 CST}
{2816841600 -18000 1 CDT}
{2834377200 -21600 0 CST}
{2848291200 -18000 1 CDT}
{2866431600 -21600 0 CST}
{2879740800 -18000 1 CDT}
{2897881200 -21600 0 CST}
{2911190400 -18000 1 CDT}
{2929330800 -21600 0 CST}
{2942640000 -18000 1 CDT}
{2960780400 -21600 0 CST}
{2974694400 -18000 1 CDT}
{2992230000 -21600 0 CST}
{3006144000 -18000 1 CDT}
{3023679600 -21600 0 CST}
{3037593600 -18000 1 CDT}
{3055734000 -21600 0 CST}
{3069043200 -18000 1 CDT}
{3087183600 -21600 0 CST}
{3100492800 -18000 1 CDT}
{3118633200 -21600 0 CST}
{3132547200 -18000 1 CDT}
{3150082800 -21600 0 CST}
{3163996800 -18000 1 CDT}
{3181532400 -21600 0 CST}
{3195446400 -18000 1 CDT}
{3212982000 -21600 0 CST}
{3226896000 -18000 1 CDT}
{3245036400 -21600 0 CST}
{3258345600 -18000 1 CDT}
{3276486000 -21600 0 CST}
{3289795200 -18000 1 CDT}
{3307935600 -21600 0 CST}
{3321849600 -18000 1 CDT}
{3339385200 -21600 0 CST}
{3353299200 -18000 1 CDT}
{3370834800 -21600 0 CST}
{3384748800 -18000 1 CDT}
{3402889200 -21600 0 CST}
{3416198400 -18000 1 CDT}
{3434338800 -21600 0 CST}
{3447648000 -18000 1 CDT}
{3465788400 -21600 0 CST}
{3479702400 -18000 1 CDT}
{3497238000 -21600 0 CST}
{3511152000 -18000 1 CDT}
{3528687600 -21600 0 CST}
{3542601600 -18000 1 CDT}
{3560137200 -21600 0 CST}
{3574051200 -18000 1 CDT}
{3592191600 -21600 0 CST}
{3605500800 -18000 1 CDT}
{3623641200 -21600 0 CST}
{3636950400 -18000 1 CDT}
{3655090800 -21600 0 CST}
{3669004800 -18000 1 CDT}
{3686540400 -21600 0 CST}
{3700454400 -18000 1 CDT}
{3717990000 -21600 0 CST}
{3731904000 -18000 1 CDT}
{3750044400 -21600 0 CST}
{3763353600 -18000 1 CDT}
{3781494000 -21600 0 CST}
{3794803200 -18000 1 CDT}
{3812943600 -21600 0 CST}
{3826252800 -18000 1 CDT}
{3844393200 -21600 0 CST}
{3858307200 -18000 1 CDT}
{3875842800 -21600 0 CST}
{3889756800 -18000 1 CDT}
{3907292400 -21600 0 CST}
{3921206400 -18000 1 CDT}
{3939346800 -21600 0 CST}
{3952656000 -18000 1 CDT}
{3970796400 -21600 0 CST}
{3984105600 -18000 1 CDT}
{4002246000 -21600 0 CST}
{4016160000 -18000 1 CDT}
{4033695600 -21600 0 CST}
{4047609600 -18000 1 CDT}
{4065145200 -21600 0 CST}
{4079059200 -18000 1 CDT}
{4096594800 -21600 0 CST}
}
|
{
"pile_set_name": "Github"
}
|
(module PinHeader_1x03_P2.54mm_Vertical_SMD_Pin1Right (layer F.Cu) (tedit 59FED5CC)
(descr "surface-mounted straight pin header, 1x03, 2.54mm pitch, single row, style 2 (pin 1 right)")
(tags "Surface mounted pin header SMD 1x03 2.54mm single row style2 pin1 right")
(attr smd)
(fp_text reference REF** (at 0 -4.87) (layer F.SilkS)
(effects (font (size 1 1) (thickness 0.15)))
)
(fp_text value PinHeader_1x03_P2.54mm_Vertical_SMD_Pin1Right (at 0 4.87) (layer F.Fab)
(effects (font (size 1 1) (thickness 0.15)))
)
(fp_line (start 1.27 3.81) (end -1.27 3.81) (layer F.Fab) (width 0.1))
(fp_line (start -1.27 -3.81) (end 0.32 -3.81) (layer F.Fab) (width 0.1))
(fp_line (start 1.27 3.81) (end 1.27 -2.86) (layer F.Fab) (width 0.1))
(fp_line (start 1.27 -2.86) (end 0.32 -3.81) (layer F.Fab) (width 0.1))
(fp_line (start -1.27 -3.81) (end -1.27 3.81) (layer F.Fab) (width 0.1))
(fp_line (start -1.27 -0.32) (end -2.54 -0.32) (layer F.Fab) (width 0.1))
(fp_line (start -2.54 -0.32) (end -2.54 0.32) (layer F.Fab) (width 0.1))
(fp_line (start -2.54 0.32) (end -1.27 0.32) (layer F.Fab) (width 0.1))
(fp_line (start 1.27 -2.86) (end 2.54 -2.86) (layer F.Fab) (width 0.1))
(fp_line (start 2.54 -2.86) (end 2.54 -2.22) (layer F.Fab) (width 0.1))
(fp_line (start 2.54 -2.22) (end 1.27 -2.22) (layer F.Fab) (width 0.1))
(fp_line (start 1.27 2.22) (end 2.54 2.22) (layer F.Fab) (width 0.1))
(fp_line (start 2.54 2.22) (end 2.54 2.86) (layer F.Fab) (width 0.1))
(fp_line (start 2.54 2.86) (end 1.27 2.86) (layer F.Fab) (width 0.1))
(fp_line (start -1.33 -3.87) (end 1.33 -3.87) (layer F.SilkS) (width 0.12))
(fp_line (start -1.33 3.87) (end 1.33 3.87) (layer F.SilkS) (width 0.12))
(fp_line (start 1.33 -1.78) (end 1.33 1.78) (layer F.SilkS) (width 0.12))
(fp_line (start -1.33 -3.87) (end -1.33 -0.76) (layer F.SilkS) (width 0.12))
(fp_line (start 1.33 -3.3) (end 2.85 -3.3) (layer F.SilkS) (width 0.12))
(fp_line (start 1.33 -3.87) (end 1.33 -3.3) (layer F.SilkS) (width 0.12))
(fp_line (start -1.33 3.3) (end -1.33 3.87) (layer F.SilkS) (width 0.12))
(fp_line (start -1.33 0.76) (end -1.33 3.87) (layer F.SilkS) (width 0.12))
(fp_line (start -3.45 -4.35) (end -3.45 4.35) (layer F.CrtYd) (width 0.05))
(fp_line (start -3.45 4.35) (end 3.45 4.35) (layer F.CrtYd) (width 0.05))
(fp_line (start 3.45 4.35) (end 3.45 -4.35) (layer F.CrtYd) (width 0.05))
(fp_line (start 3.45 -4.35) (end -3.45 -4.35) (layer F.CrtYd) (width 0.05))
(pad 2 smd rect (at -1.655 0) (size 2.51 1) (layers F.Cu F.Mask F.Paste))
(pad 1 smd rect (at 1.655 -2.54) (size 2.51 1) (layers F.Cu F.Mask F.Paste))
(pad 3 smd rect (at 1.655 2.54) (size 2.51 1) (layers F.Cu F.Mask F.Paste))
(fp_text user %R (at 0 0 90) (layer F.Fab)
(effects (font (size 1 1) (thickness 0.15)))
)
(model ${KISYS3DMOD}/Connector_PinHeader_2.54mm.3dshapes/PinHeader_1x03_P2.54mm_Vertical_SMD_Pin1Right.wrl
(at (xyz 0 0 0))
(scale (xyz 1 1 1))
(rotate (xyz 0 0 0))
)
)
|
{
"pile_set_name": "Github"
}
|
using System;
namespace TODOSQLiteSample.Models
{
public class TodoItem : Mvvm.BindableBase
{
private string _Id = default(string);
public string Id { get { return _Id; } set { Set(ref _Id, value); } }
private string _Title = default(string);
public string Title { get { return _Title; } set { Set(ref _Title, value); } }
private DateTime _DueDate = default(DateTime);
public DateTime DueDate { get { return _DueDate; } set { Set(ref _DueDate, value); } }
private bool _IsComplete = default(bool);
public bool IsComplete { get { return _IsComplete; } set { Set(ref _IsComplete, value); } }
private string _Details = default(string);
public string Details { get { return _Details; } set { Set(ref _Details, value); } }
private bool _IsFavorite = default(bool);
public bool IsFavorite { get { return _IsFavorite; } set { Set(ref _IsFavorite, value); } }
private string _ListId = default(string);
public string ListId { get { return _ListId; } set { Set(ref _ListId, value); } }
}
}
|
{
"pile_set_name": "Github"
}
|
--- ../src-base/minecraft/net/minecraft/tileentity/TileEntityHopper.java
+++ ../src-work/minecraft/net/minecraft/tileentity/TileEntityHopper.java
@@ -7,12 +7,14 @@
import net.minecraft.block.BlockHopper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
+import net.minecraft.entity.item.EntityMinecartHopper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.ContainerHopper;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
+import net.minecraft.inventory.InventoryLargeChest;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
@@ -27,6 +29,12 @@
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
+import org.bukkit.craftbukkit.entity.CraftHumanEntity;
+import org.bukkit.craftbukkit.inventory.CraftItemStack;
+import org.bukkit.entity.HumanEntity;
+import org.bukkit.event.inventory.InventoryMoveItemEvent;
+import org.bukkit.event.inventory.InventoryPickupItemEvent;
+import org.bukkit.inventory.Inventory;
public class TileEntityHopper extends TileEntityLockableLoot implements IHopper, ITickable
{
@@ -34,6 +42,32 @@
private int transferCooldown = -1;
private long tickedGameTime;
+ public List<HumanEntity> transaction = new java.util.ArrayList<HumanEntity>();
+ private int maxStack = MAX_STACK;
+
+ public List<ItemStack> getContents() {
+ return this.inventory;
+ }
+
+ public void setMaxStackSize(int size) {
+ maxStack = size;
+ }
+
+ @Override
+ public void onOpen(CraftHumanEntity who) {
+ transaction.add(who);
+ }
+
+ @Override
+ public void onClose(CraftHumanEntity who) {
+ transaction.remove(who);
+ }
+
+ @Override
+ public List<HumanEntity> getViewers() {
+ return transaction;
+ }
+
public static void registerFixesHopper(DataFixer fixer)
{
fixer.registerWalker(FixTypes.BLOCK_ENTITY, new ItemStackDataLists(TileEntityHopper.class, new String[] {"Items"}));
@@ -106,7 +140,7 @@
public int getInventoryStackLimit()
{
- return 64;
+ return maxStack;
}
public void update()
@@ -144,7 +178,7 @@
if (flag)
{
- this.setTransferCooldown(8);
+ this.setTransferCooldown(world.spigotConfig.hopperTransfer); // Spigot
this.markDirty();
return true;
}
@@ -213,11 +247,36 @@
if (!this.getStackInSlot(i).isEmpty())
{
ItemStack itemstack = this.getStackInSlot(i).copy();
- ItemStack itemstack1 = putStackInInventoryAllSlots(this, iinventory, this.decrStackSize(i, 1), enumfacing);
+ // ItemStack itemstack1 = putStackInInventoryAllSlots(this, iinventory, this.decrStackSize(i, 1), enumfacing);
+ // CraftBukkit start - Call event when pushing items into other inventories
+ CraftItemStack oitemstack = CraftItemStack.asCraftMirror(this.decrStackSize(i, 1));
+ Inventory destinationInventory;
+ // Have to special case large chests as they work oddly
+ if (iinventory instanceof InventoryLargeChest) {
+ destinationInventory = new org.bukkit.craftbukkit.inventory.CraftInventoryDoubleChest((InventoryLargeChest) iinventory);
+ } else {
+ destinationInventory = iinventory.getOwner().getInventory();
+ }
+
+ InventoryMoveItemEvent event = new InventoryMoveItemEvent(this.getOwner().getInventory(), oitemstack.clone(), destinationInventory, true);
+ this.getWorld().getServer().getPluginManager().callEvent(event);
+ if (event.isCancelled()) {
+ this.setInventorySlotContents(i, itemstack);
+ this.setTransferCooldown(8); // Delay hopper checks
+ return false;
+ }
+ ItemStack itemstack1 = putStackInInventoryAllSlots(this, iinventory, CraftItemStack.asNMSCopy(event.getItem()), enumfacing);
+
if (itemstack1.isEmpty())
{
- iinventory.markDirty();
+ // iinventory.markDirty();
+ if (event.getItem().equals(oitemstack)) {
+ iinventory.markDirty();
+ } else {
+ this.setInventorySlotContents(i, itemstack);
+ }
+ // CraftBukkit end
return true;
}
@@ -358,14 +417,47 @@
if (!itemstack.isEmpty() && canExtractItemFromSlot(inventoryIn, itemstack, index, direction))
{
ItemStack itemstack1 = itemstack.copy();
- ItemStack itemstack2 = putStackInInventoryAllSlots(inventoryIn, hopper, inventoryIn.decrStackSize(index, 1), (EnumFacing)null);
+ // ItemStack itemstack2 = putStackInInventoryAllSlots(inventoryIn, hopper, inventoryIn.decrStackSize(index, 1), (EnumFacing)null);
+ // CraftBukkit start - Call event on collection of items from inventories into the hopper
+ CraftItemStack oitemstack = CraftItemStack.asCraftMirror(inventoryIn.decrStackSize(index, hopper.getWorld().spigotConfig.hopperAmount));
+ Inventory sourceInventory;
+ // Have to special case large chests as they work oddly
+ if (inventoryIn instanceof InventoryLargeChest) {
+ sourceInventory = new org.bukkit.craftbukkit.inventory.CraftInventoryDoubleChest((InventoryLargeChest) inventoryIn);
+ } else {
+ sourceInventory = inventoryIn.getOwner().getInventory();
+ }
+
+ InventoryMoveItemEvent event = new InventoryMoveItemEvent(sourceInventory, oitemstack.clone(), hopper.getOwner().getInventory(), false);
+
+ hopper.getWorld().getServer().getPluginManager().callEvent(event);
+ if (event.isCancelled()) {
+ inventoryIn.setInventorySlotContents(index, itemstack1);
+
+ if (hopper instanceof TileEntityHopper) {
+ ((TileEntityHopper) hopper).setTransferCooldown(hopper.getWorld().spigotConfig.hopperTransfer); // Delay hopper checks
+ } else if (hopper instanceof EntityMinecartHopper) {
+ ((EntityMinecartHopper) hopper).setTransferTicker(hopper.getWorld().spigotConfig.hopperTransfer / 2); // Delay hopper minecart checks
+ }
+
+ return false;
+ }
+ int origCount = event.getItem().getAmount(); // Spigot
+ ItemStack itemstack2 = putStackInInventoryAllSlots(inventoryIn, hopper, CraftItemStack.asNMSCopy(event.getItem()), null);
+
if (itemstack2.isEmpty())
{
- inventoryIn.markDirty();
+ // inventoryIn.markDirty();
+ if (event.getItem().equals(oitemstack)) {
+ inventoryIn.markDirty();
+ } else {
+ inventoryIn.setInventorySlotContents(index, itemstack1);
+ }
+ // CraftBukkit end
return true;
}
-
+ itemstack1.shrink(origCount - itemstack2.getCount());
inventoryIn.setInventorySlotContents(index, itemstack1);
}
@@ -382,6 +474,11 @@
}
else
{
+ InventoryPickupItemEvent event = new InventoryPickupItemEvent(destination.getOwner().getInventory(), (org.bukkit.entity.Item) entity.getBukkitEntity());
+ entity.world.getServer().getPluginManager().callEvent(event);
+ if (event.isCancelled()) {
+ return false;
+ }
ItemStack itemstack = entity.getItem().copy();
ItemStack itemstack1 = putStackInInventoryAllSlots(source, destination, itemstack, (EnumFacing)null);
@@ -491,7 +588,7 @@
}
}
- tileentityhopper1.setTransferCooldown(8 - k);
+ tileentityhopper1.setTransferCooldown(tileentityhopper1.world.spigotConfig.hopperTransfer - k); // Spigot
}
}
@@ -525,6 +622,7 @@
int j = MathHelper.floor(y);
int k = MathHelper.floor(z);
BlockPos blockpos = new BlockPos(i, j, k);
+ if (!worldIn.isBlockLoaded(blockpos)) return null; // Spigot
net.minecraft.block.state.IBlockState state = worldIn.getBlockState(blockpos);
Block block = state.getBlock();
|
{
"pile_set_name": "Github"
}
|
package com.smartdevicelink.test.rpc.enums;
import com.smartdevicelink.proxy.rpc.enums.MassageCushion;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* This is a unit test class for the SmartDeviceLink library project class :
* {@link com.smartdevicelink.rpc.enums.MassageCushion}
*/
public class MassageCushionTests extends TestCase {
/**
* Verifies that the enum values are not null upon valid assignment.
*/
public void testValidEnums() {
String example = "TOP_LUMBAR";
MassageCushion enumTopLumbar = MassageCushion.valueForString(example);
example = "MIDDLE_LUMBAR";
MassageCushion enumMiddleLumbar = MassageCushion.valueForString(example);
example = "BOTTOM_LUMBAR";
MassageCushion enumBottomLumbar = MassageCushion.valueForString(example);
example = "BACK_BOLSTERS";
MassageCushion enumBackBolsters = MassageCushion.valueForString(example);
example = "SEAT_BOLSTERS";
MassageCushion enumSeatBolsters = MassageCushion.valueForString(example);
assertNotNull("TOP_LUMBAR returned null", enumTopLumbar);
assertNotNull("MIDDLE_LUMBAR returned null", enumMiddleLumbar);
assertNotNull("BOTTOM_LUMBAR returned null", enumBottomLumbar);
assertNotNull("BACK_BOLSTERS returned null", enumBackBolsters);
assertNotNull("SEAT_BOLSTERS returned null", enumSeatBolsters);
}
/**
* Verifies that an invalid assignment is null.
*/
public void testInvalidEnum() {
String example = "tOP_LUMBAR";
try {
MassageCushion temp = MassageCushion.valueForString(example);
assertNull("Result of valueForString should be null.", temp);
} catch (IllegalArgumentException exception) {
fail("Invalid enum throws IllegalArgumentException.");
}
}
/**
* Verifies that a null assignment is invalid.
*/
public void testNullEnum() {
String example = null;
try {
MassageCushion temp = MassageCushion.valueForString(example);
assertNull("Result of valueForString should be null.", temp);
} catch (NullPointerException exception) {
fail("Null string throws NullPointerException.");
}
}
/**
* Verifies the possible enum values of MassageCushion.
*/
public void testListEnum() {
List<MassageCushion> enumValueList = Arrays.asList(MassageCushion.values());
List<MassageCushion> enumTestList = new ArrayList<MassageCushion>();
enumTestList.add(MassageCushion.TOP_LUMBAR);
enumTestList.add(MassageCushion.MIDDLE_LUMBAR);
enumTestList.add(MassageCushion.BOTTOM_LUMBAR);
enumTestList.add(MassageCushion.BACK_BOLSTERS);
enumTestList.add(MassageCushion.SEAT_BOLSTERS);
assertTrue("Enum value list does not match enum class list",
enumValueList.containsAll(enumTestList) && enumTestList.containsAll(enumValueList));
}
}
|
{
"pile_set_name": "Github"
}
|
//
// LoopMath.swift
// Naterade
//
// Created by Nathan Racklyeft on 1/24/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
import HealthKit
public enum LoopMath {
static func simulationDateRangeForSamples<T: Collection>(
_ samples: T,
from start: Date? = nil,
to end: Date? = nil,
duration: TimeInterval,
delay: TimeInterval = 0,
delta: TimeInterval
) -> (start: Date, end: Date)? where T.Element: TimelineValue {
guard samples.count > 0 else {
return nil
}
if let start = start, let end = end {
return (start: start.dateFlooredToTimeInterval(delta), end: end.dateCeiledToTimeInterval(delta))
} else {
var minDate = samples.first!.startDate
var maxDate = minDate
for sample in samples {
if sample.startDate < minDate {
minDate = sample.startDate
}
if sample.endDate > maxDate {
maxDate = sample.endDate
}
}
return (
start: (start ?? minDate).dateFlooredToTimeInterval(delta),
end: (end ?? maxDate.addingTimeInterval(duration + delay)).dateCeiledToTimeInterval(delta)
)
}
}
/**
Calculates a timeline of predicted glucose values from a variety of effects timelines.
Each effect timeline:
- Is given equal weight, with the exception of the momentum effect timeline
- Can be of arbitrary size and start date
- Should be in ascending order
- Should have aligning dates with any overlapping timelines to ensure a smooth result
- parameter startingGlucose: The starting glucose value
- parameter momentum: The momentum effect timeline determined from prior glucose values
- parameter effects: The glucose effect timelines to apply to the prediction.
- returns: A timeline of glucose values
*/
public static func predictGlucose(startingAt startingGlucose: GlucoseValue, momentum: [GlucoseEffect] = [], effects: [GlucoseEffect]...) -> [PredictedGlucoseValue] {
return predictGlucose(startingAt: startingGlucose, momentum: momentum, effects: effects)
}
/**
Calculates a timeline of predicted glucose values from a variety of effects timelines.
Each effect timeline:
- Is given equal weight, with the exception of the momentum effect timeline
- Can be of arbitrary size and start date
- Should be in ascending order
- Should have aligning dates with any overlapping timelines to ensure a smooth result
- parameter startingGlucose: The starting glucose value
- parameter momentum: The momentum effect timeline determined from prior glucose values
- parameter effects: The glucose effect timelines to apply to the prediction.
- returns: A timeline of glucose values
*/
public static func predictGlucose(startingAt startingGlucose: GlucoseValue, momentum: [GlucoseEffect] = [], effects: [[GlucoseEffect]]) -> [PredictedGlucoseValue] {
var effectValuesAtDate: [Date: Double] = [:]
let unit = HKUnit.milligramsPerDeciliter
for timeline in effects {
var previousEffectValue: Double = timeline.first?.quantity.doubleValue(for: unit) ?? 0
for effect in timeline {
let value = effect.quantity.doubleValue(for: unit)
effectValuesAtDate[effect.startDate] = (effectValuesAtDate[effect.startDate] ?? 0) + value - previousEffectValue
previousEffectValue = value
}
}
// Blend the momentum effect linearly into the summed effect list
if momentum.count > 1 {
var previousEffectValue: Double = momentum[0].quantity.doubleValue(for: unit)
// The blend begins delta minutes after after the last glucose (1.0) and ends at the last momentum point (0.0)
// We're assuming the first one occurs on or before the starting glucose.
let blendCount = momentum.count - 2
let timeDelta = momentum[1].startDate.timeIntervalSince(momentum[0].startDate)
// The difference between the first momentum value and the starting glucose value
let momentumOffset = startingGlucose.startDate.timeIntervalSince(momentum[0].startDate)
let blendSlope = 1.0 / Double(blendCount)
let blendOffset = momentumOffset / timeDelta * blendSlope
for (index, effect) in momentum.enumerated() {
let value = effect.quantity.doubleValue(for: unit)
let effectValueChange = value - previousEffectValue
let split = min(1.0, max(0.0, Double(momentum.count - index) / Double(blendCount) - blendSlope + blendOffset))
let effectBlend = (1.0 - split) * (effectValuesAtDate[effect.startDate] ?? 0)
let momentumBlend = split * effectValueChange
effectValuesAtDate[effect.startDate] = effectBlend + momentumBlend
previousEffectValue = value
}
}
let prediction = effectValuesAtDate.sorted { $0.0 < $1.0 }.reduce([PredictedGlucoseValue(startDate: startingGlucose.startDate, quantity: startingGlucose.quantity)]) { (prediction, effect) -> [PredictedGlucoseValue] in
if effect.0 > startingGlucose.startDate, let lastValue = prediction.last {
let nextValue = PredictedGlucoseValue(
startDate: effect.0,
quantity: HKQuantity(unit: unit, doubleValue: effect.1 + lastValue.quantity.doubleValue(for: unit))
)
return prediction + [nextValue]
} else {
return prediction
}
}
return prediction
}
}
extension GlucoseValue {
/**
Calculates a timeline of glucose effects by applying a linear decay to a rate of change.
- parameter rate: The glucose velocity
- parameter duration: The duration the effect should continue before ending
- parameter delta: The time differential for the returned values
- returns: An array of glucose effects
*/
public func decayEffect(atRate rate: HKQuantity, for duration: TimeInterval, withDelta delta: TimeInterval = 5 * 60) -> [GlucoseEffect] {
guard let (startDate, endDate) = LoopMath.simulationDateRangeForSamples([self], duration: duration, delta: delta) else {
return []
}
let glucoseUnit = HKUnit.milligramsPerDeciliter
let velocityUnit = GlucoseEffectVelocity.perSecondUnit
// The starting rate, which we will decay to 0 over the specified duration
let intercept = rate.doubleValue(for: velocityUnit) // mg/dL/s
let decayStartDate = startDate.addingTimeInterval(delta)
let slope = -intercept / (duration - delta) // mg/dL/s/s
var values = [GlucoseEffect(startDate: startDate, quantity: quantity)]
var date = decayStartDate
var lastValue = quantity.doubleValue(for: glucoseUnit)
repeat {
let value = lastValue + (intercept + slope * date.timeIntervalSince(decayStartDate)) * delta
values.append(GlucoseEffect(startDate: date, quantity: HKQuantity(unit: glucoseUnit, doubleValue: value)))
lastValue = value
date = date.addingTimeInterval(delta)
} while date < endDate
return values
}
}
extension BidirectionalCollection where Element == GlucoseEffect {
/// Sums adjacent glucose effects into buckets of the specified duration.
///
/// Requires the receiver to be sorted chronologically by endDate
///
/// - Parameter duration: The duration of each resulting summed element
/// - Returns: An array of summed effects
public func combinedSums(of duration: TimeInterval) -> [GlucoseChange] {
var sums = [GlucoseChange]()
sums.reserveCapacity(self.count)
var lastValidIndex = sums.startIndex
for effect in reversed() {
sums.append(GlucoseChange(startDate: effect.startDate, endDate: effect.endDate, quantity: effect.quantity))
for sumsIndex in lastValidIndex..<(sums.endIndex - 1) {
guard sums[sumsIndex].endDate <= effect.endDate.addingTimeInterval(duration) else {
lastValidIndex += 1
continue
}
sums[sumsIndex].append(effect)
}
}
return sums.reversed()
}
}
extension BidirectionalCollection where Element == GlucoseEffectVelocity {
/// Subtracts an array of glucose effects with uniform intervals and no gaps from the collection of effect changes, which may not have uniform intervals.
///
/// - Parameters:
/// - otherEffects: The array of glucose effects to subtract
/// - effectInterval: The time interval between elements in the otherEffects array
/// - Returns: A resulting array of glucose effects
public func subtracting(_ otherEffects: [GlucoseEffect], withUniformInterval effectInterval: TimeInterval) -> [GlucoseEffect] {
// Trim both collections to match
let otherEffects = otherEffects.filterDateRange(self.first?.endDate, nil)
let effects = self.filterDateRange(otherEffects.first?.startDate, nil)
var subtracted: [GlucoseEffect] = []
var previousOtherEffectValue = otherEffects.first?.quantity.doubleValue(for: .milligramsPerDeciliter) ?? 0 // mg/dL
var effectIndex = effects.startIndex
for otherEffect in otherEffects.dropFirst() {
guard effectIndex < effects.endIndex else {
break
}
let otherEffectValue = otherEffect.quantity.doubleValue(for: .milligramsPerDeciliter)
let otherEffectChange = otherEffectValue - previousOtherEffectValue
previousOtherEffectValue = otherEffectValue
let effect = effects[effectIndex]
// Our effect array may have gaps, or have longer segments than 5 minutes.
guard effect.endDate <= otherEffect.endDate else {
continue // Move on to the next other effect
}
effectIndex += 1
let effectValue = effect.quantity.doubleValue(for: GlucoseEffectVelocity.perSecondUnit) // mg/dL/s
let effectValueMatchingOtherEffectInterval = effectValue * effectInterval // mg/dL
subtracted.append(GlucoseEffect(
startDate: effect.endDate,
quantity: HKQuantity(
unit: .milligramsPerDeciliter,
doubleValue: effectValueMatchingOtherEffectInterval - otherEffectChange
)
))
}
// If we have run out of otherEffect items, we assume the otherEffectChange remains zero
for effect in effects[effectIndex..<effects.endIndex] {
let effectValue = effect.quantity.doubleValue(for: GlucoseEffectVelocity.perSecondUnit) // mg/dL/s
let effectValueMatchingOtherEffectInterval = effectValue * effectInterval // mg/dL
subtracted.append(GlucoseEffect(
startDate: effect.endDate,
quantity: HKQuantity(
unit: .milligramsPerDeciliter,
doubleValue: effectValueMatchingOtherEffectInterval
)
))
}
return subtracted
}
}
|
{
"pile_set_name": "Github"
}
|
import os
import re
from tqdm import tqdm
import subprocess
import shutil
from .base import BaseTrainer
from ..helper import thirdparty_binary, make_path_safe
from ..multiprocessing import (align, mono_align_equal, compile_train_graphs,
acc_stats, tree_stats, convert_alignments,
convert_ali_to_textgrids, calc_fmllr,
compile_information)
class TriphoneTrainer(BaseTrainer):
'''
Configuration class for triphone training
Attributes
----------
num_iterations : int
Number of training iterations to perform, defaults to 40
transition_scale : float
Scaling of transition costs in alignment, defaults to 1.0
acoustic_scale : float
Scaling of acoustic costs in alignment, defaults to 0.1
self_loop_scale : float
Scaling of self loop costs in alignment, defaults to 0.1
beam : int
Default beam width for alignment, defaults = 10
retry_beam : int
Beam width to fall back on if no alignment is produced, defaults to 40
max_gaussians : int
Total number of gaussians, defaults to 1000
boost_silence : float
Factor by which to boost silence likelihoods in alignment, defaults to 1.0
realignment_iterations : list
List of iterations to perform alignment
power : float
Exponent for number of gaussians according to occurrence counts, defaults to 0.25
num_leaves : int
Number of states in the decision tree, defaults to 1000
max_gaussians : int
Number of gaussians in the decision tree, defaults to 10000
cluster_threshold : int
For build-tree control final bottom-up clustering of leaves, defaults to 100
'''
def __init__(self, default_feature_config):
super(TriphoneTrainer, self).__init__(default_feature_config)
self.num_iterations = 35
self.num_leaves = 1000
self.max_gaussians = 10000
self.cluster_threshold = -1
self.compute_calculated_properties()
def compute_calculated_properties(self):
for i in range(0, self.num_iterations, 10):
if i == 0:
continue
self.realignment_iterations.append(i)
self.initial_gaussians = self.num_leaves
@property
def train_type(self):
return 'tri'
@property
def phone_type(self):
return 'triphone'
def init_training(self, identifier, temporary_directory, corpus, dictionary, previous_trainer):
self._setup_for_init(identifier, temporary_directory, corpus, dictionary)
if os.path.exists(os.path.join(self.train_directory, 'final.mdl')):
return
align_directory = previous_trainer.align_directory
context_opts = []
ci_phones = self.dictionary.silence_csl
tree_stats(self.train_directory, align_directory,
self.data_directory, ci_phones, self.corpus.num_jobs, self)
log_path = os.path.join(self.log_directory, 'questions.log')
tree_path = os.path.join(self.train_directory, 'tree')
treeacc_path = os.path.join(self.train_directory, 'treeacc')
sets_int_path = os.path.join(self.dictionary.phones_dir, 'sets.int')
roots_int_path = os.path.join(self.dictionary.phones_dir, 'roots.int')
extra_question_int_path = os.path.join(self.dictionary.phones_dir, 'extra_questions.int')
topo_path = os.path.join(self.dictionary.output_directory, 'topo')
questions_path = os.path.join(self.train_directory, 'questions.int')
questions_qst_path = os.path.join(self.train_directory, 'questions.qst')
with open(log_path, 'w') as logf:
subprocess.call([thirdparty_binary('cluster-phones')] + context_opts +
[treeacc_path, sets_int_path, questions_path], stderr=logf)
with open(extra_question_int_path, 'r') as inf, \
open(questions_path, 'a') as outf:
for line in inf:
outf.write(line)
log_path = os.path.join(self.log_directory, 'compile_questions.log')
with open(log_path, 'w') as logf:
subprocess.call([thirdparty_binary('compile-questions')] + context_opts +
[topo_path, questions_path, questions_qst_path],
stderr=logf)
log_path = os.path.join(self.log_directory, 'build_tree.log')
with open(log_path, 'w') as logf:
subprocess.call([thirdparty_binary('build-tree')] + context_opts +
['--verbose=1', '--max-leaves={}'.format(self.initial_gaussians),
'--cluster-thresh={}'.format(self.cluster_threshold),
treeacc_path, roots_int_path, questions_qst_path,
topo_path, tree_path], stderr=logf)
log_path = os.path.join(self.log_directory, 'init_model.log')
occs_path = os.path.join(self.train_directory, '0.occs')
mdl_path = os.path.join(self.train_directory, '0.mdl')
with open(log_path, 'w') as logf:
subprocess.call([thirdparty_binary('gmm-init-model'),
'--write-occs=' + occs_path, tree_path, treeacc_path,
topo_path, mdl_path], stderr=logf)
log_path = os.path.join(self.log_directory, 'mixup.log')
with open(log_path, 'w') as logf:
subprocess.call([thirdparty_binary('gmm-mixup'),
'--mix-up={}'.format(self.initial_gaussians),
mdl_path, occs_path, mdl_path], stderr=logf)
os.remove(treeacc_path)
compile_train_graphs(self.train_directory, self.dictionary.output_directory,
self.data_directory, self.corpus.num_jobs)
os.rename(occs_path, os.path.join(self.train_directory, '1.occs'))
os.rename(mdl_path, os.path.join(self.train_directory, '1.mdl'))
convert_alignments(self.train_directory, align_directory, self.corpus.num_jobs)
print('Initialization complete!')
|
{
"pile_set_name": "Github"
}
|
###### suite/funcs_1/include/myisam_tb2.inc
--disable_warnings
drop table if exists tb2 ;
--enable_warnings
create table tb2 (
f59 numeric (0) unsigned,
f60 numeric (64) unsigned,
f61 numeric (0) zerofill,
f62 numeric (64) zerofill,
f63 numeric (0) unsigned zerofill,
f64 numeric (64) unsigned zerofill,
f65 numeric (0,0),
f66 numeric (63,30),
f67 numeric (0,0) unsigned,
f68 numeric (63,30) unsigned,
f69 numeric (0,0) zerofill,
f70 numeric (63,30) zerofill,
f71 numeric (0,0) unsigned zerofill,
f72 numeric (63,30) unsigned zerofill,
f73 real,
f74 real unsigned,
f75 real zerofill,
f76 real unsigned zerofill,
f77 double default 7.7,
f78 double unsigned default 7.7,
f79 double zerofill default 7.7,
f80 double unsigned zerofill default 8.8,
f81 float not null default 8.8,
f82 float unsigned not null default 8.8,
f83 float zerofill not null default 8.8,
f84 float unsigned zerofill not null default 8.8,
f85 float(0) not null default 8.8,
f86 float(23) not null default 8.8,
f87 float(0) unsigned not null default 8.8,
f88 float(23) unsigned not null default 8.8,
f89 float(0) zerofill not null default 8.8,
f90 float(23) zerofill not null default 8.8,
f91 float(0) unsigned zerofill not null default 8.8,
f92 float(23) unsigned zerofill not null default 8.8,
f93 float(24) not null default 8.8,
f94 float(53) not null default 8.8,
f95 float(24) unsigned not null default 8.8,
f96 float(53) unsigned not null default 8.8,
f97 float(24) zerofill not null default 8.8,
f98 float(53) zerofill not null default 8.8,
f99 float(24) unsigned zerofill not null default 8.8,
f100 float(53) unsigned zerofill not null default 8.8,
f101 date not null default '2000-01-01',
f102 time not null default 20,
f103 datetime not null default '2/2/2',
f104 timestamp not null default 20001231235959,
f105 year not null default 2000,
f106 year(3) not null default 2000,
f107 year(4) not null default 2000,
f108 enum("1enum","2enum") not null default "1enum",
f109 set("1set","2set") not null default "1set",
f110 VARBINARY(64) null,
f111 VARBINARY(27) null ,
f112 VARBINARY(64) null ,
f113 VARBINARY(192) null ,
f114 VARBINARY(192) ,
f115 VARBINARY(27) null ,
f116 VARBINARY(64) null,
f117 VARBINARY(192) null
) engine = myisam;
# The original columns. They are replaced by varbinary, because the funcs_1 tests should
# not depend on the optional availability of the geometry feature.
# f110 geometry null,
# f111 point null ,
# f112 linestring null ,
# f113 polygon null ,
# f114 geometrycollection ,
# f115 multipoint null ,
# f116 multilinestring null,
# f117 multipolygon null
--replace_result $MYSQLTEST_VARDIR <MYSQLTEST_VARDIR>
eval
load data infile '$MYSQLTEST_VARDIR/std_data/funcs_1/myisam_tb2.txt'
into table tb2;
|
{
"pile_set_name": "Github"
}
|
/**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
goog.module('goog.ui.media.MediaTest');
goog.setTestOnly();
const ControlRenderer = goog.require('goog.ui.ControlRenderer');
const Media = goog.require('goog.ui.media.Media');
const MediaModel = goog.require('goog.ui.media.MediaModel');
const MediaRenderer = goog.require('goog.ui.media.MediaRenderer');
const Size = goog.require('goog.math.Size');
const TagName = goog.require('goog.dom.TagName');
const dom = goog.require('goog.dom');
const testSuite = goog.require('goog.testing.testSuite');
const testing = goog.require('goog.html.testing');
let control; // The name 'media' collides with a built-in var in Chrome.
let renderer;
let model;
testSuite({
setUp() {
renderer = new MediaRenderer();
model = new MediaModel('http://url.com', 'a caption', 'a description');
control = new Media(model, renderer);
},
tearDown() {
control.dispose();
},
testBasicElements() {
const model =
new MediaModel('http://url.com', 'a caption', 'a description');
const thumb1 = new MediaModel.Thumbnail(
'http://thumb.com/small.jpg', new Size(320, 288));
const thumb2 = new MediaModel.Thumbnail(
'http://thumb.com/big.jpg', new Size(800, 600));
model.setThumbnails([thumb1, thumb2]);
model.setPlayer(new MediaModel.Player(
testing.newTrustedResourceUrlForTest('http://media/player.swf')));
const control = new Media(model, renderer);
control.render();
const caption = dom.getElementsByTagNameAndClass(
undefined, ControlRenderer.CSS_CLASS + '-caption');
const description = dom.getElementsByTagNameAndClass(
undefined, ControlRenderer.CSS_CLASS + '-description');
const thumbnail0 = dom.getElementsByTagNameAndClass(
TagName.IMG, ControlRenderer.CSS_CLASS + '-thumbnail0');
const thumbnail1 = dom.getElementsByTagNameAndClass(
TagName.IMG, ControlRenderer.CSS_CLASS + '-thumbnail1');
const player = dom.getElementsByTagNameAndClass(
TagName.IFRAME, ControlRenderer.CSS_CLASS + '-player');
assertNotNull(caption);
assertEquals(1, caption.length);
assertNotNull(description);
assertEquals(1, description.length);
assertNotNull(thumbnail0);
assertEquals(1, thumbnail0.length);
assertEquals('320px', thumbnail0[0].style.width);
assertEquals('288px', thumbnail0[0].style.height);
assertEquals('http://thumb.com/small.jpg', thumbnail0[0].src);
assertNotNull(thumbnail1);
assertEquals(1, thumbnail1.length);
assertEquals('800px', thumbnail1[0].style.width);
assertEquals('600px', thumbnail1[0].style.height);
assertEquals('http://thumb.com/big.jpg', thumbnail1[0].src);
// players are only shown when media is selected
assertNotNull(player);
assertEquals(0, player.length);
control.dispose();
},
testDoesntCreatesCaptionIfUnavailable() {
const incompleteModel =
new MediaModel('http://url.com', undefined, 'a description');
let incompleteMedia = new Media('', renderer);
incompleteMedia.setDataModel(incompleteModel);
incompleteMedia.render();
const caption = dom.getElementsByTagNameAndClass(
undefined, ControlRenderer.CSS_CLASS + '-caption');
const description = dom.getElementsByTagNameAndClass(
undefined, ControlRenderer.CSS_CLASS + '-description');
assertEquals(0, caption.length);
assertNotNull(description);
incompleteMedia.dispose();
},
testSetAriaLabel() {
const model =
new MediaModel('http://url.com', 'a caption', 'a description');
const thumb1 = new MediaModel.Thumbnail(
'http://thumb.com/small.jpg', new Size(320, 288));
const thumb2 = new MediaModel.Thumbnail(
'http://thumb.com/big.jpg', new Size(800, 600));
model.setThumbnails([thumb1, thumb2]);
model.setPlayer(new MediaModel.Player(
testing.newTrustedResourceUrlForTest('http://media/player.swf')));
const control = new Media(model, renderer);
assertNull(
'Media must not have aria label by default', control.getAriaLabel());
control.setAriaLabel('My media');
control.render();
const element = control.getElementStrict();
assertNotNull('Element must not be null', element);
assertEquals(
'Media element must have expected aria-label', 'My media',
element.getAttribute('aria-label'));
assertTrue(dom.isFocusableTabIndex(element));
control.setAriaLabel('My new media');
assertEquals(
'Media element must have updated aria-label', 'My new media',
element.getAttribute('aria-label'));
},
});
|
{
"pile_set_name": "Github"
}
|
.so man3/shmem_short_iget.3
|
{
"pile_set_name": "Github"
}
|
VLCSource="VLC-відео"
Playlist="Список відтворення"
LoopPlaylist="Повтор списку відтворення"
Shuffle="Перемішати список відтворення"
PlaybackBehavior="Видимість та відтворення"
PlaybackBehavior.StopRestart="Зупинити, коли не видимий. Грати з початку, коли видимий"
PlaybackBehavior.PauseUnpause="Призупинити, коли не видимий. Грати далі, коли видимий"
PlaybackBehavior.AlwaysPlay="Завжди грати навіть тоді, коли не видимий"
NetworkCaching="Кешування мережевого контенту (мс)"
PlayPause="Відтворення / Пауза"
Restart="Грати з початку"
Stop="Зупинити"
PlaylistNext="Наступний"
PlaylistPrev="Попередній"
AudioTrack="Аудіо доріжка"
SubtitleTrack="Доріжка субтитрів"
SubtitleEnable="Увімкнути субтитри"
|
{
"pile_set_name": "Github"
}
|
use strict;
use warnings;
use Test::More tests => 20;
use Catalyst::Log;
local *Catalyst::Log::_send_to_log;
local our @MESSAGES;
{
no warnings 'redefine';
*Catalyst::Log::_send_to_log = sub {
my $self = shift;
push @MESSAGES, @_;
};
}
my $LOG = 'Catalyst::Log';
can_ok $LOG, 'new';
ok my $log = $LOG->new, '... and creating a new log object should succeed';
isa_ok $log, $LOG, '... and the object it returns';
can_ok $log, 'is_info';
ok $log->is_info, '... and the default behavior is to allow info messages';
can_ok $log, 'info';
ok $log->info('hello there!'),
'... passing it an info message should succeed';
ok @MESSAGES, '... and immediately flush the log';
is scalar @MESSAGES, 1, '... with one log message';
like $MESSAGES[0], qr/^\[info\] hello there!$/,
'... which should match the format we expect';
{
package Catalyst::Log::SubclassAutoflush;
use base qw/Catalyst::Log/;
sub _send_to_log {
my $self = shift;
push @MESSAGES, '---';
push @MESSAGES, @_;
}
}
@MESSAGES = (); # clear the message log
my $SUBCLASS = 'Catalyst::Log::SubclassAutoflush';
can_ok $SUBCLASS, 'new';
ok $log = $SUBCLASS->new,
'... and the log subclass constructor should return a new object';
isa_ok $log, $SUBCLASS, '... and the object it returns';
isa_ok $log, $LOG, '... and it also';
can_ok $log, 'info';
ok $log->info('hi there!'),
'... passing it an info message should succeed';
ok @MESSAGES, '... and immediately flush the log';
is scalar @MESSAGES, 2, '... with two log messages';
is $MESSAGES[0], '---', '... with the first one being our new data';
like $MESSAGES[1], qr/^\[info\] hi there!$/,
'... which should match the format we expect';
|
{
"pile_set_name": "Github"
}
|
--------------------------------------------------------------------------------
Alpha 2
--------------------------------------------------------------------------------
[+] Reworked Lua stuff.
[+] New Lua-based custom dialogs engine.
[+] dialogs.CheckBoxesDialog. IF:G implementation swithed to dialogs.CheckBoxesDialog.
[+] Lua memory-management functions, hooks, Default metatable for numbers, bit.ToTable, bit.FromTable, Color functions, os.writelog, events support.
[-] _PlaceObject didn't preserve ebx register.
[+] !?OB - trigger for any object.
[-] BM:G was insecure (could be used to change any value in memory).
[+-] MR:N didn't work when a copy of monster was passed to !?MR. Now it returns -1 in this case and BM-1 changes current (from !?MR or currently active) monseter's properties.
[+] CA:B3/$/1 - check if the structure is built - works for non-upgraded buildings if upgrade is built.
[+] !?BA54 - called on both sides(?) after showing battlefield (after showing tactics dialog in case tactics is enabled).
[-] fixed SOD bug: def compression type 1 didn't work when used for map objects.
[+] now WoG supports locale in edits.
[+] CA:S# returns town income.
[+] !?CI0 trigger - change town income, !?CI1 trigger - change monster growth in town, !!CI reciever.
[+] CA:M4/level/# returns monster growth per week.
[+] Lua scripts path is configured in WoG.ini: [Common] LuaScriptsPath.
[+] UX:Gtown/$ - get/check/set town-specific grail effect state (0 - disabled, 1 - enabled) (for example, UX:G8/0 will disable the Conflux grail effect of learning all spells).
[+] !#FU:E can be used in instructions.
[-] Local functions weren't handled correctly in map scripts.
[-] Local functions weren't callable from instructions.
[+] CA:B3 - 2 more checks: CA:B3/#/1, CA:B3/#/2.
[-] SC:L was wrong
[-] For some unknown reason artifact hints were locked in IF:Q dialogs. Now they are unlocked.
[+] MessageEx - highly customazable message in Lua
[+] OB:T$/1, OB:C$/1 - type and control word of object, ignoring hero on top of it (works as usual if there's no hero standing on the object)
[+] !?FC trigger - change flag color, !!FC reciever
[+] !?DG trigger - digging for Grail, !!DG reciever
[+] Modern Bink format support
[+] !$HL post-trigger, getting skills in !?HL trigger
[-] Using UN:L inside !?OB trigger with enabled standard reaction caused a trade dialog of the hero with himself to occur.
[+] New HE:Y syntax: HE:Y$1/$2/$3, HE:Y0/0/0/3.
[-] HE:Y2 was totally broken.
[+] SoD campaigns are playable again. WoG campaigns have their separate button.
[+] Allow multiple copies if [Common]AllowMultipleCopies is set to 1 in WoG.ini
[+] HE:A5/$1/$2/?3/?4 - control artifact locks.
[+] !?AI - triggered when AI gets weight of a map square
[-] SoD bug: damage to be inflicted wasn't shown if Creature Info was disabled
[-] HE:F was redrawing adventure screen ONLY when check syntax is used (now it doesn't redraw screen at all)
[-] OW:R and some other commands were redrawing parts of adventure screen even if it's not active
[-] SoD bug: wrong check for free disk space
[+] New better GOTO. !!la, !!go in trigger.
[+] Number of if-el-en levels is now unlimited.
[+] File and line number information for ERM errors.
[-] SoD bug: rare crash on game start.
[!] Need to update help: BU:O may return values 0 - 3. 0 means no obstacle, 1 is an obstacle that can be passed through, but can be removed, 2 and 3 are unpassable (thanks to pHOMM).
[!] For help: IF:Q type 8 (artifact) subtype = <artifact number> + 0x10000*<spell number> (for scrolls)
[!] For help: change HE:A4 into HE:A4/#
[!] For help: BM:G description is inaccurate: $2 - Set/check/get level in school of the spell
[!] For help: OW:H has 2 kinds of syntax - with 2 parameters and with 3. They are mixed together in help. (description of $2 applies to 2-param syntax)
[!] For help: Additions to "List of all buildings" in CA.
[!] For help: HE:X: $1=5 means "+2 Speed to all units". No subtype of the speciality exists.
!?CI0 trigger - change town income, !?CI1 - change monster growth in town, !!CI reciever.
!?CI0 is triggered when the game calculates castle income.
!?CI1 is triggered when the game calculates monster growth in a castle.
!!CI:I$ set/check/get resulting income (or growth)
!!CI:I$/1 set/check/get base income (or growth) before ERM scripts changed it. ERM scripts shouldn't change this normally.
!!CI:L$ set/check/get monster level for CI1 (returns -1 for CI0)
Example:
!?CI;
!!CA-1:T?v1; [get town type]
!!CI&v1=1:Id500; [increase income of all Ramparts by 500]
CA:B3 - 2 more checks: CA:B3/#/1, CA:B3/#/2.
CA:B3/#/1 checks if the building is built with respect to upgrades,
CA:B3/#/2 checks if the building is enabled
Example:
!!CA-1:B3/30/1;
!!IF&1:M^Dwelling 1 is built^;
This will work even if you build the upgraded dwelling, or horde dwelling.
!?FC trigger - change flag color, !!FC reciever.
!?FC is triggered when the game needs flag color. Now any object can have a flag.
Use !!FC:T$ to get the type of object.
Use !!FC:U$ to get the subtype of object.
!!FC:C$ is the color of the flag.
v998, v999 and v1000 keep coordinates of the object entrance.
!?DG trigger - digging for Grail, !!DG reciever
!?DG is triggered when a hero is digging for Grail and the hole has already been placed
!!DG:P$/$/$ returns coordinates.
!!DG:G$ is 1 if the hero finds Grail, 0 otherwise.
!!DG:R$ is 1 to enable standard reaction, 0 to disable (the reaction is giving Grail to hero or showing failure message)
v998, v999 and v1000 keep coordinates.
Flag 1000 shows you that the hero belongs to the player sitting at the monitor.
HE-1 gives you the digging hero.
Example:
!?DG;
!!DG:G?y-1; [found Grail?]
!!FU&y-1=0:E; [exit if not found]
!!DG:R0; [no standard reaction]
!!VRz1:S^UltimateArtifact.wav^;
!!SN&1000:Pz1; [play Grail sound, if it's the player's hero]
!!IF&1000:M^Congratulations! After spending many hours digging here, your hero has uncovered A SKELETON!^; [show message]
!!HE-1:C2/56/1/1; [give 1 skeleton]
!$HL post-trigger, getting skills in !?HL trigger
Now you can get actual numbers of secondary skills in HL:S. You can still use value -2, but it will cause a skill to be generated again.
!$HL triggers after the dialog is closed and skills are enhanced.
!!HL:R gives you the number of secondary skill player chose in the dialog.
Example:
ZVSE
* this script lets heroes learn all 28 skills
!#VRv100:S0;
!?HL-1;
!!HE-1:S=8;
!!VRv100&1:S1;
!!HE-1&1:S7; [set number of shown skills to 7 to allow new skills]
!!HL&1:Sd/-2/-2; [generate skills again]
!$HL-1&v100<>0; [if we altered the number of shown skills]
!!VRv100:S0;
!!HE-1:S8; [restore the number of shown skills]
New HE:Y syntax: HE:Y$1/$2/$3, HE:Y0/0/0/3.
HE:Y now supports all syntax variations, so 4th parameter is usually unneeded.
Examples:
!!HE-1:Yv1/v2/v3 - set curse.
!!HE-1:Yv1/dv2/dv3 - add/sub curse.
!!HE-1:Yv1/0/0 - delete curse.
!!HE-1:Yv1/?v2/?v3 - get curse.
The only case when it's needed is unmentioned in Help:
HE:Y0/0/0/3 - remove all curses/blessings from the hero.
HE:Y2 was totally broken.
Here's how it works now. The syntax in ERM Help is wrong. Slot number is passed as second parameter ("power"). If it's -1, the slot is chosen randomly.
Here's the list of slot lock indexes (it's not the same as format AP):
0 head
1 shoulders
2 neck
3 right hand
4 left hand
5 torso
6 rings
7 feet
8 misc. slots
9 ballista (war machine 1)
10 ammo cart (war machine 2)
11 first aid tent (war machine 3)
12 catapult
13 spell book
HE:A5/$1/$2/?3/?4 - control artifact locks.
$1 is the lock slot (see "HE:Y2 was totally broken" for list of slots).
$2 is the number of locks in the locks slot.
(?3 and ?4 are optional)
?3 returnes the number of free artifact slots for the lock slot ($2 sholdn't exceed ?3).
?4 returnes the total number of artifact slots for the lock slot.
!?AI - triggered when AI gets weight of a map square
!!AI:W$ is the weight.
!!AI:W$/1 is the base weight, that was before ERM triggers changed it
!!AI:M$ is the number of movement points needed to reach the square (modified by in-game function and triggers).
!!AI:M$/1 is the number of movement points needed to reach the square, not modified by the in-game function.
v998, v999, v1000 keep coordinates of the square.
HE-1 is the hero for which the value is calculated.
Example:
!?AI&v998=42/v999=2/v1000=0; [object at 42/2/0]
!!AI:M?v1; [get distance to object in movement points]
!!AI&v1>500:W1000000; [this is the ultimate goal of every AI hero that stands further than 5 squares from it]
[however, note that the object will be ignored if it's beyond AI thinking radius]
Here are examples of standard weights:
Stables:
If it gives more movement points than the hero spends to get to it, the weight is 10000.
Otherwise, the weight is 50 + (importance of cavaliers upgrade).
Keymaster's Tent:
5000, if it's needed.
Objects that give moral or luck:
Weight is 0 if the hero can't reach the square at this turn.
Weight is usually proportional to army strength (total AI value of army).
For morale - if all stacks are undead, the weight is 0.
Objects that give a resource:
(resource count)*(resource importance for the owner)
Fountain of Youth (it gives +200 movement and +1 morale):
If it's closer than 200 movement points, the weight is 10000.
Otherwise, the weight is the usual weight of moral enhancement, AI:M$ is decreased by 200 (so, it doesn't match AI:M$/1 even without any triggers).
Shipyard:
1000, if it's needed.
Weight of guarded objects depends on bonus and comparsion of hero's army and defending army.
Mine:
(2 or 3)*(resource count per day)*(resource importance for the owner) - (guards penalty to weight)
"2 or 3" is 2 if it's a neutral mine and 3 if the mine belongs to other player (even an ally! This is probably a bug).
[+] New better GOTO. !!la, !!go in trigger.
This GOTO is preferrable. There may be 50 labels (0...49).
Use !!la0:; to !!la49:; to set a label.
Use !!go0:; to !!go49:; to go to a label.
Examples:
1)
!?FU255;
!!la0:; [label 0]
(...)
!!la1:; [label 1]
(...)
!!go0&1:; [go to label 0]
!!go1&2:; [go to label 1]
2)
A single 'for' loop:
!?FU255;
!!VRy1:S0;
!!la0:; [label 0]
!!if&y1<100:;
(...)
!!VRy1:+1;
!!go0:; [goto label 0]
!!en:;
This is equivalent to while y1<100 do { (...) y1 = y1 + 1; }
You can also make one loop inside another and anything you could do with regular DO, but much faster and without a need for a free function number.
[!] For help: Additions to "List of all buildings" in CA.
20 Shipyard with a ship in it
22 Also: Decorations, always present (8).
23 Also: Decorations. For Village hall (1, 4, 8) or always present (0, 7).
27 Decorations. For Town Hall (1, 4, 8) or always present (6).
28 Decorations for City Hall (1, 4, 8)
29 Decorations for Capitol (1, 4, 8)
|
{
"pile_set_name": "Github"
}
|
---
title: Azure Notebooks プレビュー用のサンプル Jupyter ノートブック
description: サンプルは、無料の Azure Notebooks クラウド サービスで実行される Jupyter ノートブックを体験するための優れた方法です。
ms.topic: sample
ms.date: 01/11/2019
ms.openlocfilehash: 397e40f628e6e935fef74d2225d2e477aac7b276
ms.sourcegitcommit: 62717591c3ab871365a783b7221851758f4ec9a4
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 08/22/2020
ms.locfileid: "85833997"
---
# <a name="discover-and-use-sample-notebooks-in-azure-notebooks-preview"></a>Azure Notebooks プレビューでサンプル ノートブックを検出して使用する
[!INCLUDE [notebooks-status](../../includes/notebooks-status.md)]
インターネットには、Azure Notebooks に簡単に取り込むことができて、人々の関心が高い便利な Jupyter ノートブックのコレクションが多数あります。 この記事では、注目すべきサンプルの一覧を示します。
検索する対象のノートブックを特定したら、次に示すいくつかの詳細情報を把握しておきます。
- ノートブックが既に Azure Notebooks 内にある場合は、プロジェクト ダッシュボード上の **[複製]** ボタンを使用して、ご自身のアカウントにプロジェクトのコピーを作成します。
- 一部のノートブックでは、特定のパッケージを実行する必要があります。 `!pip install` (Python) または `install.packages` (R) を使用してノートブック自体からパッケージをインストールできますが、[適切な環境を利用して Azure Notebooks プロジェクトを構成する](configure-manage-azure-notebooks-projects.md)ことも可能です。
## <a name="great-sample-notebooks"></a>優れたサンプル ノートブック
- [Azure Notebooks スターター セット](https://notebooks.azure.com/#sample-redirect)には、データ アクセス、Azure Machine Learning、いくつかのデータ サイエンス エクスペリエンスを示すノートブックと共に、Python、R、および F# の紹介が含まれています。
- [Jupyter Notebooks の概要](https://nbviewer.jupyter.org/github/jupyter/notebook/blob/master/docs/source/examples/Notebook/Notebook%20Basics.ipynb) (jupyter.org)
- [データ サイエンスの概要](https://github.com/jakevdp/PythonDataScienceHandbook/tree/master/notebooks) (Jake Vanderplas 氏)
- [便利なノートブックのギャラリー](https://github.com/ipython/ipython/wiki/A-gallery-of-interesting-IPython-Notebooks) (GitHub 上の Jupyter プロジェクト)
- [nbviewer.jupyter.org](https://nbviewer.jupyter.org)
- [インペリアル カレッジ ロンドンの物理学部](https://notebooks.azure.com/cvanbreu/libraries)による物理の手引き
- [Azure Machine Learning の入門サンプル](https://notebooks.azure.com/azureml/projects/azureml-getting-started)
## <a name="next-steps"></a>次のステップ
- [方法: プロジェクトの構成と管理](configure-manage-azure-notebooks-projects.md)
- [方法: データ ファイルの操作](work-with-project-data-files.md)
- [方法: データ リソースへのアクセス](access-data-resources-jupyter-notebooks.md)
- [方法: Azure Machine Learning の使用](use-machine-learning-services-jupyter-notebooks.md)
|
{
"pile_set_name": "Github"
}
|
import * as NexusSchema from '@nexus/schema'
import type { NexusSchemaExtensionConfig } from '@nexus/schema/dist/extensions'
import { stripIndent, stripIndents } from 'common-tags'
import * as Lo from 'lodash'
import * as Path from 'path'
import * as Schema from '../../runtime/schema'
import * as Layout from '../layout'
import * as Logger from '../nexus-logger'
import * as Plugin from '../plugin'
const log = Logger.rootLogger.child('schemaTypegen')
interface GenerateArtifactsParams {
graphqlSchema: NexusSchema.core.NexusGraphQLSchema
schemaSettings: Schema.SettingsData
layout: Layout.Layout
plugins: Plugin.RuntimeContributions[]
}
export async function generateArtifacts(params: GenerateArtifactsParams): Promise<void> {
const typegenConfig = resolveTypegenConfig(params)
const typegenMetadata = new NexusSchema.core.TypegenMetadata(typegenConfig)
await typegenMetadata.generateArtifacts(params.graphqlSchema)
}
function resolveTypegenConfig(params: GenerateArtifactsParams) {
const schemaConfig = params.graphqlSchema.extensions.nexus.config
const typegenOutput = params.layout.projectPath('node_modules/@types/typegen-nexus/index.d.ts')
let schemaOutput
if (params.schemaSettings.generateGraphQLSDLFile === false) {
schemaOutput = false
} else {
schemaOutput = params.layout.projectPathOrAbsolute(params.schemaSettings.generateGraphQLSDLFile)
}
schemaConfig.outputs = {
typegen: typegenOutput,
schema: schemaOutput,
}
schemaConfig.shouldGenerateArtifacts = true
const schemaConfigWithTypegen = withCustomTypegenConfig(schemaConfig, params.plugins)
return NexusSchema.core.resolveTypegenConfig(schemaConfigWithTypegen)
}
/**
* Augment @nexus/schema typegen config with contributions from plugins.
*/
function withCustomTypegenConfig(
nexusConfig: NexusSchemaExtensionConfig,
plugins: Plugin.RuntimeContributions[]
) {
// Integrate plugin typegenAutoConfig contributions
const typegenAutoConfigFromPlugins = {}
for (const p of plugins) {
if (p.schema?.typegenAutoConfig) {
Lo.merge(typegenAutoConfigFromPlugins, p.schema.typegenAutoConfig)
}
}
const typegenAutoConfigObject = Lo.merge({}, typegenAutoConfigFromPlugins, nexusConfig.typegenAutoConfig!)
nexusConfig.typegenAutoConfig = undefined
function contextTypeContribSpecToCode(ctxTypeContribSpec: Record<string, string>): string {
return stripIndents`
interface Context {
${Object.entries(ctxTypeContribSpec)
.map(([name, type]) => {
// Quote key name to handle case of identifier-incompatible key names
return `'${name}': ${type}`
})
.join('\n')}
}
`
}
// Our use-case of multiple context sources seems to require a custom
// handling of typegenConfig. Opened an issue about maybe making our
// curreent use-case, fairly basic, integrated into the auto system, here:
// https://github.com/prisma-labs/nexus/issues/323
nexusConfig.typegenConfig = async (schema, outputPath) => {
const configurator = await NexusSchema.core.typegenAutoConfig(typegenAutoConfigObject)
const config = await configurator(schema, outputPath)
// Initialize
config.imports.push('interface Context {}')
config.imports.push(stripIndent`
declare global {
interface NexusContext extends Context {}
}
`)
config.contextType = 'NexusContext'
// Integrate plugin context contributions
for (const p of plugins) {
if (!p.context) continue
if (p.context.typeGen.imports) {
for (const typegenImport of p.context.typeGen.imports) {
const relativeImportPath = (Path.isAbsolute(typegenImport.from)
? NexusSchema.core.relativePathTo(typegenImport.from, outputPath)
: typegenImport.from
).replace(/(\.d)?\.ts/, '')
const importStatement = `import * as ${typegenImport.as} from "${relativeImportPath}"`
if (!config.imports.includes(importStatement)) {
config.imports.push(importStatement)
}
}
}
config.imports.push(contextTypeContribSpecToCode(p.context.typeGen.fields))
}
config.imports.push(
"import * as Logger from 'nexus/components/logger'",
contextTypeContribSpecToCode({
log: 'Logger.Logger',
})
)
config.nexusSchemaImportId = 'nexus/components/schema'
log.trace('built up Nexus typegenConfig', { config })
return config
}
return nexusConfig
}
|
{
"pile_set_name": "Github"
}
|
package com.yalantis.starwars;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import com.yalantis.starwars.interfaces.TilesFrameLayoutListener;
import com.yalantis.starwars.render.StarWarsRenderer;
import com.yalantis.starwars.widget.StarWarsTilesGLSurfaceView;
/**
* Created by Artem Kholodnyi on 11/9/15.
*/
public class TilesFrameLayout extends FrameLayout {
private StarWarsTilesGLSurfaceView mGLSurfaceView;
private StarWarsRenderer mRenderer;
private TilesFrameLayoutListener mListener;
private int mAnimationDuration;
private int mNumberOfTilesX;
public TilesFrameLayout(Context context) {
super(context);
init(context, null, 0);
}
public TilesFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public TilesFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public TilesFrameLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.sw_StarWarsTilesFrameLayout, defStyle, 0);
mAnimationDuration = a.getInt(R.styleable.sw_StarWarsTilesFrameLayout_sw_animationDuration, 1500);
mNumberOfTilesX = a.getInt(R.styleable.sw_StarWarsTilesFrameLayout_sw_numberOfTilesX, 35);
a.recycle();
initGlSurfaceView();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
addView(mGLSurfaceView);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
private void initGlSurfaceView() {
mGLSurfaceView = new StarWarsTilesGLSurfaceView(getContext());
mGLSurfaceView.setBackgroundColor(Color.TRANSPARENT);
// Check if the system supports OpenGL ES 2.0.
final ActivityManager activityManager = (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE);
final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000;
if (supportsEs2) {
// Request an OpenGL ES 2.0 compatible context.
mGLSurfaceView.setEGLContextClientVersion(2);
mRenderer = new StarWarsRenderer(mGLSurfaceView, this, mAnimationDuration, mNumberOfTilesX);
mGLSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
mGLSurfaceView.getHolder().setFormat(PixelFormat.TRANSPARENT);
mGLSurfaceView.setRenderer(mRenderer);
mGLSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
mGLSurfaceView.setZOrderOnTop(true);
} else {
throw new UnsupportedOperationException();
}
}
public void startAnimation() {
drawToTexture();
}
private void drawToTexture() {
Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_4444);
Canvas canvas = new Canvas(bitmap);
super.draw(canvas);
mRenderer.updateTexture(bitmap);
}
public void reveal() {
mGLSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
mRenderer.startAnimation();
removeViewAt(0);
}
});
}
});
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
}
public void onResume() {
mGLSurfaceView.onResume();
}
public void onPause() {
mGLSurfaceView.onPause();
}
public void onAnimationFinished() {
if (mListener != null) {
mListener.onAnimationFinished();
}
}
public void setOnAnimationFinishedListener(TilesFrameLayoutListener listener) {
this.mListener = listener;
}
}
|
{
"pile_set_name": "Github"
}
|
{ Options form for the lazarus package manager
Copyright (C) 2011 Darius Blaszyk
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 with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your 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 Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA.
}
unit fppkg_optionsfrm;
{$mode objfpc}{$H+}
interface
uses
SysUtils, Forms, Dialogs, ComCtrls, ButtonPanel, StdCtrls, ExtCtrls, Buttons,
pkgoptions, pkgglobals;
type
TPkgColumn = record
Name: string;
Visible: boolean;
end;
{ TPackageManagerOption }
TPackageManagerOption = class(TObject)
private
FPkgColumnCount: integer;
FPkgColumns: array of TPkgColumn;
FVerbosity: TLogLevels;
function GetPkgColumns(index: integer): TPkgColumn;
procedure SetPkgColumnCount(const AValue: integer);
procedure SetPkgColumns(index: integer; const AValue: TPkgColumn);
procedure AddPkgColumn(Name: string; Visible: boolean);
procedure SetVerbosity(const AValue: TLogLevels);
public
constructor Create;
destructor Destroy; override;
property PkgColumns[index: integer]: TPkgColumn read GetPkgColumns write SetPkgColumns;
property PkgColumnCount: integer read FPkgColumnCount write SetPkgColumnCount;
function PkgColumnByName(AName: string): integer;
property Verbosity: TLogLevels read FVerbosity write SetVerbosity;
end;
{ TOptionsForm }
TOptionsForm = class(TForm)
Button1: TButton;
CheckBox5: TCheckBox;
CheckBox6: TCheckBox;
RemoveFromVisibleColumnsButton: TSpeedButton;
VisibleColumnsLabel: TLabel;
VisibleColumnsListBox: TListBox;
AvailableColumnsLabel: TLabel;
AvailableColumnsListBox: TListBox;
AddToVisibleColumnsButton: TSpeedButton;
lblMiddle: TLabel;
UserInterfaceTabSheet: TTabSheet;
VerbosityCheckGroup: TCheckGroup;
ComboBox1: TComboBox;
ComboBox2: TComboBox;
CompilerConfigCheckBox2: TCheckBox;
CompilerOptionsButton: TButton;
ButtonPanel1: TButtonPanel;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
CheckBox3: TCheckBox;
CheckBox4: TCheckBox;
CompilerConfigCheckBox: TCheckBox;
CompilerConfigCheckBox1: TCheckBox;
CompilerConfigEdit: TEdit;
CompilerOptionsButton1: TButton;
CompilerOptionsEdit: TEdit;
CompilerOptionsEdit1: TEdit;
CompilerOptionsGroupBox1: TGroupBox;
Edit1: TEdit;
GlobalListView: TListView;
CompilerListView: TListView;
FPMakeListView: TListView;
FPMakePageControl: TPageControl;
GlobalTabSheet: TTabSheet;
CompilerTabSheet: TTabSheet;
FPMakeTabSheet: TTabSheet;
GroupBox1: TGroupBox;
CompilerOptionsGroupBox: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
OpenDialog: TOpenDialog;
ConfigTabSheet: TTabSheet;
TabSheet1: TTabSheet;
procedure AddToVisibleColumnsButtonClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure RemoveFromVisibleColumnsButtonClick(Sender: TObject);
private
procedure SetupColumnVisibility;
public
end;
var
OptionsForm: TOptionsForm;
LazPkgOptions: TPackageManagerOption;
implementation
{$R *.lfm}
uses
fppkg_const;
{ TPackageManagerOption }
function TPackageManagerOption.GetPkgColumns(index: integer): TPkgColumn;
begin
Result := FPkgColumns[index];
end;
procedure TPackageManagerOption.SetPkgColumnCount(const AValue: integer);
begin
if FPkgColumnCount=AValue then exit;
FPkgColumnCount:=AValue;
SetLength(FPkgColumns,FPkgColumnCount);
end;
procedure TPackageManagerOption.SetPkgColumns(index: integer;
const AValue: TPkgColumn);
begin
FPkgColumns[index] := AValue;
end;
constructor TPackageManagerOption.Create;
begin
PkgColumnCount := 0;
AddPkgColumn('Name', True);
AddPkgColumn('State', True);
AddPkgColumn('Version', True);
AddPkgColumn('Info', True);
AddPkgColumn('Description', False);
AddPkgColumn('Keywords', False);
AddPkgColumn('Category', False);
AddPkgColumn('Support', False);
{ AddPkgColumn('Author', False);
AddPkgColumn('License', False);
AddPkgColumn('HomepageURL', False);
AddPkgColumn('DownloadURL', False);
AddPkgColumn('FileName', False);
AddPkgColumn('Email', False);
AddPkgColumn('OS', False);
AddPkgColumn('CPU', False);
}
Verbosity := DefaultLogLevels;
end;
destructor TPackageManagerOption.Destroy;
begin
inherited Destroy;
end;
function TPackageManagerOption.PkgColumnByName(AName: string): integer;
var
i: integer;
begin
for i := 0 to PkgColumnCount - 1 do
if FPkgColumns[i].Name = AName then
begin
Result := i;
Exit;
end;
end;
procedure TPackageManagerOption.AddPkgColumn(Name: string;
Visible: boolean);
begin
PkgColumnCount := PkgColumnCount + 1;
FPkgColumns[PkgColumnCount-1].Name := Name;
FPkgColumns[PkgColumnCount-1].Visible := Visible;
end;
procedure TPackageManagerOption.SetVerbosity(const AValue: TLogLevels);
begin
if FVerbosity=AValue then exit;
FVerbosity:=AValue;
LogLevels := AValue;
end;
{ TOptionsForm }
procedure TOptionsForm.FormCreate(Sender: TObject);
procedure AddListItem(LV: TListView; ACaption, AValue: string);
var
li: TListItem;
begin
li := LV.Items.Add;
li.Caption:= ACaption;
li.SubItems.Add(AValue);
end;
begin
Caption := rsFppkgOptions;
//global
{ AddListItem(GlobalListView, rsRemoteMirrorsURL, GlobalOptions.GlobalSection.RemoteMirrorsURL);
AddListItem(GlobalListView, rsRemoteRepository, GlobalOptions.GlobalSection.RemoteRepository);
AddListItem(GlobalListView, rsLocalRepository, GlobalOptions.GlobalSection.LocalRepository);
AddListItem(GlobalListView, rsBuildDirectory, GlobalOptions.GlobalSection.BuildDir);
AddListItem(GlobalListView, rsArchivesDirectory, GlobalOptions.GlobalSection.ArchivesDir);
AddListItem(GlobalListView, rsCompilerConfigDirectory, GlobalOptions.GlobalSection.CompilerConfigDir);
AddListItem(GlobalListView, rsDefaultCompilerConfig, GlobalOptions.GlobalSection.CompilerConfig);
AddListItem(GlobalListView, rsFpmakeCompilerConfig, GlobalOptions.GlobalSection.FPMakeCompilerConfig);
AddListItem(GlobalListView, rsDownloader, GlobalOptions.GlobalSection.Downloader);
AddListItem(GlobalListView, rsCustomFpmakeOptions, GlobalOptions.GlobalSection.CustomFPMakeOptions);
//compiler
AddListItem(CompilerListView, rsCompiler, CompilerOptions.Compiler);
AddListItem(CompilerListView, rsCompilerTarget, CompilerOptions.CompilerTarget);
AddListItem(CompilerListView, rsCompilerVersion, CompilerOptions.CompilerVersion);
AddListItem(CompilerListView, rsGlobalPrefix, CompilerOptions.GlobalPrefix);
AddListItem(CompilerListView, rsLocalPrefix, CompilerOptions.LocalPrefix);
AddListItem(CompilerListView, rsGlobalInstallDir, CompilerOptions.GlobalInstallDir);
AddListItem(CompilerListView, rsLocalInstallDir, CompilerOptions.LocalInstallDir);
AddListItem(CompilerListView, rsOptions, CompilerOptions.Options.DelimitedText);
}
//fpmake
// Load FPMake compiler config, this is normally the same config as above
{ AddListItem(FPMakeListView, rsCompiler, FPMakeCompilerOptions.Compiler);
AddListItem(FPMakeListView, rsCompilerTarget, FPMakeCompilerOptions.CompilerTarget);
AddListItem(FPMakeListView, rsCompilerVersion, FPMakeCompilerOptions.CompilerVersion);
AddListItem(FPMakeListView, rsGlobalPrefix, FPMakeCompilerOptions.GlobalPrefix);
AddListItem(FPMakeListView, rsLocalPrefix, FPMakeCompilerOptions.LocalPrefix);
AddListItem(FPMakeListView, rsGlobalInstallDir, FPMakeCompilerOptions.GlobalInstallDir);
AddListItem(FPMakeListView, rsLocalInstallDir, FPMakeCompilerOptions.LocalInstallDir);
AddListItem(FPMakeListView, rsOptions, FPMakeCompilerOptions.Options.DelimitedText);
}
FPMakePageControl.ActivePage := ConfigTabSheet;
end;
procedure TOptionsForm.FormShow(Sender: TObject);
begin
SetupColumnVisibility;
//setup verbosity
with VerbosityCheckGroup do
begin
Checked[Items.IndexOf('Error')] := llError in LazPkgOptions.Verbosity;
Checked[Items.IndexOf('Warning')] := llWarning in LazPkgOptions.Verbosity;
Checked[Items.IndexOf('Info')] := llInfo in LazPkgOptions.Verbosity;
Checked[Items.IndexOf('Commands')] := llCommands in LazPkgOptions.Verbosity;
Checked[Items.IndexOf('Debug')] := llDebug in LazPkgOptions.Verbosity;
Checked[Items.IndexOf('Progress')] := llProgres in LazPkgOptions.Verbosity;
end;
end;
procedure TOptionsForm.OKButtonClick(Sender: TObject);
begin
//save the data to settings file
//save verbosity
LazPkgOptions.Verbosity := [];
with VerbosityCheckGroup do
begin
if Checked[Items.IndexOf('Error')] then
LazPkgOptions.Verbosity := LazPkgOptions.Verbosity + [llError];
if Checked[Items.IndexOf('Warning')] then
LazPkgOptions.Verbosity := LazPkgOptions.Verbosity + [llWarning];
if Checked[Items.IndexOf('Info')] then
LazPkgOptions.Verbosity := LazPkgOptions.Verbosity + [llInfo];
if Checked[Items.IndexOf('Commands')] then
LazPkgOptions.Verbosity := LazPkgOptions.Verbosity + [llCommands];
if Checked[Items.IndexOf('Debug')] then
LazPkgOptions.Verbosity := LazPkgOptions.Verbosity + [llDebug];
if Checked[Items.IndexOf('Progress')] then
LazPkgOptions.Verbosity := LazPkgOptions.Verbosity + [llProgres];
end;
Close;
end;
procedure TOptionsForm.RemoveFromVisibleColumnsButtonClick(Sender: TObject);
var
i: integer;
pkg: TPkgColumn;
c: integer;
begin
i := 0;
c := -1;
while i < VisibleColumnsListBox.Items.Count do
begin
if VisibleColumnsListBox.Selected[i] then
c := i;
Inc(i);
end;
if c <> -1 then
begin
i := LazPkgOptions.PkgColumnByName(VisibleColumnsListBox.Items[c]);
pkg := LazPkgOptions.PkgColumns[i];
pkg.Visible := False;
LazPkgOptions.PkgColumns[i] := pkg;
SetupColumnVisibility;
end;
end;
procedure TOptionsForm.SetupColumnVisibility;
var
i: integer;
begin
VisibleColumnsListBox.Clear;
AvailableColumnsListBox.Clear;
for i := 0 to LazPkgOptions.PkgColumnCount - 1 do
begin
if LazPkgOptions.PkgColumns[i].Visible then
VisibleColumnsListBox.Items.Add(LazPkgOptions.PkgColumns[i].Name)
else
AvailableColumnsListBox.Items.Add(LazPkgOptions.PkgColumns[i].Name)
end;
end;
procedure TOptionsForm.Button1Click(Sender: TObject);
begin
if OpenDialog.Execute then
CompilerConfigEdit.Text := OpenDialog.FileName;
end;
procedure TOptionsForm.AddToVisibleColumnsButtonClick(Sender: TObject);
var
i: integer;
pkg: TPkgColumn;
c: integer;
begin
i := 0;
c := -1;
while i < AvailableColumnsListBox.Items.Count do
begin
if AvailableColumnsListBox.Selected[i] then
c := i;
Inc(i);
end;
if c <> -1 then
begin
i := LazPkgOptions.PkgColumnByName(AvailableColumnsListBox.Items[c]);
pkg := LazPkgOptions.PkgColumns[i];
pkg.Visible := True;
LazPkgOptions.PkgColumns[i] := pkg;
SetupColumnVisibility;
end;
end;
procedure TOptionsForm.CancelButtonClick(Sender: TObject);
begin
Close;
end;
initialization
LazPkgOptions := TPackageManagerOption.Create;
finalization
FreeAndNil(LazPkgOptions);
end.
|
{
"pile_set_name": "Github"
}
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.requests.extensions.IMessageCopyRequest;
import com.microsoft.graph.requests.extensions.MessageCopyRequest;
import com.microsoft.graph.models.extensions.Message;
import com.microsoft.graph.core.BaseActionRequestBuilder;
import com.microsoft.graph.core.BaseFunctionRequestBuilder;
import com.microsoft.graph.core.IBaseClient;
import com.google.gson.JsonElement;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Message Copy Request Builder.
*/
public class MessageCopyRequestBuilder extends BaseActionRequestBuilder implements IMessageCopyRequestBuilder {
/**
* The request builder for this MessageCopy
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
* @param destinationId the destinationId
*/
public MessageCopyRequestBuilder(final String requestUrl, final IBaseClient client, final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions, final String destinationId) {
super(requestUrl, client, requestOptions);
bodyParams.put("destinationId", destinationId);
}
/**
* Creates the IMessageCopyRequest
*
* @param requestOptions the options for the request
* @return the IMessageCopyRequest instance
*/
public IMessageCopyRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions) {
return buildRequest(getOptions(requestOptions));
}
/**
* Creates the IMessageCopyRequest with specific requestOptions instead of the existing requestOptions
*
* @param requestOptions the options for the request
* @return the IMessageCopyRequest instance
*/
public IMessageCopyRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
MessageCopyRequest request = new MessageCopyRequest(
getRequestUrl(),
getClient(),
requestOptions
);
if (hasParameter("destinationId")) {
request.body.destinationId = getParameter("destinationId");
}
return request;
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
namespace services\merapi;
use Yii;
use yii\db\ActiveRecord;
use yii\web\UnprocessableEntityHttpException;
use common\enums\CacheEnum;
use common\helpers\ArrayHelper;
use common\models\merchant\Member;
use common\models\merapi\AccessToken;
use common\components\Service;
use common\enums\StatusEnum;
use common\enums\MerchantStateEnum;
use common\models\merchant\Merchant;
/**
* Class AccessTokenService
* @package services\merapi
* @author jianyan74 <751393839@qq.com>
*/
class AccessTokenService extends Service
{
/**
* 是否加入缓存
*
* @var bool
*/
public $cache = false;
/**
* 缓存过期时间
*
* @var int
*/
public $timeout;
/**
* 获取token
*
* @param Member $member
* @param $group
* @param int $cycle_index 重新获取次数
* @return array
* @throws \yii\base\Exception
*/
public function getAccessToken(Member $member, $group, $cycle_index = 1)
{
$model = $this->findModel($member->id, $group);
$model->member_id = $member->id;
$model->merchant_id = $member->merchant_id;
$model->group = $group;
// 删除缓存
!empty($model->access_token) && Yii::$app->cache->delete($this->getCacheKey($model->access_token));
$model->refresh_token = Yii::$app->security->generateRandomString() . '_' . time();
$model->access_token = Yii::$app->security->generateRandomString() . '_' . time();
$model->status = StatusEnum::ENABLED;
if (!$model->save()) {
if ($cycle_index <= 3) {
$cycle_index++;
return self::getAccessToken($member, $group, $cycle_index);
}
throw new UnprocessableEntityHttpException($this->getError($model));
}
$result = [];
$result['refresh_token'] = $model->refresh_token;
$result['access_token'] = $model->access_token;
$result['expiration_time'] = Yii::$app->params['user.accessTokenExpire'];
// 记录访问次数
Yii::$app->services->merchantMember->lastLogin($member);
// 关联账号信息
/** @var Merchant $merchant */
if ($merchant = $member->merchant) {
if ($merchant->status == StatusEnum::DELETE) {
throw new UnprocessableEntityHttpException('所属商户不存在');
}
if ($merchant->state == MerchantStateEnum::DISABLED) {
throw new UnprocessableEntityHttpException('所属商户未通过审核');
}
if ($merchant->state == MerchantStateEnum::AUDIT) {
throw new UnprocessableEntityHttpException('所属商户正在审核');
}
} else {
throw new UnprocessableEntityHttpException('所属商户不存在');
}
$account = $member->account;
$member = ArrayHelper::toArray($member);
unset($member['password_hash'], $member['auth_key'], $member['password_reset_token'], $member['access_token'], $member['refresh_token']);
$result['member'] = $member;
$result['member']['merchant'] = ArrayHelper::toArray($merchant);
$result['member']['account'] = ArrayHelper::toArray($account);
// 写入缓存
$this->cache === true && Yii::$app->cache->set($this->getCacheKey($model->access_token), $model, $this->timeout);
return $result;
}
/**
* @param $token
* @param $type
* @return array|mixed|null|ActiveRecord
*/
public function getTokenToCache($token, $type)
{
if ($this->cache == false) {
return $this->findByAccessToken($token);
}
$key = $this->getCacheKey($token);
if (!($model = Yii::$app->cache->get($key))) {
$model = $this->findByAccessToken($token);
Yii::$app->cache->set($key, $model, $this->timeout);
}
return $model;
}
/**
* 禁用token
*
* @param $access_token
*/
public function disableByAccessToken($access_token)
{
$this->cache === true && Yii::$app->cache->delete($this->getCacheKey($access_token));
if ($model = $this->findByAccessToken($access_token)) {
$model->status = StatusEnum::DISABLED;
return $model->save();
}
return false;
}
/**
* 获取token
*
* @param $token
* @return array|null|ActiveRecord|AccessToken
*/
public function findByAccessToken($token)
{
return AccessToken::find()
->where(['access_token' => $token, 'status' => StatusEnum::ENABLED])
->andFilterWhere(['merchant_id' => $this->getMerchantId()])
->one();
}
/**
* @param $access_token
* @return string
*/
protected function getCacheKey($access_token)
{
return CacheEnum::getPrefix('merapiAccessToken') . $access_token;
}
/**
* 返回模型
*
* @param $member_id
* @param $group
* @return array|AccessToken|null|ActiveRecord
*/
protected function findModel($member_id, $group)
{
if (empty(($model = AccessToken::find()->where([
'member_id' => $member_id,
'group' => $group
])->andFilterWhere(['merchant_id' => $this->getMerchantId()])->one()))) {
$model = new AccessToken();
return $model->loadDefaultValues();
}
return $model;
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2011 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.
#ifndef CHROME_BROWSER_UI_COCOA_FRAMED_BROWSER_WINDOW_H_
#define CHROME_BROWSER_UI_COCOA_FRAMED_BROWSER_WINDOW_H_
#pragma once
#import <Cocoa/Cocoa.h>
#include "base/memory/scoped_nsobject.h"
#include "chrome/browser/ui/cocoa/chrome_browser_window.h"
// Offsets from the top/left of the window frame to the top of the window
// controls (zoom, close, miniaturize) for a window with a tabstrip.
const NSInteger kFramedWindowButtonsWithTabStripOffsetFromTop = 11;
const NSInteger kFramedWindowButtonsWithTabStripOffsetFromLeft = 11;
// Offsets from the top/left of the window frame to the top of the window
// controls (zoom, close, miniaturize) for a window without a tabstrip.
const NSInteger kFramedWindowButtonsWithoutTabStripOffsetFromTop = 4;
const NSInteger kFramedWindowButtonsWithoutTabStripOffsetFromLeft = 8;
// Cocoa class representing a framed browser window.
// We need to override NSWindow with our own class since we need access to all
// unhandled keyboard events and subclassing NSWindow is the only method to do
// this. We also handle our own window controls and custom window frame drawing.
@interface FramedBrowserWindow : ChromeBrowserWindow {
@private
BOOL shouldHideTitle_;
BOOL hasTabStrip_;
NSButton* closeButton_;
NSButton* miniaturizeButton_;
NSButton* zoomButton_;
CGFloat windowButtonsInterButtonSpacing_;
}
// Tells the window to suppress title drawing.
- (void)setShouldHideTitle:(BOOL)flag;
// Returns the desired spacing between window control views.
- (CGFloat)windowButtonsInterButtonSpacing;
// Calls the superclass's implementation of |-toggleFullScreen:|.
- (void)toggleSystemFullScreen;
@end
@interface NSWindow (UndocumentedAPI)
// Undocumented Cocoa API to suppress drawing of the window's title.
// -setTitle: still works, but the title set only applies to the
// miniwindow and menus (and, importantly, Expose). Overridden to
// return |shouldHideTitle_|.
-(BOOL)_isTitleHidden;
@end
#endif // CHROME_BROWSER_UI_COCOA_FRAMED_BROWSER_WINDOW_H_
|
{
"pile_set_name": "Github"
}
|
(ns cheshire.custom
"DEPRECATED
Methods used for extending JSON generation to different Java classes.
Has the same public API as core.clj so they can be swapped in and out."
(:use [cheshire.factory])
(:require [cheshire.core :as core]
[cheshire.generate :as generate])
(:import (java.io BufferedWriter ByteArrayOutputStream StringWriter)
(java.util Date SimpleTimeZone)
(java.text SimpleDateFormat)
(java.sql Timestamp)
(com.fasterxml.jackson.dataformat.smile SmileFactory)
(com.fasterxml.jackson.core JsonFactory JsonGenerator
JsonGenerator$Feature
JsonGenerationException JsonParser)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;; DEPRECATED, DO NOT USE ;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; date format rebound for custom encoding
(def ^{:dynamic true :private true} *date-format*)
;; pre-allocated exception for fast-failing core attempt for custom encoding
(def ^{:private true} core-failure (JsonGenerationException.
"Cannot custom JSON encode object"))
(defprotocol JSONable
(to-json [t jg]))
(defn encode*
(^String [obj]
(encode* obj nil))
(^String [obj opt-map]
(binding [*date-format* (or (:date-format opt-map) default-date-format)]
(let [sw (StringWriter.)
generator (.createJsonGenerator
^JsonFactory (or *json-factory* json-factory) sw)]
(when (:pretty opt-map)
(.useDefaultPrettyPrinter generator))
(when (:escape-non-ascii opt-map)
(.enable generator JsonGenerator$Feature/ESCAPE_NON_ASCII))
(if obj
(to-json obj generator)
(.writeNull generator))
(.flush generator)
(.toString sw)))))
(def encode encode*)
(core/copy-arglists encode encode*)
(defn encode-stream*
(^String [obj ^BufferedWriter w]
(encode-stream* obj w nil))
(^String [obj ^BufferedWriter w opt-map]
(binding [*date-format* (or (:date-format opt-map) default-date-format)]
(let [generator (.createJsonGenerator
^JsonFactory (or *json-factory* json-factory) w)]
(when (:pretty opt-map)
(.useDefaultPrettyPrinter generator))
(when (:escape-non-ascii opt-map)
(.enable generator JsonGenerator$Feature/ESCAPE_NON_ASCII))
(to-json obj generator)
(.flush generator)
w))))
(def encode-stream encode-stream*)
(core/copy-arglists encode-stream encode-stream*)
(defn encode-smile*
(^bytes [obj]
(encode-smile* obj nil))
(^bytes [obj opt-map]
(binding [*date-format* (or (:date-format opt-map) default-date-format)]
(let [baos (ByteArrayOutputStream.)
generator (.createJsonGenerator ^SmileFactory
(or *smile-factory* smile-factory)
baos)]
(to-json obj generator)
(.flush generator)
(.toByteArray baos)))))
(def encode-smile encode-smile*)
(core/copy-arglists encode-smile encode-smile*)
;; there are no differences in parsing, but these are here to make
;; this a self-contained namespace if desired
(def parse core/decode)
(core/copy-arglists parse core/decode)
(def parse-string core/decode)
(core/copy-arglists parse-string core/decode)
(def parse-stream core/decode-stream)
(core/copy-arglists parse-stream core/decode-stream)
(def parse-smile core/decode-smile)
(core/copy-arglists parse-smile core/decode-smile)
(def parsed-seq core/parsed-seq)
(core/copy-arglists parsed-seq core/parsed-seq)
(def decode core/parse-string)
(core/copy-arglists decode core/parse-string)
(def decode-stream parse-stream)
(core/copy-arglists decode-stream core/parse-stream)
(def decode-smile parse-smile)
(core/copy-arglists decode-smile core/parse-smile)
;; aliases for encoding
(def generate-string encode*)
(core/copy-arglists generate-string encode*)
(def generate-string* encode*)
(core/copy-arglists generate-string* encode*)
(def generate-stream encode-stream*)
(core/copy-arglists generate-stream encode-stream*)
(def generate-stream* encode-stream*)
(core/copy-arglists generate-stream* encode-stream*)
(def generate-smile encode-smile*)
(core/copy-arglists generate-smile encode-smile*)
(def generate-smile* encode-smile*)
(core/copy-arglists generate-smile* encode-smile*)
;; Generic encoders, these can be used by someone writing a custom
;; encoder if so desired, after transforming an arbitrary data
;; structure into a clojure one, these can just be called.
(defn encode-nil
"Encode null to the json generator."
[_ ^JsonGenerator jg]
(.writeNull jg))
(defn encode-str
"Encode a string to the json generator."
[^String s ^JsonGenerator jg]
(.writeString jg (str s)))
(defn encode-number
"Encode anything implementing java.lang.Number to the json generator."
[^java.lang.Number n ^JsonGenerator jg]
(generate/encode-number n jg))
(defn encode-long
"Encode anything implementing java.lang.Number to the json generator."
[^Long n ^JsonGenerator jg]
(.writeNumber jg (long n)))
(defn encode-int
"Encode anything implementing java.lang.Number to the json generator."
[n ^JsonGenerator jg]
(.writeNumber jg (long n)))
(defn encode-ratio
"Encode a clojure.lang.Ratio to the json generator."
[^clojure.lang.Ratio n ^JsonGenerator jg]
(.writeNumber jg (double n)))
(defn encode-seq
"Encode a seq to the json generator."
[s ^JsonGenerator jg]
(.writeStartArray jg)
(doseq [i s]
(to-json i jg))
(.writeEndArray jg))
(defn encode-date
"Encode a date object to the json generator."
[^Date d ^JsonGenerator jg]
(let [sdf (SimpleDateFormat. *date-format*)]
(.setTimeZone sdf (SimpleTimeZone. 0 "UTC"))
(.writeString jg (.format sdf d))))
(defn encode-bool
"Encode a Boolean object to the json generator."
[^Boolean b ^JsonGenerator jg]
(.writeBoolean jg b))
(defn encode-named
"Encode a keyword to the json generator."
[^clojure.lang.Keyword k ^JsonGenerator jg]
(.writeString jg (if-let [ns (namespace k)]
(str ns "/" (name k))
(name k))))
(defn encode-map
"Encode a clojure map to the json generator."
[^clojure.lang.IPersistentMap m ^JsonGenerator jg]
(.writeStartObject jg)
(doseq [[k v] m]
(.writeFieldName jg (if (instance? clojure.lang.Keyword k)
(if-let [ns (namespace k)]
(str ns "/" (name k))
(name k))
(str k)))
(to-json v jg))
(.writeEndObject jg))
(defn encode-symbol
"Encode a clojure symbol to the json generator."
[^clojure.lang.Symbol s ^JsonGenerator jg]
(.writeString jg (str s)))
;; extended implementations for clojure datastructures
(extend nil
JSONable
{:to-json encode-nil})
(extend java.lang.String
JSONable
{:to-json encode-str})
;; This is lame, thanks for changing all the BigIntegers to BigInts
;; in 1.3 clojure/core :-/
(defmacro handle-bigint []
(when (not= {:major 1 :minor 2} (select-keys *clojure-version*
[:major :minor]))
`(extend clojure.lang.BigInt
JSONable
{:to-json ~'(fn encode-bigint
[^clojure.lang.BigInt n ^JsonGenerator jg]
(.writeNumber jg (.toBigInteger n)))})))
(handle-bigint)
(extend clojure.lang.Ratio
JSONable
{:to-json encode-ratio})
(extend Long
JSONable
{:to-json encode-long})
(extend Short
JSONable
{:to-json encode-int})
(extend Byte
JSONable
{:to-json encode-int})
(extend java.lang.Number
JSONable
{:to-json encode-number})
(extend clojure.lang.ISeq
JSONable
{:to-json encode-seq})
(extend clojure.lang.IPersistentVector
JSONable
{:to-json encode-seq})
(extend clojure.lang.IPersistentSet
JSONable
{:to-json encode-seq})
(extend clojure.lang.IPersistentList
JSONable
{:to-json encode-seq})
(extend java.util.Date
JSONable
{:to-json encode-date})
(extend java.sql.Timestamp
JSONable
{:to-json #(encode-date (Date. (.getTime ^java.sql.Timestamp %1)) %2)})
(extend java.util.UUID
JSONable
{:to-json encode-str})
(extend java.lang.Boolean
JSONable
{:to-json encode-bool})
(extend clojure.lang.Keyword
JSONable
{:to-json encode-named})
(extend clojure.lang.IPersistentMap
JSONable
{:to-json encode-map})
(extend clojure.lang.Symbol
JSONable
{:to-json encode-symbol})
(extend clojure.lang.Associative
JSONable
{:to-json encode-map})
(extend java.util.Map
JSONable
{:to-json encode-map})
(extend java.util.Set
JSONable
{:to-json encode-seq})
(extend java.util.List
JSONable
{:to-json encode-seq})
;; Utility methods to add and remove encoders
(defn add-encoder
"Provide an encoder for a type not handled by Cheshire.
ex. (add-encoder java.net.URL encode-string)
See encode-str, encode-map, etc, in the cheshire.custom
namespace for encoder examples."
[cls encoder]
(extend cls
JSONable
{:to-json encoder}))
(defn remove-encoder
"Remove encoder for a given type.
ex. (remove-encoder java.net.URL)"
[cls]
(alter-var-root #'JSONable #(assoc % :impls (dissoc (:impls %) cls)))
(clojure.core/-reset-methods JSONable))
|
{
"pile_set_name": "Github"
}
|
!function( $ ) {
"use strict"
var PopoverExt = function ( element, options ) {
this.init('popoverext', element, options)
}
/* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js
========================================== */
PopoverExt.prototype = $.extend({}, $.fn.popover.Constructor.prototype, {
constructor: PopoverExt
, init: function ( type, element, options ) {
var eventIn
, eventOut
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.enabled = true
if (this.options.trigger != 'manual') {
eventIn = this.options.trigger == 'hover' ? 'mouseenter' : 'focus'
eventOut = this.options.trigger == 'hover' ? 'mouseleave' : 'blur'
this.$element.on(eventIn, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut, this.options.selector, $.proxy(this.leave, this))
}
//console.log(this.tip())
var $tip = this.tip();
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
, setContent: function () {
var $tip = this.tip()
, title = this.getTitle()
, content = this.getContent()
, footer = this.getFooter();
$tip.find('.popover-title')[ $.type(title) == 'object' ? 'append' : 'html' ](title);
$tip.find('.popover-content > *')[ $.type(content) == 'object' ? 'append' : 'html' ](content);
$tip.find('.popover-footer')[ $.type(footer) == 'object' ? 'append' : 'html' ](footer);
$tip.removeClass('fade top bottom left right in');
}
, hasContent: function () {
return this.getTitle() || this.getContent()
}
, setId: function() {
var $tip;
if(this.options.id) {
$tip = this.tip();
$tip.attr("id",this.$element.attr("id") + "Popover");
}
}
, show: function () {
var $tip
, inside
, pos
, actualWidth
, actualHeight
, placement
, tp;
if (this.hasContent() && this.enabled) {
$tip = this.tip();
this.setContent();
this.setId();
if (this.options.animation) {
$tip.addClass('fade')
}
placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement;
inside = /in/.test(placement)
$tip
.remove()
.css({ top: 0, left: 0, display: 'block' })
.appendTo(inside ? this.$element : document.body);
if(this.options.hideOnBlur) {
$tip
.attr("tabindex","-1")
.on("blur", $.proxy(this.hide, this))
.trigger("focus");
}
pos = this.getPosition(inside)
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
switch (inside ? placement.split(' ')[1] : placement) {
case 'bottom':
tp = {top: pos.top + pos.height + this.options.topOffset, left: pos.left + pos.width / 2 - actualWidth / 2}
break
case 'bottom left':
tp = {top: pos.top + pos.height + this.options.topOffset, left: pos.left + this.options.leftOffset}
break
case 'bottom right':
tp = {top: pos.top + pos.height + this.options.topOffset , left: (pos.left + pos.width) - actualWidth - this.options.leftOffset }
break
case 'top':
tp = {top: pos.top - actualHeight + this.options.topOffset, left: pos.left + (pos.width / 2 - actualWidth / 2) + this.options.leftOffset}
break
case 'top right':
tp = {top: pos.top - actualHeight + this.options.topOffset, left: (pos.left + pos.width) - actualWidth - this.options.leftOffset}
break
case 'top left':
tp = {top: pos.top - actualHeight + this.options.topOffset, left: pos.left + this.options.leftOffset}
break
case 'left':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}
break
case 'right':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}
break
}
$tip
.css(tp)
.addClass(placement)
.addClass('in')
if(this.options.fixed == true) {
$tip.css("position","fixed");
}
}
this.options.onShow();
}
, getFooter: function () {
var footer
, $e = this.$element
, o = this.options;
footer = $e.attr('data-footer')
|| (typeof o.content == 'function' ? o.footer.call($e[0]) : o.footer);
footer = footer.toString().replace(/(^\s*|\s*$)/, "");
return footer;
}
})
/* POPOVER PLUGIN DEFINITION
* ======================= */
$.fn.popoverext = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('popoverext')
, options = typeof option == 'object' && option
if (!data) $this.data('popoverext', (data = new PopoverExt(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.popoverext.Constructor = PopoverExt
$.fn.popoverext.defaults = $.extend({} , $.fn.popover.defaults, {
fixed: false,
template: '<div class="popover"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div><div class="popover-footer"></div></div></div>',
id: false,
footer: '',
onShow:$.empty,
leftOffset: 0,
topOffset: 0,
hideOnBlur: false
})
}( window.jQuery );
|
{
"pile_set_name": "Github"
}
|
import java.util.*;
/**
* 因为离边界越远的节点越可能成为根节点,所以每次删除叶子节点,一层一层往里收缩,最后留下的就是可能的根节点
* 使用拓扑排序的类似算法,每次删除入度为1的节点,最后剩下的1个或两个入度为1的节点就是可能的最小高度树的根节点
*/
class Solution {
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
List<Integer> res = new ArrayList<>();
//特殊情况:
if(n <= 2){
for(int i = 0;i < n;i++) res.add(i);
return res;
}
//构造邻接矩阵。注意,因为这里每次修改的节点都是叶子节点,只有一个邻接点,所以可以使用Set,如果有多个邻接点,则不能用Set
//因为Set不能边遍历边修改,会报ConcurrentModificationException
Set<Integer>[] graph = new Set[n];
//初始化
for(int i = 0;i < n;i++){
graph[i] = new HashSet<>();
}
//入度数组
int[] degrees = new int[n];
for (int[] edge : edges) {
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
degrees[edge[0]]++;
degrees[edge[1]]++;
}
//将入度为1的节点放入Queue
LinkedList<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (degrees[i] == 1)
queue.addLast(i);
}
//使得最后剩下一个或两个节点
while (n > 2) {
int size = queue.size();
//一次性减去所有的叶子节点
n -= size;
while (size-- > 0) {
//得到当前叶子节点
Integer cur = queue.poll();
//出度改变
degrees[cur]--;
//对于其所有的邻接点入度-1
if(!graph[cur].isEmpty()){
for(int node : graph[cur]){
degrees[node]--;
if(degrees[node] == 1) queue.add(node);
//删除叶子节点和邻接点的关系
graph[cur].remove(node);
graph[node].remove(cur);
}
}
}
}
//剩下位于Queue中的节点就是根节点
return queue;
}
}
public class $310_MinimumHeightTrees {
}
|
{
"pile_set_name": "Github"
}
|
//hong QQ:1410919373
package fl.controls {
import fl.core.*;
import flash.display.*;
import fl.managers.*;
public class Button extends LabelButton implements IFocusManagerComponent {
private static var defaultStyles:Object = {
emphasizedSkin:"Button_emphasizedSkin",
emphasizedPadding:2
};
public static var createAccessibilityImplementation:Function;
protected var emphasizedBorder:DisplayObject;
protected var _emphasized:Boolean = false;
public function Button(){
_emphasized = false;
super();
}
public static function getStyleDefinition():Object{
return (UIComponent.mergeStyles(LabelButton.getStyleDefinition(), defaultStyles));
}
override public function drawFocus(_arg1:Boolean):void{
var _local2:Number;
var _local3:*;
super.drawFocus(_arg1);
if (_arg1){
_local2 = Number(getStyleValue("emphasizedPadding"));
if ((((_local2 < 0)) || (!(_emphasized)))){
_local2 = 0;
};
_local3 = getStyleValue("focusRectPadding");
_local3 = ((_local3)==null) ? 2 : _local3;
_local3 = (_local3 + _local2);
uiFocusRect.x = -(_local3);
uiFocusRect.y = -(_local3);
uiFocusRect.width = (width + (_local3 * 2));
uiFocusRect.height = (height + (_local3 * 2));
};
}
public function set emphasized(_arg1:Boolean):void{
_emphasized = _arg1;
invalidate(InvalidationType.STYLES);
}
override protected function draw():void{
if (((isInvalid(InvalidationType.STYLES)) || (isInvalid(InvalidationType.SIZE)))){
drawEmphasized();
};
super.draw();
if (emphasizedBorder != null){
setChildIndex(emphasizedBorder, (numChildren - 1));
};
}
public function get emphasized():Boolean{
return (_emphasized);
}
override protected function initializeAccessibility():void{
if (Button.createAccessibilityImplementation != null){
Button.createAccessibilityImplementation(this);
};
}
protected function drawEmphasized():void{
var _local1:Object;
var _local2:Number;
if (emphasizedBorder != null){
removeChild(emphasizedBorder);
};
emphasizedBorder = null;
if (!_emphasized){
return;
};
_local1 = getStyleValue("emphasizedSkin");
if (_local1 != null){
emphasizedBorder = getDisplayObjectInstance(_local1);
};
if (emphasizedBorder != null){
addChildAt(emphasizedBorder, 0);
_local2 = Number(getStyleValue("emphasizedPadding"));
emphasizedBorder.x = (emphasizedBorder.y = -(_local2));
emphasizedBorder.width = (width + (_local2 * 2));
emphasizedBorder.height = (height + (_local2 * 2));
};
}
}
}//package fl.controls
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>CMSIS DSP Software Library: CMSIS DSP Software Library</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javaScript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body onload='searchBox.OnSelectItem(0);'>
<!-- Generated by Doxygen 1.7.2 -->
<script type="text/javascript"><!--
var searchBox = new SearchBox("searchBox", "search",false,'Search');
--></script>
<div class="navigation" id="top">
<div class="tabs">
<ul class="tablist">
<li class="current"><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li id="searchli">
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
</div>
<div class="header">
<div class="headertitle">
<h1>CMSIS DSP Software Library </h1> </div>
</div>
<div class="contents">
<h3 class="version">Version1.0.10 </h3><p><b>Introduction</b></p>
<p>This user manual describes the CMSIS DSP software library, a suite of common signal processing functions for use on Cortex-M processor based devices.</p>
<p>The library is divided into a number of modules each covering a specific category:</p>
<ul>
<li>Basic math functions</li>
<li>Fast math functions</li>
<li>Complex math functions</li>
<li>Filters</li>
<li>Matrix functions</li>
<li>Transforms</li>
<li>Motor control functions</li>
<li>Statistical functions</li>
<li>Support functions</li>
<li>Interpolation functions</li>
</ul>
<p>The library has separate functions for operating on 8-bit integers, 16-bit integers, 32-bit integer and 32-bit floating-point values.</p>
<p><b>Processor Support</b></p>
<p>The library is completely written in C and is fully CMSIS compliant. High performance is achieved through maximum use of Cortex-M4 intrinsics.</p>
<p>The supplied library source code also builds and runs on the Cortex-M3 and Cortex-M0 processor, with the DSP intrinsics being emulated through software.</p>
<p><b>Toolchain Support</b></p>
<p>The library has been developed and tested with MDK-ARM version 4.21. The library is being tested in GCC and IAR toolchains and updates on this activity will be made available shortly.</p>
<p><b>Using the Library</b></p>
<p>The library installer contains prebuilt versions of the libraries in the <code>Lib</code> folder.</p>
<ul>
<li>arm_cortexM4lf_math.lib (Little endian and Floating Point Unit on Cortex-M4)</li>
<li>arm_cortexM4bf_math.lib (Big endian and Floating Point Unit on Cortex-M4)</li>
<li>arm_cortexM4l_math.lib (Little endian on Cortex-M4)</li>
<li>arm_cortexM4b_math.lib (Big endian on Cortex-M4)</li>
<li>arm_cortexM3l_math.lib (Little endian on Cortex-M3)</li>
<li>arm_cortexM3b_math.lib (Big endian on Cortex-M3)</li>
<li>arm_cortexM0l_math.lib (Little endian on Cortex-M0)</li>
<li>arm_cortexM0b_math.lib (Big endian on Cortex-M3)</li>
</ul>
<p>The library functions are declared in the public file <code><a class="el" href="arm__math_8h.html">arm_math.h</a></code> which is placed in the <code>Include</code> folder. Simply include this file and link the appropriate library in the application and begin calling the library functions. The Library supports single public header file <code> <a class="el" href="arm__math_8h.html">arm_math.h</a></code> for Cortex-M4/M3/M0 with little endian and big endian. Same header file will be used for floating point unit(FPU) variants. Define the appropriate pre processor MACRO ARM_MATH_CM4 or ARM_MATH_CM3 or ARM_MATH_CM0 depending on the target processor in the application.</p>
<p><b>Examples</b></p>
<p>The library ships with a number of examples which demonstrate how to use the library functions.</p>
<p><b>Building the Library</b></p>
<p>The library installer contains project files to re build libraries on MDK Tool chain in the <code>CMSIS</code> folder.</p>
<ul>
<li>arm_cortexM0b_math.uvproj</li>
<li>arm_cortexM0l_math.uvproj</li>
<li>arm_cortexM3b_math.uvproj</li>
<li>arm_cortexM3l_math.uvproj</li>
<li>arm_cortexM4b_math.uvproj</li>
<li>arm_cortexM4l_math.uvproj</li>
<li>arm_cortexM4bf_math.uvproj</li>
<li>arm_cortexM4lf_math.uvproj</li>
</ul>
<p>Each library project have differant pre-processor macros.</p>
<p><b>ARM_MATH_CMx:</b> Define macro ARM_MATH_CM4 for building the library on Cortex-M4 target, ARM_MATH_CM3 for building library on Cortex-M3 target and ARM_MATH_CM0 for building library on cortex-M0 target.</p>
<p><b>ARM_MATH_BIG_ENDIAN:</b> Define macro ARM_MATH_BIG_ENDIAN to build the library for big endian targets. By default library builds for little endian targets.</p>
<p><b>ARM_MATH_MATRIX_CHECK:</b> Define macro for checking on the input and output sizes of matrices</p>
<p><b>ARM_MATH_ROUNDING:</b> Define macro for rounding on support functions</p>
<p><b>__FPU_PRESENT:</b> Initialize macro __FPU_PRESENT = 1 when building on FPU supported Targets. Enable this macro for M4bf and M4lf libraries</p>
<p>The project can be built by opening the appropriate project in MDK-ARM 4.21 chain and defining the optional pre processor MACROs detailed above.</p>
<p><b>Copyright Notice</b></p>
<p>Copyright (C) 2010 ARM Limited. All rights reserved. </p>
</div>
<!--- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark"> </span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark"> </span>Defines</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<hr class="footer"/><address class="footer"><small>Generated on Fri Jul 15 2011 13:16:15 for CMSIS DSP Software Library by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.2 </small></address>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_79) on Mon Jun 29 06:45:50 CEST 2015 -->
<title>PropertyOutputStream (Apache Ant API)</title>
<meta name="date" content="2015-06-29">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="PropertyOutputStream (Apache Ant API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/tools/ant/util/ProcessUtil.html" title="class in org.apache.tools.ant.util"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/tools/ant/util/ProxySetup.html" title="class in org.apache.tools.ant.util"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/tools/ant/util/PropertyOutputStream.html" target="_top">Frames</a></li>
<li><a href="PropertyOutputStream.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#fields_inherited_from_class_java.io.ByteArrayOutputStream">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.tools.ant.util</div>
<h2 title="Class PropertyOutputStream" class="title">Class PropertyOutputStream</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.io.OutputStream</li>
<li>
<ul class="inheritance">
<li>java.io.ByteArrayOutputStream</li>
<li>
<ul class="inheritance">
<li>org.apache.tools.ant.util.PropertyOutputStream</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Closeable, java.io.Flushable, java.lang.AutoCloseable</dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">PropertyOutputStream</span>
extends java.io.ByteArrayOutputStream</pre>
<div class="block">Exception thrown when an attempt is made to get an OutputStream
from an immutable Resource.</div>
<dl><dt><span class="strong">Since:</span></dt>
<dd>Ant 1.7</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="fields_inherited_from_class_java.io.ByteArrayOutputStream">
<!-- -->
</a>
<h3>Fields inherited from class java.io.ByteArrayOutputStream</h3>
<code>buf, count</code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/tools/ant/util/PropertyOutputStream.html#PropertyOutputStream(org.apache.tools.ant.Project,%20java.lang.String)">PropertyOutputStream</a></strong>(<a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a> p,
java.lang.String s)</code>
<div class="block">Construct a new PropertyOutputStream for the specified Project
and property name, trimming the property value.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/tools/ant/util/PropertyOutputStream.html#PropertyOutputStream(org.apache.tools.ant.Project,%20java.lang.String,%20boolean)">PropertyOutputStream</a></strong>(<a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a> p,
java.lang.String s,
boolean b)</code>
<div class="block">Construct a new PropertyOutputStream for
the specified Project, property name, and trim mode.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/util/PropertyOutputStream.html#close()">close</a></strong>()</code>
<div class="block">Close the PropertyOutputStream, storing the property.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.io.ByteArrayOutputStream">
<!-- -->
</a>
<h3>Methods inherited from class java.io.ByteArrayOutputStream</h3>
<code>reset, size, toByteArray, toString, toString, toString, write, write, writeTo</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.io.OutputStream">
<!-- -->
</a>
<h3>Methods inherited from class java.io.OutputStream</h3>
<code>flush, write</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="PropertyOutputStream(org.apache.tools.ant.Project, java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>PropertyOutputStream</h4>
<pre>public PropertyOutputStream(<a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a> p,
java.lang.String s)</pre>
<div class="block">Construct a new PropertyOutputStream for the specified Project
and property name, trimming the property value.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>p</code> - the associated Ant Project.</dd><dd><code>s</code> - the String property name.</dd></dl>
</li>
</ul>
<a name="PropertyOutputStream(org.apache.tools.ant.Project, java.lang.String, boolean)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>PropertyOutputStream</h4>
<pre>public PropertyOutputStream(<a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a> p,
java.lang.String s,
boolean b)</pre>
<div class="block">Construct a new PropertyOutputStream for
the specified Project, property name, and trim mode.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>p</code> - the associated Ant Project.</dd><dd><code>s</code> - the String property name.</dd><dd><code>b</code> - the boolean trim mode.</dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="close()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>close</h4>
<pre>public void close()</pre>
<div class="block">Close the PropertyOutputStream, storing the property.</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>close</code> in interface <code>java.io.Closeable</code></dd>
<dt><strong>Specified by:</strong></dt>
<dd><code>close</code> in interface <code>java.lang.AutoCloseable</code></dd>
<dt><strong>Overrides:</strong></dt>
<dd><code>close</code> in class <code>java.io.ByteArrayOutputStream</code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/tools/ant/util/ProcessUtil.html" title="class in org.apache.tools.ant.util"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/tools/ant/util/ProxySetup.html" title="class in org.apache.tools.ant.util"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/tools/ant/util/PropertyOutputStream.html" target="_top">Frames</a></li>
<li><a href="PropertyOutputStream.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#fields_inherited_from_class_java.io.ByteArrayOutputStream">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </auto-generated>
namespace Microsoft.AppCenter.Ingestion.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Required explicit begin session log (a marker event for analytics
/// service).
/// </summary>
[Newtonsoft.Json.JsonObject("startSession")]
public partial class StartSessionLog : Log
{
/// <summary>
/// Initializes a new instance of the StartSessionLog class.
/// </summary>
public StartSessionLog()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the StartSessionLog class.
/// </summary>
/// <param name="timestamp">Log timestamp, example:
/// '2017-03-13T18:05:42Z'.
/// </param>
/// <param name="sid">When tracking an analytics session, logs can be
/// part of the session by specifying this identifier.
/// This attribute is optional, a missing value means the session
/// tracking is disabled (like when using only error reporting
/// feature).
/// Concrete types like StartSessionLog or PageLog are always part of a
/// session and always include this identifier.
/// </param>
/// <param name="userId">optional string used for associating logs with
/// users.
/// </param>
/// <param name="distributionGroupId">Distribution group
/// identifier.</param>
public StartSessionLog(Device device, System.DateTime? timestamp = default(System.DateTime?), System.Guid? sid = default(System.Guid?), string userId = default(string), System.Guid? distributionGroupId = default(System.Guid?))
: base(device, timestamp, sid, userId)
{
DistributionGroupId = distributionGroupId;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets distribution group identifier.
/// </summary>
[JsonProperty(PropertyName = "distributionGroupId")]
public System.Guid? DistributionGroupId { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public override void Validate()
{
base.Validate();
}
}
}
|
{
"pile_set_name": "Github"
}
|
.segment-viewer-overlay-container {
background-color: rgba(255, 255, 255, 0.5);
color: black;
display: inline-block;
left: 0;
position: absolute;
top: 0;
}
.segment-viewer-legend-container {
display: inline-block;
bottom: 0;
position: absolute;
right: 0;
}
.segment-viewer-legend-item {
font-family: monospace;
font-size: small;
white-space: nowrap;
}
.segment-viewer-legend-label {
color: gray;
}
.segment-viewer-legend-colorbox {
background-color: white;
border: 1px solid gray;
display: inline-block;
height: .7em;
vertical-align: middle;
width: .7em;
}
.segment-viewer-container {
background-color: gray;
display: inline-block;
position: relative;
}
.segment-viewer-layer {
left: 0;
position: absolute;
top: 0;
zoom: 1.0;
-moz-transform: scale(1.0);
}
.segment-annotator-outer-container {
display: inline-block;
overflow: auto;
}
.segment-annotator-inner-container {
background-color: #ccc;
position: relative;
zoom: 1.0;
-moz-transform: scale(1.0);
-moz-transform-origin: top left;
}
.segment-annotator-layer {
left: 0;
position: absolute;
top: 0;
cursor: pointer;
}
.edit-sidebar {
font-family: monospace;
}
.edit-sidebar p {
/* font-family: serif; */
padding: 0 0.5em;
width: 100%;
}
.edit-sidebar-button {
position: relative;
background-color: #eee;
cursor: pointer;
padding-left: 2px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.edit-sidebar-button:hover {
background-color: #aaa;
}
.edit-sidebar-button-selected,
.edit-sidebar-button-enabled {
background-color: #ccc;
}
.edit-sidebar-button-highlight {
background-color: #aaa;
}
.edit-sidebar-legend-colorbox {
background-color: white;
border: 1px solid gray;
display: inline-block;
height: .7em;
vertical-align: middle;
width: .7em;
}
.edit-sidebar-legend-label {
color: gray;
display: inline-block;
width: 10em;
padding: 0 0.3em;
}
.edit-sidebar-legend-label-active {
color: black;
font-weight: bold;
}
.edit-sidebar-popup-trigger {
display: inline-block;
position: relative;
min-width: 1em;
text-align: center;
background-color: #ddd;
}
.edit-sidebar-popup-trigger:hover {
background-color: #999;
}
.edit-sidebar-popup {
display: none;
position: absolute;
top: 1em;
right: 0;
padding: 0.1em 0.3em;
background-color: #ccc;
z-index: 1;
}
.edit-sidebar-popup-active {
display: block;
}
.edit-sidebar-spacer {
height: 1em;
}
.edit-sidebar-submit {
margin-left: 1em;
}
.edit-image-top-menu {
height: 1em;
font-family: monospace;
}
.edit-image-top-menu-item {
display: inline-block;
background-color: #eee;
padding: 0 2px;
min-width: 1em;
text-align: center;
}
.edit-image-top-button {
display: inline-block;
background-color: #eee;
cursor: pointer;
padding: 0 2px;
min-width: 1em;
text-align: center;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.edit-image-top-button:hover {
background-color: #aaa;
}
.edit-image-top-button-enabled {
background-color: #ccc;
}
.edit-image-top-spacer {
display: inline-block;
width: 1em;
}
.edit-image-display {
display: inline-block;
vertical-align: top;
}
.edit-main-container {
white-space: nowrap;
}
.edit-top-menu-block {
display: inline-block;
margin: 0 .5em;
}
|
{
"pile_set_name": "Github"
}
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Παράρτημα A. Γλώσσες - Κατάλογος με κωδικούς κατά ISO 639</title>
<link rel="stylesheet" type="text/css" href="OmegaT.css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="index.html" title="OmegaT - Εγχειρίδιο χρήστη">
<link rel="up" href="index.html" title="OmegaT - Εγχειρίδιο χρήστη">
<link rel="prev" href="chapter.misc.html" title="Κεφάλαιο 20. Διάφορα θέματα">
<link rel="next" href="appendix.keyboard.html" title="Παράρτημα B. Συντμεύσεις πληκτρολογίου στο πρόγραμμα επεξεργασίας (editor)">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Παράρτημα A. Γλώσσες - Κατάλογος με κωδικούς κατά ISO 639
</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="chapter.misc.html">Προηγ</a>
</td>
<th width="60%" align="center"> </th>
<td width="20%" align="right"> <a accesskey="n" href="appendix.keyboard.html">Επόμενο</a></td>
</tr>
</table>
<hr>
</div>
<div class="appendix">
<div class="titlepage">
<div>
<div>
<h1 class="title"><a name="appendix.languages"></a>Παράρτημα A. Γλώσσες - Κατάλογος με κωδικούς κατά ISO 639<a class="indexterm" name="d0e8641"></a>
<a class="indexterm" name="d0e8645"></a>
<a class="indexterm" name="d0e8649"></a>
</h1>
</div>
</div>
</div>
<p>Παρακαλώ ελέγξτε τους<a class="ulink" href="http://www.sil.org/ISO639-3/codes.asp" target="_top"> Πίνακες με τους κωδικούς κατά ISO 639</a> για περισσότερες και πιο πρόσφατες πληροφορίες σχετικά με τους κωδικούς γλώσσας.
</p>
<div class="table"><a name="table.language.code.list"></a><p class="title"><b>Πίνακας A.1. Κατάλογος κωδικών γλώσσας κατά ISO 639-1/639-2</b></p>
<div class="table-contents">
<table class="table" summary="Κατάλογος κωδικών γλώσσας κατά ISO 639-1/639-2" border="1">
<colgroup>
<col align="left">
<col align="left">
<col align="left">
</colgroup>
<thead>
<tr>
<th align="left">Όνομα γλώσσας</th>
<th align="left">ISO 639-1</th>
<th align="left">ISO 639-2</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">Αμπχαζιανά</td>
<td align="left">ab</td>
<td align="left">abk</td>
</tr>
<tr>
<td align="left">Αφάρ</td>
<td align="left">aa</td>
<td align="left">aar</td>
</tr>
<tr>
<td align="left">Αφρικάνς, Afrikaans</td>
<td align="left">af</td>
<td align="left">afr</td>
</tr>
<tr>
<td align="left">Ακάν</td>
<td align="left">ak</td>
<td align="left">aka</td>
</tr>
<tr>
<td align="left">Αλβανικά</td>
<td align="left">sq</td>
<td align="left">sqi</td>
</tr>
<tr>
<td align="left">Αμχαρικά</td>
<td align="left">am</td>
<td align="left">amh</td>
</tr>
<tr>
<td align="left">Αραβικά</td>
<td align="left">ar</td>
<td align="left">ara</td>
</tr>
<tr>
<td align="left">Αραγονέζικα</td>
<td align="left">an</td>
<td align="left">arg</td>
</tr>
<tr>
<td align="left">Αρμενικά</td>
<td align="left">hy</td>
<td align="left">hye</td>
</tr>
<tr>
<td align="left">Ασσαμέζικα, Assamese</td>
<td align="left">as</td>
<td align="left">asm</td>
</tr>
<tr>
<td align="left">Αβαρικά, Avaric</td>
<td align="left">av</td>
<td align="left">ava</td>
</tr>
<tr>
<td align="left">Αβεστανικά, Avestan</td>
<td align="left">ae</td>
<td align="left">ave</td>
</tr>
<tr>
<td align="left">Αϋμάρα, Aymara</td>
<td align="left">ay</td>
<td align="left">aym</td>
</tr>
<tr>
<td align="left">Αζέρικα</td>
<td align="left">az</td>
<td align="left">aze</td>
</tr>
<tr>
<td align="left">Μπαμπάρα</td>
<td align="left">bm</td>
<td align="left">bam</td>
</tr>
<tr>
<td align="left">Μπασκίρ, Bashkir</td>
<td align="left">ba</td>
<td align="left">bak</td>
</tr>
<tr>
<td align="left">Βασκικά</td>
<td align="left">eu</td>
<td align="left">eus</td>
</tr>
<tr>
<td align="left">Λευκορωσικά</td>
<td align="left">be</td>
<td align="left">bel</td>
</tr>
<tr>
<td align="left">Μπενγκαλέζικα</td>
<td align="left">bn</td>
<td align="left">ben</td>
</tr>
<tr>
<td align="left">Μπιχάρι, Bihari</td>
<td align="left">bh</td>
<td align="left">bih</td>
</tr>
<tr>
<td align="left">Μπισλάμα</td>
<td align="left">bi</td>
<td align="left">bis</td>
</tr>
<tr>
<td align="left">Βοσνιακά</td>
<td align="left">bs</td>
<td align="left">bos</td>
</tr>
<tr>
<td align="left">Βρετονικά, Breton</td>
<td align="left">br</td>
<td align="left">bre</td>
</tr>
<tr>
<td align="left">Βουλγαρικά</td>
<td align="left">bg</td>
<td align="left">bul</td>
</tr>
<tr>
<td align="left">Μπουρμέζικα, Burmese</td>
<td align="left">my</td>
<td align="left">mya</td>
</tr>
<tr>
<td align="left">Καταλανικά</td>
<td align="left">ca</td>
<td align="left">cat</td>
</tr>
<tr>
<td align="left">Τσαμόρο, Chamorro</td>
<td align="left">ch</td>
<td align="left">cha</td>
</tr>
<tr>
<td align="left">Τσετσενικά</td>
<td align="left">ce</td>
<td align="left">che</td>
</tr>
<tr>
<td align="left">Τσιτσέβα, Τσέβα, Νυάντζα</td>
<td align="left">ny</td>
<td align="left">nya</td>
</tr>
<tr>
<td align="left">Κινεζικά</td>
<td align="left">zh</td>
<td align="left">zho</td>
</tr>
<tr>
<td align="left">Τσουβάς, Chuvash</td>
<td align="left">cv</td>
<td align="left">chv</td>
</tr>
<tr>
<td align="left">Cornish</td>
<td align="left">kw</td>
<td align="left">cor</td>
</tr>
<tr>
<td align="left">Κορσικανικά</td>
<td align="left">co</td>
<td align="left">cos</td>
</tr>
<tr>
<td align="left">Cree</td>
<td align="left">cr</td>
<td align="left">cre</td>
</tr>
<tr>
<td align="left">Κροατικά</td>
<td align="left">hr</td>
<td align="left">hrv</td>
</tr>
<tr>
<td align="left">Τσεχικά</td>
<td align="left">cs</td>
<td align="left">ces</td>
</tr>
<tr>
<td align="left">Δανέζικα</td>
<td align="left">da</td>
<td align="left">dan</td>
</tr>
<tr>
<td align="left">Ντιβέχι, Ντιβέχι, Μαλδιβιανά</td>
<td align="left">dv</td>
<td align="left">div</td>
</tr>
<tr>
<td align="left">Ολανδικά</td>
<td align="left">nl</td>
<td align="left">nld</td>
</tr>
<tr>
<td align="left">Τζόνγκα, Dzongkha</td>
<td align="left">dz</td>
<td align="left">dzo</td>
</tr>
<tr>
<td align="left">Αγγλικά</td>
<td align="left">en</td>
<td align="left">eng</td>
</tr>
<tr>
<td align="left">Εσπεράντο</td>
<td align="left">eo</td>
<td align="left">epo</td>
</tr>
<tr>
<td align="left">Εσθονικά</td>
<td align="left">et</td>
<td align="left">est</td>
</tr>
<tr>
<td align="left">Ewe</td>
<td align="left">ee</td>
<td align="left">ewe</td>
</tr>
<tr>
<td align="left">Faroese</td>
<td align="left">fo</td>
<td align="left">fao</td>
</tr>
<tr>
<td align="left">Fijian</td>
<td align="left">fj</td>
<td align="left">fij</td>
</tr>
<tr>
<td align="left">Φινλανδικά</td>
<td align="left">fi</td>
<td align="left">fin</td>
</tr>
<tr>
<td align="left">Γαλλικά</td>
<td align="left">fr</td>
<td align="left">fra</td>
</tr>
<tr>
<td align="left">Φούλα, Φούλα, Πουλάαρ, Πουλάρ</td>
<td align="left">ff</td>
<td align="left">ful</td>
</tr>
<tr>
<td align="left">Γαλικιανά</td>
<td align="left">gl</td>
<td align="left">glg</td>
</tr>
<tr>
<td align="left">Γεωργιανά</td>
<td align="left">ka</td>
<td align="left">kat</td>
</tr>
<tr>
<td align="left">Γερμανικά</td>
<td align="left">de</td>
<td align="left">deu</td>
</tr>
<tr>
<td align="left">Ελληνικά, Νέα</td>
<td align="left">el</td>
<td align="left">ell</td>
</tr>
<tr>
<td align="left">Γκουαρανί</td>
<td align="left">gn</td>
<td align="left">grn</td>
</tr>
<tr>
<td align="left">Γκουτζαράτι</td>
<td align="left">gu</td>
<td align="left">guj</td>
</tr>
<tr>
<td align="left">Αϊτιανά, Κρεολικά Αίτιανά</td>
<td align="left">ht</td>
<td align="left">hat</td>
</tr>
<tr>
<td align="left">Χάουζα, Hausa</td>
<td align="left">ha</td>
<td align="left">hau</td>
</tr>
<tr>
<td align="left">Εβραϊκά (σύγχρονα)</td>
<td align="left">he</td>
<td align="left">heb</td>
</tr>
<tr>
<td align="left">Χερέρο</td>
<td align="left">hz</td>
<td align="left">her</td>
</tr>
<tr>
<td align="left">Χίντι, Hindi</td>
<td align="left">hi</td>
<td align="left">hin</td>
</tr>
<tr>
<td align="left">Χίρι Μότου</td>
<td align="left">ho</td>
<td align="left">hmo</td>
</tr>
<tr>
<td align="left">Ουγγρικά</td>
<td align="left">hu</td>
<td align="left">hun</td>
</tr>
<tr>
<td align="left">Ιντερλίνγκουα</td>
<td align="left">ia</td>
<td align="left">ina</td>
</tr>
<tr>
<td align="left">Ινδονησιακά</td>
<td align="left">id</td>
<td align="left">ind</td>
</tr>
<tr>
<td align="left">Interlingue</td>
<td align="left">ie</td>
<td align="left">ile</td>
</tr>
<tr>
<td align="left">Ιρλανδικά</td>
<td align="left">ga</td>
<td align="left">gle</td>
</tr>
<tr>
<td align="left">Ίγκμπο</td>
<td align="left">ig</td>
<td align="left">ibo</td>
</tr>
<tr>
<td align="left">Ινούπιακ</td>
<td align="left">ik</td>
<td align="left">ipk</td>
</tr>
<tr>
<td align="left">Ίντο, Ido</td>
<td align="left">io</td>
<td align="left">ido</td>
</tr>
<tr>
<td align="left">Ισλανδικά</td>
<td align="left">is</td>
<td align="left">isl</td>
</tr>
<tr>
<td align="left">Ιταλικά</td>
<td align="left">it</td>
<td align="left">ita</td>
</tr>
<tr>
<td align="left">Ινουκτίτουτ</td>
<td align="left">iu</td>
<td align="left">iku</td>
</tr>
<tr>
<td align="left">Ιαπωνικά</td>
<td align="left">ja</td>
<td align="left">jpn</td>
</tr>
<tr>
<td align="left">Ιαβαϊκά</td>
<td align="left">jv</td>
<td align="left">jav</td>
</tr>
<tr>
<td align="left">Καλάλισουτ, Γροιλανδικά</td>
<td align="left">kl</td>
<td align="left">kal</td>
</tr>
<tr>
<td align="left">Κάναντα, Kannada</td>
<td align="left">kn</td>
<td align="left">kan</td>
</tr>
<tr>
<td align="left">Κανούρι, Kanuri</td>
<td align="left">kr</td>
<td align="left">kau</td>
</tr>
<tr>
<td align="left">Κασμιριανά</td>
<td align="left">ks</td>
<td align="left">kas</td>
</tr>
<tr>
<td align="left">Καζακικά</td>
<td align="left">kk</td>
<td align="left">kaz</td>
</tr>
<tr>
<td align="left">Χμέρ, Khmer</td>
<td align="left">km</td>
<td align="left">khm</td>
</tr>
<tr>
<td align="left">Κικούγιου, Γκικούγιου</td>
<td align="left">ki</td>
<td align="left">kik</td>
</tr>
<tr>
<td align="left">Κινυαργουάντα, Kinyarwanda</td>
<td align="left">rw</td>
<td align="left">kin</td>
</tr>
<tr>
<td align="left">Κιργιζιανά, Κιργιζία</td>
<td align="left">ky</td>
<td align="left">kir</td>
</tr>
<tr>
<td align="left">Κόμι</td>
<td align="left">kv</td>
<td align="left">kom</td>
</tr>
<tr>
<td align="left">Κόγκο</td>
<td align="left">kg</td>
<td align="left">kon</td>
</tr>
<tr>
<td align="left">Κορεατικά</td>
<td align="left">ko</td>
<td align="left">kor</td>
</tr>
<tr>
<td align="left">Κουρδικά</td>
<td align="left">ku</td>
<td align="left">kur</td>
</tr>
<tr>
<td align="left">Κουανιάμα, Κουανιάμα</td>
<td align="left">kj</td>
<td align="left">kua</td>
</tr>
<tr>
<td align="left">Λατινικά</td>
<td align="left">la</td>
<td align="left">lat</td>
</tr>
<tr>
<td align="left">Λουξεμβουργιανά, Letzeburgesch</td>
<td align="left">lb</td>
<td align="left">ltz</td>
</tr>
<tr>
<td align="left">Λουγκάντα</td>
<td align="left">lg</td>
<td align="left">lug</td>
</tr>
<tr>
<td align="left">Λιμβουργιανά, Limburgan, Limburger</td>
<td align="left">li</td>
<td align="left">lim</td>
</tr>
<tr>
<td align="left">Λινγκάλα</td>
<td align="left">ln</td>
<td align="left">lin</td>
</tr>
<tr>
<td align="left">Λάο</td>
<td align="left">lo</td>
<td align="left">lao</td>
</tr>
<tr>
<td align="left">Λιθουανικά</td>
<td align="left">lt</td>
<td align="left">lit</td>
</tr>
<tr>
<td align="left">Λούμπα-Κατάνγκα</td>
<td align="left">lu</td>
<td align="left">lub</td>
</tr>
<tr>
<td align="left">Λατβιανά</td>
<td align="left">lv</td>
<td align="left">lav</td>
</tr>
<tr>
<td align="left">Μάνξ</td>
<td align="left">gv</td>
<td align="left">glv</td>
</tr>
<tr>
<td align="left">Σλαβομακεδονικά</td>
<td align="left">mk</td>
<td align="left">mkd</td>
</tr>
<tr>
<td align="left">Μαλαγάσυ</td>
<td align="left">mg</td>
<td align="left">mlg</td>
</tr>
<tr>
<td align="left">Μαλαισιανά</td>
<td align="left">ms</td>
<td align="left">msa</td>
</tr>
<tr>
<td align="left">Μαλαγιάλαμ</td>
<td align="left">ml</td>
<td align="left">mal</td>
</tr>
<tr>
<td align="left">Μαλτεζικά</td>
<td align="left">mt</td>
<td align="left">mlt</td>
</tr>
<tr>
<td align="left">Μαορί</td>
<td align="left">mi</td>
<td align="left">mri</td>
</tr>
<tr>
<td align="left">Μαράθι (Marāṭhī)</td>
<td align="left">mr</td>
<td align="left">mar</td>
</tr>
<tr>
<td align="left">Μαρσαλιανά, Marshallese</td>
<td align="left">mh</td>
<td align="left">mah</td>
</tr>
<tr>
<td align="left">Μογγολικά</td>
<td align="left">mn</td>
<td align="left">mon</td>
</tr>
<tr>
<td align="left">Ναούρου</td>
<td align="left">na</td>
<td align="left">nau</td>
</tr>
<tr>
<td align="left">Ναβάχο, Navaho</td>
<td align="left">nv</td>
<td align="left">nav</td>
</tr>
<tr>
<td align="left">Νορβηγικά Bokmål</td>
<td align="left">nb</td>
<td align="left">nob</td>
</tr>
<tr>
<td align="left">Βορ. Ντέμπελε</td>
<td align="left">nd</td>
<td align="left">nde</td>
</tr>
<tr>
<td align="left">Νεπαλέζικα</td>
<td align="left">ne</td>
<td align="left">nep</td>
</tr>
<tr>
<td align="left">Ντόνγκα</td>
<td align="left">ng</td>
<td align="left">ndo</td>
</tr>
<tr>
<td align="left">Νορβηγικά Νυνόρσκ</td>
<td align="left">nn</td>
<td align="left">nno</td>
</tr>
<tr>
<td align="left">Νορβηγικά</td>
<td align="left">no</td>
<td align="left">nor</td>
</tr>
<tr>
<td align="left">Νουόζου, Nuosu</td>
<td align="left">ii</td>
<td align="left">iii</td>
</tr>
<tr>
<td align="left">Νοτ. Ντέμπελε</td>
<td align="left">nr</td>
<td align="left">nbl</td>
</tr>
<tr>
<td align="left">Οξιτάνικα</td>
<td align="left">oc</td>
<td align="left">oci</td>
</tr>
<tr>
<td align="left">Οτζίμπουε, Οτζίμπουε</td>
<td align="left">oj</td>
<td align="left">oji</td>
</tr>
<tr>
<td align="left">Σλαβονικά Παλαιοεκκλησιαστικά, Σλαβική Εκκλησία, Σλαβονική Εκκλησία, Παλιά Βουλγαρικά, Παλιά Σλαβονικά</td>
<td align="left">cu</td>
<td align="left">chu</td>
</tr>
<tr>
<td align="left">Ορόμο</td>
<td align="left">om</td>
<td align="left">orm</td>
</tr>
<tr>
<td align="left">Ορίγια</td>
<td align="left">or</td>
<td align="left">ori</td>
</tr>
<tr>
<td align="left">Οσσετιανά, Οσσετικά</td>
<td align="left">os</td>
<td align="left">oss</td>
</tr>
<tr>
<td align="left">Παντζάμπι, Punjabi</td>
<td align="left">pa</td>
<td align="left">pan</td>
</tr>
<tr>
<td align="left">Πάλι, Pāli</td>
<td align="left">pi</td>
<td align="left">pli</td>
</tr>
<tr>
<td align="left">Περσικά</td>
<td align="left">fa</td>
<td align="left">fas</td>
</tr>
<tr>
<td align="left">Πολωνικά</td>
<td align="left">pl</td>
<td align="left">pol</td>
</tr>
<tr>
<td align="left">Πάστο, Pushto</td>
<td align="left">ps</td>
<td align="left">pus</td>
</tr>
<tr>
<td align="left">Πορτογαλικά</td>
<td align="left">pt</td>
<td align="left">por</td>
</tr>
<tr>
<td align="left">Κέτσουα</td>
<td align="left">qu</td>
<td align="left">que</td>
</tr>
<tr>
<td align="left">Ρωμανικά, Romansh</td>
<td align="left">rm</td>
<td align="left">roh</td>
</tr>
<tr>
<td align="left">Κιρούντι</td>
<td align="left">rn</td>
<td align="left">run</td>
</tr>
<tr>
<td align="left">Ρουμανικά, Μολδαβικά, Moldovan</td>
<td align="left">ro</td>
<td align="left">ron</td>
</tr>
<tr>
<td align="left">Ρωσικά</td>
<td align="left">ru</td>
<td align="left">rus</td>
</tr>
<tr>
<td align="left">Σανσκριτικά (Saṁskṛta)</td>
<td align="left">sa</td>
<td align="left">san</td>
</tr>
<tr>
<td align="left">Σαρδηνιακά</td>
<td align="left">sc</td>
<td align="left">srd</td>
</tr>
<tr>
<td align="left">Σίντι, Sindhi</td>
<td align="left">sd</td>
<td align="left">snd</td>
</tr>
<tr>
<td align="left">Βορ. Σάμι</td>
<td align="left">se</td>
<td align="left">sme</td>
</tr>
<tr>
<td align="left">Σαμοανικά, Samoan</td>
<td align="left">sm</td>
<td align="left">smo</td>
</tr>
<tr>
<td align="left">Σάνγκο</td>
<td align="left">sg</td>
<td align="left">sag</td>
</tr>
<tr>
<td align="left">Σερβικά</td>
<td align="left">sr</td>
<td align="left">srp</td>
</tr>
<tr>
<td align="left">Σκωτικά Γαελικά, Gaelic</td>
<td align="left">gd</td>
<td align="left">gla</td>
</tr>
<tr>
<td align="left">Σόνα, Shona</td>
<td align="left">sn</td>
<td align="left">sna</td>
</tr>
<tr>
<td align="left">Σινχάλα, Sinhalese</td>
<td align="left">si</td>
<td align="left">sin</td>
</tr>
<tr>
<td align="left">Σλοβακικά</td>
<td align="left">sk</td>
<td align="left">slk</td>
</tr>
<tr>
<td align="left">Σλοβενικά</td>
<td align="left">sl</td>
<td align="left">slv</td>
</tr>
<tr>
<td align="left">Σομαλέζικα</td>
<td align="left">so</td>
<td align="left">som</td>
</tr>
<tr>
<td align="left">Νοτ. Σόθο, Southern Sotho</td>
<td align="left">st</td>
<td align="left">sot</td>
</tr>
<tr>
<td align="left">Ισπανικά, Καστίλης</td>
<td align="left">es</td>
<td align="left">spa</td>
</tr>
<tr>
<td align="left">Σουδανέζικα</td>
<td align="left">su</td>
<td align="left">sun</td>
</tr>
<tr>
<td align="left">Σουαχίλι</td>
<td align="left">sw</td>
<td align="left">swa</td>
</tr>
<tr>
<td align="left">Σουάτι, Swati</td>
<td align="left">ss</td>
<td align="left">ssw</td>
</tr>
<tr>
<td align="left">Σουηδικά</td>
<td align="left">sv</td>
<td align="left">swe</td>
</tr>
<tr>
<td align="left">Ταμίλ</td>
<td align="left">ta</td>
<td align="left">tam</td>
</tr>
<tr>
<td align="left">Τελούγκου</td>
<td align="left">te</td>
<td align="left">tel</td>
</tr>
<tr>
<td align="left">Τατζικικά, Tajik</td>
<td align="left">tg</td>
<td align="left">tgk</td>
</tr>
<tr>
<td align="left">ΤάΪ, Thai</td>
<td align="left">th</td>
<td align="left">tha</td>
</tr>
<tr>
<td align="left">Τιγκρίνυα, Tigrinya</td>
<td align="left">ti</td>
<td align="left">tir</td>
</tr>
<tr>
<td align="left">Τυπικά Θιβετιανά, Θιβετιανά, Κεντρικά</td>
<td align="left">bo</td>
<td align="left">bod</td>
</tr>
<tr>
<td align="left">Τουρκμενικά</td>
<td align="left">tk</td>
<td align="left">tuk</td>
</tr>
<tr>
<td align="left">Τάγκαλογκ, Tagalog</td>
<td align="left">tl</td>
<td align="left">tgl</td>
</tr>
<tr>
<td align="left">Τσουάνα, Tswana</td>
<td align="left">tn</td>
<td align="left">tsn</td>
</tr>
<tr>
<td align="left">Τόγκα (Νήσοι Tonga)</td>
<td align="left">to</td>
<td align="left">ton</td>
</tr>
<tr>
<td align="left">Τουρκικά</td>
<td align="left">tr</td>
<td align="left">tur</td>
</tr>
<tr>
<td align="left">Τσόγκα, Tsonga</td>
<td align="left">ts</td>
<td align="left">tso</td>
</tr>
<tr>
<td align="left">Ταταρικά</td>
<td align="left">tt</td>
<td align="left">tat</td>
</tr>
<tr>
<td align="left">Τουί, Twi</td>
<td align="left">tw</td>
<td align="left">twi</td>
</tr>
<tr>
<td align="left">ΤαΪτιανά</td>
<td align="left">ty</td>
<td align="left">tah</td>
</tr>
<tr>
<td align="left">Ουιγουρικά, Uyghur</td>
<td align="left">ug</td>
<td align="left">uig</td>
</tr>
<tr>
<td align="left">Ουκρανικά</td>
<td align="left">uk</td>
<td align="left">ukr</td>
</tr>
<tr>
<td align="left">Ούρντου, Urdu</td>
<td align="left">ur</td>
<td align="left">urd</td>
</tr>
<tr>
<td align="left">Ουζμπεκικά</td>
<td align="left">uz</td>
<td align="left">uzb</td>
</tr>
<tr>
<td align="left">Βέντα, Venda</td>
<td align="left">ve</td>
<td align="left">ven</td>
</tr>
<tr>
<td align="left">Βιετναμέζικα</td>
<td align="left">vi</td>
<td align="left">vie</td>
</tr>
<tr>
<td align="left">Βόλαπουκ, Volapük</td>
<td align="left">vo</td>
<td align="left">vol</td>
</tr>
<tr>
<td align="left">Βαλούν, Walloon</td>
<td align="left">wa</td>
<td align="left">wln</td>
</tr>
<tr>
<td align="left">Ουαλικά, Welsh</td>
<td align="left">cy</td>
<td align="left">cym</td>
</tr>
<tr>
<td align="left">Γουόλοφ, Wolof</td>
<td align="left">wo</td>
<td align="left">wol</td>
</tr>
<tr>
<td align="left">Δυτ. Φρυσικά, West. Frisian</td>
<td align="left">fy</td>
<td align="left">fry</td>
</tr>
<tr>
<td align="left">Ξόζα, Xhosa</td>
<td align="left">xh</td>
<td align="left">xho</td>
</tr>
<tr>
<td align="left">Γίντις, Yiddish</td>
<td align="left">yi</td>
<td align="left">yid</td>
</tr>
<tr>
<td align="left">Γιορούμπα, Yoruba</td>
<td align="left">yo</td>
<td align="left">yor</td>
</tr>
<tr>
<td align="left">Ζουάνγκ, Τσουάνγκ</td>
<td align="left">za</td>
<td align="left">zha</td>
</tr>
<tr>
<td align="left">Ζουλού</td>
<td align="left">zu</td>
<td align="left">zul</td>
</tr>
</tbody>
</table>
</div>
</div><br class="table-break"></div>
<div class="navfooter">
<hr>
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="chapter.misc.html">Προηγ</a>
</td>
<td width="20%" align="center"> </td>
<td width="40%" align="right"> <a accesskey="n" href="appendix.keyboard.html">Επόμενο</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Κεφάλαιο 20. Διάφορα θέματα </td>
<td width="20%" align="center"><a accesskey="h" href="index.html">Αρχή</a></td>
<td width="40%" align="right" valign="top"> Παράρτημα B. Συντμεύσεις πληκτρολογίου στο πρόγραμμα επεξεργασίας (editor)</td>
</tr>
</table>
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
<?php
/**
*
* bareos-webui - Bareos Web-Frontend
*
* @link https://github.com/bareos/bareos for the canonical source repository
* @copyright Copyright (c) 2013-2017 Bareos GmbH & Co. KG (http://www.bareos.org/)
* @license GNU Affero General Public License (http://www.gnu.org/licenses/)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
?>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?php echo $this->translate('Most recent job status per job name'); ?>
<a href="#" onClick="refreshPartials();return false;" title="Refresh"><span class="glyphicon glyphicon-refresh pull-right" aria-hidden="true"></span></a>
</h3>
</div>
<div class="panel-body">
<table class="table table-no-bordered table-hover" id="jobs-last-status">
<thead class="bg-primary">
<th><?php echo $this->translate("Job name"); ?></th>
<!-- <th data-cell-style="cellStyle"><?php echo $this->translate("Status"); ?></th> -->
<th><?php echo $this->translate("Status"); ?></th>
<th><?php echo $this->translate("Job ID"); ?></th>
<th><?php echo $this->translate("Client"); ?></th>
<th><?php echo $this->translate("Level"); ?></th>
<th><?php echo $this->translate("Start"); ?></th>
<th><?php echo $this->translate("End"); ?></th>
<th><?php echo $this->translate("Bytes"); ?></th>
</thead>
</table>
</div>
</div>
<script>
/*
function cellStyle(value, row, index) {
var classes = ['active', 'success', 'info', 'warning', 'danger'];
switch(value) {
case "T":
return { classes: classes[1] };
case "f":
case "E":
return { classes: classes[4] };
case "W":
return { classes: classes[3] };
case "R":
return { classes: classes[2] };
default:
return {};
}
}
*/
</script>
|
{
"pile_set_name": "Github"
}
|
<?php
/*******
* doesn't allow this file to be loaded with a browser.
*/
if (!defined('AT_INCLUDE_PATH')) { exit; }
/******
* this file must only be included within a Module obj
*/
if (!isset($this) || (isset($this) && (strtolower(get_class($this)) != 'module'))) { exit(__FILE__ . ' is not a Module'); }
/*******
* assign the instructor and admin privileges to the constants.
*/
define('AT_PRIV_FARCHIVE', $this->getPrivilege());
//define('AT_ADMIN_PRIV_FARCHIVE', $this->getAdminPrivilege());
/*******
* instructor Manage section:
*/
$this->_pages['mods/_standard/farchive/index_instructor.php']['title_var'] = 'farchive_export';
$this->_pages['mods/_standard/farchive/index_instructor.php']['parent'] = 'mods/_standard/forums/index.php';
$this->_pages['mods/_standard/farchive/index_instructor.php']['guide'] = 'instructor/?p=forum_export.php';
$this->_pages['mods/_standard/forums/index.php']['children'] = array('mods/_standard/farchive/index_instructor.php');
if($_SESSION['is_admin'] > 0 || authenticate(AT_PRIV_FARCHIVE, TRUE)){
$this->_pages_i['mods/_standard/farchive/index_instructor.php']['title_var'] = 'farchive_export';
$this->_pages_i['mods/_standard/farchive/index_instructor.php']['other_parent'] = 'mods/_standard/forums/forum/list.php';
$this->_pages_i['mods/_standard/forums/forum/list.php']['children'] = array('mods/_standard/farchive/index_instructor.php');
}
?>
|
{
"pile_set_name": "Github"
}
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>buffered_write_stream::get_io_context</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../index.html" title="Asio">
<link rel="up" href="../buffered_write_stream.html" title="buffered_write_stream">
<link rel="prev" href="get_executor.html" title="buffered_write_stream::get_executor">
<link rel="next" href="get_io_service.html" title="buffered_write_stream::get_io_service">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../asio.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="get_executor.html"><img src="../../../prev.png" alt="Prev"></a><a accesskey="u" href="../buffered_write_stream.html"><img src="../../../up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../home.png" alt="Home"></a><a accesskey="n" href="get_io_service.html"><img src="../../../next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="asio.reference.buffered_write_stream.get_io_context"></a><a class="link" href="get_io_context.html" title="buffered_write_stream::get_io_context">buffered_write_stream::get_io_context</a>
</h4></div></div></div>
<p>
<a class="indexterm" name="asio.indexterm.buffered_write_stream.get_io_context"></a>
(Deprecated:
Use <code class="computeroutput">get_executor()</code>.) Get the <a class="link" href="../io_context.html" title="io_context"><code class="computeroutput">io_context</code></a>
associated with the object.
</p>
<pre class="programlisting">asio::io_context & get_io_context();
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2018 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="get_executor.html"><img src="../../../prev.png" alt="Prev"></a><a accesskey="u" href="../buffered_write_stream.html"><img src="../../../up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../home.png" alt="Home"></a><a accesskey="n" href="get_io_service.html"><img src="../../../next.png" alt="Next"></a>
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<component type="desktop">
<id>org.zealdocs.Zeal.desktop</id>
<name>Zeal</name>
<metadata_license>CC0-1.0</metadata_license>
<project_license>GPL-3.0-only</project_license>
<summary>Documentation browser</summary>
<description>
<p>Zeal is a simple offline documentation browser inspired by Dash.</p>
</description>
<url type="homepage">https://zealdocs.org/</url>
<url type="bugtracker">https://github.com/zealdocs/zeal/issues</url>
<url type="help">https://zealdocs.org/usage.html</url>
<screenshots>
<screenshot type="default">
<image>https://i.imgur.com/qBkZduS.png</image>
</screenshot>
</screenshots>
<provides>
<id>zeal.desktop</id>
</provides>
<releases>
<release date="${RELEASE_DATE}" version="${Zeal_VERSION}" />
</releases>
<update_contact>zeal@zealdocs.org</update_contact>
<content_rating type="oars-1.1">
<content_attribute id="violence-cartoon">none</content_attribute>
<content_attribute id="violence-fantasy">none</content_attribute>
<content_attribute id="violence-realistic">none</content_attribute>
<content_attribute id="violence-bloodshed">none</content_attribute>
<content_attribute id="violence-sexual">none</content_attribute>
<content_attribute id="violence-desecration">none</content_attribute>
<content_attribute id="violence-slavery">none</content_attribute>
<content_attribute id="violence-worship">none</content_attribute>
<content_attribute id="drugs-alcohol">none</content_attribute>
<content_attribute id="drugs-narcotics">none</content_attribute>
<content_attribute id="drugs-tobacco">none</content_attribute>
<content_attribute id="sex-nudity">none</content_attribute>
<content_attribute id="sex-themes">none</content_attribute>
<content_attribute id="sex-homosexuality">none</content_attribute>
<content_attribute id="sex-prostitution">none</content_attribute>
<content_attribute id="sex-adultery">none</content_attribute>
<content_attribute id="sex-appearance">none</content_attribute>
<content_attribute id="language-profanity">none</content_attribute>
<content_attribute id="language-humor">none</content_attribute>
<content_attribute id="language-discrimination">none</content_attribute>
<content_attribute id="social-chat">none</content_attribute>
<content_attribute id="social-info">none</content_attribute>
<content_attribute id="social-audio">none</content_attribute>
<content_attribute id="social-location">none</content_attribute>
<content_attribute id="social-contacts">none</content_attribute>
<content_attribute id="money-purchasing">none</content_attribute>
<content_attribute id="money-gambling">none</content_attribute>
</content_rating>
</component>
|
{
"pile_set_name": "Github"
}
|
function ExampleAnalog()
% function OutputAnalogVector = ExampleAnalog()
% Prompt for the correct DLL
disp(' '); % Blank line
DLLName = input('DLL Name: ', 's');
% Load the appropriate DLL
[nsresult] = ns_SetLibrary(DLLName);
if (nsresult ~= 0)
disp('DLL was not found!');
return
end
% Find out the data file from user
disp(' '); % Blank line
filename = input('Data file: ', 's');
% Load data file and display some info about the file
% Open data file
[nsresult, hfile] = ns_OpenFile(filename);
if (nsresult ~= 0)
disp('Data file did not open!');
return
end
clear filename;
% Get file information
[nsresult, FileInfo] = ns_GetFileInfo(hfile);
% Gives you EntityCount, TimeStampResolution and TimeSpan
if (nsresult ~= 0)
disp('Data file information did not load!');
return
end
% Define some variables needed for firing rates
stepsize = 0.02; % seconds
stepsize1 = 0.1; % seconds
if FileInfo.TimeSpan > 150 % Limit the timespan shown in the graphs to 150 seconds
totaltime = 150;
else
totaltime = FileInfo.TimeSpan; % seconds
end
time = 0 : stepsize : totaltime; % Initialize time axis for gaussian plot
% Build catalogue of entities
[nsresult, EntityInfo] = ns_GetEntityInfo(hfile, [1 : 1 : FileInfo.EntityCount]);
NeuralList = find([EntityInfo.EntityType] == 4); % List of EntityIDs needed to retrieve the information and data
SegmentList = find([EntityInfo.EntityType] == 3);
AnalogList = find([EntityInfo.EntityType] == 2);
EventList = find([EntityInfo.EntityType] == 1);
% How many of a particular entity do we have
cNeural = length(NeuralList);
cSegment = length(SegmentList);
cAnalog = length(AnalogList);
cEvent = length(EventList);
clear FileInfo;
if (cNeural == 0)
disp('No neural events available!');
end
if (cSegment == 0)
disp('No segment entities available!');
end
if (cAnalog == 0)
disp('No analog entities available!');
end
if (cEvent == 0)
disp('No event entities available!');
end
% prompt to get the number of points
max_count = input('How many data points (x-axis) do you want max? ');
% Have user pick a channels or channels for further analysis
% Show the user how many channels are available
disp(' ');
disp(['There are ' num2str(cAnalog) ' analog channels.']);
disp(' ');
yes = input('Show first all analog channels? y/n ', 's');
if (yes == 'y')
for i = 1 : 1 : length(AnalogList)
chan = AnalogList(i);
count = min(max_count, EntityInfo(chan).ItemCount);
% Get the fist data points of the waveform and show it
[nsresult, ContinuousCount, wave] = ns_GetAnalogData(hfile, AnalogList(i), 1, count);
figure;
plot(wave);
end
return;
end
disp(['First analog entity: ' num2str(AnalogList(1)) ]);
channel = input('Which data channels would you like to display? (e.g. 1 or [1 2 3])');
if (EntityInfo(channel).EntityType == 2) % Have to check that the selected channel actually exists
else
disp('Channel is not of type analog');
return
end
clear cNeural cSegment;
% Throw away entity infos we don't need to save memory
EntityInfo = rmfield(EntityInfo, 'EntityType');
%
% Load the waveform data and do the analysis
%
count = min(max_count, EntityInfo(channel).ItemCount);
% Get the fist data points of the waveform and show it
[nsresult, ContinuousCount, wave] = ns_GetAnalogData(hfile, channel, 1, count);
plot(wave);
return;
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) Facebook, Inc. and its affiliates.
// All rights reserved.
//
// Copyright 2019 Google LLC
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include <assert.h>
#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <fp16.h>
#include <xnnpack.h>
#include <xnnpack/allocator.h>
#include <xnnpack/log.h>
#include <xnnpack/operator.h>
#include <xnnpack/params-init.h>
#include <xnnpack/params.h>
static enum xnn_status create_global_average_pooling_nwc(
size_t channels,
size_t input_stride,
size_t output_stride,
uint32_t flags,
uint32_t log2_element_size,
size_t params_offset,
const void* params,
size_t params_size,
uint32_t datatype_init_flags,
enum xnn_operator_type operator_type,
xnn_operator_t* global_average_pooling_op_out)
{
xnn_operator_t global_average_pooling_op = NULL;
enum xnn_status status = xnn_status_uninitialized;
if ((xnn_params.init_flags & XNN_INIT_FLAG_XNNPACK) == 0) {
xnn_log_error("failed to create %s operator: XNNPACK is not initialized",
xnn_operator_type_to_string(operator_type));
goto error;
}
status = xnn_status_unsupported_hardware;
if ((xnn_params.init_flags & datatype_init_flags) == 0) {
xnn_log_error("failed to create %s operator: operations on data type are not supported",
xnn_operator_type_to_string(operator_type));
goto error;
}
status = xnn_status_invalid_parameter;
if (channels == 0) {
xnn_log_error(
"failed to create %s operator with %zu channels: number of channels must be non-zero",
xnn_operator_type_to_string(operator_type), channels);
goto error;
}
if (input_stride < channels) {
xnn_log_error(
"failed to create %s operator with input element stride of %zu: "
"stride must be at least as large as the number of channels (%zu)",
xnn_operator_type_to_string(operator_type), input_stride, channels);
goto error;
}
if (output_stride < channels) {
xnn_log_error(
"failed to create %s operator with output element stride of %zu: "
"stride must be at least as large as the number of channels (%zu)",
xnn_operator_type_to_string(operator_type), output_stride, channels);
goto error;
}
status = xnn_status_out_of_memory;
global_average_pooling_op = xnn_allocate_zero_simd_memory(sizeof(struct xnn_operator));
if (global_average_pooling_op == NULL) {
xnn_log_error(
"failed to allocate %zu bytes for %s operator descriptor",
sizeof(struct xnn_operator), xnn_operator_type_to_string(operator_type));
goto error;
}
const size_t zero_size = (channels << log2_element_size) + XNN_EXTRA_BYTES;
void* zero_buffer = xnn_allocate_zero_simd_memory(zero_size);
if (zero_buffer == NULL) {
xnn_log_error(
"failed to allocate %zu bytes for %s operator zero padding",
zero_size, xnn_operator_type_to_string(operator_type));
goto error;
}
global_average_pooling_op->zero_buffer = zero_buffer;
global_average_pooling_op->channels = channels;
global_average_pooling_op->input_pixel_stride = input_stride;
global_average_pooling_op->output_pixel_stride = output_stride;
memcpy((void*) ((uintptr_t) global_average_pooling_op + params_offset), params, params_size);
global_average_pooling_op->type = operator_type;
global_average_pooling_op->ukernel.type = xnn_ukernel_type_global_average_pooling;
global_average_pooling_op->state = xnn_run_state_invalid;
*global_average_pooling_op_out = global_average_pooling_op;
return xnn_status_success;
error:
xnn_delete_operator(global_average_pooling_op);
return status;
}
static enum xnn_status setup_global_average_pooling_nwc(
xnn_operator_t global_average_pooling_op,
size_t batch_size,
size_t width,
const void* input,
void* output,
size_t log2_element_size,
const struct gavgpool_parameters gavgpool[restrict XNN_MIN_ELEMENTS(1)],
uint32_t datatype_init_flags,
enum xnn_operator_type expected_operator_type,
const void* params,
size_t params_size,
void (*update_params)(xnn_operator_t, size_t),
pthreadpool_t threadpool)
{
if (global_average_pooling_op->type != expected_operator_type) {
xnn_log_error("failed to setup operator: operator type mismatch (expected %s, got %s)",
xnn_operator_type_to_string(expected_operator_type),
xnn_operator_type_to_string(global_average_pooling_op->type));
return xnn_status_invalid_parameter;
}
global_average_pooling_op->state = xnn_run_state_invalid;
if ((xnn_params.init_flags & XNN_INIT_FLAG_XNNPACK) == 0) {
xnn_log_error("failed to setup %s operator: XNNPACK is not initialized",
xnn_operator_type_to_string(global_average_pooling_op->type));
return xnn_status_uninitialized;
}
if ((xnn_params.init_flags & datatype_init_flags) == 0) {
xnn_log_error("failed to setup %s operator: operations on data type are not supported",
xnn_operator_type_to_string(global_average_pooling_op->type));
return xnn_status_unsupported_hardware;
}
if (width == 0) {
xnn_log_error("failed to setup %s operator with width %zu: width must be non-zero",
xnn_operator_type_to_string(global_average_pooling_op->type), width);
return xnn_status_invalid_parameter;
}
if (batch_size == 0) {
global_average_pooling_op->state = xnn_run_state_skip;
return xnn_status_success;
}
global_average_pooling_op->batch_size = batch_size;
global_average_pooling_op->input_width = width;
global_average_pooling_op->input = input;
global_average_pooling_op->output = output;
update_params(global_average_pooling_op, width);
assert(gavgpool->mr != 0);
const size_t input_stride_in_bytes = global_average_pooling_op->input_pixel_stride << log2_element_size;
const size_t channels = global_average_pooling_op->channels;
global_average_pooling_op->context.global_average_pooling_nwc = (struct global_average_pooling_nwc_context) {
.input = input,
.zero = global_average_pooling_op->zero_buffer,
.input_pixel_stride = input_stride_in_bytes,
.input_batch_stride = input_stride_in_bytes * width,
.input_elements = width,
.channels = channels,
.output = output,
.output_batch_stride = (global_average_pooling_op->output_pixel_stride << log2_element_size),
};
memcpy(&global_average_pooling_op->context.global_average_pooling_nwc.params, params, params_size);
global_average_pooling_op->compute.type = xnn_parallelization_type_1d;
global_average_pooling_op->compute.range[0] = batch_size;
if (width <= gavgpool->mr) {
global_average_pooling_op->compute.task_1d = (pthreadpool_task_1d_t) xnn_compute_global_average_pooling_nwc_unipass;
global_average_pooling_op->context.global_average_pooling_nwc.unipass_ukernel = gavgpool->up;
} else {
global_average_pooling_op->compute.task_1d = (pthreadpool_task_1d_t) xnn_compute_global_average_pooling_nwc_multipass;
global_average_pooling_op->context.global_average_pooling_nwc.multipass_ukernel = gavgpool->mp;
}
global_average_pooling_op->state = xnn_run_state_ready;
return xnn_status_success;
}
enum xnn_status xnn_create_global_average_pooling_nwc_qu8(
size_t channels,
size_t input_stride,
size_t output_stride,
uint8_t input_zero_point,
float input_scale,
uint8_t output_zero_point,
float output_scale,
uint8_t output_min,
uint8_t output_max,
uint32_t flags,
xnn_operator_t* global_average_pooling_op_out)
{
if (input_scale <= 0.0f || !isnormal(input_scale)) {
xnn_log_error(
"failed to create %s operator with %.7g input scale: scale must be finite, normalized, and positive",
xnn_operator_type_to_string(xnn_operator_type_global_average_pooling_nwc_qu8), input_scale);
return xnn_status_invalid_parameter;
}
if (output_scale <= 0.0f || !isnormal(output_scale)) {
xnn_log_error(
"failed to create %s operator with %.7g output scale: scale must be finite, normalized, and positive",
xnn_operator_type_to_string(xnn_operator_type_global_average_pooling_nwc_qu8), output_scale);
return xnn_status_invalid_parameter;
}
if (output_min >= output_max) {
xnn_log_error(
"failed to create %s operator with [%" PRIu8 ", %" PRIu8 "] output range: range min must be below range max",
xnn_operator_type_to_string(xnn_operator_type_global_average_pooling_nwc_qu8), output_min, output_max);
return xnn_status_invalid_parameter;
}
const float input_output_scale = input_scale / output_scale;
if (input_output_scale < 0x1.0p-8f || input_output_scale >= 0x1.0p+8f) {
xnn_log_error(
"failed to create %s operator with %.7g input-to-output scale ratio: scale ratio must be in [2**-8, 2**8) range",
xnn_operator_type_to_string(xnn_operator_type_global_average_pooling_nwc_qu8), input_output_scale);
return xnn_status_unsupported_parameter;
}
const union xnn_qu8_avgpool_params params =
xnn_init_qu8_avgpool_params(
0 /* bias */, 1.0f /* scale */,
output_zero_point, output_min, output_max);
const enum xnn_status status = create_global_average_pooling_nwc(
channels, input_stride, output_stride, flags,
0 /* log2(sizeof(uint8_t)) */,
offsetof(struct xnn_operator, params.qu8_gavgpool),
¶ms, sizeof(params),
XNN_INIT_FLAG_QU8,
xnn_operator_type_global_average_pooling_nwc_qu8,
global_average_pooling_op_out);
if (status == xnn_status_success) {
xnn_operator_t global_average_pooling_op = *global_average_pooling_op_out;
global_average_pooling_op->input_zero_point = (int32_t) (uint32_t) input_zero_point;
global_average_pooling_op->input_scale = input_scale;
global_average_pooling_op->output_scale = output_scale;
}
return status;
}
enum xnn_status xnn_create_global_average_pooling_nwc_qs8(
size_t channels,
size_t input_stride,
size_t output_stride,
int8_t input_zero_point,
float input_scale,
int8_t output_zero_point,
float output_scale,
int8_t output_min,
int8_t output_max,
uint32_t flags,
xnn_operator_t* global_average_pooling_op_out)
{
if (input_scale <= 0.0f || !isnormal(input_scale)) {
xnn_log_error(
"failed to create %s operator with %.7g input scale: scale must be finite, normalized, and positive",
xnn_operator_type_to_string(xnn_operator_type_global_average_pooling_nwc_qs8), input_scale);
return xnn_status_invalid_parameter;
}
if (output_scale <= 0.0f || !isnormal(output_scale)) {
xnn_log_error(
"failed to create %s operator with %.7g output scale: scale must be finite, normalized, and positive",
xnn_operator_type_to_string(xnn_operator_type_global_average_pooling_nwc_qs8), output_scale);
return xnn_status_invalid_parameter;
}
if (output_min >= output_max) {
xnn_log_error(
"failed to create %s operator with [%" PRId8 ", %" PRId8 "] output range: range min must be below range max",
xnn_operator_type_to_string(xnn_operator_type_global_average_pooling_nwc_qs8), output_min, output_max);
return xnn_status_invalid_parameter;
}
const float input_output_scale = input_scale / output_scale;
if (input_output_scale < 0x1.0p-8f || input_output_scale >= 0x1.0p+8f) {
xnn_log_error(
"failed to create %s operator with %.7g input-to-output scale ratio: scale ratio must be in [2**-8, 2**8) range",
xnn_operator_type_to_string(xnn_operator_type_global_average_pooling_nwc_qs8), input_output_scale);
return xnn_status_unsupported_parameter;
}
const union xnn_qs8_avgpool_params params =
xnn_init_qs8_avgpool_params(
0 /* bias */, 1.0f /* scale */,
output_zero_point, output_min, output_max);
const enum xnn_status status = create_global_average_pooling_nwc(
channels, input_stride, output_stride, flags,
0 /* log2(sizeof(int8_t)) */,
offsetof(struct xnn_operator, params.qs8_gavgpool),
¶ms, sizeof(params),
XNN_INIT_FLAG_QS8,
xnn_operator_type_global_average_pooling_nwc_qs8,
global_average_pooling_op_out);
if (status == xnn_status_success) {
xnn_operator_t global_average_pooling_op = *global_average_pooling_op_out;
global_average_pooling_op->input_zero_point = (int32_t) input_zero_point;
global_average_pooling_op->input_scale = input_scale;
global_average_pooling_op->output_scale = output_scale;
}
return status;
}
enum xnn_status xnn_create_global_average_pooling_nwc_f16(
size_t channels,
size_t input_stride,
size_t output_stride,
float output_min,
float output_max,
uint32_t flags,
xnn_operator_t* global_average_pooling_op_out)
{
if (isnan(output_min)) {
xnn_log_error(
"failed to create %s operator with NaN output lower bound: lower bound must be non-NaN",
xnn_operator_type_to_string(xnn_operator_type_global_average_pooling_nwc_f16));
return xnn_status_invalid_parameter;
}
if (isnan(output_max)) {
xnn_log_error(
"failed to create %s operator with NaN output upper bound: upper bound must be non-NaN",
xnn_operator_type_to_string(xnn_operator_type_global_average_pooling_nwc_f16));
return xnn_status_invalid_parameter;
}
if (fp16_ieee_to_fp32_value(fp16_ieee_from_fp32_value(output_min)) >= fp16_ieee_to_fp32_value(fp16_ieee_from_fp32_value(output_max))) {
xnn_log_error(
"failed to create %s operator with [%.7g, %.7g] output range: lower bound must be below upper bound",
xnn_operator_type_to_string(xnn_operator_type_global_average_pooling_nwc_f16),
fp16_ieee_to_fp32_value(fp16_ieee_from_fp32_value(output_min)),
fp16_ieee_to_fp32_value(fp16_ieee_from_fp32_value(output_max)));
return xnn_status_invalid_parameter;
}
const struct xnn_f16_scaleminmax_params params =
xnn_init_f16_scaleminmax_params(
UINT16_C(0x7E00) /* NaN */,
fp16_ieee_from_fp32_value(output_min),
fp16_ieee_from_fp32_value(output_max));
return create_global_average_pooling_nwc(
channels, input_stride, output_stride, flags,
1 /* log2(sizeof(uint16_t)) */,
offsetof(struct xnn_operator, params.f16_scaleminmax),
¶ms, sizeof(params),
XNN_INIT_FLAG_F16,
xnn_operator_type_global_average_pooling_nwc_f16,
global_average_pooling_op_out);
}
enum xnn_status xnn_create_global_average_pooling_nwc_f32(
size_t channels,
size_t input_stride,
size_t output_stride,
float output_min,
float output_max,
uint32_t flags,
xnn_operator_t* global_average_pooling_op_out)
{
if (isnan(output_min)) {
xnn_log_error(
"failed to create %s operator with NaN output lower bound: lower bound must be non-NaN",
xnn_operator_type_to_string(xnn_operator_type_global_average_pooling_nwc_f32));
return xnn_status_invalid_parameter;
}
if (isnan(output_max)) {
xnn_log_error(
"failed to create %s operator with NaN output upper bound: upper bound must be non-NaN",
xnn_operator_type_to_string(xnn_operator_type_global_average_pooling_nwc_f32));
return xnn_status_invalid_parameter;
}
if (output_min >= output_max) {
xnn_log_error(
"failed to create %s operator with [%.7g, %.7g] output range: lower bound must be below upper bound",
xnn_operator_type_to_string(xnn_operator_type_global_average_pooling_nwc_f32), output_min, output_max);
return xnn_status_invalid_parameter;
}
const union xnn_f32_scaleminmax_params params =
xnn_init_f32_scaleminmax_params(
0.0f /* scale */, output_min, output_max);
return create_global_average_pooling_nwc(
channels, input_stride, output_stride, flags,
2 /* log2(sizeof(float)) */,
offsetof(struct xnn_operator, params.f32_scaleminmax),
¶ms, sizeof(params),
XNN_INIT_FLAG_F32,
xnn_operator_type_global_average_pooling_nwc_f32,
global_average_pooling_op_out);
}
static void update_params_qu8(
xnn_operator_t global_average_pooling_op,
size_t width)
{
const int32_t bias = -((int32_t) width * global_average_pooling_op->input_zero_point);
const float scale = global_average_pooling_op->input_scale / (global_average_pooling_op->output_scale * (float) width);
xnn_update_qu8_avgpool_params(&global_average_pooling_op->params.qu8_gavgpool, bias, scale);
}
enum xnn_status xnn_setup_global_average_pooling_nwc_qu8(
xnn_operator_t global_average_pooling_op,
size_t batch_size,
size_t width,
const uint8_t* input,
uint8_t* output,
pthreadpool_t threadpool)
{
return setup_global_average_pooling_nwc(
global_average_pooling_op,
batch_size, width,
input, output,
0 /* log2(sizeof(uint8_t)) */,
&xnn_params.qu8.gavgpool,
XNN_INIT_FLAG_QU8,
xnn_operator_type_global_average_pooling_nwc_qu8,
&global_average_pooling_op->params.qu8_gavgpool,
sizeof(global_average_pooling_op->params.qu8_gavgpool),
update_params_qu8,
threadpool);
}
static void update_params_qs8(
xnn_operator_t global_average_pooling_op,
size_t width)
{
const int32_t bias = -((int32_t) width * global_average_pooling_op->input_zero_point);
const float scale = global_average_pooling_op->input_scale / (global_average_pooling_op->output_scale * (float) width);
xnn_update_qs8_avgpool_params(&global_average_pooling_op->params.qs8_gavgpool, bias, scale);
}
enum xnn_status xnn_setup_global_average_pooling_nwc_qs8(
xnn_operator_t global_average_pooling_op,
size_t batch_size,
size_t width,
const int8_t* input,
int8_t* output,
pthreadpool_t threadpool)
{
return setup_global_average_pooling_nwc(
global_average_pooling_op,
batch_size, width,
input, output,
0 /* log2(sizeof(int8_t)) */,
&xnn_params.qs8.gavgpool,
XNN_INIT_FLAG_QS8,
xnn_operator_type_global_average_pooling_nwc_qs8,
&global_average_pooling_op->params.qs8_gavgpool,
sizeof(global_average_pooling_op->params.qs8_gavgpool),
update_params_qs8,
threadpool);
}
static void update_params_f16(
xnn_operator_t global_average_pooling_op,
size_t width)
{
xnn_update_f16_scaleminmax_params(
&global_average_pooling_op->params.f16_scaleminmax,
fp16_ieee_from_fp32_value(1.0f / (float) width));
}
enum xnn_status xnn_setup_global_average_pooling_nwc_f16(
xnn_operator_t global_average_pooling_op,
size_t batch_size,
size_t width,
const void* input,
void* output,
pthreadpool_t threadpool)
{
return setup_global_average_pooling_nwc(
global_average_pooling_op,
batch_size, width,
input, output,
1 /* log2(sizeof(uint16_t)) */,
&xnn_params.f16.gavgpool,
XNN_INIT_FLAG_F16,
xnn_operator_type_global_average_pooling_nwc_f16,
&global_average_pooling_op->params.f16_scaleminmax,
sizeof(global_average_pooling_op->params.f16_scaleminmax),
update_params_f16,
threadpool);
}
static void update_params_f32(
xnn_operator_t global_average_pooling_op,
size_t width)
{
xnn_update_f32_scaleminmax_params(&global_average_pooling_op->params.f32_scaleminmax, 1.0f / (float) width);
}
enum xnn_status xnn_setup_global_average_pooling_nwc_f32(
xnn_operator_t global_average_pooling_op,
size_t batch_size,
size_t width,
const float* input,
float* output,
pthreadpool_t threadpool)
{
return setup_global_average_pooling_nwc(
global_average_pooling_op,
batch_size, width,
input, output,
2 /* log2(sizeof(float)) */,
&xnn_params.f32.gavgpool,
XNN_INIT_FLAG_F32,
xnn_operator_type_global_average_pooling_nwc_f32,
&global_average_pooling_op->params.f32_scaleminmax,
sizeof(global_average_pooling_op->params.f32_scaleminmax),
update_params_f32,
threadpool);
}
|
{
"pile_set_name": "Github"
}
|
// RUN: %clang_cc1 -fblocks -analyze -analyzer-checker=osx.cocoa.MissingSuperCall -verify -Wno-objc-root-class %s
// Define used Classes
@protocol NSObject
- (id)retain;
- (oneway void)release;
@end
@interface NSObject <NSObject> {}
- (id)init;
+ (id)alloc;
@end
typedef char BOOL;
typedef double NSTimeInterval;
typedef enum UIViewAnimationOptions {
UIViewAnimationOptionLayoutSubviews = 1 << 0
} UIViewAnimationOptions;
@interface NSCoder : NSObject {}
@end
// Define the Superclasses for our Checks
@interface UIViewController : NSObject {}
- (void)addChildViewController:(UIViewController *)childController;
- (void)viewDidAppear:(BOOL)animated;
- (void)viewDidDisappear:(BOOL)animated;
- (void)viewDidUnload;
- (void)viewDidLoad;
- (void)viewWillUnload;
- (void)viewWillAppear:(BOOL)animated;
- (void)viewWillDisappear:(BOOL)animated;
- (void)didReceiveMemoryWarning;
- (void)removeFromParentViewController;
- (void)transitionFromViewController:(UIViewController *)fromViewController
toViewController:(UIViewController *)toViewController
duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options
animations:(void (^)(void))animations
completion:(void (^)(BOOL finished))completion;
@end
@interface UIResponder : NSObject {}
- (BOOL)resignFirstResponder;
@end
@interface NSResponder : NSObject {}
- (void)restoreStateWithCoder:(NSCoder *)coder;
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder;
@end
@interface NSDocument : NSObject {}
- (void)restoreStateWithCoder:(NSCoder *)coder;
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder;
@end
// Checks
// Do not warn if UIViewController/*Responder/NSDocument is not our superclass
@interface TestA
@end
@implementation TestA
- (void)addChildViewController:(UIViewController *)childController {}
- (void)viewDidAppear:(BOOL)animated {}
- (void)viewDidDisappear:(BOOL)animated {}
- (void)viewDidUnload {}
- (void)viewDidLoad {}
- (void)viewWillUnload {}
- (void)viewWillAppear:(BOOL)animated {}
- (void)viewWillDisappear:(BOOL)animated {}
- (void)didReceiveMemoryWarning {}
- (void)removeFromParentViewController {}
- (BOOL)resignFirstResponder { return 0; }
- (void)restoreStateWithCoder:(NSCoder *)coder {}
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder {}
@end
// Do not warn for the implementation in the superclass itself.
@implementation UIViewController
- (void)addChildViewController:(UIViewController *)childController {}
- (void)viewDidAppear:(BOOL)animated {}
- (void)viewDidDisappear:(BOOL)animated {}
- (void)viewDidUnload {}
- (void)viewDidLoad {}
- (void)viewWillUnload {}
- (void)viewWillAppear:(BOOL)animated {}
- (void)viewWillDisappear:(BOOL)animated {}
- (void)didReceiveMemoryWarning {}
- (void)removeFromParentViewController {}
- (void)transitionFromViewController:(UIViewController *)fromViewController
toViewController:(UIViewController *)toViewController
duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options
animations:(void (^)(void))animations
completion:(void (^)(BOOL finished))completion {}
@end
// Warn if UIViewController is our superclass and we do not call super
@interface TestB : UIViewController {}
@end
@implementation TestB
- (void)addChildViewController:(UIViewController *)childController {
int addChildViewController = 5;
for (int i = 0; i < addChildViewController; i++)
[self viewDidAppear:i];
} // expected-warning {{The 'addChildViewController:' instance method in UIViewController subclass 'TestB' is missing a [super addChildViewController:] call}}
- (void)viewDidAppear:(BOOL)animated {} // expected-warning {{The 'viewDidAppear:' instance method in UIViewController subclass 'TestB' is missing a [super viewDidAppear:] call}}
- (void)viewDidDisappear:(BOOL)animated {} // expected-warning {{The 'viewDidDisappear:' instance method in UIViewController subclass 'TestB' is missing a [super viewDidDisappear:] call}}
- (void)viewDidUnload {} // expected-warning {{The 'viewDidUnload' instance method in UIViewController subclass 'TestB' is missing a [super viewDidUnload] call}}
- (void)viewDidLoad {} // expected-warning {{The 'viewDidLoad' instance method in UIViewController subclass 'TestB' is missing a [super viewDidLoad] call}}
- (void)viewWillUnload {} // expected-warning {{The 'viewWillUnload' instance method in UIViewController subclass 'TestB' is missing a [super viewWillUnload] call}}
- (void)viewWillAppear:(BOOL)animated {} // expected-warning {{The 'viewWillAppear:' instance method in UIViewController subclass 'TestB' is missing a [super viewWillAppear:] call}}
- (void)viewWillDisappear:(BOOL)animated {} // expected-warning {{The 'viewWillDisappear:' instance method in UIViewController subclass 'TestB' is missing a [super viewWillDisappear:] call}}
- (void)didReceiveMemoryWarning {} // expected-warning {{The 'didReceiveMemoryWarning' instance method in UIViewController subclass 'TestB' is missing a [super didReceiveMemoryWarning] call}}
- (void)removeFromParentViewController {} // expected-warning {{The 'removeFromParentViewController' instance method in UIViewController subclass 'TestB' is missing a [super removeFromParentViewController] call}}
// Do not warn for methods were it shouldn't
- (void)shouldAutorotate {}
@end
// Do not warn if UIViewController is our superclass but we did call super
@interface TestC : UIViewController {}
@end
@implementation TestC
- (BOOL)methodReturningStuff {
return 1;
}
- (void)methodDoingStuff {
[super removeFromParentViewController];
}
- (void)addChildViewController:(UIViewController *)childController {
[super addChildViewController:childController];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewWillUnload {
[super viewWillUnload];
}
- (void)viewWillAppear:(BOOL)animated {
int i = 0; // Also don't start warning just because we do additional stuff
i++;
[self viewDidDisappear:i];
[super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:[self methodReturningStuff]];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
// We expect a warning here because at the moment the super-call can't be
// done from another method.
- (void)removeFromParentViewController {
[self methodDoingStuff];
} // expected-warning {{The 'removeFromParentViewController' instance method in UIViewController subclass 'TestC' is missing a [super removeFromParentViewController] call}}
@end
// Do warn for UIResponder subclasses that don't call super
@interface TestD : UIResponder {}
@end
@implementation TestD
- (BOOL)resignFirstResponder {
return 0;
} // expected-warning {{The 'resignFirstResponder' instance method in UIResponder subclass 'TestD' is missing a [super resignFirstResponder] call}}
@end
// Do not warn for UIResponder subclasses that do the right thing
@interface TestE : UIResponder {}
@end
@implementation TestE
- (BOOL)resignFirstResponder {
return [super resignFirstResponder];
}
@end
// Do warn for NSResponder subclasses that don't call super
@interface TestF : NSResponder {}
@end
@implementation TestF
- (void)restoreStateWithCoder:(NSCoder *)coder {
} // expected-warning {{The 'restoreStateWithCoder:' instance method in NSResponder subclass 'TestF' is missing a [super restoreStateWithCoder:] call}}
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder {
} // expected-warning {{The 'encodeRestorableStateWithCoder:' instance method in NSResponder subclass 'TestF' is missing a [super encodeRestorableStateWithCoder:] call}}
@end
// Do not warn for NSResponder subclasses that do the right thing
@interface TestG : NSResponder {}
@end
@implementation TestG
- (void)restoreStateWithCoder:(NSCoder *)coder {
[super restoreStateWithCoder:coder];
}
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder {
[super encodeRestorableStateWithCoder:coder];
}
@end
// Do warn for NSDocument subclasses that don't call super
@interface TestH : NSDocument {}
@end
@implementation TestH
- (void)restoreStateWithCoder:(NSCoder *)coder {
} // expected-warning {{The 'restoreStateWithCoder:' instance method in NSDocument subclass 'TestH' is missing a [super restoreStateWithCoder:] call}}
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder {
} // expected-warning {{The 'encodeRestorableStateWithCoder:' instance method in NSDocument subclass 'TestH' is missing a [super encodeRestorableStateWithCoder:] call}}
@end
// Do not warn for NSDocument subclasses that do the right thing
@interface TestI : NSDocument {}
@end
@implementation TestI
- (void)restoreStateWithCoder:(NSCoder *)coder {
[super restoreStateWithCoder:coder];
}
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder {
[super encodeRestorableStateWithCoder:coder];
}
@end
|
{
"pile_set_name": "Github"
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
//using UnityEditor;
public class PokedexHandler : MonoBehaviour {
// Usage Variables
public Vector2 cursorPosition;
public float boxNum;
private float pokemonNum;
private Texture[] pokeSprites;
private bool screen2;
// GameObject like vars
private Texture cursor;
private Texture preview;
private new Text name;
private Text nameShadow;
private Text id;
private Text idShadow;
private Text boxLabel;
private Text boxLabelShadow;
public Texture[] pokePreview;
public Texture background;
private Texture type1;
private Texture type2;
private Text ability1;
private Text ability2;
private Text ability1shadow;
private Text ability2shadow;
[SerializeField]
private float moveSpeed = 0.16f;
// Ressource vars
public Texture[] types;
public AudioClip selectClip;
void Awake () {
//cursor = GameObject.Find ("Cursor").GetComponent<Texture>();
//preview = GameObject.Find ("SelectedSprite").GetComponent<Texture> ();
//name = GameObject.Find ("SelectedName").GetComponent<Text>();
//nameShadow = GameObject.Find ("SelectedNameShadow").GetComponent<Text>();
//id = GameObject.Find ("SelectedID").GetComponent<Text>();
//idShadow = GameObject.Find ("SelectedIDShadow").GetComponent<Text>();
//boxLabel = GameObject.Find ("BoxHeader").GetComponent<Text>();
//boxLabelShadow = GameObject.Find ("BoxHeaderShadow").GetComponent<Text>();
//pokeSprites = new Texture[45];
//for (int i = 0; i < 45; i++) {
// pokePreview[i] = GameObject.Find ("Pokemon" + i).GetComponent<Texture>();
//}
////background = GameObject.Find ("PokedexBackground").GetComponent<Texture> ();
//
//type1 = GameObject.Find ("SelectedType1").GetComponent<Texture>();
//type2 = GameObject.Find ("SelectedType2").GetComponent<Texture>();
//ability1 = GameObject.Find ("SelectedAbility1").GetComponent<Text> ();
//ability2 = GameObject.Find ("SelectedAbility2").GetComponent<Text> ();
//ability1shadow = GameObject.Find ("SelectedAbility1Shadow").GetComponent<Text> ();
//ability2shadow = GameObject.Find ("SelectedAbility2Shadow").GetComponent<Text> ();
}
public IEnumerator control(){
cursorPosition = Vector2.zero;
boxNum = 0;
updateBox ((int) boxNum);
StartCoroutine(ScreenFade.main.Fade(true, ScreenFade.defaultSpeed));
bool running = true;
while (running) {
// Input
if (cursorPosition.y == -1 && screen2 != true) {
if (Input.GetAxis ("Horizontal") > 0 && boxNum != 18) {
boxNum += 1;
updateBox ((int)boxNum);
SfxHandler.Play (selectClip);
yield return new WaitForSeconds (0.2f);
} else if (Input.GetAxis ("Horizontal") < 0 && boxNum != 0) {
boxNum -= 1;
updateBox ((int)boxNum);
SfxHandler.Play (selectClip);
yield return new WaitForSeconds (0.2f);
}
} else {
if (Input.GetAxis ("Horizontal") > 0 && cursorPosition.x != 8 && cursorPosition.y != -1 && cursorPosition.y != 6 && screen2 != true) {
cursorPosition += new Vector2 (1, 0);
SfxHandler.Play (selectClip);
yield return new WaitForSeconds (0.2f);
} else if (Input.GetAxis ("Horizontal") < 0 && cursorPosition.x != 0 && cursorPosition.y != -1 && cursorPosition.y != 6 && screen2 != true) {
cursorPosition -= new Vector2 (1, 0);
SfxHandler.Play (selectClip);
yield return new WaitForSeconds (0.2f);
}
if (Input.GetButton ("Select")) {
yield return StartCoroutine (informationScreen ());
}
}
if (Input.GetAxis ("Vertical") > 0 && cursorPosition.y != -1 && screen2 != true) {
cursorPosition -= new Vector2 (0, 1);
SfxHandler.Play (selectClip);
yield return new WaitForSeconds (0.2f);
} else if (Input.GetAxis ("Vertical") < 0 && cursorPosition.y != 5 && screen2 != true) {
cursorPosition += new Vector2 (0, 1);
SfxHandler.Play (selectClip);
yield return new WaitForSeconds (0.2f);
}
// Cursor Position
if (screen2 != true){
if (cursorPosition.y == -1) {
//cursor.transform.position = new Vector3(200, 307, 13);
} else if (cursorPosition.y == 5) {
} else {
float y = 5f - cursorPosition.y;
float x = cursorPosition.x;
//cursor.transform.position = new Vector3(64 + x * 42f, 128 - 38 + y * 38, 13);
yield return StartCoroutine(moveCursor(new Vector2(25 + x * 24, 25 + y * 24)));
y = cursorPosition.y;
pokemonNum = boxNum * 45f + y * 9f + x + 1;
updatePreview ((int) pokemonNum,(int)( y * 9 + x));
}
}
yield return null;
}
StopCoroutine("animateIcons");
//yield return new WaitForSeconds(sceneTransition.FadeOut());
yield return StartCoroutine(ScreenFade.main.Fade(false, ScreenFade.defaultSpeed));
GlobalVariables.global.resetFollower();
this.gameObject.SetActive(false);
}
public IEnumerator informationScreen(){
float increment = 0;
//float startX = background.pixelInset.x;
//float startY = background.pixelInset.y;
//float distanceX = -200;
while (increment < 1)
{
increment += (1 / moveSpeed) * Time.deltaTime;
if (increment > 1)
{
increment = 1;
}
GameObject[] pokedexUI = GameObject.FindGameObjectsWithTag ("Pokedex");
for (int x = 0; x < pokedexUI.Length; x++) {
//pokedexUI [x].GetComponent<Texture> ().pixelInset = new Rect (startX + (distanceX * increment), startY, pokedexUI [x].GetComponent<Texture> ().pixelInset.width, pokedexUI [x].GetComponent<Texture> ().pixelInset.height);
}
yield return null;
}
}
// Usability Functions
private void updatePreview(int id, int num){
//setTyping (id);
//preview.texture = pokeSprites[num];
setText (id);
setTyping (id);
updateAbilities (id);
}
private Texture getSprite(int id){
Texture[] animation;
animation = Resources.LoadAll<Texture>("PokemonSprites" + "/" + toNum(id) + "/");
if (animation.Length == 0){
Debug.LogWarning ("Attempt Loading Charizard");
animation = Resources.LoadAll<Texture>("PokemonSprites" + "/" + toNum(6).ToString() + "/");
}
return animation [0];
}
private string toNum(int n){
string result = n.ToString();
while (result.Length < 3)
{
result = "0" + result;
}
return result;
}
private void updateAbilities(int i){
/*PokemonDataOld pokemon = PokemonDatabaseOld.getPokemon (i);
if (pokemon == null) {
ability1.text = "Unknown";
ability2.text = "Unknown";
ability1shadow.text = "Unknown";
ability2shadow.text = "Unknown";
} else {
ability1.text = pokemon.getAbility (0);
ability2.text = pokemon.getAbility (1);
ability1shadow.text = pokemon.getAbility (0);
ability2shadow.text = pokemon.getAbility (1);
if (ability1.text == ability2.text) {
ability2.text = "";
ability2shadow.text = "";
}
}*/
}
private IEnumerator moveCursor(Vector2 destination)
{
float increment = 0;
//float startX = cursor.pixelInset.x;
//float startY = cursor.pixelInset.y;
//float distanceX = destination.x - startX;
//float distanceY = destination.y - startY;
while (increment < 1)
{
increment += (1 / moveSpeed) * Time.deltaTime;
if (increment > 1)
{
increment = 1;
}
//cursor.pixelInset = new Rect(startX + (distanceX * increment), startY + (distanceY * increment), cursor.pixelInset.width, cursor.pixelInset.height);
yield return null;
}
}
private void setText(int i){
id.text = "#" + toNum (i);
idShadow.text = "#" + toNum (i);
/*PokemonDataOld pokemon = PokemonDatabaseOld.getPokemon (i);
if (pokemon == null) {
name.text = "None";
nameShadow.text = "None";
} else {
name.text = pokemon.getName ();
nameShadow.text = pokemon.getName ();
}*/
}
private void setTyping(int id){
/*if (PokemonDatabaseOld.getPokemon (id) != null) {
type1.texture = typeToImage (PokemonDatabaseOld.getPokemon (id).getType1 ());
if (PokemonDatabaseOld.getPokemon (id).getType2 () == PokemonDataOld.Type.NONE) {
type2.gameObject.SetActive (false);
} else {
type2.gameObject.SetActive (true);
type2.texture = typeToImage (PokemonDatabaseOld.getPokemon (id).getType2 ());
}
} else {
type1.texture = typeToImage (PokemonDataOld.Type.NONE);
type2.texture = typeToImage (PokemonDataOld.Type.NONE);
}*/
}
private Texture getIcon(int id){
Texture[] icons = Resources.LoadAll<Texture>("PokemonIcons/icon" + toNum(id));
if (icons.Length == 0)
{
icons = Resources.LoadAll<Texture>("PokemonIcons/icon006");
}
return icons[0];
}
private void updateBox(int boxNum){
string label = "Pokedex " + toNum(boxNum * 45 + 1) + " - " + toNum(boxNum * 45 + 45);
boxLabel.text = label;
boxLabelShadow.text = label;
for (int i = 0; i < 45; i++) {
//pokePreview [i].texture = getIcon (boxNum * 45 + i + 1);
}
for (int i = 0; i < 45; i++) {
pokeSprites [i] = getSprite (boxNum * 45 + i + 1);
}
}
private Texture typeToImage(PokemonUnity.Types type){
if (type == PokemonUnity.Types.NORMAL) {
return types [0];
} else if (type == PokemonUnity.Types.FIGHTING) {
return types [1];
} else if (type == PokemonUnity.Types.FLYING) {
return types [2];
} else if (type == PokemonUnity.Types.POISON) {
return types [3];
} else if (type == PokemonUnity.Types.GROUND) {
return types [4];
} else if (type == PokemonUnity.Types.ROCK) {
return types [5];
} else if (type == PokemonUnity.Types.BUG) {
return types [6];
} else if (type == PokemonUnity.Types.GHOST) {
return types [7];
} else if (type == PokemonUnity.Types.STEEL) {
return types [8];
} else if (type == PokemonUnity.Types.NONE) {
return types [9];
} else if (type == PokemonUnity.Types.FIRE) {
return types [10];
} else if (type == PokemonUnity.Types.WATER) {
return types [11];
} else if (type == PokemonUnity.Types.GRASS) {
return types [12];
} else if (type == PokemonUnity.Types.ELECTRIC) {
return types [13];
} else if (type == PokemonUnity.Types.PSYCHIC) {
return types [14];
} else if (type == PokemonUnity.Types.ICE) {
return types [15];
} else if (type == PokemonUnity.Types.DRAGON) {
return types [16];
} else if (type == PokemonUnity.Types.DARK) {
return types [17];
} else if (type == PokemonUnity.Types.FAIRY) {
return types [18];
} else {
return types [9];
}
}
}
|
{
"pile_set_name": "Github"
}
|
using UnityEngine;
namespace RPGCoreUnity.Demo.BoardGame
{
public class SelectionRenderer : MonoBehaviour
{
[Header("Height Scaling")]
[SerializeField] private float maxScale = 1.0f;
[SerializeField] private float heightScaleDamped = 0.3f;
[Header("Positioning")]
[SerializeField] private float positionDamped = 0.3f;
private PlayerSelection playerSelection;
private Rect currentRect;
private float currentHeight;
public void Render(PlayerSelection playerSelection)
{
this.playerSelection = playerSelection;
}
private void Update()
{
if (playerSelection == null)
{
return;
}
var targetRect = playerSelection.AsRect;
float targetHeight = playerSelection.isSelected
? maxScale
: 0.0f;
if (playerSelection.isSelected)
{
currentRect = RectLerp(currentRect, targetRect, Time.deltaTime * positionDamped);
}
else
{
currentRect = targetRect;
}
currentHeight = Mathf.Lerp(currentHeight, targetHeight, Time.deltaTime * heightScaleDamped);
transform.position = new Vector3(currentRect.center.x, 0.0f, currentRect.center.y);
transform.localScale = new Vector3(currentRect.width, currentHeight, currentRect.height);
}
private static Rect RectLerp(Rect from, Rect to, float time)
{
return new Rect()
{
x = Mathf.Lerp(from.x, to.x, time),
y = Mathf.Lerp(from.y, to.y, time),
width = Mathf.Lerp(from.width, to.width, time),
height = Mathf.Lerp(from.height, to.height, time),
};
}
}
}
|
{
"pile_set_name": "Github"
}
|
<%@page import="com.qq.info.news.newsserver.Media" %>
<%@page import="com.qq.info.news.newsserver.client.NewsServiceClientFactory" %>
<%@ page contentType="text/html; charset=utf-8" language="java" %>
<%@ page import="com.qq.conf.ProfileManager" %>
<%@ page import="com.qq.oidb.OIDBService.KeyType" %>
<%@ page import="com.qq.portal.platform.tools.user.AvatarClient" %>
<%@ page import="com.qq.portal.platform.tools.user.GetUserDefineAvatarUrlRes" %>
<%@ page import="java.util.Arrays" %>
<%@ include file="include.jsp" %>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,user-scalable=no" />
<meta name="format-detection" content="telephone=no">
<meta name="author" content="Tencent..gavinning" />
<meta name="copyright" content="Copyright (c) 1998-2014 Tencent." />
<meta name="description" content="手机腾讯网" />
<title>mtwebapp</title>
<style type="text/css">
.virtualPage {
display: none
}
.virtualPage[selected='true'] {
display: block
}
</style>
<%if(testEnv) {%>
<link href="http://gavinning.kf0309.3g.qq.com/webapp_html/info/video/css/home.css" rel="stylesheet" type="text/css">
<%} else {%>
<link href="http://gavinning.kf0309.3g.qq.com/webapp_html/info/video/css/home.css" rel="stylesheet" type="text/css">
<%}%>
<link rel="stylesheet" type="text/css" href="http://3glogo.gtimg.com/wap30/info/info5/css/ptlogin_info.css" />
<script>
window.CONFIG = {};
window.CONFIG.USER = {};
window.CONFIG.USER.sid = "<%=sid%>";
window.CONFIG.USER.qq = <%= uinL %> ;
window.CONFIG.USER.isLogin = <%= isLogin %> ;
window.CONFIG.mqqlink = "<%=info_news_comment_mqqlink%>";
window.CONFIG.USER.userImg = "<%=userImg%>";
window.apiUrl = "<%=apiUrl%>";
window.isOs7 = (navigator.userAgent).indexOf('OS 7') !== -1;
if (window.screen.height == 568) {
document.querySelector('meta[name="viewport"]').content = "width=320,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no";
}
</script>
</head>
<body>
<div id="t_page">
<header class="header " id="t_header" style="position:fixed;width:100%;z-index:100;">
<h1 class="title mediatitle">mtwebapp</h1>
<nav>
<a class="left iback t_header_back" href="javascript:;" style="display:none"></a>
<a class="icenter right " href="javascript:;" id='t_login_btn'>
<img id='t_headimage' style="display:none" src="http://3gimg.qq.com/wap30/infoapp/touch/zhoukan/images/user-face-mark.png " alt="">
</a>
</nav>
</header>
<div id="scroll" style="padding-top:40px;z-index:1;overflow:hidden;">
<div id="wrapper"></div>
</div>
</div>
<%if(!testEnv) {%>
<script type="text/javascript" id="file_config">
var g_config = {
jsmap: {
"jqmobi": "/base.js",
"pm": "/base.js",
"basepage": "/base.js",
"iScroll": "/base.js",
"txTpl": "/base.js",
"msgMod": "/base.js",
"mock": "/base.js",
"loadIngModule": "/base.js",
"loginMod": "/base.js",
"tipsModule": "/base.js",
"loadUtil": "/base.js",
"mockUtil": "/base.js",
"mockRandom": "/base.js",
"channel": "/pages/channel.js",
"index": "/pages/index.js",
"init": "/base.js"
},
storeInc: {
"store": true,
"inc": true,
"debug": false
},
testEnv: false,
staticPath: '/infocdn/info_app/mtwebapp',
realPath: 'http://infocdn.3g.qq.com/g/storeinc',
ver: '2014061900015',
buildType: 'project'
}
</script>
<%} else {%>
<script type="text/javascript">
var g_config = {
jsmap: {
"jqmobi": "/common/jqmobi.js",
"pm": "/common/pm.js",
"basepage": "/common/basepage.js",
"iScroll": "/common/iScroll.js",
"txTpl": "/common/txTpl.js",
"msgMod": "/common/msgMod.js",
"mock": "/common/mock.js",
"loadIngModule": "/common/loadIngModule.js",
"loginMod": "/common/loginMod.js",
"tipsModule": "/common/tipsModule.js",
"loadUtil": "/common/loadUtil.js",
"mockUtil": "/common/mockUtil.js",
"mockRandom": "/common/mockRandom.js",
"channel": "/pages/channel.js",
"index": "/pages/index.js",
"init": "/init.js"
},
storeInc: {},
staticPath: 'js',
testEnv: true
};
</script>
<%}%>
<script type="text/javascript" src="http://3gimg.qq.com/wap30/info/storeIncLoad-core-cdnlog.js"></script>
<script type="text/javascript">
MT.config(g_config);
require('init');
</script>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Exceptionless.Core.Extensions;
using Microsoft.Extensions.Logging;
namespace Exceptionless.Core.Plugins.EventProcessor {
public abstract class EventProcessorPluginBase : PluginBase, IEventProcessorPlugin {
public EventProcessorPluginBase(AppOptions options, ILoggerFactory loggerFactory = null) : base(options, loggerFactory) { }
protected bool ContinueOnError { get; set; }
public virtual Task StartupAsync() {
return Task.CompletedTask;
}
public virtual async Task EventBatchProcessingAsync(ICollection<EventContext> contexts) {
foreach (var ctx in contexts) {
try {
await EventProcessingAsync(ctx).AnyContext();
} catch (Exception ex) {
bool cont = false;
try {
cont = HandleError(ex, ctx);
} catch { }
if (!cont)
ctx.SetError(ex.Message, ex);
}
}
}
public virtual Task EventProcessingAsync(EventContext context) {
return Task.CompletedTask;
}
public virtual async Task EventBatchProcessedAsync(ICollection<EventContext> contexts) {
foreach (var ctx in contexts) {
try {
await EventProcessedAsync(ctx).AnyContext();
} catch (Exception ex) {
bool cont = false;
try {
cont = HandleError(ex, ctx);
} catch { }
if (!cont)
ctx.SetError(ex.Message, ex);
}
}
}
public virtual Task EventProcessedAsync(EventContext context) {
return Task.CompletedTask;
}
public virtual bool HandleError(Exception exception, EventContext context) {
return ContinueOnError;
}
}
}
|
{
"pile_set_name": "Github"
}
|
# 常用 Git 命令清单
## [Git Commit message 和 Change log 编写指南](http://www.ruanyifeng.com/blog/2016/01/commit_message_change_log.html)
## [Commitizen 的安装和使用](https://www.jianshu.com/p/d264f88d13a4)
## 新建代码库
``` bash
# 在当前目录新建一个Git代码库
$ git init
# 新建一个目录,将其初始化为Git代码库
$ git init [project-name]
# 下载一个项目和它的整个代码历史
$ git clone [url]
```
## 配置
Git 的设置文件为`.gitconfig`,它可以在用户主目录下(全局配置),也可以在项目目录下(项目配置)。
``` bash
# 显示当前的Git配置
$ git config --list
# 编辑Git配置文件
$ git config -e [--global]
# 设置提交代码时的用户信息
$ git config [--global] user.name "[name]"
$ git config [--global] user.email "[email address]"
```
## 增加 / 删除文件
``` bash
# 添加指定文件到暂存区
$ git add [file1] [file2] ...
# 添加指定目录到暂存区,包括子目录
$ git add [dir]
# 添加当前目录的所有文件到暂存区
$ git add .
# 添加每个变化前,都会要求确认
# 对于同一个文件的多处变化,可以实现分次提交
$ git add -p
# 删除工作区文件,并且将这次删除放入暂存区
$ git rm [file1] [file2] ...
# 停止追踪指定文件,但该文件会保留在工作区
$ git rm --cached [file]
# 改名文件,并且将这个改名放入暂存区
$ git mv [file-original] [file-renamed]
```
## 代码提交
``` bash
# 提交暂存区到仓库区
$ git commit -m [message]
# 提交暂存区的指定文件到仓库区
$ git commit [file1] [file2] ... -m [message]
# 提交工作区自上次commit之后的变化,直接到仓库区
$ git commit -a
# 提交时显示所有diff信息
$ git commit -v
# 使用一次新的commit,替代上一次提交
# 如果代码没有任何新变化,则用来改写上一次commit的提交信息
$ git commit --amend -m [message]
# 重做上一次commit,并包括指定文件的新变化
$ git commit --amend [file1] [file2] ...
```
## 分支
``` bash
# 列出所有本地分支
$ git branch
# 列出所有远程分支
$ git branch -r
# 列出所有本地分支和远程分支
$ git branch -a
# 新建一个分支,但依然停留在当前分支
$ git branch [branch-name]
# 新建一个分支,并切换到该分支
$ git checkout -b [branch]
# 新建一个分支,指向指定commit
$ git branch [branch] [commit]
# 新建一个分支,与指定的远程分支建立追踪关系
$ git branch --track [branch] [remote-branch]
# 切换到指定分支,并更新工作区
$ git checkout [branch-name]
# 切换到上一个分支
$ git checkout -
# 建立追踪关系,在现有分支与指定的远程分支之间
$ git branch --set-upstream [branch] [remote-branch]
# 合并指定分支到当前分支
$ git merge [branch]
# 选择一个commit,合并进当前分支
$ git cherry-pick [commit]
# 删除分支
$ git branch -d [branch-name]
# 删除远程分支
$ git push origin --delete [branch-name]
$ git branch -dr [remote/branch]
```
## 标签
``` bash
# 列出所有tag
$ git tag
# 新建一个tag在当前commit
$ git tag [tag]
# 新建一个tag在指定commit
$ git tag [tag] [commit]
# 删除本地tag
$ git tag -d [tag]
# 删除远程tag
$ git push origin :refs/tags/[tagName]
# 查看tag信息
$ git show [tag]
# 提交指定tag
$ git push [remote] [tag]
# 提交所有tag
$ git push [remote] --tags
# 新建一个分支,指向某个tag
$ git checkout -b [branch] [tag]
```
## 查看信息
``` bash
# 显示有变更的文件
$ git status
# 显示当前分支的版本历史
$ git log
# 显示commit历史,以及每次commit发生变更的文件
$ git log --stat
# 搜索提交历史,根据关键词
$ git log -S [keyword]
# 显示某个commit之后的所有变动,每个commit占据一行
$ git log [tag] HEAD --pretty=format:%s
# 显示某个commit之后的所有变动,其"提交说明"必须符合搜索条件
$ git log [tag] HEAD --grep feature
# 显示某个文件的版本历史,包括文件改名
$ git log --follow [file]
$ git whatchanged [file]
# 显示指定文件相关的每一次diff
$ git log -p [file]
# 显示过去5次提交
$ git log -5 --pretty --oneline
# 显示所有提交过的用户,按提交次数排序
$ git shortlog -sn
# 显示指定文件是什么人在什么时间修改过
$ git blame [file]
# 显示暂存区和工作区的差异
$ git diff
# 显示暂存区和上一个commit的差异
$ git diff --cached [file]
# 显示工作区与当前分支最新commit之间的差异
$ git diff HEAD
# 显示两次提交之间的差异
$ git diff [first-branch]...[second-branch]
# 显示今天你写了多少行代码
$ git diff --shortstat "@{0 day ago}"
# 显示某次提交的元数据和内容变化
$ git show [commit]
# 显示某次提交发生变化的文件
$ git show --name-only [commit]
# 显示某次提交时,某个文件的内容
$ git show [commit]:[filename]
# 显示当前分支的最近几次提交
$ git reflog
```
## 远程同步
``` bash
# 下载远程仓库的所有变动
$ git fetch [remote]
# 显示所有远程仓库
$ git remote -v
# 显示某个远程仓库的信息
$ git remote show [remote]
# 增加一个新的远程仓库,并命名
$ git remote add [shortname] [url]
# 取回远程仓库的变化,并与本地分支合并
$ git pull [remote] [branch]
# 上传本地指定分支到远程仓库
$ git push [remote] [branch]
# 强行推送当前分支到远程仓库,即使有冲突
$ git push [remote] --force
# 推送所有分支到远程仓库
$ git push [remote] --all
```
## 撤销
``` bash
# 恢复暂存区的指定文件到工作区
$ git checkout [file]
# 恢复某个commit的指定文件到暂存区和工作区
$ git checkout [commit] [file]
# 恢复暂存区的所有文件到工作区
$ git checkout .
# 重置暂存区的指定文件,与上一次commit保持一致,但工作区不变
$ git reset [file]
# 重置暂存区与工作区,与上一次commit保持一致
$ git reset --hard
# 重置当前分支的指针为指定commit,同时重置暂存区,但工作区不变
$ git reset [commit]
# 重置当前分支的HEAD为指定commit,同时重置暂存区和工作区,与指定commit一致
$ git reset --hard [commit]
# 重置当前HEAD为指定commit,但保持暂存区和工作区不变
$ git reset --keep [commit]
# 新建一个commit,用来撤销指定commit
# 后者的所有变化都将被前者抵消,并且应用到当前分支
$ git revert [commit]
# 暂时将未提交的变化移除,稍后再移入
$ git stash
$ git stash pop
```
## 其他
``` bash
# 生成一个可供发布的压缩包
$ git archive
```
## 相关链接
* [http://www.ruanyifeng.com/blog/2015/12/git-cheat-sheet.html](http://www.ruanyifeng.com/blog/2015/12/git-cheat-sheet.html)
|
{
"pile_set_name": "Github"
}
|
@testset "Cookies" begin
c = HTTP.Cookies.Cookie()
@test c.name == ""
@test HTTP.Cookies.domainmatch(c, "")
c.path = "/any"
@test HTTP.Cookies.pathmatch(c, "/any/path")
@test !HTTP.Cookies.pathmatch(c, "/nottherightpath")
writesetcookietests = [
(HTTP.Cookie("cookie-1", "v\$1"), "cookie-1=v\$1"),
(HTTP.Cookie("cookie-2", "two", maxage=3600), "cookie-2=two; Max-Age=3600"),
(HTTP.Cookie("cookie-3", "three", domain=".example.com"), "cookie-3=three; Domain=example.com"),
(HTTP.Cookie("cookie-4", "four", path="/restricted/"), "cookie-4=four; Path=/restricted/"),
(HTTP.Cookie("cookie-5", "five", domain="wrong;bad.abc"), "cookie-5=five"),
(HTTP.Cookie("cookie-6", "six", domain="bad-.abc"), "cookie-6=six"),
(HTTP.Cookie("cookie-7", "seven", domain="127.0.0.1"), "cookie-7=seven; Domain=127.0.0.1"),
(HTTP.Cookie("cookie-8", "eight", domain="::1"), "cookie-8=eight"),
(HTTP.Cookie("cookie-9", "expiring", expires=HTTP.Dates.unix2datetime(1257894000)), "cookie-9=expiring; Expires=Tue, 10 Nov 2009 23:00:00 GMT"),
# According to IETF 6265 Section 5.1.1.5, the year cannot be less than 1601
(HTTP.Cookie("cookie-10", "expiring-1601", expires=HTTP.Dates.DateTime(1601, 1, 1, 1, 1, 1, 1)), "cookie-10=expiring-1601; Expires=Mon, 01 Jan 1601 01:01:01 GMT"),
(HTTP.Cookie("cookie-11", "invalid-expiry", expires=HTTP.Dates.DateTime(1600, 1, 1, 1, 1, 1, 1)), "cookie-11=invalid-expiry"),
# The "special" cookies have values containing commas or spaces which
# are disallowed by RFC 6265 but are common in the wild.
(HTTP.Cookie("special-1", "a z"), "special-1=a z"),
(HTTP.Cookie("special-2", " z"), "special-2=\" z\""),
(HTTP.Cookie("special-3", "a "), "special-3=\"a \""),
(HTTP.Cookie("special-4", " "), "special-4=\" \""),
(HTTP.Cookie("special-5", "a,z"), "special-5=a,z"),
(HTTP.Cookie("special-6", ",z"), "special-6=\",z\""),
(HTTP.Cookie("special-7", "a,"), "special-7=\"a,\""),
(HTTP.Cookie("special-8", ","), "special-8=\",\""),
(HTTP.Cookie("empty-value", ""), "empty-value="),
(HTTP.Cookie("", ""), ""),
(HTTP.Cookie("\t", ""), ""),
]
@testset "String(::Cookie)" begin
for (cookie, expected) in writesetcookietests
@test String(cookie, false) == expected
end
cookies = [HTTP.Cookie("cookie-1", "v\$1"),
HTTP.Cookie("cookie-2", "v\$2"),
HTTP.Cookie("cookie-3", "v\$3"),
]
@test HTTP.stringify("", cookies) == "cookie-1=v\$1; cookie-2=v\$2; cookie-3=v\$3"
end
@testset "readsetcookies" begin
cookietests = [
(Dict(["Set-Cookie"=> "Cookie-1=v\$1"]), [HTTP.Cookie("Cookie-1", "v\$1")]),
(Dict(["Set-Cookie"=> "NID=99=YsDT5i3E-CXax-; expires=Wed, 23-Nov-2011 01:05:03 GMT; path=/; domain=.google.ch; HttpOnly"]),
[HTTP.Cookie("NID", "99=YsDT5i3E-CXax-"; path="/", domain="google.ch", httponly=true, expires=HTTP.Dates.DateTime(2011, 11, 23, 1, 5, 3, 0))]),
(Dict(["Set-Cookie"=> ".ASPXAUTH=7E3AA; expires=Wed, 07-Mar-2012 14:25:06 GMT; path=/; HttpOnly"]),
[HTTP.Cookie(".ASPXAUTH", "7E3AA"; path="/", expires=HTTP.Dates.DateTime(2012, 3, 7, 14, 25, 6, 0), httponly=true)]),
(Dict(["Set-Cookie"=> "ASP.NET_SessionId=foo; path=/; HttpOnly"]),
[HTTP.Cookie("ASP.NET_SessionId", "foo"; path="/", httponly=true)]),
(Dict(["Set-Cookie"=> "special-1=a z"]), [HTTP.Cookie("special-1", "a z")]),
(Dict(["Set-Cookie"=> "special-2=\" z\""]), [HTTP.Cookie("special-2", " z")]),
(Dict(["Set-Cookie"=> "special-3=\"a \""]), [HTTP.Cookie("special-3", "a ")]),
(Dict(["Set-Cookie"=> "special-4=\" \""]), [HTTP.Cookie("special-4", " ")]),
(Dict(["Set-Cookie"=> "special-5=a,z"]), [HTTP.Cookie("special-5", "a,z")]),
(Dict(["Set-Cookie"=> "special-6=\",z\""]), [HTTP.Cookie("special-6", ",z")]),
(Dict(["Set-Cookie"=> "special-7=a,"]), [HTTP.Cookie("special-7", "a,")]),
(Dict(["Set-Cookie"=> "special-8=\",\""]), [HTTP.Cookie("special-8", ",")]),
]
for (h, c) in cookietests
@test HTTP.Cookies.readsetcookies("", [Dict(h)["Set-Cookie"]]) == c
end
end
@testset "SetCookieDoubleQuotes" begin
cookiestrings = [
"quoted0=none; max-age=30",
"quoted1=\"cookieValue\"; max-age=31",
"quoted2=cookieAV; max-age=\"32\"",
"quoted3=\"both\"; max-age=\"33\"",
]
want = [
HTTP.Cookie("quoted0", "none", maxage=30),
HTTP.Cookie("quoted1", "cookieValue", maxage=31),
HTTP.Cookie("quoted2", "cookieAV"),
HTTP.Cookie("quoted3", "both"),
]
@test all(HTTP.Cookies.readsetcookies("", cookiestrings) .== want)
end
@testset "Cookie sanitize value" begin
values = Dict(
"foo" => "foo",
"foo;bar" => "foobar",
"foo\\bar" => "foobar",
"foo\"bar" => "foobar",
String(UInt8[0x00, 0x7e, 0x7f, 0x80]) => String(UInt8[0x7e]),
"\"withquotes\"" => "withquotes",
"a z" => "a z",
" z" => "\" z\"",
"a " => "\"a \"",
)
for (k, v) in values
@test HTTP.Cookies.sanitizeCookieValue(k) == v
end
end
@testset "Cookie sanitize path" begin
paths = Dict(
"/path" => "/path",
"/path with space/" => "/path with space/",
"/just;no;semicolon\0orstuff/" => "/justnosemicolonorstuff/",
)
for (k, v) in paths
@test HTTP.Cookies.sanitizeCookiePath(k) == v
end
end
@testset "HTTP.readcookies" begin
testcookies = [
(Dict("Cookie" => "Cookie-1=v\$1; c2=v2"), "", [HTTP.Cookie("Cookie-1", "v\$1"), HTTP.Cookie("c2", "v2")]),
(Dict("Cookie" => "Cookie-1=v\$1; c2=v2"), "c2", [HTTP.Cookie("c2", "v2")]),
(Dict("Cookie" => "Cookie-1=v\$1; c2=v2"), "", [HTTP.Cookie("Cookie-1", "v\$1"), HTTP.Cookie("c2", "v2")]),
(Dict("Cookie" => "Cookie-1=v\$1; c2=v2"), "c2", [HTTP.Cookie("c2", "v2")]),
(Dict("Cookie" => "Cookie-1=\"v\$1\"; c2=\"v2\""), "", [HTTP.Cookie("Cookie-1", "v\$1"), HTTP.Cookie("c2", "v2")]),
]
for (h, filter, cookies) in testcookies
@test HTTP.Cookies.readcookies(h, filter) == cookies
end
end
end
|
{
"pile_set_name": "Github"
}
|
$91-60-10-02-1-0
[soundStopAll]
[bgm BGM_EVENT_2 0.1]
[scene 10202]
[charaSet A 8001001 1 マシュ]
[charaSet B 98003000 2 Dr.ロマン]
[charaSet C 98002000 2 フォウ]
[charaSet D 6010001 1 ステンノ]
[charaSet E 98006100 1 ???]
[charaSet F 4001001 0 メドゥーサ]
[charaTalk A]
[charaFace D 0]
[charaFadein D 0 0]
[charaFace A 12]
[charaFadein A 0 2]
[fadein black 1]
[wait fade]
@マシュ
不埒者退治?[r]……あの。流石に、二度目は。わたしたちでも、その。
[k]
@ステンノ
もう、勘違いなさらないで。前回とは違うのです。[r]今回のお願いは以前のそれとは趣旨を変えてみたの。
[k]
@ステンノ
具体的にはね[line 2]
[k]
[charaFace A 8]
@マシュ
……趣旨を変えてみた。[r]前回、その言葉の意味をきちんと理解すべきでした。
[k]
[charaFace A 7]
@マシュ
つまり、あなたは再び、[r]思い付いた遊びにわたしたちを巻き込みたいと?
[k]
[charaFace D 1]
@ステンノ
あら、素敵。[r]アナタは頭の回転が良いのね、マシュ。
[k]
[charaFace A 12]
@マシュ
いえ、その……。[r]魅了スキルが効いていませんから……。
[k]
[charaFace A 7]
@マシュ
本当にわたしを言いくるめるつもりなら、[r]前回と同じロジックではなくて、もう少し手を[line 2]
[k]
[charaFadeout D 0.1]
[charaFace B 1]
[charaFadein B 0.1 0]
@Dr.ロマン
承知しました女神ステンノ![r]このロマニ・アーキマン、一命を賭して勤め上げます!
[k]
[charaFace A 6]
@マシュ
あっ。
[k]
[charaFadeout B 0.1]
[charaFace C 0]
[charaFadein C 0.1 0]
@フォウ
フォウ、フォーウフォウ!!
[k]
[charaFace A 4]
@マシュ
フォウさんまで……。
[k]
?1:女神さまー!!
[charaFace A 14]
@マシュ
……また、先輩まで……。
[k]
?2:やれやれ
[charaFace A 1]
@マシュ
……あ、今回は大丈夫なんですね!?
[k]
?!
[charaFace A 0]
@マシュ
……それで、ステンノさん。[r]今回もまた「カタチのある島」で不埒者退治ですか?
[k]
[charaFadeout C 0.1]
[charaFace D 1]
[charaFadein D 0.1 0]
@ステンノ
ええ、そうよ。[r]でも今度は本当に趣向を凝らしているの、楽しんでね♪
[k]
[charaFadeout D 0.1]
[charaFace B 1]
[charaFadein B 0.1 0]
@Dr.ロマン
楽しい! 既にボクは楽しいですとも女神サマ![r]さーやるぞマシュ、[%1][&君:ちゃん]! いざ!
[k]
[charaFace A 14]
@マシュ
(ええー)
[k]
@Dr.ロマン
レイシフト開始!![r]行ってらっしゃい一世紀!!
[k]
[charaFadeout A 0.1]
[charaFadeout B 0.1]
[charaFace D 1]
[charaFadein D 0.1 1]
@ステンノ
気を付けてね、ふたりとも。[r]今度は、すこうし、大変なクエストかもしれなくてよ?
[k]
[messageOff]
[effect bit_talk_07]
[se ad12]
[charaFadeout B 0.1]
[charaFadeout D 0.1]
[wt 4]
[fadeout white 1]
[effectStop]
[wait effect]
[wait fade]
[scene 21100]
[charaFace A 4]
[charaFadein A 0 1]
[fadein white 1]
[wait fade]
[se ad37]
[wt 2]
[seStop ad37 3]
@マシュ
……また、来てしまいました。[r]これまでに何度も訪れた、地中海の島……。
[k]
[charaFace A 7]
@マシュ
周囲にサーヴァント反応は……。[r]感じられませんね。ですが、油断できません。
[k]
@マシュ
前回の例もありますから、[r]ステンノさんがいる可能性も考慮しないと。
[k]
?1:さくさく済ませよう
?2:洞窟だよね。早く行こう
?!
[charaFace A 0]
@マシュ
はい、先輩。
[k]
[charaFadeout A 0.1]
[charaFadein A 0.1 2]
[communicationChara 98003003 0 5 0 1]
[wt 0.3]
@Dr.ロマン
さあ、キミたち。出発だ![r]ステンノさまのお言葉によれば宝物を隠したのは洞窟!
[k]
@Dr.ロマン
以前にも入ったあの洞窟だね、[r]場所はわかるよね。じゃあ行ってらっしゃい!
[k]
[communicationCharaClear]
[wait communicationChara]
[charaFace A 12]
@マシュ
一語一句同じ言葉を……。[r]ドクター、すっかり魅了スキルに……。
[k]
[charaFace C 0]
[charaFadein C 0.1 0]
@フォウ
フォウ……。
[k]
[messageOff]
[charaFadeout A 0.5]
[charaFadeout C 0.5]
[fadeout black 0.5]
[wait fade]
[bgmStop BGM_EVENT_2 0.4]
[bgm BGM_EVENT_3 0.1]
[wt 0.5]
[scene 20110]
[charaFace E 0]
[charaFadein E 0 1]
[fadein black 0.5]
[wait fade]
@???
ゲッゲッゲ……。[r]ここから先を通すわけにはいかん……。
[k]
@???
すべては美しき女神ステンノさまのため……。[r]ステンノさまのお言葉通り、宝物は必ず守ろうぞ!
[k]
[charaFadeout E 0.1]
[charaTalk A]
[charaFadein E 0.1 0]
[charaFace A 4]
[charaFadein A 0.1 2]
@マシュ
…………。
[k]
[charaFadeout A 0.1]
[charaFace C 0]
[charaFadein C 0.1 2]
@フォウ
…………。
[k]
@???
我らの気迫を前にして言葉もないと見える![r]ゲッゲッゲ、ならば帰れ! 帰ってしまうがいい!
[k]
@???
かえれー、かえれー。[r]宝物はくれてやらんぞ、かえれー!
[k]
@???
うおー! ステンノさま、うおおーーーー![r]不埒者は許さんぞー!!
[k]
[charaFadeout C 0.1]
[charaFace A 4]
[charaFadein A 0.1]
@マシュ
……また、同じ……。
[k]
?1:やろう、マシュ!
?2:彼らの頑張りを無駄にはできない!
?!
[charaFace A 7]
@マシュ
そ、そうですね。[r]了解です、マスター。戦闘指示をお願いします!
[k]
[messageOff]
[fadeout black 0.5]
[bgmStop BGM_EVENT_3 0.4]
[wait fade]
[soundStopAll]
[end]
|
{
"pile_set_name": "Github"
}
|
"""External interface to the BeautifulSoup HTML parser.
"""
__all__ = ["fromstring", "parse", "convert_tree"]
import re
from lxml import etree, html
try:
from bs4 import (
BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString,
Declaration, Doctype)
_DECLARATION_OR_DOCTYPE = (Declaration, Doctype)
except ImportError:
from BeautifulSoup import (
BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString,
Declaration)
_DECLARATION_OR_DOCTYPE = Declaration
def fromstring(data, beautifulsoup=None, makeelement=None, **bsargs):
"""Parse a string of HTML data into an Element tree using the
BeautifulSoup parser.
Returns the root ``<html>`` Element of the tree.
You can pass a different BeautifulSoup parser through the
`beautifulsoup` keyword, and a diffent Element factory function
through the `makeelement` keyword. By default, the standard
``BeautifulSoup`` class and the default factory of `lxml.html` are
used.
"""
return _parse(data, beautifulsoup, makeelement, **bsargs)
def parse(file, beautifulsoup=None, makeelement=None, **bsargs):
"""Parse a file into an ElemenTree using the BeautifulSoup parser.
You can pass a different BeautifulSoup parser through the
`beautifulsoup` keyword, and a diffent Element factory function
through the `makeelement` keyword. By default, the standard
``BeautifulSoup`` class and the default factory of `lxml.html` are
used.
"""
if not hasattr(file, 'read'):
file = open(file)
root = _parse(file, beautifulsoup, makeelement, **bsargs)
return etree.ElementTree(root)
def convert_tree(beautiful_soup_tree, makeelement=None):
"""Convert a BeautifulSoup tree to a list of Element trees.
Returns a list instead of a single root Element to support
HTML-like soup with more than one root element.
You can pass a different Element factory through the `makeelement`
keyword.
"""
root = _convert_tree(beautiful_soup_tree, makeelement)
children = root.getchildren()
for child in children:
root.remove(child)
return children
# helpers
def _parse(source, beautifulsoup, makeelement, **bsargs):
if beautifulsoup is None:
beautifulsoup = BeautifulSoup
if hasattr(beautifulsoup, "HTML_ENTITIES"): # bs3
if 'convertEntities' not in bsargs:
bsargs['convertEntities'] = 'html'
if hasattr(beautifulsoup, "DEFAULT_BUILDER_FEATURES"): # bs4
if 'features' not in bsargs:
bsargs['features'] = 'html.parser' # use Python html parser
tree = beautifulsoup(source, **bsargs)
root = _convert_tree(tree, makeelement)
# from ET: wrap the document in a html root element, if necessary
if len(root) == 1 and root[0].tag == "html":
return root[0]
root.tag = "html"
return root
_parse_doctype_declaration = re.compile(
r'(?:\s|[<!])*DOCTYPE\s*HTML'
r'(?:\s+PUBLIC)?(?:\s+(\'[^\']*\'|"[^"]*"))?'
r'(?:\s+(\'[^\']*\'|"[^"]*"))?',
re.IGNORECASE).match
class _PseudoTag:
# Minimal imitation of BeautifulSoup.Tag
def __init__(self, contents):
self.name = 'html'
self.attrs = []
self.contents = contents
def __iter__(self):
return self.contents.__iter__()
def _convert_tree(beautiful_soup_tree, makeelement):
if makeelement is None:
makeelement = html.html_parser.makeelement
# Split the tree into three parts:
# i) everything before the root element: document type
# declaration, comments, processing instructions, whitespace
# ii) the root(s),
# iii) everything after the root: comments, processing
# instructions, whitespace
first_element_idx = last_element_idx = None
html_root = declaration = None
for i, e in enumerate(beautiful_soup_tree):
if isinstance(e, Tag):
if first_element_idx is None:
first_element_idx = i
last_element_idx = i
if html_root is None and e.name and e.name.lower() == 'html':
html_root = e
elif declaration is None and isinstance(e, _DECLARATION_OR_DOCTYPE):
declaration = e
# For a nice, well-formatted document, the variable roots below is
# a list consisting of a single <html> element. However, the document
# may be a soup like '<meta><head><title>Hello</head><body>Hi
# all<\p>'. In this example roots is a list containing meta, head
# and body elements.
if first_element_idx is None:
pre_root = post_root = []
roots = beautiful_soup_tree.contents
else:
pre_root = beautiful_soup_tree.contents[:first_element_idx]
roots = beautiful_soup_tree.contents[first_element_idx:last_element_idx+1]
post_root = beautiful_soup_tree.contents[last_element_idx+1:]
# Reorganize so that there is one <html> root...
if html_root is not None:
# ... use existing one if possible, ...
i = roots.index(html_root)
html_root.contents = roots[:i] + html_root.contents + roots[i+1:]
else:
# ... otherwise create a new one.
html_root = _PseudoTag(roots)
convert_node = _init_node_converters(makeelement)
# Process pre_root
res_root = convert_node(html_root)
prev = res_root
for e in reversed(pre_root):
converted = convert_node(e)
if converted is not None:
prev.addprevious(converted)
prev = converted
# ditto for post_root
prev = res_root
for e in post_root:
converted = convert_node(e)
if converted is not None:
prev.addnext(converted)
prev = converted
if declaration is not None:
try:
# bs4 provides full Doctype string
doctype_string = declaration.output_ready()
except AttributeError:
doctype_string = declaration.string
match = _parse_doctype_declaration(doctype_string)
if not match:
# Something is wrong if we end up in here. Since soupparser should
# tolerate errors, do not raise Exception, just let it pass.
pass
else:
external_id, sys_uri = match.groups()
docinfo = res_root.getroottree().docinfo
# strip quotes and update DOCTYPE values (any of None, '', '...')
docinfo.public_id = external_id and external_id[1:-1]
docinfo.system_url = sys_uri and sys_uri[1:-1]
return res_root
def _init_node_converters(makeelement):
converters = {}
ordered_node_types = []
def converter(*types):
def add(handler):
for t in types:
converters[t] = handler
ordered_node_types.append(t)
return handler
return add
def find_best_converter(node):
for t in ordered_node_types:
if isinstance(node, t):
return converters[t]
return None
def convert_node(bs_node, parent=None):
# duplicated in convert_tag() below
try:
handler = converters[type(bs_node)]
except KeyError:
handler = converters[type(bs_node)] = find_best_converter(bs_node)
if handler is None:
return None
return handler(bs_node, parent)
def map_attrs(bs_attrs):
if isinstance(bs_attrs, dict): # bs4
attribs = {}
for k, v in bs_attrs.items():
if isinstance(v, list):
v = " ".join(v)
attribs[k] = unescape(v)
else:
attribs = dict((k, unescape(v)) for k, v in bs_attrs)
return attribs
def append_text(parent, text):
if len(parent) == 0:
parent.text = (parent.text or '') + text
else:
parent[-1].tail = (parent[-1].tail or '') + text
# converters are tried in order of their definition
@converter(Tag, _PseudoTag)
def convert_tag(bs_node, parent):
attrs = bs_node.attrs
if parent is not None:
attribs = map_attrs(attrs) if attrs else None
res = etree.SubElement(parent, bs_node.name, attrib=attribs)
else:
attribs = map_attrs(attrs) if attrs else {}
res = makeelement(bs_node.name, attrib=attribs)
for child in bs_node:
# avoid double recursion by inlining convert_node(), see above
try:
handler = converters[type(child)]
except KeyError:
pass
else:
if handler is not None:
handler(child, res)
continue
convert_node(child, res)
return res
@converter(Comment)
def convert_comment(bs_node, parent):
res = html.HtmlComment(bs_node)
if parent is not None:
parent.append(res)
return res
@converter(ProcessingInstruction)
def convert_pi(bs_node, parent):
if bs_node.endswith('?'):
# The PI is of XML style (<?as df?>) but BeautifulSoup
# interpreted it as being SGML style (<?as df>). Fix.
bs_node = bs_node[:-1]
res = etree.ProcessingInstruction(*bs_node.split(' ', 1))
if parent is not None:
parent.append(res)
return res
@converter(NavigableString)
def convert_text(bs_node, parent):
if parent is not None:
append_text(parent, unescape(bs_node))
return None
return convert_node
# copied from ET's ElementSoup
try:
from html.entities import name2codepoint # Python 3
except ImportError:
from htmlentitydefs import name2codepoint
handle_entities = re.compile(r"&(\w+);").sub
try:
unichr
except NameError:
# Python 3
unichr = chr
def unescape(string):
if not string:
return ''
# work around oddities in BeautifulSoup's entity handling
def unescape_entity(m):
try:
return unichr(name2codepoint[m.group(1)])
except KeyError:
return m.group(0) # use as is
return handle_entities(unescape_entity, string)
|
{
"pile_set_name": "Github"
}
|
# Time Zone Administration

> *Landscape with the Arrival of Aeneas before the City of Pallanteum* by Claude Lorrain (c. 1625)
## Contents
> This workshop enumerates and explains organizations and agencies which maintain and organize international time zones as well as the methodology implemented for reasons of precision.<br>For information relating to improvements in local time-keeping accuracy, refer to [Historical Time Keeping](./time-keeping.md)
<!-- markdownlint-disable MD101 -->
* [Overview](#overview)
* [Methodology](#methodology)
* [Apparent Solar Time](#apparent-solar-time)
* [Mean Solar Time](#mean-solar-time)
* [Problem Solving](#problem-solving)
* [Applications](#applications)
* [Officiating Bodies](#officiating-bodies)
* [True Solar Time](#true-solar-time)
* [True Zenith Time](#true-zenith-time)
* [Martian Time Zones](#martian-time-zones)
* [Comparative Statistics](#comparative-statistics)
* [The Martian Day](#the-martian-day)
* [Mars Retrograde](#mars-retrograde)
<!-- markdownlint-enable MD101 -->
---
## Overview
Time zones were conceived to standardize the differences in time between geographical locations by reliable method. The idea of relative time began as a tool of *navigation*, but grew into a tool of *administration*, as technology allowed and globalization necessitated.
<!-- markdownlint-disable MD105 -->
Modern time zones are standardized to Greenwich Mean Time (GMT) also called Coordinated Universal Time (UTC). Modern time keeping is so precise the Earth's slowing rotation is considered during calculation.<sup>[1](https://www.ietf.org/timezones/data/leap-seconds.list)</sup>
<!-- markdownlint-enable MD105 -->
---
## Methodology
### Apparent Solar Time
* Solar day (24 hours) is derived via measurement of one complete solar cycle.
* Used in conjunction with the sidereal day (23 hours 56 minutes), calculated from the location of the stars.
* Problems:
* Elliptical orbit of Earth around the sun.
* Imperfect rotational axis; effects of latitude.
* Difference in solar and sidereal day lengths.

### Mean Solar Time
* Day begins at 00:00 which corresponds to midnight, 12:00 is set at the zenith of the sun.
* Mean solar day is calculated based on a one year solar cycle.
* The length of the mean solar day is gradually increasing each year.

### Problem Solving
Find apparent solar time (AST) at 8:00 a.m. MST on 21 July in Phoenix, AZ, which is located at 112° W longitude and 33.43° N latitude.
**Parameters**:
* Phoenix does not observe DST.
* 21 July is day 202.
* [Local Standard Time Meridian](https://web.archive.org/web/20140201055941/http://pvcdrom.pveducation.org/SUNLIGHT/SOLART.HTM): <b>*LSTM* = 15° * ΔT<sub>GMT</sub></b>
* The [equation of time](http://info.ifpan.edu.pl/firststep/aw-works/fsII/mul/mueller.pdf): <b>*EoT =* 9.87<small>sin</small>(2*B*) - 7.53<small>cos</small>(*B*) - 1.5<small>sin</small>(*B*)</b> where, <b>*B* = 360°/365 * (*d* - 81)</b> and *d* is the number of days since the start of the year.
* For these purposes, *B* = 119.342
* The [time correction factor](https://sailtraininginternational.org/sailtraining/the-rule-of-rating-and-time-correction-factor-explained/): <b>*TC* = 4(*LSTM* - *Longitude*) + *EoT*</b>
**Solution**:
*EoT* = 9.87<small>sin</small>(288.384°) - 7.53<small>cos</small>(119.342°) - 1.5<small>sin</small>(119.342°)<br>
= -6.05 minutes
*LSTM* = 15° * (112°/15°)<br>
= 105°
TC = 4 <small>minutes</small> * (105° - 112°) - 6.05<small>minutes</small><br>
= -34.05 <small>minutes</small>
At 8:00 a.m. on 21 July, apparent solar time is 7:26 a.m.
> Refer to [Applications](#applications) for additional calculations which relate to apparent solar time and local time.
---
## Applications
### Officiating Bodies
Despite international cooperation in a number of practices, different components of international time are still organized by different agencies.

* The [Internet Assigned Numbers Authority](https://www.iana.org/) maintains the `tz` or `zoneinfo` database, which contains code and data for many representative locations around the globe. It is updated periodically to reflect changes made by political bodies to time zone boundaries, UTC offsets, and daylight-saving rules.<sup>[33](https://tools.ietf.org/html/rfc6557)</sup>
* Historical time zones are recorded from 1 June, 1970 (Unix epoch) for the entire planet, as well as other celestial bodies.
* Pre-1970 time zones are recorded on a best-effort basis.

* The [International Telecommunications Union](https://www.itu.int/en/Pages/default.aspx) regulates the precise definition of UTC according to guideline [*Rec. ITU-R TF.460-6*](http://www.itu.int/dms_pubrec/itu-r/rec/tf/R-REC-TF.460-6-200202-I!!PDF-E.pdf).
* Current regulatory issues revolve around correcting discrepancies between International Atomic Time and Universal Coordinated Time.<sup>[32](https://hpiers.obspm.fr/iers/bul/bulc/bulletinc.dat)</sup>

* The [Bureau International des Poids et Mesures](https://www.bipm.org/en/about-us/) coordinates time among roughly 400 atomic clocks throughout its 60 member countries to definitively establish a scientific standard time.
* Established 20 May, 1875 to standardize units of measurement among disparate nations.
<!-- markdownlint-disable MD101 -->
### True Solar Time
As an observer travels longitudinally, that is, east to west or vice versa, true solar time is constantly changing. Because of the complications this introduces to calculation, large tracts of land are often given a derived mean time zone, as seen on the map below.

<a name="table"></a>
Listed below are various large cities, their central latitude and longitude, the UTC offset applied to calculate local time, and their populations.
City | Latitude | Longitude | UTC Offset (hours) | Population (million)
--|:--:|:--:|:--:|:--:
Berlin | 51°30'35'' N | 13°23'20'' E | +1 | 3.58
Chicago |41°52'55'' N | 87°41'05'' W | -6 | 2.72
Kamchatka Peninsula | 56°20' N | 160° E | +12 | 0.32
London | 51°30'35'' N | 0°7'39'' W | 0 | 8.14
Los Angeles | 34°3' N | 118°15' W | -8 | 4.0
Moscow | 55°45'7'' N | 37°37' E | +3 | 11.9
New York | 40°43'50'' N | 70°0'21'' W | -5 | 8.6
Omsk | 54°59'32'' N | 73°22' E | +6 | 1.2
Rio de Janeiro | 22°54'39'' S | 43°11'47'' W | -3 | 6.3
Saint Petersburg | 59°57' N | 30°18'31'' E | +3 | 5.0
Tokyo | 36°39'10'' N | 139°41' E | +9 | 9.3
Warsaw | 52°14'13'' N | 21°1' E | +1 | 1.8
> Source: Google Maps, 2018<sup>[33](https://www.google.com/maps)</sup>
**Assumptions**:
* The Earth is a sphere.
* The sun traverses this sphere in 23 hours 56 minutes and 4.1 seconds (23.933 hours for calculation).<sup>[34](https://plus.maths.org/content/how-long-day)</sup>
* Each longitudinal degree represents ±4 minutes from the origin.
**Procedure**:
* Calculate true solar time using SQL.
* Derive margin of error of UTC offset.
> Download the [`true-solar-time` CSV](./resources/true-solar-time.csv) file and [parser configuration](./resources/time-zone-parser.xml) used to insert data into ATSD.
**Calculation**:
```sql
SELECT longitude.tags.city AS "City", longitude.value AS "Longitude", "offset".value AS "Offset (Hours)", abs(longitude.value*4) AS "True Offset (Minutes)", abs("offset".value*60) AS "UTC Offset (Minutes)", abs((longitude.value*4) - abs("offset".value*60)) AS "Margin of Error (Minutes)"
FROM "longitude"
JOIN "offset"
WHERE longitude.tags.city != 'null'
ORDER BY "Margin of Error (Minutes)" ASC
```
| City| Longitude | Offset (Hours) | True Offset (Minutes) | UTC Offset (Minutes) | Margin of Error (Minutes) |
|---|:---:|:---:|:---:|:---:|:---:|
| London | 0.0| 0.0| 0.0| 0.0| 0.0
| Berlin | 13.3 | 1.0| 53.2| 60.0 | 6.8
| Los Angeles | 118.3| 8.0| 473.2 | 480.0| 6.8
| Rio de Janeiro | 43.2 | 3.0| 172.8 | 180.0| 7.2
| Chicago | 87.6 | 6.0| 350.4 | 360.0| 9.6
| New York | 70.0 | 5.0| 280.0 | 300.0| 20.0
| Warsaw | 21.0 | 1.0| 84.0| 60.0 | 24.0
| Moscow | 37.6 | 3.0| 150.4 | 180.0| 29.6
| Tokyo | 149.6| 9.0| 598.4 | 540.0| 58.4
| Saint Petersburg | 30.3 | 3.0| 121.2 | 180.0| 58.8
| Omsk| 73.3 | 6.0| 293.2 | 360.0| 66.8
| Kamchatka Peninsula | 160.0| 12.0 | 640.0 | 720.0| 80.0
### True Zenith Time
According to the principles of mean solar time, 12:00 corresponds to the sun's highest point in the sky during the day. Because time zones are regulated by a longitudinally oriented system, significant latitudinal distance is encapsulated within one time zone.

Because Earth orbits the sun on an elliptical path and rotates about an axis whose absolute angle is not 0°, the length of days differs throughout the year naturally.

**Assumptions**:
* [Local Standard Time Meridian](https://web.archive.org/web/20140201055941/http://pvcdrom.pveducation.org/SUNLIGHT/SOLART.HTM): <b>*LSTM* = 15° * ΔT<sub>GMT</sub></b>
* The [equation of time](http://info.ifpan.edu.pl/firststep/aw-works/fsII/mul/mueller.pdf): <b>*EoT =* 9.87<small>sin</small>(2*B*) - 7.53<small>cos</small>(*B*) - 1.5<small>sin</small>(*B*)</b> where, <b>*B* = 360°/365 * (*d* - 81)</b> and *d* is the number of days since the start of the year.
* The [time correction factor](https://sailtraininginternational.org/sailtraining/the-rule-of-rating-and-time-correction-factor-explained/): <b>*TC* = 4(*Longitude* - *LSTM*) + *EoT*</b>
* The Earth rotates about an axis at an angle of 23.45°.
**Procedure**:
* Calculate LSTM and EoT values to derive time correction factor.
* Check answers using the formula for local solar time: <b>*LST* = *LT* + *TC*/60</b>
**Calculation**:
```sql
SELECT city AS "City", RADIANS(lat) AS "Latitude (rad)", RADIANS("long") AS "Longitude (rad)", lstm AS "LSTM", (4 * RADIANS("long") - lstm) + ((9.87 * sin(2 * DEGREES(360/365 * jan1))) - (7.53 * cos(DEGREES(360/365 * jan1))) - (1.5 * sin(DEGREES(360/365 * jan1)))) AS "1 Jan", (4 * RADIANS("long") - lstm) + ((9.87 * sin(2 * DEGREES(360/365 * may1))) - (7.53 * cos(DEGREES(360/365 * may1))) - (1.5 * sin(DEGREES(360/365 * may1)))) AS "1 May", (4 * RADIANS("long") - lstm) + ((9.87 * sin(2 * DEGREES(360/365 * sep1))) - (7.53 * cos(DEGREES(360/365 * sep1))) - (1.5 * sin(DEGREES(360/365 * sep1)))) AS "1 Sep"
FROM
(
SELECT latitude.tags.city AS "city", latitude.value AS "lat", longitude.value AS "long", -80 AS "jan1", 40 AS "may1", 161 AS "sep1", RADIANS(15) * "offset".value AS "lstm"
FROM "latitude"
JOIN "longitude"
JOIN "offset"
WHERE longitude.tags.city != 'null'
)
ORDER BY city ASC
```
| City | Latitude (rad) | Longitude (rad) | LSTM | 1 Jan | 1 May | 1 Sep |
|---------------------|-----------------|-----------------|------|-------|-------|-------|
| Berlin | 0.899 | 0.232 | 0.262 | 5.6 | 0.5 | 3.1 |
| Chicago | 0.731 | 1.529 | -1.571 | 12.6 | -7.5 | -3.9 |
| Kamchatka Peninsula | 0.983 | 2.793 | 3.1 | 13.0 | 7.9 | 4.3 |
| London | 0.899 | 0.000 | 0.000 | 4.9 | -0.1 | 23.8 |
| Los Angeles | 0.595 | 2.065 | -2.065 | -15.3 | -10.2 | 6.6 |
| Moscow | 0.970 | 0.656 | 0.785 | 6.8 | 10.7 | 21.9 |
| New York | 0.709 | 1.279 | -1.222 | 1.1 | -6.1 | -2.4 |
| Omsk | 0.958 | 1.371 | 1.571 | 8.5 | 3.4 | 2.0 |
| Rio de Janeiro | -0.398 | 0.754 | -0.785 | 8.7 | -3.7 | 0.0 |
| Saint Petersburg | 1.045 | 0.529 | 0.785 | 6.3 | 1.2 | -2.4 |
| Tokyo | 0.639 | 2.611 | 2.356 | -13.0 | -17.9 | -14.3 |
| Warsaw | 0.913 | 0.367 | 0.262 | -6.1 | 15.1 | 32.6 |
**Margin of Error**:
City | 1 Jan Derived | 1 Jan Recorded | 1 Jan Error | 1 May Derived | 1 May Recorded | 1 May Error | 1 Sep Derived | 1 Sep Recorded | 1 Sep Error | | Overall Error|
--|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|--
Berlin | 12:07 | 12:09 | 0.27% | 12:01 | 12:03 | 0.27% | 12:03 | 12:06 | 0.43% | | 0.32%
Chicago | 11:47 | 11:54 | 0.98% | 11:52 | 11:47 | 0.70% | 11:56 | 11:50 | 0.82% | | 0.83%
Kamchatka Peninsula | 12:13 | 12:28 | 2.05% | 12:08 | 12:17 | 1.24% | 12:04 | 12:20 | 2.16% | | 1.82%
London | 12:05 | 12:04 | 0.14% | 12:00 | 11:57 | 0.42% | 12:24 | 12:24 | 0.00% | | 0.19%
Los Angeles | 11:55 | 11:56 | 0.14% | 11:45 | 11:50 | 0.70% | 11:50 | 11:52 | 0.27% | | 0.37%
Moscow | 12:07 | 12:13 | 0.82% | 12:11 | 12:16 | 0.68% | 12:22 | 12:29 | 0.94% | | 0.81%
New York | 12:01 | 11:59 | 0.27%| 11:54 | 11:53 | 0.14% | 11:57 | 11:55 | 0.27% | | 0.23%
Omsk | 12:09 | 12:09 | 0.00% | 12:03 | 12.03 | 0.00% | 12:02 | 12:06 | 0.55% | | 0.18%
Rio de Janeiro | 11:51 | 11:56 | 0.42% | 11:56 | 11:49 | 0.99% | 11:56 | 11:52 | 0.56% | | 0.66%
Saint Petersburg | 12:06 | 12:02 | 0.55% | 11:59 | 11:55 | 0.55% | 11:58 | 11:58 | 0.00% | | 0.36%
Tokyo | 11:51 | 11:44 | 0.99% | 11:43 | 11:38 | 0.82% | 11:46 | 11:41 | 0.42% | | 0.42%
Warsaw | 11:54 | 11:54 | 0.00% | 12:25 | 12:33 | 1.01% | 12:33 | 12:36 | 0.43% | | 0.48%
> <big><b>Average Margin of Error</b><sup>^</sup>:</big><br>
1 January: 0.48%<br>1 May: 0.52%<br>1 Sep: 0.57%<br>Overall: 0.52%<br><sup>^</sup>Does not include <b>Kamchatka Peninsula</b> data.
<!-- markdownlint-enable MD101 -->
### Martian Time Zones
[Mars](https://mars.nasa.gov/#red_planet/0), pictured below, is the fourth of eight planets in our solar system and among the most similar to Earth.<sup>[35](http://curious.astro.cornell.edu/about-us/63-our-solar-system/planets-and-dwarf-planets/comparisons-with-earth/264-which-planet-is-most-similar-to-earth-intermediate)</sup>

* Coordinated Mars Time (MTC) is a proposed Martian derivative of UTC along the prime meridian proposed by German astronomers Wilhelm Beer and Johann Heinrich Mädler in **1830**.<sup>[36](https://www.jpl.nasa.gov/spaceimages/details.php?id=PIA03207)</sup>
#### Comparative Statistics
| | Earth | Mars |
|--|--|--|
Angle of Rotation | 23.5° | 25.2°
Diameter | 12,742 km | 6,787 km |
Length of Day | 24 hours | 24 hours 39 minutes (24.655 for calculations)|
Orbital Period | 365 days | 687 days
Average Distance from the Sun | 149.6 * 10<sup>6</sup> km (1 AU) | 1.524 AU
Highest Point on Surface | 6,263 m | 24,000 m
> Source: NASA [Jet Propulsion Lab](https://pds.jpl.nasa.gov/planets/special/mars.htm).
* The [Darian System](http://ops-alaska.com/time/gangale_converter/calendar_clock.htm), established by American aerospace engineer Thomas Gangale, is the most widely used Martian calendar.
* Due to Mars' longer orbital path and period, the Martian calendar is 22 months long.

> A sol is the duration of a solar day on Mars: 24 hours 39 minutes and 35.244 seconds.<sup>[37](https://www.jpl.nasa.gov/news/fact_sheets/viking.pdf)</sup><br>Adopted during the [Viking Lander](https://mars.nasa.gov/programmissions/missions/past/viking/) missions.
* Each longitudinal degree represents ± 4.11 minutes from the origin.

> Source: University of Texas, Richard Fitzpatrick.<sup>[38](http://farside.ph.utexas.edu/Books/Syntaxis/Almagest/node37.html)</sup>
* Mars' severe axis of rotation, and its asynchronous orbit create a distorted version of the Equation of Time function.
* Longer orbital path as well as angle of rotation increases the amount of time by which solar days differentiate throughout the year.
#### The Martian Day
* The diameter of Earth is roughly 187% that of Mars, but sidereal and solar days only differ by 2%.
* Within our solar system, planetary days range from 10 (Jupiter) to 5832 (Venus) hours.
* This similarity is explained by the culmination of billions of years, billions of events, and in the end: coincidence.
* Mars and Earth are different sizes.
* Mars and Earth have a different number of moons (Mars has two).<sup>[39](https://solarsystem.nasa.gov/moons/mars-moons/overview/?page=0&per_page=40&order=name+asc&search=&condition_1=6%3Aparent_id&condition_2=moon%3Abody_type%3Ailike)</sup>
* Mars and Earth are dramatically different distances from the sun.
#### Mars Retrograde

> Mars retrograde, visualized by position.<br>Source: [NASA Mars Expedition](https://mars.nasa.gov/).
* Biennial event whereby the position of Mars in the night sky moves from east to west, caused by relative differences in planetary orbits.<sup>[40](https://mars.nasa.gov/allaboutmars/nightsky/retrograde/)</sup>
|
{
"pile_set_name": "Github"
}
|
# 『食』
------
フェルトの名前をこそぎ取り、『食事』を始めたはずのバテンカイトスが嘔吐する。
苦しげに呻き、胃液を吐き出す『暴食』の態度には嘘がない。実際に形のあるモノを口にしたわけではないのに、嘔吐するときは胃を絞り出されるのか。
そんな益体のない感想が浮かぶ、不可思議な光景だった。
「クソ、いてーな……ふざけやがって……」
突き飛ばされた胸を撫でつけ、擦り傷だらけの姿でフェルトが立ち上がる。その表情は苛立ちと不満を宿しているが、致命的な被害を受けた様子はない。
彼女を視界の端に捉えるベアトリスらも、フェルトを忘れてなどいない。
『暴食』の食事は失敗したのだ。
「がっ、げほっ、おええッ!」
「理由はわからんが……好機だ!」
口の端から胃液をこぼし、完全に戦場から意識の外れるバテンカイトスへとダイナスが強襲を仕掛ける。
二刀が翻り、容赦なくバテンカイトスへ叩きつけられた。
無防備な首筋に、小刀の剣閃が迫り――、
「ぎ、ォォ!」
獣の雄叫びのような声が上がり、バテンカイトスが体術で刃をいなす。
回避の遅れた髪の毛が斬撃に持っていかれるが、肌を切り裂くには至らない。小柄な体を高速で回転させ、悪夢めいた挙動で『暴食』は攻撃範囲から逃れる。
「商人!」
「わかってます、よ!!」
ベアトリスの呼びかけに、応じるオットーが右腕を振り切った。その袖から投じられる二発の魔鉱石が、攻撃を逃れたバテンカイトスに当たる。
瞬間、光が爆ぜて、生じる魔力の奔流がその体を吹き飛ばす――だが、バテンカイトスはこれに驚異的な反射神経で対応した。
「ヒューマぁ!」
膨れ上がる光が、その破壊の力にバテンカイトスを呑み込む瞬間、バテンカイトスは魔法を発動し、爆ぜる魔鉱石を氷の中に包んで固めたのだ。
魔鉱石の爆裂は力の行き場を失い、ただの氷の塊になって音を立てて地面に落ちる。無色の魔力波に、高速で術式を割り込ませる超高等技術だ。
それすらもおそらく、バテンカイトスがこれまでに喰らった『名前』の中の一つがやってのけたのだろう。それだけの技術を習得した『誰か』も、誰の記憶にも残らないまま胃袋に奥に沈められていると考えると反吐が出る。
だが、今はそれらの感慨も後回しだ。
この場で重要なのは――。
「はァッ!危ない危ない……けど、しのいだよッ」
魔鉱石を閉じ込めた氷を蹴りつけ、水路に落としたバテンカイトスが笑う。彼は口の中に残る胃液をペッと吐くと、口元を腕で拭って首を傾けた。
その濁った瞳が見るのは、手足を回して負傷の程度を確かめるフェルトだ。フェルトは自分を見るバテンカイトスに気付くと、その鼻を鳴らす。
「んだよ。てめーにムカついてんのはアタシも同じだぞ」
「ムカついてるだなんてとんでもないッ、感心してるところさァ。見た目で、おつむの出来が悪そうだなんて思って悪かったよォ」
「はぁ?何を言い出してやが……」
「まさか、僕たち相手に偽名を使うだけの小賢しさがあるだなんて思わなかった。すっかり騙されたよ。『名前』を暴くまでがっつくのは避けてたつもりだったんだけど……まァさか、それを逆手に取られるだなんてね」
「――――」
偽名、とバテンカイトスが口にしたのを聞いて、フェルトが押し黙った。
眉をひそめるフェルトの反応は、思わぬ内容を聞かされたものが示す反応だ。彼女には今のバテンカイトスの言い分に、心当たりがないと見るべきだろう。
一方で、今の話を聞いていたベアトリスには、先のバテンカイトスの『食事』の失敗の原因が理解できていた。
バテンカイトスは『名前』を知った人間に触れて、いかなる手段か『名前』を喰らう権能の持ち主――だが、それは正式な名前である必要があるのだ。
偽名、あるいは愛称のようなものではそれは機能しない。
フェルトの名前だけでは『食事』としての条件を満たしていなかったため、それを味わったバテンカイトスが痛い目を見ることになった。
となれば、
「そっちのお兄さんにフェルトちゃん……名前のわからないのが二人もいて、どっちも食べると決めた相手だなんて厄介だなァ」
純粋に名前のわからないオットーと、偽名を用いているらしいフェルト。
すでに名前の割れているダイナスと、レムの記憶から知られているベアトリスはもはや障害ではないような『暴食』の振る舞いは癇に障るが、美食家を名乗って『名前』を喰らうことに拘り続けるのであれば、そこに付け入る隙もある。
「おい!さっきっから黙って聞いてりゃー、何の言いがかりだ?」
考え込むベアトリスと、睥睨するバテンカイトス。オットーやダイナスも機を見計らう最中、声を荒げたのはフェルトだ。
彼女は自分を余所に結論を出されたことに苛立ち、ミーティアを突き付けてバテンカイトスに吠える。
「偽名だのなんだの、ふざっけんな。アタシはもう十五年、ロム爺にもらったフェルトって名前で生きてきてんだ。それが嘘だなんて冗談じゃねーぞ」
「当人に偽名の自覚がないタイプかァ。そりゃ、君の育ての親がよっぽどうまくやったってことだろうねッ。僕たちにとっちゃ厄介極まりないけど……つまり、その名前より前にちゃァんと付けられた名前があるんだよ、君には」
「アタシを路地裏に捨ててったクソ親がつけた名前か?ならきっと、『厄介者』か『無駄飯食らい』か『ゴミ』だぜ。そう言って、ぺろっと食べてみるか?」
「当てずっぽうの総当たりとか、美食家の意識に反するなァ。――あァ、そうだ」
八重歯を見せ、怒りの笑みを浮かべるフェルトにバテンカイトスが手を打った。彼はフェルトの体を上から下まで眺めると、
「君以外を喰らったあとで、君は大切に保管しよう。で、君に偽物の名前を付けたロム爺に会いにいこうじゃないか。ロム爺なら君の名前を知ってるかもしれない。俺たちは、知ってることを聞き出すのは得意なんだ。任せてくれていいさァ」
「……そこまで手間暇かけて。諦めるって選択肢はないんですかね?」
醜悪な予定を口にする『暴食』に、思わずオットーが口を挟んだ。それを聞いたバテンカイトスは口に手を当て、愉しげに喉を鳴らすと、
「世に命の数が有限なら、その中で美食に値する数もまた有限なのさァ。なら、僕たちは限られた美食と出会える機会を逃さないッ。暴飲ッ!暴食ッ!舐めてしゃぶって啜ってこそいで、皿の上のタレまで舐め尽くして味わってやるさァ。おっと、もちろんお兄さんも例外じゃァないから安心していいよォ?」
バテンカイトスの視線は、この場に残る四人を決して逃すまいと決めている。
『暴食』の食事への拘りは、『美食』に値すると評価されたベアトリスたちには理解不能だ。ただ、執念深い厄介者に目を付けられた以上の意味はない。
そして、その冒涜者の食へ至る欲求は、いたくフェルトの不興を買った。
「そーかよ。ここでどうにかしねーと、ロム爺にまで手ぇ出すってんだな」
静かな声で言って、フェルトが自分の足を振った。
履いていた靴がすっぽ抜け、フェルトはもう片方の足も同じように。両足を素足の状態で石畳を踏み、彼女はミーティアを横へ転がすと短剣を抜いた。
「――?わっかんないなァ、フェルトちゃん。それ、切り札なんじゃァないの?」
「慣れてねー道具に頼るより、こっちの方がやりやすいんだよ。もともと、そこまで拘るもんでもねー。道具は使える奴が、使いやすいのを使うのがいいって、な!」
素足が地面を掴むように丸まり、次の瞬間にフェルトの体が弾かれるように前に射出されていた。瞬きの合間に接敵する速度、まさに風のようだ。
これにはバテンカイトスも目を剥き、振りかぶられる刃に対して余裕の態度を忘れて対応する。腕を振り、身を捌き、記憶に沈めた体術を引っ張り出す応戦だ。
「っらぁ!」
裸足のフェルトの速度は、ただ身軽な少女の出せる勢いを凌駕している。
人智を超えた力の援護――すなわち加護を帯びていることは間違いない。短剣が幾度も閃いて、バテンカイトスの短剣術とそれなりに渡り合っている。
無論、その技量はバテンカイトスに圧倒的に軍配が上がるが、ただフェルトが押し切られずに済むのはダイナスの援護が入るからだ。
「大事な体で、あまり無茶をするな!」
「オッサンこそうっせーな、遅れてんじゃねーよ!」
巧みに二刀を操り、ダイナスは『暴食』の反撃の隙間をどうにか塞ぐ。その間にフェルトが『暴食』の死角に回り込んで急襲、鋼同士が噛み合う音がして、火花を散らしながらもみ合う三人の影が入り乱れる。
またしても決定打に欠ける乱戦。
ただし今回は、決定打がきっちりと乱戦の外側に用意されている――。
「術式……通した、ぶちかますかしら!」
「お二人とも、離れてください!」
蚊帳の外に置かれながら、じっくりと時間をかけて一つの術式を組み上げる。
普段ならばさして手こずる必要もない作業に、余計なフィルターを挟んでいるせいで細心の注意を払う工程が入った。
それだけの労力を払った結果、ようやくそれが形になる。
「――――」
オットーの叫びに従い、フェルトとダイナスがバテンカイトスの傍を離れる。とっさにフェルトに手を伸ばす『暴食』だが、触れたところでフェルトの『名前』を喰らう準備は整っていない。
「はな、せ!」
乱暴に掴まれた足首を振りほどき、フェルトは片足で大きく背後へ飛んだ。ダイナスも転がるようにその場を離れて、ベアトリスの射線上に『暴食』だけが残る。
そこへ目掛けて、ベアトリスは発動に『千』の力を必要とする魔法を、『千』の力を真っ当に通して完成させた。
「今度は冗談じゃなく、本当に……ウル・ミーニャ!!」
詠唱に応じて紫の輝きが迸り、バテンカイトスを中心に光が円を描く。何事が起こるのかと顔を上げるバテンカイトスだが、その反応では遅い。
構えるのではなく、形振り構わず逃げ出すのが正解だ。
「――ッ!」
光の輪が一気に収束し、バテンカイトスの胴体が腕ごと輪に抑え込まれる。上半身の動きを拘束された『暴食』に、さらに光の輪が連鎖して閉ざしにかかった。
そのまま全身を光の輪に包まれれば、ウル・ミーニャの威力から逃れられない。
結晶化する紫の光が、バテンカイトスの上半身を次々と締め付ける。そのまま輪の支配は下半身にまで及び、身動きを感じられた『暴食』がその場に倒れ込んだ。
そして大気が軋むような音を立てて、強大な紫紺の輝きが倒れる冒涜者の頭上に浮かび上がり、その先端をバテンカイトスへと向けている。
拘束し、叩き潰すウル・ミーニャの威力。
ベアトリスの持てる技術を緊急的に叩き込み、実現させた破壊がバテンカイトスへと降り注いだ。
「――――!」
雄叫びが掠れて聞こえたが、それは破壊を生み出す紫の光の前に掻き消された。
圧倒的な光の威力に石畳がめくれ上がり、巻き起こる爆風が大広場を光と噴煙で包み込み、ベアトリスのドレスのスカートが大きくはためく。
「やったか!?」
「やりましたか!?」
「やったのか!?」
爆風に煽られながら、身を伏せていた三者が同時にそう声を上げた。
爆心地のど真ん中、そこにいたバテンカイトスに回避の手段はなかった。今の一撃をまともに浴びていれば、その肉体は骨片すら残さず消滅して――。
「まだ終わっちゃいないかしら!」
――そう、まともに当たっていればだ。
ベアトリスが高い声で警戒を促し、快哉を叫んだ三人の顔色が変わる。三人よりもいち早く、ベアトリスが失策に気付けたのは難しい話ではない。
感触だ。
「――あと、四つ」
懐に仕舞い込んでいた大魔石が、今のウル・ミーニャの術式に耐え切れず、バテンカイトスを仕留める寸前で砕け散っていた。
発動まで持ち込めたものの、効果の十全な発揮には不十分な位置での消失。輝きはバテンカイトスを焼き尽くすには届かず、『暴食』の体は――、
「今のはちょっとだけ焦ったかもッ!」
「――!」
噴煙の中を突き抜けて、バテンカイトスが低い姿勢からベアトリスへ飛びかかる。今の魔法の威力から、もっとも早々に消すべきが誰かを判断した結果だろう。
魔法使いとして卓越した技術を持つベアトリスだが、その身のこなしは常人――外見通り、幼い少女の域を脱してはいない。
達人の体術を操るバテンカイトスと、接近戦を行えるだけの能力はないのだ。
故にベアトリスはこの接敵に対して、即座に三つ目の魔石を利用する。
「――ムラク!」
「小細工したところで――」
バテンカイトスの手が届く寸前、かろうじてベアトリスの詠唱が先手を打った。
伸び上がる指先は、いかなる妨害があってもベアトリスを逃がすまい、それだけの意思が込められたものだった。だが、その意はまたしても外れる。
指先がドレスを掠めたかと思った瞬間、ベアトリスの体がまるで風に押される木の葉のように真後ろへ吹っ飛んだのだ。
「――――」
ベアトリスの詠唱した『ムラク』は、重力に干渉する陰魔法だ。地面へ引きつけられる力や、自らの体重などに干渉する魔法だが、ベアトリスはそれを利用して自分の体重を一瞬だけ完全にゼロにした。
それこそ風に浮かび、触れようとする指先に大きく弾かれるほどに。
「こ、っの――!?」
目論見通りに、ベアトリスの体はバテンカイトスを離れて、一気に大広場の端っこの方まで飛んでいく。それに追い縋ろうとしたバテンカイトスは、しかし背後に生じた大げさな足音を聞いて、とっさにそちらへ振り返ってしまった。
短剣を背後へ繰り出し、無粋な乱入者を斬りつけようとする。しかし、その一撃は空を切った。なぜなら、そこに足音の人物はおらず、
「ガーフィールとか『腸狩り』とか、そういう人ばっかり引っかかりますよねえ!」
風魔法の応用で、『足音を飛ばした』オットーが背中を向けさせたバテンカイトスにさらに魔石を投じた。剥き出しの背中に破裂する魔石の熱波が襲い掛かり、今度は防がれなかった爆風にバテンカイトスが吹っ飛ぶ。
「今度こそ終わりだ!」
ゴロゴロと広場を転がり、五体を投げ出して倒れるバテンカイトス。その姿に飛びかかり、二刀を逆手に構えたダイナスが止めを刺そうと――、
「――――」
ぼそりと、倒れる少年が何事か囁いた。
それが命乞いか、あるいは後悔の言葉であってもダイナスは躊躇わない。傭兵稼業を生きてきた彼にとって、命の奪い合いはシビアに競った結果だ。
そこに大人か子どもかの問題は些少なことであり、悼むことも悔やむことも全ては生き残ったあとにこそできる感傷でしかない。
故に割り切った。ただ、割り切ったダイナスの動きに淀みはないが、それでも不可解を胸に抱かずにはおれなかった。
今のバテンカイトスの囁きが、こう聞こえたからだ。
――月食、と。
「――お?」
その音の正しい響きに至った直後、間の抜けた声が漏れた。
次の瞬間、小刀を振りかぶるダイナスの四肢が一斉に血を噴いている。四肢にはそれぞれ深々と短剣を突き込まれた傷が浮かび、正確に腱を抉られていた。
すなわち、四肢の機能の完全な喪失を意味し、崩れ落ちる体を止められない。
「く、あ!?」
顔面から石畳に落ちたダイナス、その頭が真上から思い切り踏みつけにされる。鼻面を石畳に潰されて、衝撃に呑まれたダイナスの意識が吹っ飛んだ。
うつ伏せで動かなくなるダイナス、その体を蹴りつけて、立ち上がったバテンカイトスがゆっくりと、オットーの方を振り返った。
「……ぁ」
その濁った瞳と、視線を交わすのは初めてではない。
なのにオットーの精神は、その濁った瞳に一瞬で絡め取られてしまった。
渦巻く狂気と怨嗟が、先ほどまでのそれと段違いにどす黒いものだったから。
「――――」
一瞬だった。
瞬きの間に距離が詰まり、気付いたときにはオットーの両足を灼熱が貫いた。見れば両足の腿の前面を、短剣が十字の傷口を生むように抉っている。
果物の皮でも剥くように、ぺろりとズボンとその下の肌がめくれた。肌の裏の赤い断面と桃色の筋肉、その中を這い回る白い神経と骨に、緑の血管が一切、傷付けられずに摘出されていて、オットーの喉が場違いな感慨に詰まった。
呆気に取られる。ここまで美しい技法は、お目にかかったことがない。
最小限の出血――否、一切の出血がないのだ。真に卓越した熟練の刃の扱いは、人間の肉体をこれほど耽美に破壊してせしめる。
「――――」
しゃがみ込んで、バテンカイトスがその傷口に口付けした。ざらりとした舌の感触が、肌の内側にあったオットーの足の重要部分の全てを舐める。
筋肉、骨、血管、神経、それらが舐られる感覚に身震いがあり、次の瞬間に視覚的にも触覚的にも、堪え難い嫌悪と激痛がオットーの脳を沸騰させた。
「あ、ぎゃあああああ――ッ!?」
血は、出ていない。意味がわからない。
ただ痛みだけがある。それも血の噴出の代わりとばかりに、剥き出しの骨や神経が湿った風に撫ぜられ、筋肉を丹念に針で剥かれるような凄絶な痛みが。
視界が明滅し、脳が爆ぜる。痛みを理解する器官が、その理解を拒絶する。絶叫する喉は血を吐くように震え上がり、動かない両足で悶えることもできない。
そうしてオットーが絶叫する中、それを見下ろすバテンカイトスは首を傾げた。長い焦げ茶の髪が肩を滑り落ち、『暴食』は疲れたような嘆息する。
「食休みかと思えばこの有様。美食だの悪食だのどうでもいいのに……本当、私たち以外は食事のなんたるかが全然わかってない」
それまでの、狂気的な笑みも態度も仕舞い込んで、ひどく達観した声音だった。
バテンカイトスがゆっくりと首を振り、まるで自嘲するかのような振る舞い――かと思えば、パッとその表情が変わり、
「そういう言い方はするなよォ。確かにちょっと遊んでて面倒はあったけど、それでもルイ好みの御馳走は見つけたんだからさァ」
牙を見せ、首を巡らせたバテンカイトスの視線がベアトリスたちを見た。その視線と、オットーの惨状に思わず二人の少女は息を呑む。が、そんな二人の反応を見たバテンカイトスの表情がまた、空虚でけだるげなものへと変わった。
「確かに悪くはないみたいだけど……中身より器の確保でしょう。それに、福音書の記述だって読み切れてないし」
「ルイは見えないかもだけど、それは僕たちの中にいる子が教えてくれてるさァ。あそこにいる、ベアトリス様がそうだよ、たぶん。やりきれば心身ともに満ちる、絶好の機会ってやつじゃないかッ!」
右を見て言い合い、左を見て言い合い、バテンカイトスは己の胸中ではなく、外からもはっきり見えるような形で自問自答する。
まるでそれは、自分の内側にいる別の何者かと会話するような光景だった。
いや、事実、その可能性がある。
『名前』を喰らう冒涜者、ライ・バテンカイトスの中には無数の魂がある。ならばそのいずれかと言葉を交わし、あるいは合議することすら可能なのかもしれない。
ならばこのおぞましい自問自答にも、理解が及ぶというものだ。
「動けるかしら、チビッ子」
「ああ?そっちの方こそ、ビビッてねーだろうな、チビ」
互いを罵り合いながら、ベアトリスとフェルトが意思疎通を交わす。お互いの瞳を覗き込み、どちらの戦意も折れていないことを確認。
フェルトは小さく鼻を鳴らすと、顎をしゃくって大広場の一角を示した。ベアトリスはそこに散らばるものを確かめて、その意図を察する。
「……あいつらはこのあと、ベティー狙いでくるかしら。足止めはしてやるのよ」
「止められんのかよ?攪乱ならアタシの方が……」
「二回ゲロ吐くほどアホなのを期待するわけにもいかんかしら。それに決め手はどう足掻いても、ベティーには扱えないものなのよ。お前がやるしかないかしら」
ベアトリスの提言に、フェルトが考え込む素振りを見せる。が、眉間に皺を寄せた彼女はすぐに首をひねり、金髪を掻き毟って「あー!」と声を上げた。
そして、ベアトリスに拳を向けると、
「しくじんなよ、チビッ子」
「お前こそかしら、チビ」
向けられた拳には特に何も返さず、互いに悪態だけついて決戦に挑む。
ベアトリスたちの話し合いが終わるのと、バテンカイトスの自問自答の終わりはほとんど同時だ。ダイナスとオットーを切り倒した戦闘力、あれが十全に発揮される場合、それと真っ向からぶつかれる自信はベアトリスにはない。
「それで、準備はよろしいですかァ、ベアトリス様ァ?」
「できてないって答えて猶予がもらえるならそうするのよ。でも、そうじゃないなら質問に意味なんてないかしら」
「まったくその通りです。んじゃァ、改めて――イタダキマス!」
真っ向から、バテンカイトスがベアトリスを目掛けて一直線に飛びついてくる。速度は先ほどの、悪夢じみた脅威ほどではない。とはいえ、それでもベアトリスには十分な脅威。接近戦の不利は変わらない。
だから、真っ向からぶつからないことが陰魔法の使い手としての本領だ。
「そォ、らァ――!」
ベアトリスの前方で、地面に手をついたバテンカイトスの体が縦に回る。振り下ろされる踵がベアトリスの真上から迫り、鋭い一撃が少女の脳天に突き刺さる。
「そうはいかないのよ」
――寸前、ベアトリスの体がまたしても蹴りの風圧に背後へ傾いた。先ほど発動した『ムラク』の効果を切らずに残していた結果だ。
風圧に背後へ傾き、ベアトリスはその場で大きく真上へ飛び上がる。重力から解放され、体重という頸木もない少女の体はあまりにも軽々と浮かび上がった。
ドレスの裾を巧みに翻し、風を浴びるベアトリスの体が不規則に宙を舞う。
「お見事!ですがァ、対処が甘い!」
舌を伸ばしたバテンカイトスが落下地点に回り込んで、その着地を待たずに中空のベアトリスへ向かって掴みかかった。
猛禽が獲物を捕らえるような勢いと正確さで、その指先がベアトリスへ届く。しかしそれは同時に、逃げ場のない中空へ相手も上がった証拠だ。
魔法の残弾が限られている以上、当てることが最大の焦点。
ベアトリスは真下から迫るバテンカイトスへ掌を向け、四百年の生涯、そしてこの一年でもっとも使い慣れた魔法を詠唱する。
すなわち――、
「シャマク!!」
懐で魔石が砕け散り、ベアトリスの詠唱に応じて黒い靄が噴出――跳躍するバテンカイトスはそれに頭から突っ込み、無理解の世界へと閉じ込められた。
「もがァ――!?」
黒い靄が取り付き、バテンカイトスの体が無防備に石畳へ落ちる。振り切るまで何もできない状態が続くはずだが、シャマクの効果はそれほど長くない。
今のベアトリスの手札――利用できる魔石一つで致命打は奪えない。ならばベアトリスがこの瞬間、選ぶべき手段は。
「あァ!やってくれるなァ、ベアトリス様ッ。まるで、あの人みたいな戦い方をして……影響でも受けたんですかァ!?」
シャマクを振り払い、身を回したバテンカイトスが牙を剥いた。彼はぐるりと広場を見渡し、ベアトリスを目に留めるとそうのたまう。
彼の中にいる少女の記憶では、ベアトリスがスバルの隣に並び立っている光景はないはずだ。だから、ベアトリスがこうして奮戦する姿に彼の影響を見ても、それがどれだけ大きな意味を持つのか気付けない。
「そら、最後の魔石で大盤振る舞いなのよ!」
感傷を振り切り、ベアトリスは足下に転がるオットーへと掌を向けた。最後の魔石の魔力を使って、のたうち回るオットーの足の傷に癒しの波動を送る。
完全治癒は遠いが、それでも絶望的な痛みは遠のいたはずだ。涙を流して転がっていたオットーが、嗚咽まじりに大きく咳き込む。
「そんな役立たず、今、復活させてどうなるのッ?」
「こうなるのよ!」
一手を無駄にしたと嘲笑うバテンカイトスに、ベアトリスが怒鳴り返した。
その啖呵に眉を寄せた直後、バテンカイトスの足に背後から何かが食らいついた。左足に深々と牙を立てられて、体勢の崩れるバテンカイトス。
とっさの自分の足を見下ろし、それを見たバテンカイトスの目が見開かれた。
「はァ!?」
理解できないものへの驚き、そこにいたのは血塗れの水竜だ。
首を伸ばして、石畳を猛進した水竜がバテンカイトスに食らいついている。一度は戦闘不能まで追い込まれた水竜が、最後の意地を貫いて。
五つの魔石のうち、三つ目の魔石の使い道だ。
一つ目で強烈な、しかし不発に終わったウル・ミーニャ、二つ目が緊急回避用のムラクに使用され、そしてムラクで弾かれた先にいた瀕死の水竜を、三つ目の魔石で回復。
四つ目でシャマクを放ち、五つ目でオットーの痛みを遠ざけた。
それがベアトリスの五手、勝利を掴むための魔石の使い道だ。
「――ぁぁ!痛い痛い、痛いぃ!」
喉が嗄れるほど叫び、絶叫の中に水竜への呼びかけを隠したオットーが、役目を果たして今度こそ自分の痛覚のために泣き叫ぶ。
ベアトリスの治療を受けた直後、即座に求められるところを理解するあたり、オットーは本当に優秀だ。不本意にも戦いに巻き込まれることの多い、エミリア陣営の内政官は彼にしか勤まるまい。
「よくやったかしら、天職なのよ!」
「なんかわかんないけど嬉しくないんですが!」
ベアトリスの滅多にない称賛を浴びて、涙を流すオットーがそう応じる。そして二人の眼前、水竜に足を食らいつかれたバテンカイトスが地面に引き倒され、どうにかその牙を外して立ち上がろうとする。
しかし、それらの反応全てが、切り札を前に間に合わない。
「――準備、万端。よく稼いだぜ、チビッ子」
勝ち誇った声がして、硬い音を立ててミーティアの尻が地面を叩いた。
腰溜めに杖を構えて、フェルトはその先端をバテンカイトスへ向ける。彼女の手の中でミーティアはうっすらと光を帯び、その余波が包みを吹き飛ばした。
白い包みが外されると、そこから露わになったのは純白の細長い杖だ。
柄の長さは槍といっても通じるほど長く、凝った意匠もなければ、目を惹くような機構が組み込まれているわけでもない。
実用性一辺倒のその造りは、まさに造物主の精神を反映しているといえる。
道具に道具以上の価値を求めない、エキドナという『魔女』の精神そのものを。
「お母様……」
ベアトリスは実際に、エキドナがその杖を振るうところを見たことはない。それでもその杖の製作された目的と、その威力は知っている。
神龍ボルカニカへの嫌がらせ――神龍に干渉し得る、そうした兵器であると。
とはいえ、使用にはいくつかの条件がある。
その条件を満たすことが難しいのと、使用者の問題もあり、その底無しのスペックの全てを発揮しきることは厳しいが――。
「さぁ、ラインハルトさんにも通用する威力、味わってみろやぁ!」
条件を満たした状態で、マナが満タンのフェルトが使用者ならば期待値は十分。
握る所有者のマナをぐんぐんと吸い上げて、ミーティアは際限なく力を溜め込み、先端へ集まる光がバテンカイトスへ照準を定めた。
「――ッ」
さすがのバテンカイトスも、その威力には余裕を保っていられない。
致命の可能性があると見るや、バテンカイトスは即座に足を拘束する水竜の鼻面を短剣で一撃、牙がゆるんだ瞬間に足を引き抜き、裂傷を負いながら飛びずさる。
その瞬間、ミーティアが一際強く瞬いた。
「いっけ――っ!!」
ミーティアの先端で光が膨れ上がり、白光がバテンカイトスへ放たれた。
とっさに水竜の拘束を逃れたバテンカイトスは、その傷付いた足でどうにかその射線上から転がり出る。そのまま光は狙いを外し、水竜へと衝突――する直前、軌道が曲がった。光は複雑な軌道を描き、バテンカイトスへ追い縋る。
「な――ッ!?」
逃れる自分へ追い縋る光弾に、バテンカイトスは声を上げた。そのまま鋭い身のこなしと跳躍で、再接近する光弾の軌道から外れる。
しかし、無駄だ。光弾はバテンカイトスが逃れても、転がっても、跳躍しても、弧を描き、円を描き、追い縋り、直撃を狙う。
あれがエキドナの生み出した魔法兵器『ミーティア』の、最大の強み。
照準と定めた対象への、永続的な追尾機能だ。
エキドナが神龍ボルカニカへの『嫌がらせ』のために作った兵器。凝り性のエキドナが本気で、ただ『嫌がらせ』のために道具を製作すれば、それはその目的のために妥協を許さないものに仕上がって当然だ。
故にあの魔法器は、対象を逃さず、外れず、確実に届く兵器に成り果てた。
「ぬ、っぐ……なら、これはどうかなァ!?」
逃げても逃げても限度のない光弾の追跡に、業を煮やしたバテンカイトスが逆襲に打って出る。魔法力が高まり、バテンカイトスの周囲が凍り付いた。
浮かび上がる複数の氷柱が鋭い先端を光弾へ向け、嵐のような弾幕が白光へと飛び込んでいく――だが、その抗いは間違いだ。
氷柱は白光に当たる寸前、その先端からマナへと還元されて、命中する前に粉々になって光弾へ呑み込まれてしまう。それだけに留まらず、光弾は迫ってきた魔法迎撃を全て吸収して、ますますその威力と規模を拡大して対象へ迫るのだ。
「クソ、こんな……こんなッ!」
転がり、軌道からなんとか逃れ、バテンカイトスが悪態をこぼす。しかし、その左足の傷は深く、万全な跳躍を可能とはしない。
あるいは機敏に動ければ、ベアトリスたちの方へと光弾を誘導したり、フェルト本人を狙うことが可能だったかもしれないが、そこまでの余力はない。
やがて光弾は転がるバテンカイトスの周囲を回り、その逃げ場を塞ぎながら、ゆっくりと嬲るように『暴食』の体を破壊の力に押し包み――、
「こんな、馬鹿みたいなことで、僕たちが俺たちが――!」
「ごちゃごちゃうるさい。さっさと、日食を切ればいい」
直撃の瞬間、みじめったらしい声をバテンカイトスが上げ、それがまたひどく冷めた声に塗り潰された。そして、光が炸裂する。
「――――」
眩い白光が大広場の中央で膨れ上がり、これまでで最大のクレーターが生じる。
膨らんだ光は世界を白く塗り潰し、塗り潰された部分は色を失ったかのように消失してしまっていた。
丸い球状に大広場が抉られて、水路へ通じたそこに水が流れ込む。
だが、
「やれやれ、まったく。本当に出来の悪い兄弟を持つと苦労する」
その破壊の惨状の横で、水路を覗き込んでいる影がある。
焦げ茶の髪を長く伸ばし、傷だらけの体をした人物だ。その肉体的特徴は言うまでもなく、相対していたライ・バテンカイトスに他ならない。
如何なる方法でか、あの光弾の攻撃を回避したのか――しかし、この場でもっとも驚きに値するのはそこではない。
「どういう、ことかしら」
ベアトリスの呟きは、攻撃が当たらなかったことへの驚きではない。
そもそも、攻撃の当たる当たらないの問題ではないのだ。光弾が当たるべきはバテンカイトスであって、バテンカイトス以外には当たらないのだから。
だから、そこでこちらに背中を向ける、筋骨隆々とした大男には当たらなくて当然。問題はその男が、いったいどこから現れたのか。
「あれは『暴食』……ですか?」
苦しげに顔を上げて、同じものを見るオットーがそうこぼした。
否定してやりたいところだが、今のベアトリスにはそのための言葉がない。押し黙るベアトリスたちの視線に、ふとその大男が振り返った。
そこにいたのは、バテンカイトスとは似ても似つかない厳つい顔つきの男だ。
四十路に迫ろうかという見た目で、あの冒涜者と重なる部分は微塵もない。目を細めるベアトリスの前で、その男は自分の顎に手を当てて、
「そう不思議そうな顔をする必要はないわ。私たちはただ、こうしただけ」
と、見た目を裏切る女言葉で言って、男は自分の長い髪を軽く手刀で断つ。パラパラと髪の毛が舞い散り、それを見たベアトリスは光弾の回避方法を理解した。
ミーティアの追尾は、命中したという判定が為されるまで成立する。
あの威力だ。体の一部分にでも当たれば、十分に全身を巻き込むことができる。その点を逆手に取られた。
男――おそらくバテンカイトスは、自らの髪の毛を切断し、それを光弾に『肉体への接触』と錯覚させたのだ。そして、攻撃範囲から全力で逃れて、被害を免れた。
あるいは成立しない可能性もあった方策だが、今回に限れば満点の回答だ。
もともと、ミーティアに標的を定めさせるためには、標的となるものを識別するための『照準』を合わせる必要がある。
対象のオド、あるいはゲートと繋げて狙わせるのがベストだが、今回の場合は緊急的な措置として、戦いの最中に落ちたバテンカイトスの髪の毛を利用した。その分、髪の毛の囮の方に光弾の方も逸れてしまったのだ。
「――――」
そこまで考えたところで、ベアトリスは状況の悪さに歯噛みする。
切り札であったミーティアを、まさかそんな方法で回避されるとは思わなかった。魔石は使い切り、手元にあるのは自活用であり、パックのために温存したい一個。
オットーや他の男たちも戦えず、ミーティアにマナの大半を吸われたフェルトも、その場に崩れ落ちて荒い息をついている。
万事休す――そんな考えが浮かびかけるが、ベアトリスは首を横に振る。
敗北を受け入れるのは死んでからにすべきだ。スバルが絶望的な状況でこそ活路を見出すように、自分もそうしなくてはならない。
だからベアトリスはキッと顔を上げ、その男を睨みつけた。
視線を向けられて、バテンカイトスは目を丸くする。それから彼は腰に片手を当て、もう片方の掌で顔を覆った。そして、
「いい、いいわ、いいわね、いいわよ、いいじゃない、いいじゃないのさ、いいだろうからこそ……私たちも、あたしたちも、『食す』価値をあなたに見る」
「――っ」
告げられる戯言にベアトリスが反論する前に、バテンカイトスの体に変化が生じる。音を立てて骨が歪み、痛々しく血が噴出、大男の体が萎んだ。
新たに生じた傷口から大量の血を流し、息を荒げるのは少年の姿を取り戻したバテンカイトスだった。
バテンカイトスはその満身創痍の状態で、しかし狂的な笑みを浮かべる。低く喉を鳴らしながらこちらを見る『暴食』は、嬉しそうに両手を広げた。
「私たちの名前は、魔女教大罪司教『暴食』担当、ルイ・アルネブ」
「ルイ……?」
ライ・バテンカイトス、それが奴の名前のはずだ。
ふいに違う名前を名乗る意図が読めず、ベアトリスは眉を寄せる。と、その戸惑いの隙間を縫って、バテンカイトスは右足だけで強く地を蹴った。
何事かと身を固くするベアトリスだが、『暴食』は広場の端っこへ飛び、そこに落ちていたボロ切れを回収すると、傷だらけの肌を隠すようにまとう。
その上で、
「残念だけど今日はここまで。ライもロイも消耗しすぎたから。これ以上は産み落とすのに支障をきたすわ。また会いましょう、可愛いお嬢ちゃん」
「――!逃がすと、思っているのかしら!」
「強がりはやめなさいな。『蝕』はこの体じゃまともに扱えないけど、それでも全滅させるぐらいはできるのよ。そうしないのは、食卓が整っていないから」
踏み込もうとするベアトリスに、指を突き付けてバテンカイトスは首を振る。
ひどく女性的な仕草――否、実際、今のバテンカイトスは女性なのかもしれない。その本質の部分で、理解しがたい何かが起きている。
嫌悪感と警戒心から足の止まるベアトリスに、バテンカイトスは頷いた。
「美食のライも、悪食のロイもなァんにもわかってない。だってそう。食事は『何を食べるか』じゃない。『誰と食べるか』だもの」
「――――」
「じゃァね。次はきっと、あなたの大切な人と一緒に会いにきてね」
「待――」
待て、と呼びかけるより早く、バテンカイトスは大広場の影に滑り込んで消えた。あとを追いかけることは、負傷者だらけの状況でベアトリスにはできない。
深追いして、『暴食』の有利な状況へ引き込まれるのも無謀だ。
切り札であるミーティアが外された時点で、こうなる他にない。
「……してやられたって、ことなのよ」
舌打ちしたい気持ちを堪えて、ベアトリスは周囲を見渡す。
痛みにオットーは意識を朦朧とさせ、傭兵たちとフェルトの従者は気絶、失神。フェルトは悔しげにしているが、今にも倒れ込んでしまいそうだ。
そしてそれはベアトリスも例外ではない。
キリタカの必死の訴えに応じて、どうにか死者を出さずに済んだことだけが、ベアトリスがこの戦場へ参じた結果と受け止めるべきか。
いずれにせよ――。
「胸を張って、スバルに抱っこしてもらうわけにもいかなそうかしら……」
逃がした獲物――ライ・バテンカイトスの中に、少女の魂が眠っている。
そのことに確信を得て、それをスバルにどう伝えるべきか。
ベアトリスはひどく重苦しい悩みを抱きながら、朦朧とするフェルトに声をかけるためにそちらへ足を向けたのだった。
皮肉にも、大罪司教の離脱によってこの戦場の戦いも終息し――、
水門都市の戦場も、残すところあとわずかであった。
|
{
"pile_set_name": "Github"
}
|
#
# Copyright (C) 2018 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas 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 Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
module Schemas::Lti
class ToolConfiguration < Schemas::Base
SCHEMA = {
"type" => "object",
"required" => [
"title",
"description",
# to be reenabled after scopes bug fix
# "scopes",
"target_link_uri",
"oidc_initiation_url"
].freeze,
"properties" => {
"title" => {
"type" => "string"
}.freeze,
# "public_jwk" => verified in ToolConfiguration model
"public_jwk_url" => {
"type" => "string"
}.freeze,
"is_lti_key" => {
"type" => "boolean"
}.freeze,
"description" => {
"type" => "string"
}.freeze,
"icon_url" => {
"type" => "string"
}.freeze,
"scopes" => {
"type" => "array",
"items" => {
"type" => "string",
"enum" => [*TokenScopes::LTI_SCOPES.keys, *TokenScopes::LTI_HIDDEN_SCOPES.keys].freeze
}
}.freeze,
"extensions" => {
"type" => "array",
"items" => {
"type" => "object",
"required" => [
"platform",
"settings"
].freeze,
"properties" => {
"domain" => {
"type" => "string"
}.freeze,
"tool_id" => {
"type" => "string"
}.freeze,
"platform" => {
"type" => "string"
}.freeze,
"settings" => {
"type" => "object",
"required" => [
"placements"
].freeze,
"properties" => {
"text" => {
"type" => "string"
}.freeze,
"icon_url" => {
"type" => "string"
}.freeze,
"placements" => {
"type" => "array",
"items" => {
"type" => "object",
"required" => [
"placement"
].freeze,
"properties" => {
"placement" => {
"type" => "string",
"enum" => [
"account_navigation",
"similarity_detection",
"assignment_edit",
"assignment_group_menu",
"assignment_index_menu",
"assignment_menu",
"assignment_selection",
"assignment_view",
"collaboration",
"conference_selection",
"course_assignments_menu",
"course_home_sub_navigation",
"course_navigation",
"course_settings_sub_navigation",
"discussion_topic_menu",
"discussion_topic_index_menu",
"editor_button",
"file_menu",
"file_index_menu",
"global_navigation",
"homework_submission",
"link_selection",
"migration_selection",
"module_group_menu",
"module_index_menu",
"module_menu",
"post_grades",
"quiz_index_menu",
"quiz_menu",
"resource_selection",
"submission_type_selection",
"student_context_card",
"tool_configuration",
"user_navigation",
"wiki_index_menu",
"wiki_page_menu"
].freeze
}.freeze,
"target_link_uri" => {
"type" => "string"
}.freeze,
"text" => {
"type" => "string"
}.freeze,
"icon_url" => {
"type" => "string"
}.freeze,
"message_type" => {
"type" => "string",
"enum" => [
"LtiDeepLinkingRequest",
"LtiResourceLinkRequest"
].freeze
}.freeze,
"canvas_icon_class": {
"type" => "string",
"enum" => [
"icon-lti"
].freeze
}.freeze,
"selection_width" => {
"type" => "number"
}.freeze,
"selection_height" => {
"type" => "number"
}.freeze,
}.freeze
}.freeze
}.freeze
}.freeze
}.freeze,
"privacy_level" => {
"type" => "string",
"enum" => [
"public",
"email_only",
"name_only",
"anonymous"
].freeze
}.freeze
}.freeze
}.freeze
}.freeze,
"target_link_uri" => {
"type" => "string"
}.freeze,
"oidc_initiation_url" => {
"type" => "string"
}.freeze,
"custom_fields" => {
"anyOf": [
{"type" => "string"}.freeze,
{"type" => "object"}.freeze
].freeze
}.freeze
}.freeze
}.freeze
private
def schema
SCHEMA
end
end
end
|
{
"pile_set_name": "Github"
}
|
# Copyright (c) 2020 SUSE LLC
# Licensed under the terms of the MIT license.
#
# 1) bootstrap a new CentOS minion via salt-ssh
# 2) subscribe it to a base channel for testing
@ceos7_ssh_minion
Feature: Bootstrap a SSH-managed CentOS 7 minion and do some basic operations on it
Scenario: Bootstrap a SSH-managed CentOS 7 minion
Given I am authorized
When I go to the bootstrapping page
Then I should see a "Bootstrap Minions" text
When I check "manageWithSSH"
And I enter the hostname of "ceos7_ssh_minion" as "hostname"
And I enter "linux" as "password"
And I select "1-ceos7_ssh_minion_key" from "activationKeys"
And I select the hostname of "proxy" from "proxies"
And I click on "Bootstrap"
Then I wait until I see "Successfully bootstrapped host!" text
And I wait until onboarding is completed for "ceos7_ssh_minion"
@proxy
Scenario: Check connection from SSH-managed CentOS 7 minion to proxy
Given I am on the Systems overview page of this "ceos7_ssh_minion"
When I follow "Details" in the content area
And I follow "Connection" in the content area
Then I should see "proxy" hostname
@proxy
Scenario: Check registration on proxy of SSH-managed CentOS 7 minion
Given I am on the Systems overview page of this "proxy"
When I follow "Details" in the content area
And I follow "Proxy" in the content area
Then I should see "ceos7_ssh_minion" hostname
Scenario: Prepare a SSH-managed CentOS 7 minion
Given I am authorized
And I install package "hwdata m2crypto wget" on this "ceos7_ssh_minion"
And I install package "rhn-client-tools rhn-check rhn-setup rhnsd osad rhncfg-actions" on this "ceos7_ssh_minion"
And I install package "spacewalk-oscap scap-security-guide" on this "ceos7_ssh_minion"
Scenario: Check events history for failures on SSH-managed CentOS 7 minion
Given I am on the Systems overview page of this "ceos7_ssh_minion"
Then I check for failed events on history event page
|
{
"pile_set_name": "Github"
}
|
import React from 'react';
import PropTypes from 'prop-types';
import {addEventListener} from '../../../utils';
import classNames from 'classnames';
import warning from 'warning';
import Steps from './Steps';
import Marks from './Marks';
import Handle from '../RcHandle';
import * as utils from '../utils';
import Tip from "./Tip";
function noop() {
}
export default function createSlider(Component) {
return class ComponentEnhancer extends Component {
static displayName = `ComponentEnhancer(${Component.displayName})`;
static propTypes = {
...Component.propTypes,
min: PropTypes.number,
max: PropTypes.number,
step: PropTypes.number,
marks: PropTypes.object,
included: PropTypes.bool,
className: PropTypes.string,
prefixCls: PropTypes.string,
disabled: PropTypes.bool,
children: PropTypes.node,
onBeforeChange: PropTypes.func,
onChange: PropTypes.func,
onAfterChange: PropTypes.func,
handle: PropTypes.func,
dots: PropTypes.bool,
vertical: PropTypes.bool,
style: PropTypes.object,
minimumTrackStyle: PropTypes.object, // just for compatibility, will be deperecate
maximumTrackStyle: PropTypes.object, // just for compatibility, will be deperecate
handleStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.arrayOf(PropTypes.object)]),
trackStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.arrayOf(PropTypes.object)]),
railStyle: PropTypes.object,
dotStyle: PropTypes.object,
activeDotStyle: PropTypes.object,
autoFocus: PropTypes.bool,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
};
static defaultProps = {
...Component.defaultProps,
prefixCls: 'rc-slider',
className: '',
min: 0,
max: 100,
step: 1,
marks: {},
handle({index, ...restProps}) {
delete restProps.dragging;
return <Handle {...restProps} key={index}/>;
},
onBeforeChange: noop,
onChange: noop,
onAfterChange: noop,
included: true,
disabled: false,
dots: false,
vertical: false,
trackStyle: [{}],
handleStyle: [{}],
railStyle: {},
dotStyle: {},
activeDotStyle: {},
};
constructor(props) {
super(props);
if (process.env.NODE_ENV !== 'production') {
const {step, max, min} = props;
warning(
step && Math.floor(step) === step ? (max - min) % step === 0 : true,
'Slider[max] - Slider[min] (%s) should be a multiple of Slider[step] (%s)',
max - min,
step
);
}
this.handlesRefs = {};
this.tipPercent = 0;
}
componentWillUnmount() {
if (super.componentWillUnmount) super.componentWillUnmount();
this.removeDocumentEvents();
}
componentDidMount() {
// Snapshot testing cannot handle refs, so be sure to null-check this.
this.document = this.sliderRef && this.sliderRef.ownerDocument;
}
onMouseDown = (e) => {
if (e.button !== 0) {
return;
}
const isVertical = this.props.vertical;
let position = utils.getMousePosition(isVertical, e);
if (!utils.isEventFromHandle(e, this.handlesRefs)) {
this.dragOffset = 0;
} else {
const handlePosition = utils.getHandleCenterPosition(isVertical, e.target);
this.dragOffset = position - handlePosition;
position = handlePosition;
}
this.removeDocumentEvents();
this.onStart(position);
this.addDocumentMouseEvents();
};
onTouchStart = (e) => {
if (utils.isNotTouchEvent(e)) return;
const isVertical = this.props.vertical;
let position = utils.getTouchPosition(isVertical, e);
if (!utils.isEventFromHandle(e, this.handlesRefs)) {
this.dragOffset = 0;
} else {
const handlePosition = utils.getHandleCenterPosition(isVertical, e.target);
this.dragOffset = position - handlePosition;
position = handlePosition;
}
this.onStart(position);
this.addDocumentTouchEvents();
utils.pauseEvent(e);
};
onFocus = (e) => {
const {onFocus, vertical} = this.props;
if (utils.isEventFromHandle(e, this.handlesRefs)) {
const handlePosition = utils.getHandleCenterPosition(vertical, e.target);
this.dragOffset = 0;
this.onStart(handlePosition);
utils.pauseEvent(e);
if (onFocus) {
onFocus(e);
}
}
};
onBlur = (e) => {
const {onBlur} = this.props;
this.onEnd(e);
if (onBlur) {
onBlur(e);
}
};
addDocumentTouchEvents() {
// just work for Chrome iOS Safari and Android Browser
this.onTouchMoveListener = addEventListener(this.document, 'touchmove', this.onTouchMove);
this.onTouchUpListener = addEventListener(this.document, 'touchend', this.onEnd);
}
addDocumentMouseEvents() {
this.onMouseMoveListener = addEventListener(this.document, 'mousemove', this.onMouseMove);
this.onMouseUpListener = addEventListener(this.document, 'mouseup', this.onEnd);
}
removeDocumentEvents() {
/* eslint-disable no-unused-expressions */
this.onTouchMoveListener && this.onTouchMoveListener.remove();
this.onTouchUpListener && this.onTouchUpListener.remove();
this.onMouseMoveListener && this.onMouseMoveListener.remove();
this.onMouseUpListener && this.onMouseUpListener.remove();
/* eslint-enable no-unused-expressions */
}
onMouseUp = () => {
if (this.handlesRefs[this.prevMovedHandleIndex]) {
this.handlesRefs[this.prevMovedHandleIndex].clickFocus();
}
};
onMouseMoveTooltip = (e) => {
this.tipOffset = utils.getMousePosition(this.props.vertical, e) - this.getSliderStart();
this.tipPercent = this.calcValueByPos(utils.getMousePosition(this.props.vertical, e));
this.tipVisible = !(this.tipOffset > this.getSliderLength() || this.tipOffset < 0);
this.forceUpdate();
};
onMouseLeaveTooltip = () => {
this.tipVisible = false;
this.forceUpdate();
};
onMouseEnterTooltip = () => {
this.tipVisible = true;
this.forceUpdate();
};
onMouseMove = (e) => {
if (!this.sliderRef) {
this.onEnd();
return;
}
const position = utils.getMousePosition(this.props.vertical, e);
this.onMove(e, position - this.dragOffset);
};
onTouchMove = (e) => {
if (utils.isNotTouchEvent(e) || !this.sliderRef) {
this.onEnd();
return;
}
const position = utils.getTouchPosition(this.props.vertical, e);
this.onMove(e, position - this.dragOffset);
};
onKeyDown = (e) => {
if (this.sliderRef && utils.isEventFromHandle(e, this.handlesRefs)) {
this.onKeyboard(e);
}
};
focus() {
if (!this.props.disabled) {
this.handlesRefs[0].focus();
}
}
blur() {
if (!this.props.disabled) {
this.handlesRefs[0].blur();
}
}
getSliderStart() {
const slider = this.sliderRef;
const rect = slider.getBoundingClientRect();
return this.props.vertical ? rect.top : rect.left;
}
getSliderLength() {
const slider = this.sliderRef;
if (!slider) {
return 0;
}
const coords = slider.getBoundingClientRect();
return this.props.vertical ? coords.height : coords.width;
}
calcValue(offset) {
const {vertical, min, max} = this.props;
const ratio = Math.abs(Math.max(offset, 0) / this.getSliderLength());
const value = vertical ? (1 - ratio) * (max - min) + min : ratio * (max - min) + min;
return value;
}
calcValueByPos(position) {
const pixelOffset = position - this.getSliderStart();
const nextValue = this.trimAlignValue(this.calcValue(pixelOffset));
return nextValue;
}
calcOffset(value) {
const {min, max} = this.props;
const ratio = (value - min) / (max - min);
return ratio * 100;
}
saveSlider = (slider) => {
this.sliderRef = slider;
};
saveHandle(index, handle) {
this.handlesRefs[index] = handle;
}
onClickMarkLabel = (e, value) => {
e.stopPropagation();
this.onChange({value});
};
render() {
const {
prefixCls,
className,
marks,
dots,
step,
included,
disabled,
vertical,
min,
max,
children,
maximumTrackStyle,
style,
railStyle,
dotStyle,
activeDotStyle,
tipMode,
tipFormatter
} = this.props;
const {tracks, handles} = super.render();
const showTipComponent = !disabled && tipMode === 'all';
let tipComponentListener = {};
if (showTipComponent) {
tipComponentListener = {
onMouseMove: disabled ? noop : this.onMouseMoveTooltip,
onMouseLeave: disabled ? noop : this.onMouseLeaveTooltip,
onMouseEnter: disabled ? noop : this.onMouseEnterTooltip,
};
}
const sliderClassName = classNames(prefixCls, {
[`${prefixCls}-with-marks`]: Object.keys(marks).length,
[`${prefixCls}-disabled`]: disabled,
[`${prefixCls}-vertical`]: vertical,
[className]: className,
});
return (
<div
ref={this.saveSlider}
className={sliderClassName}
{...tipComponentListener}
onTouchStart={disabled ? noop : this.onTouchStart}
onMouseDown={disabled ? noop : this.onMouseDown}
onMouseUp={disabled ? noop : this.onMouseUp}
onKeyDown={disabled ? noop : this.onKeyDown}
onFocus={disabled ? noop : this.onFocus}
onBlur={disabled ? noop : this.onBlur}
style={style}
>
{
// 添加滚动条tooltip功能,tipMode="all"
showTipComponent &&
<Tip
prefixCls={prefixCls}
title={tipFormatter ? tipFormatter(this.tipPercent) : ''}
position={this.tipOffset}
visible={this.tipVisible}
vertical={this.props.vertical}
/>
}
<div
className={`${prefixCls}-rail`}
style={{
...maximumTrackStyle,
...railStyle,
}}
/>
{tracks}
<Steps
prefixCls={prefixCls}
vertical={vertical}
marks={marks}
dots={dots}
step={step}
included={included}
lowerBound={this.getLowerBound()}
upperBound={this.getUpperBound()}
max={max}
min={min}
dotStyle={dotStyle}
activeDotStyle={activeDotStyle}
/>
{handles}
<Marks
className={`${prefixCls}-mark`}
onClickLabel={disabled ? noop : this.onClickMarkLabel}
vertical={vertical}
marks={marks}
included={included}
lowerBound={this.getLowerBound()}
upperBound={this.getUpperBound()}
max={max}
min={min}
/>
{children}
</div>
);
}
};
}
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CSS Reftest Reference</title>
<link rel="author" title="Mirela Budăeș" href="mailto:mbudaes@adobe.com">
<style>
.container{
margin: 30px;
width: 130px;
height: 130px;
float: left;
background: yellow;/*rgb(255,255,0);*/
}
.simple{
background: lime;/* rgb(0,255,0);*/
width: 100px;
height: 100px;
position: fixed;
}
.mixed {
background: red;/*rgb(255,0,0);*/
margin-top: 20px;
margin-left: 20px;
width: 100px;
height: 100px;
}
.overlap {
background: black;/*rgb(0,0,0);*/
width: 80px;
height: 80px;
}
</style>
</head>
<body>
<p>Test passes if there is no complete red square on the screen. <br>
You should see two overlapping lime and red squares on top of a yellow one. <br>
At the intersection of the lime and red squares, a black square will be created. </p>
<div class="container">
<div class="simple">
<div class="mixed">
<div class="overlap"></div>
</div>
</div>
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
module.exports = function (grunt) {
grunt.registerMultiTask('run-test', 'Runs KeeWeb browser-tests', function () {
const done = this.async();
const opt = this.options();
const file = this.files[0].src[0];
const path = require('path');
const puppeteer = require('puppeteer');
(async function () {
grunt.log.writeln('Running tests...');
const fullPath = 'file://' + path.resolve(file);
const browser = await puppeteer.launch({
headless: opt.headless
});
const page = await browser.newPage();
await page.goto(fullPath);
async function check() {
const result = await page.evaluate(() => {
const { output, done } = window;
window.output = [];
return { output, done };
});
for (const out of result.output) {
if (!out.args.length) {
continue;
}
// eslint-disable-next-line no-console
console[out.method](...out.args);
}
if (result.done) {
await browser.close();
const { failures } = result.done;
if (failures) {
grunt.warn(`Failed ${failures} test${failures > 1 ? 's' : ''}.`);
} else {
grunt.log.writeln('All tests passed');
done();
}
} else {
setTimeout(check, 100);
}
}
check();
})();
});
};
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<licenseinfo>
<fileset>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_slideleft_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_scrollright_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_slideleft_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollright_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_restore_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollleft_pressed_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_maximize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_slideleft_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_restore_group_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_maximize_disabled_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_pin_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_slideright_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_popup_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollright_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_pin_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_scrollright_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_restore_group_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_scrollright_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_restore_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollleft_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_maximize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_scrollleft_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_maximize_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_scrollright_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_maximize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_minimize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_pin_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollleft_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_maximize_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollright_pressed_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_minimize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_popup_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_minimize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_slideleft_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_slideleft_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_maximize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_scrollright_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_maximize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_minimize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollright_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_slideleft_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_scrollright_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_minimize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_restore_group_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_scrollright_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_restore_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_minimize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_pin_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_pin_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollleft_rollover_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_maximize_rollover_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_restore_group_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_scrollright_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollright_disabled_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_maximize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_maximize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_popup_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_maximize_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_minimize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_slidebottom_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_restore_group_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_slideleft_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_scrollleft_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_pin_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_minimize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_minimize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_restore_pressed_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_popup_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_maximize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_minimize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_restore_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollright_rollover_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_restore_group_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_restore_group_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_scrollleft_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_slidebottom_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_minimize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollleft_enabled_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_pin_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_slideright_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_slidebottom_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_minimize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_popup_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_popup_pressed_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_restore_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_scrollleft_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_slideleft_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_scrollleft_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_pin_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_slideleft_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_maximize_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_maximize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_popup_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_maximize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_scrollright_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_restore_group_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_pin_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_scrollleft_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_slideright_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_slideright_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_maximize_enabled_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_scrollright_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_slideright_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_popup_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_pin_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/busy_icon.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_restore_group_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_pin_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_popup_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_slideleft_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_maximize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_maximize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_maximize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_restore_rollover_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_scrollleft_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_pin_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_minimize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_minimize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_scrollright_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_scrollleft_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_restore_group_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_minimize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_scrollleft_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_restore_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_minimize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_restore_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_scrollleft_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollleft_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_slidebottom_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_maximize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_restore_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_scrollleft_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_pin_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_popup_enabled_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_restore_group_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_slidebottom_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_restore_group_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_minimize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_restore_group_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_slidebottom_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_popup_disabled_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_scrollright_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_popup_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_scrollleft_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_slideleft_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_restore_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_scrollright_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_popup_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_pin_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_scrollright_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_slideright_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_minimize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_slidebottom_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollright_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_restore_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_scrollleft_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_slideleft_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_restore_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_slideright_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_slideright_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_restore_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_slideright_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_scrollleft_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_popup_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_popup_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_slidebottom_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_restore_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_scrollright_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_pin_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_restore_group_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_restore_group_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_popup_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_minimize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_maximize_pressed_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_minimize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_restore_enabled_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_popup_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_scrollleft_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_maximize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_restore_group_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_slidebottom_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_slidebottom_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_scrollleft_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollright_enabled_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_restore_group_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_slideright_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_popup_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_restore_group_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_slidebottom_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_popup_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_scrollleft_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_restore_group_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_restore_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_maximize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_popup_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_minimize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_scrollright_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_slidebottom_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_restore_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_scrollleft_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_slidebottom_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_restore_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_popup_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_scrollright_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_scrollleft_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollleft_disabled_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_scrollleft_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_minimize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_slideright_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_popup_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_minimize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_maximize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_restore_disabled_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_slidebottom_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_restore_group_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_pin_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_pin_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_maximize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_slidebottom_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_restore_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_popup_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_restore_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_scrollleft_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_scrollleft_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_scrollleft_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_popup_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_restore_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_scrollright_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_slideleft_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_slidebottom_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_scrollright_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_slidebottom_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_scrollright_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_slideleft_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_slideright_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_slideleft_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_slideright_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_maximize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_scrollright_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_scrollleft_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_restore_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_scrollright_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_scrollright_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_scrollright_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_restore_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_minimize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_maximize_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_popup_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_slidebottom_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_maximize_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_slideright_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_pin_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_restore_group_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_slideright_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_popup_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_pin_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_restore_group_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_restore_group_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_slideright_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/gtk_slideleft_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_slideright_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_scrollleft_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_slideright_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_pin_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_popup_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_slideleft_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_popup_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/mac_maximize_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_pin_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_popup_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_popup_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_popup_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/vista_restore_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_scrollright_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_scrollleft_disabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_slideleft_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win8_restore_group_rollover.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/nimbus_popup_rollover_dark.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/xp_restore_enabled.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/win_restore_pressed.png</file>
<file>src/org/netbeans/swing/tabcontrol/resources/metal_maximize_disabled.png</file>
<license ref="Apache-2.0-ASF" />
<comment type="COMMENT_UNSUPPORTED" />
</fileset>
</licenseinfo>
|
{
"pile_set_name": "Github"
}
|
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Server config checks management
*
* @package PhpMyAdmin
*/
declare(strict_types=1);
namespace PhpMyAdmin\Config;
use PhpMyAdmin\Config\ConfigFile;
use PhpMyAdmin\Config\Descriptions;
use PhpMyAdmin\Core;
use PhpMyAdmin\Sanitize;
use PhpMyAdmin\Setup\Index as SetupIndex;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
/**
* Performs various compatibility, security and consistency checks on current config
*
* Outputs results to message list, must be called between SetupIndex::messagesBegin()
* and SetupIndex::messagesEnd()
*
* @package PhpMyAdmin
*/
class ServerConfigChecks
{
/**
* @var ConfigFile configurations being checked
*/
protected $cfg;
/**
* Constructor.
*
* @param ConfigFile $cfg Configuration
*/
public function __construct(ConfigFile $cfg)
{
$this->cfg = $cfg;
}
/**
* Perform config checks
*
* @return void
*/
public function performConfigChecks()
{
$blowfishSecret = $this->cfg->get('blowfish_secret');
$blowfishSecretSet = false;
$cookieAuthUsed = false;
list($cookieAuthUsed, $blowfishSecret, $blowfishSecretSet)
= $this->performConfigChecksServers(
$cookieAuthUsed,
$blowfishSecret,
$blowfishSecretSet
);
$this->performConfigChecksCookieAuthUsed(
$cookieAuthUsed,
$blowfishSecretSet,
$blowfishSecret
);
//
// $cfg['AllowArbitraryServer']
// should be disabled
//
if ($this->cfg->getValue('AllowArbitraryServer')) {
$sAllowArbitraryServerWarn = sprintf(
__(
'This %soption%s should be disabled as it allows attackers to '
. 'bruteforce login to any MySQL server. If you feel this is necessary, '
. 'use %srestrict login to MySQL server%s or %strusted proxies list%s. '
. 'However, IP-based protection with trusted proxies list may not be '
. 'reliable if your IP belongs to an ISP where thousands of users, '
. 'including you, are connected to.'
),
'[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
'[/a]',
'[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
'[/a]',
'[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
'[/a]'
);
SetupIndex::messagesSet(
'notice',
'AllowArbitraryServer',
Descriptions::get('AllowArbitraryServer'),
Sanitize::sanitizeMessage($sAllowArbitraryServerWarn)
);
}
$this->performConfigChecksLoginCookie();
$sDirectoryNotice = __(
'This value should be double checked to ensure that this directory is '
. 'neither world accessible nor readable or writable by other users on '
. 'your server.'
);
//
// $cfg['SaveDir']
// should not be world-accessible
//
if ($this->cfg->getValue('SaveDir') != '') {
SetupIndex::messagesSet(
'notice',
'SaveDir',
Descriptions::get('SaveDir'),
Sanitize::sanitizeMessage($sDirectoryNotice)
);
}
//
// $cfg['TempDir']
// should not be world-accessible
//
if ($this->cfg->getValue('TempDir') != '') {
SetupIndex::messagesSet(
'notice',
'TempDir',
Descriptions::get('TempDir'),
Sanitize::sanitizeMessage($sDirectoryNotice)
);
}
$this->performConfigChecksZips();
}
/**
* Check config of servers
*
* @param boolean $cookieAuthUsed Cookie auth is used
* @param string $blowfishSecret Blowfish secret
* @param boolean $blowfishSecretSet Blowfish secret set
*
* @return array
*/
protected function performConfigChecksServers(
$cookieAuthUsed,
$blowfishSecret,
$blowfishSecretSet
) {
$serverCnt = $this->cfg->getServerCount();
for ($i = 1; $i <= $serverCnt; $i++) {
$cookieAuthServer
= ($this->cfg->getValue("Servers/$i/auth_type") == 'cookie');
$cookieAuthUsed |= $cookieAuthServer;
$serverName = $this->performConfigChecksServersGetServerName(
$this->cfg->getServerName($i),
$i
);
$serverName = htmlspecialchars($serverName);
list($blowfishSecret, $blowfishSecretSet)
= $this->performConfigChecksServersSetBlowfishSecret(
$blowfishSecret,
$cookieAuthServer,
$blowfishSecretSet
);
//
// $cfg['Servers'][$i]['ssl']
// should be enabled if possible
//
if (! $this->cfg->getValue("Servers/$i/ssl")) {
$title = Descriptions::get('Servers/1/ssl') . " ($serverName)";
SetupIndex::messagesSet(
'notice',
"Servers/$i/ssl",
$title,
__(
'You should use SSL connections if your database server '
. 'supports it.'
)
);
}
$sSecurityInfoMsg = Sanitize::sanitizeMessage(sprintf(
__(
'If you feel this is necessary, use additional protection settings - '
. '%1$shost authentication%2$s settings and %3$strusted proxies list%4%s. '
. 'However, IP-based protection may not be reliable if your IP belongs '
. 'to an ISP where thousands of users, including you, are connected to.'
),
'[a@' . Url::getCommon(['page' => 'servers', 'mode' => 'edit', 'id' => $i]) . '#tab_Server_config]',
'[/a]',
'[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
'[/a]'
));
//
// $cfg['Servers'][$i]['auth_type']
// warn about full user credentials if 'auth_type' is 'config'
//
if ($this->cfg->getValue("Servers/$i/auth_type") == 'config'
&& $this->cfg->getValue("Servers/$i/user") != ''
&& $this->cfg->getValue("Servers/$i/password") != ''
) {
$title = Descriptions::get('Servers/1/auth_type')
. " ($serverName)";
SetupIndex::messagesSet(
'notice',
"Servers/$i/auth_type",
$title,
Sanitize::sanitizeMessage(sprintf(
__(
'You set the [kbd]config[/kbd] authentication type and included '
. 'username and password for auto-login, which is not a desirable '
. 'option for live hosts. Anyone who knows or guesses your phpMyAdmin '
. 'URL can directly access your phpMyAdmin panel. Set %1$sauthentication '
. 'type%2$s to [kbd]cookie[/kbd] or [kbd]http[/kbd].'
),
'[a@' . Url::getCommon(['page' => 'servers', 'mode' => 'edit', 'id' => $i]) . '#tab_Server]',
'[/a]'
))
. ' ' . $sSecurityInfoMsg
);
}
//
// $cfg['Servers'][$i]['AllowRoot']
// $cfg['Servers'][$i]['AllowNoPassword']
// serious security flaw
//
if ($this->cfg->getValue("Servers/$i/AllowRoot")
&& $this->cfg->getValue("Servers/$i/AllowNoPassword")
) {
$title = Descriptions::get('Servers/1/AllowNoPassword')
. " ($serverName)";
SetupIndex::messagesSet(
'notice',
"Servers/$i/AllowNoPassword",
$title,
__('You allow for connecting to the server without a password.')
. ' ' . $sSecurityInfoMsg
);
}
}
return [
$cookieAuthUsed,
$blowfishSecret,
$blowfishSecretSet,
];
}
/**
* Set blowfish secret
*
* @param string $blowfishSecret Blowfish secret
* @param boolean $cookieAuthServer Cookie auth is used
* @param boolean $blowfishSecretSet Blowfish secret set
*
* @return array
*/
protected function performConfigChecksServersSetBlowfishSecret(
$blowfishSecret,
$cookieAuthServer,
$blowfishSecretSet
) {
if ($cookieAuthServer && $blowfishSecret === null) {
$blowfishSecretSet = true;
$this->cfg->set('blowfish_secret', Util::generateRandom(32));
}
return [
$blowfishSecret,
$blowfishSecretSet,
];
}
/**
* Define server name
*
* @param string $serverName Server name
* @param int $serverId Server id
*
* @return string Server name
*/
protected function performConfigChecksServersGetServerName(
$serverName,
$serverId
) {
if ($serverName == 'localhost') {
$serverName .= " [$serverId]";
return $serverName;
}
return $serverName;
}
/**
* Perform config checks for zip part.
*
* @return void
*/
protected function performConfigChecksZips()
{
$this->performConfigChecksServerGZipdump();
$this->performConfigChecksServerBZipdump();
$this->performConfigChecksServersZipdump();
}
/**
* Perform config checks for zip part.
*
* @return void
*/
protected function performConfigChecksServersZipdump()
{
//
// $cfg['ZipDump']
// requires zip_open in import
//
if ($this->cfg->getValue('ZipDump') && ! $this->functionExists('zip_open')) {
SetupIndex::messagesSet(
'error',
'ZipDump_import',
Descriptions::get('ZipDump'),
Sanitize::sanitizeMessage(sprintf(
__(
'%sZip decompression%s requires functions (%s) which are unavailable '
. 'on this system.'
),
'[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Import_export]',
'[/a]',
'zip_open'
))
);
}
//
// $cfg['ZipDump']
// requires gzcompress in export
//
if ($this->cfg->getValue('ZipDump') && ! $this->functionExists('gzcompress')) {
SetupIndex::messagesSet(
'error',
'ZipDump_export',
Descriptions::get('ZipDump'),
Sanitize::sanitizeMessage(sprintf(
__(
'%sZip compression%s requires functions (%s) which are unavailable on '
. 'this system.'
),
'[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Import_export]',
'[/a]',
'gzcompress'
))
);
}
}
/**
* Check config of servers
*
* @param boolean $cookieAuthUsed Cookie auth is used
* @param boolean $blowfishSecretSet Blowfish secret set
* @param string $blowfishSecret Blowfish secret
*
* @return void
*/
protected function performConfigChecksCookieAuthUsed(
$cookieAuthUsed,
$blowfishSecretSet,
$blowfishSecret
) {
//
// $cfg['blowfish_secret']
// it's required for 'cookie' authentication
//
if ($cookieAuthUsed) {
if ($blowfishSecretSet) {
// 'cookie' auth used, blowfish_secret was generated
SetupIndex::messagesSet(
'notice',
'blowfish_secret_created',
Descriptions::get('blowfish_secret'),
Sanitize::sanitizeMessage(__(
'You didn\'t have blowfish secret set and have enabled '
. '[kbd]cookie[/kbd] authentication, so a key was automatically '
. 'generated for you. It is used to encrypt cookies; you don\'t need to '
. 'remember it.'
))
);
} else {
$blowfishWarnings = [];
// check length
if (strlen($blowfishSecret) < 32) {
// too short key
$blowfishWarnings[] = __(
'Key is too short, it should have at least 32 characters.'
);
}
// check used characters
$hasDigits = (bool) preg_match('/\d/', $blowfishSecret);
$hasChars = (bool) preg_match('/\S/', $blowfishSecret);
$hasNonword = (bool) preg_match('/\W/', $blowfishSecret);
if (! $hasDigits || ! $hasChars || ! $hasNonword) {
$blowfishWarnings[] = Sanitize::sanitizeMessage(
__(
'Key should contain letters, numbers [em]and[/em] '
. 'special characters.'
)
);
}
if (! empty($blowfishWarnings)) {
SetupIndex::messagesSet(
'error',
'blowfish_warnings' . count($blowfishWarnings),
Descriptions::get('blowfish_secret'),
implode('<br>', $blowfishWarnings)
);
}
}
}
}
/**
* Check configuration for login cookie
*
* @return void
*/
protected function performConfigChecksLoginCookie()
{
//
// $cfg['LoginCookieValidity']
// value greater than session.gc_maxlifetime will cause
// random session invalidation after that time
$loginCookieValidity = $this->cfg->getValue('LoginCookieValidity');
if ($loginCookieValidity > ini_get('session.gc_maxlifetime')
) {
SetupIndex::messagesSet(
'error',
'LoginCookieValidity',
Descriptions::get('LoginCookieValidity'),
Sanitize::sanitizeMessage(sprintf(
__(
'%1$sLogin cookie validity%2$s greater than %3$ssession.gc_maxlifetime%4$s may '
. 'cause random session invalidation (currently session.gc_maxlifetime '
. 'is %5$d).'
),
'[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
'[/a]',
'[a@' . Core::getPHPDocLink('session.configuration.php#ini.session.gc-maxlifetime') . ']',
'[/a]',
ini_get('session.gc_maxlifetime')
))
);
}
//
// $cfg['LoginCookieValidity']
// should be at most 1800 (30 min)
//
if ($loginCookieValidity > 1800) {
SetupIndex::messagesSet(
'notice',
'LoginCookieValidity',
Descriptions::get('LoginCookieValidity'),
Sanitize::sanitizeMessage(sprintf(
__(
'%sLogin cookie validity%s should be set to 1800 seconds (30 minutes) '
. 'at most. Values larger than 1800 may pose a security risk such as '
. 'impersonation.'
),
'[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
'[/a]'
))
);
}
//
// $cfg['LoginCookieValidity']
// $cfg['LoginCookieStore']
// LoginCookieValidity must be less or equal to LoginCookieStore
//
if (($this->cfg->getValue('LoginCookieStore') != 0)
&& ($loginCookieValidity > $this->cfg->getValue('LoginCookieStore'))
) {
SetupIndex::messagesSet(
'error',
'LoginCookieValidity',
Descriptions::get('LoginCookieValidity'),
Sanitize::sanitizeMessage(sprintf(
__(
'If using [kbd]cookie[/kbd] authentication and %sLogin cookie store%s '
. 'is not 0, %sLogin cookie validity%s must be set to a value less or '
. 'equal to it.'
),
'[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
'[/a]',
'[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
'[/a]'
))
);
}
}
/**
* Check GZipDump configuration
*
* @return void
*/
protected function performConfigChecksServerBZipdump()
{
//
// $cfg['BZipDump']
// requires bzip2 functions
//
if ($this->cfg->getValue('BZipDump')
&& (! $this->functionExists('bzopen') || ! $this->functionExists('bzcompress'))
) {
$functions = $this->functionExists('bzopen')
? '' :
'bzopen';
$functions .= $this->functionExists('bzcompress')
? ''
: ($functions ? ', ' : '') . 'bzcompress';
SetupIndex::messagesSet(
'error',
'BZipDump',
Descriptions::get('BZipDump'),
Sanitize::sanitizeMessage(
sprintf(
__(
'%1$sBzip2 compression and decompression%2$s requires functions (%3$s) which '
. 'are unavailable on this system.'
),
'[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Import_export]',
'[/a]',
$functions
)
)
);
}
}
/**
* Check GZipDump configuration
*
* @return void
*/
protected function performConfigChecksServerGZipdump()
{
//
// $cfg['GZipDump']
// requires zlib functions
//
if ($this->cfg->getValue('GZipDump')
&& (! $this->functionExists('gzopen') || ! $this->functionExists('gzencode'))
) {
SetupIndex::messagesSet(
'error',
'GZipDump',
Descriptions::get('GZipDump'),
Sanitize::sanitizeMessage(sprintf(
__(
'%1$sGZip compression and decompression%2$s requires functions (%3$s) which '
. 'are unavailable on this system.'
),
'[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Import_export]',
'[/a]',
'gzencode'
))
);
}
}
/**
* Wrapper around function_exists to allow mock in test
*
* @param string $name Function name
*
* @return boolean
*/
protected function functionExists($name)
{
return function_exists($name);
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8" ?>
<plugin pluginId="Gallio.AutoCAD"
recommendedInstallationPath="AutoCAD"
xmlns="http://www.gallio.org/">
<traits>
<name>AutoCAD Integration Plugin</name>
<version>3.2.0.0</version>
<description>Provides support for testing ObjectARX extensions within AutoCAD.</description>
<icon>plugin://Gallio.AutoCAD/Resources/Gallio.AutoCAD.ico</icon>
</traits>
<dependencies>
<dependency pluginId="Gallio" />
</dependencies>
<files>
<file path="Gallio.AutoCAD.plugin" />
<file path="Gallio.AutoCAD.dll" />
<file path="Gallio.AutoCAD.Plugin.dll" />
<file path="Resources\Gallio.AutoCAD.ico" />
</files>
<assemblies>
<assembly fullName="Gallio.AutoCAD, Version=3.2.0.0, Culture=neutral, PublicKeyToken=eb9cfa67ee6ab36e"
codeBase="Gallio.AutoCAD.dll"
qualifyPartialName="true" />
</assemblies>
<services>
<service serviceId="Gallio.AutoCAD.AcadLocator"
serviceType="Gallio.AutoCAD.IAcadLocator, Gallio.AutoCAD" />
<service serviceId="Gallio.AutoCAD.Preferences.AcadPreferenceManager"
serviceType="Gallio.AutoCAD.Preferences.IAcadPreferenceManager, Gallio.AutoCAD" />
<service serviceId="Gallio.AutoCAD.ProcessManagement.AcadProcessFactory"
serviceType="Gallio.AutoCAD.ProcessManagement.IAcadProcessFactory, Gallio.AutoCAD" />
</services>
<components>
<component componentId="Gallio.AutoCAD.AcadLocator"
serviceId="Gallio.AutoCAD.AcadLocator"
componentType="Gallio.AutoCAD.AcadLocator, Gallio.AutoCAD" />
<component componentId="Gallio.AutoCAD.Preferences.AcadPreferenceManager"
serviceId="Gallio.AutoCAD.Preferences.AcadPreferenceManager"
componentType="Gallio.AutoCAD.Preferences.AcadPreferenceManager, Gallio.AutoCAD" />
<component componentId="Gallio.AutoCAD.ProcessManagement.AcadProcessFactory"
serviceId="Gallio.AutoCAD.ProcessManagement.AcadProcessFactory"
componentType="Gallio.AutoCAD.ProcessManagement.AcadProcessFactory, Gallio.AutoCAD" />
<component componentId="AutoCAD.AcadTestRunnerFactory"
serviceId="Gallio.TestRunnerFactory"
componentType="Gallio.Runner.DefaultTestRunnerFactory, Gallio">
<parameters>
<testIsolationProvider>${AutoCAD.AcadTestIsolationProvider}</testIsolationProvider>
</parameters>
<traits>
<name>AutoCAD</name>
<description>
Runs tests within an AutoCAD process.
Supported test runner properties:
- AcadAttachToExisting: If "true" attaches to an existing AutoCAD process, otherwise starts a new one.
- AcadExePath: Specifies the full path of the "acad.exe" program.
</description>
</traits>
</component>
<component componentId="AutoCAD.AcadTestIsolationProvider"
serviceId="Gallio.TestIsolationProvider"
componentType="Gallio.AutoCAD.Isolation.AcadTestIsolationProvider, Gallio.AutoCAD" />
</components>
</plugin>
|
{
"pile_set_name": "Github"
}
|
require File.dirname(__FILE__) + '/../test_helper'
require 'pictures_controller'
# Re-raise errors caught by the controller.
class PicturesController; def rescue_action(e) raise e end; end
class PicturesControllerTest < Test::Unit::TestCase
def setup
@controller = PicturesController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@account = Account.find(:first)
end
def test_show_pictures_for_current_account_only
@alt_account = Account.new; @alt_account.expires_at = 5.minutes.from_now; @alt_account.save!
picture = returning(Picture.build(uploaded_file('1.jpg'))) do |pict|
pict.update_attributes(:account => @alt_account, :public => true)
end
assert_raises(ActiveRecord::RecordNotFound) do
get :retrieve, :id => picture.id, :mime_type => 'image/jpeg', :format => 'JPEG'
end
end
def test_show_public_picture_to_anyone
p = Picture.build_picture_from_local_file(File.join(RAILS_ROOT, 'test', 'fixtures', 'pictures', '1.jpg'))
p.update_attributes!(:account => @account, :public => true)
get :retrieve, :id => p.id, :mime_type => 'image/jpeg', :format => 'JPEG'
assert_response :success
assert_match %r{image/jpeg}, @response.headers['Content-Type']
assert_match /^public/, @response.headers['Cache-Control']
assert_match /inline/, @response.headers['Content-Disposition']
assert_match /#{p.filename}/, @response.headers['Content-Disposition']
end
def test_allow_retrieve_private_picture_to_authenticated_user
p = Picture.build_picture_from_local_file(File.join(RAILS_ROOT, 'test', 'fixtures', 'pictures', '1.jpg'))
p.update_attributes!(:account => @account)
login!(:bob)
get :retrieve, :id => p.id, :mime_type => 'image/jpeg', :format => 'JPEG'
assert_response :success
assert_match %r{image/jpeg}, @response.headers['Content-Type']
assert_match /^private/, @response.headers['Cache-Control']
assert_match /inline/, @response.headers['Content-Disposition']
assert_match /#{p.filename}/, @response.headers['Content-Disposition']
end
def test_dont_show_private_picture_to_unauthenticated_user
p = Picture.build_picture_from_local_file(File.join(RAILS_ROOT, 'test', 'fixtures', 'pictures', '1.jpg'))
p.update_attributes!(:account => @account)
assert !p.public?, 'Picture should be private by default'
get :retrieve, :id => p.id, :mime_type => 'image/jpeg', :format => 'JPEG'
assert_match /not found/i, @response.body
assert_response :missing
end
end
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.