text
stringlengths 2
99.9k
| meta
dict |
---|---|
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0700"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForAnalyzing = "YES"
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES">
<BuildableReference
BuildableIdentifier = 'primary'
BlueprintIdentifier = 'FF36E126DC830C4A4E5647AE06C9B70E'
BlueprintName = 'SIOSocket'
ReferencedContainer = 'container:Pods.xcodeproj'
BuildableName = 'libSIOSocket.a'>
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
buildConfiguration = "Debug"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES"
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
| {
"pile_set_name": "Github"
} |
zzz = storage(xxx)
| {
"pile_set_name": "Github"
} |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Reliability
{
class DoReconfigurationMessageBody : public ConfigurationMessageBody
{
public:
DoReconfigurationMessageBody() :
phase0Duration_(Common::TimeSpan::MaxValue)
{}
DoReconfigurationMessageBody(
Reliability::FailoverUnitDescription const & fudesc,
Reliability::ServiceDescription const & serviceDesc,
std::vector<Reliability::ReplicaDescription> && replicas) :
ConfigurationMessageBody(fudesc, serviceDesc, std::move(replicas)),
phase0Duration_(Common::TimeSpan::MaxValue)
{
}
DoReconfigurationMessageBody(
Reliability::FailoverUnitDescription const & fudesc,
Reliability::ServiceDescription const & serviceDesc,
std::vector<Reliability::ReplicaDescription> && replicas,
Common::TimeSpan phase0Duration) :
ConfigurationMessageBody(fudesc, serviceDesc, std::move(replicas)),
phase0Duration_(phase0Duration)
{
}
__declspec(property(get = get_Phase0Duration)) Common::TimeSpan Phase0Duration;
Common::TimeSpan get_Phase0Duration() const { return phase0Duration_; }
void WriteTo(Common::TextWriter& w, Common::FormatOptions const&) const;
void WriteToEtw(uint16 contextSequenceId) const;
FABRIC_FIELDS_01(phase0Duration_);
private:
Common::TimeSpan phase0Duration_;
};
}
| {
"pile_set_name": "Github"
} |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TSTypeAnnotation = TSTypeAnnotation;
exports.TSTypeParameterDeclaration = exports.TSTypeParameterInstantiation = TSTypeParameterInstantiation;
exports.TSTypeParameter = TSTypeParameter;
exports.TSParameterProperty = TSParameterProperty;
exports.TSDeclareFunction = TSDeclareFunction;
exports.TSDeclareMethod = TSDeclareMethod;
exports.TSQualifiedName = TSQualifiedName;
exports.TSCallSignatureDeclaration = TSCallSignatureDeclaration;
exports.TSConstructSignatureDeclaration = TSConstructSignatureDeclaration;
exports.TSPropertySignature = TSPropertySignature;
exports.tsPrintPropertyOrMethodName = tsPrintPropertyOrMethodName;
exports.TSMethodSignature = TSMethodSignature;
exports.TSIndexSignature = TSIndexSignature;
exports.TSAnyKeyword = TSAnyKeyword;
exports.TSUnknownKeyword = TSUnknownKeyword;
exports.TSNumberKeyword = TSNumberKeyword;
exports.TSObjectKeyword = TSObjectKeyword;
exports.TSBooleanKeyword = TSBooleanKeyword;
exports.TSStringKeyword = TSStringKeyword;
exports.TSSymbolKeyword = TSSymbolKeyword;
exports.TSVoidKeyword = TSVoidKeyword;
exports.TSUndefinedKeyword = TSUndefinedKeyword;
exports.TSNullKeyword = TSNullKeyword;
exports.TSNeverKeyword = TSNeverKeyword;
exports.TSThisType = TSThisType;
exports.TSFunctionType = TSFunctionType;
exports.TSConstructorType = TSConstructorType;
exports.tsPrintFunctionOrConstructorType = tsPrintFunctionOrConstructorType;
exports.TSTypeReference = TSTypeReference;
exports.TSTypePredicate = TSTypePredicate;
exports.TSTypeQuery = TSTypeQuery;
exports.TSTypeLiteral = TSTypeLiteral;
exports.tsPrintTypeLiteralOrInterfaceBody = tsPrintTypeLiteralOrInterfaceBody;
exports.tsPrintBraced = tsPrintBraced;
exports.TSArrayType = TSArrayType;
exports.TSTupleType = TSTupleType;
exports.TSOptionalType = TSOptionalType;
exports.TSRestType = TSRestType;
exports.TSUnionType = TSUnionType;
exports.TSIntersectionType = TSIntersectionType;
exports.tsPrintUnionOrIntersectionType = tsPrintUnionOrIntersectionType;
exports.TSConditionalType = TSConditionalType;
exports.TSInferType = TSInferType;
exports.TSParenthesizedType = TSParenthesizedType;
exports.TSTypeOperator = TSTypeOperator;
exports.TSIndexedAccessType = TSIndexedAccessType;
exports.TSMappedType = TSMappedType;
exports.TSLiteralType = TSLiteralType;
exports.TSExpressionWithTypeArguments = TSExpressionWithTypeArguments;
exports.TSInterfaceDeclaration = TSInterfaceDeclaration;
exports.TSInterfaceBody = TSInterfaceBody;
exports.TSTypeAliasDeclaration = TSTypeAliasDeclaration;
exports.TSAsExpression = TSAsExpression;
exports.TSTypeAssertion = TSTypeAssertion;
exports.TSEnumDeclaration = TSEnumDeclaration;
exports.TSEnumMember = TSEnumMember;
exports.TSModuleDeclaration = TSModuleDeclaration;
exports.TSModuleBlock = TSModuleBlock;
exports.TSImportType = TSImportType;
exports.TSImportEqualsDeclaration = TSImportEqualsDeclaration;
exports.TSExternalModuleReference = TSExternalModuleReference;
exports.TSNonNullExpression = TSNonNullExpression;
exports.TSExportAssignment = TSExportAssignment;
exports.TSNamespaceExportDeclaration = TSNamespaceExportDeclaration;
exports.tsPrintSignatureDeclarationBase = tsPrintSignatureDeclarationBase;
function TSTypeAnnotation(node) {
this.token(":");
this.space();
if (node.optional) this.token("?");
this.print(node.typeAnnotation, node);
}
function TSTypeParameterInstantiation(node) {
this.token("<");
this.printList(node.params, node, {});
this.token(">");
}
function TSTypeParameter(node) {
this.word(node.name);
if (node.constraint) {
this.space();
this.word("extends");
this.space();
this.print(node.constraint, node);
}
if (node.default) {
this.space();
this.token("=");
this.space();
this.print(node.default, node);
}
}
function TSParameterProperty(node) {
if (node.accessibility) {
this.word(node.accessibility);
this.space();
}
if (node.readonly) {
this.word("readonly");
this.space();
}
this._param(node.parameter);
}
function TSDeclareFunction(node) {
if (node.declare) {
this.word("declare");
this.space();
}
this._functionHead(node);
this.token(";");
}
function TSDeclareMethod(node) {
this._classMethodHead(node);
this.token(";");
}
function TSQualifiedName(node) {
this.print(node.left, node);
this.token(".");
this.print(node.right, node);
}
function TSCallSignatureDeclaration(node) {
this.tsPrintSignatureDeclarationBase(node);
}
function TSConstructSignatureDeclaration(node) {
this.word("new");
this.space();
this.tsPrintSignatureDeclarationBase(node);
}
function TSPropertySignature(node) {
const {
readonly,
initializer
} = node;
if (readonly) {
this.word("readonly");
this.space();
}
this.tsPrintPropertyOrMethodName(node);
this.print(node.typeAnnotation, node);
if (initializer) {
this.space();
this.token("=");
this.space();
this.print(initializer, node);
}
this.token(";");
}
function tsPrintPropertyOrMethodName(node) {
if (node.computed) {
this.token("[");
}
this.print(node.key, node);
if (node.computed) {
this.token("]");
}
if (node.optional) {
this.token("?");
}
}
function TSMethodSignature(node) {
this.tsPrintPropertyOrMethodName(node);
this.tsPrintSignatureDeclarationBase(node);
this.token(";");
}
function TSIndexSignature(node) {
const {
readonly
} = node;
if (readonly) {
this.word("readonly");
this.space();
}
this.token("[");
this._parameters(node.parameters, node);
this.token("]");
this.print(node.typeAnnotation, node);
this.token(";");
}
function TSAnyKeyword() {
this.word("any");
}
function TSUnknownKeyword() {
this.word("unknown");
}
function TSNumberKeyword() {
this.word("number");
}
function TSObjectKeyword() {
this.word("object");
}
function TSBooleanKeyword() {
this.word("boolean");
}
function TSStringKeyword() {
this.word("string");
}
function TSSymbolKeyword() {
this.word("symbol");
}
function TSVoidKeyword() {
this.word("void");
}
function TSUndefinedKeyword() {
this.word("undefined");
}
function TSNullKeyword() {
this.word("null");
}
function TSNeverKeyword() {
this.word("never");
}
function TSThisType() {
this.word("this");
}
function TSFunctionType(node) {
this.tsPrintFunctionOrConstructorType(node);
}
function TSConstructorType(node) {
this.word("new");
this.space();
this.tsPrintFunctionOrConstructorType(node);
}
function tsPrintFunctionOrConstructorType(node) {
const {
typeParameters,
parameters
} = node;
this.print(typeParameters, node);
this.token("(");
this._parameters(parameters, node);
this.token(")");
this.space();
this.token("=>");
this.space();
this.print(node.typeAnnotation.typeAnnotation, node);
}
function TSTypeReference(node) {
this.print(node.typeName, node);
this.print(node.typeParameters, node);
}
function TSTypePredicate(node) {
this.print(node.parameterName);
this.space();
this.word("is");
this.space();
this.print(node.typeAnnotation.typeAnnotation);
}
function TSTypeQuery(node) {
this.word("typeof");
this.space();
this.print(node.exprName);
}
function TSTypeLiteral(node) {
this.tsPrintTypeLiteralOrInterfaceBody(node.members, node);
}
function tsPrintTypeLiteralOrInterfaceBody(members, node) {
this.tsPrintBraced(members, node);
}
function tsPrintBraced(members, node) {
this.token("{");
if (members.length) {
this.indent();
this.newline();
for (const member of members) {
this.print(member, node);
this.newline();
}
this.dedent();
this.rightBrace();
} else {
this.token("}");
}
}
function TSArrayType(node) {
this.print(node.elementType, node);
this.token("[]");
}
function TSTupleType(node) {
this.token("[");
this.printList(node.elementTypes, node);
this.token("]");
}
function TSOptionalType(node) {
this.print(node.typeAnnotation, node);
this.token("?");
}
function TSRestType(node) {
this.token("...");
this.print(node.typeAnnotation, node);
}
function TSUnionType(node) {
this.tsPrintUnionOrIntersectionType(node, "|");
}
function TSIntersectionType(node) {
this.tsPrintUnionOrIntersectionType(node, "&");
}
function tsPrintUnionOrIntersectionType(node, sep) {
this.printJoin(node.types, node, {
separator() {
this.space();
this.token(sep);
this.space();
}
});
}
function TSConditionalType(node) {
this.print(node.checkType);
this.space();
this.word("extends");
this.space();
this.print(node.extendsType);
this.space();
this.token("?");
this.space();
this.print(node.trueType);
this.space();
this.token(":");
this.space();
this.print(node.falseType);
}
function TSInferType(node) {
this.token("infer");
this.space();
this.print(node.typeParameter);
}
function TSParenthesizedType(node) {
this.token("(");
this.print(node.typeAnnotation, node);
this.token(")");
}
function TSTypeOperator(node) {
this.token(node.operator);
this.space();
this.print(node.typeAnnotation, node);
}
function TSIndexedAccessType(node) {
this.print(node.objectType, node);
this.token("[");
this.print(node.indexType, node);
this.token("]");
}
function TSMappedType(node) {
const {
readonly,
typeParameter,
optional
} = node;
this.token("{");
this.space();
if (readonly) {
tokenIfPlusMinus(this, readonly);
this.word("readonly");
this.space();
}
this.token("[");
this.word(typeParameter.name);
this.space();
this.word("in");
this.space();
this.print(typeParameter.constraint, typeParameter);
this.token("]");
if (optional) {
tokenIfPlusMinus(this, optional);
this.token("?");
}
this.token(":");
this.space();
this.print(node.typeAnnotation, node);
this.space();
this.token("}");
}
function tokenIfPlusMinus(self, tok) {
if (tok !== true) {
self.token(tok);
}
}
function TSLiteralType(node) {
this.print(node.literal, node);
}
function TSExpressionWithTypeArguments(node) {
this.print(node.expression, node);
this.print(node.typeParameters, node);
}
function TSInterfaceDeclaration(node) {
const {
declare,
id,
typeParameters,
extends: extendz,
body
} = node;
if (declare) {
this.word("declare");
this.space();
}
this.word("interface");
this.space();
this.print(id, node);
this.print(typeParameters, node);
if (extendz) {
this.space();
this.word("extends");
this.space();
this.printList(extendz, node);
}
this.space();
this.print(body, node);
}
function TSInterfaceBody(node) {
this.tsPrintTypeLiteralOrInterfaceBody(node.body, node);
}
function TSTypeAliasDeclaration(node) {
const {
declare,
id,
typeParameters,
typeAnnotation
} = node;
if (declare) {
this.word("declare");
this.space();
}
this.word("type");
this.space();
this.print(id, node);
this.print(typeParameters, node);
this.space();
this.token("=");
this.space();
this.print(typeAnnotation, node);
this.token(";");
}
function TSAsExpression(node) {
const {
expression,
typeAnnotation
} = node;
this.print(expression, node);
this.space();
this.word("as");
this.space();
this.print(typeAnnotation, node);
}
function TSTypeAssertion(node) {
const {
typeAnnotation,
expression
} = node;
this.token("<");
this.print(typeAnnotation, node);
this.token(">");
this.space();
this.print(expression, node);
}
function TSEnumDeclaration(node) {
const {
declare,
const: isConst,
id,
members
} = node;
if (declare) {
this.word("declare");
this.space();
}
if (isConst) {
this.word("const");
this.space();
}
this.word("enum");
this.space();
this.print(id, node);
this.space();
this.tsPrintBraced(members, node);
}
function TSEnumMember(node) {
const {
id,
initializer
} = node;
this.print(id, node);
if (initializer) {
this.space();
this.token("=");
this.space();
this.print(initializer, node);
}
this.token(",");
}
function TSModuleDeclaration(node) {
const {
declare,
id
} = node;
if (declare) {
this.word("declare");
this.space();
}
if (!node.global) {
this.word(id.type === "Identifier" ? "namespace" : "module");
this.space();
}
this.print(id, node);
if (!node.body) {
this.token(";");
return;
}
let body = node.body;
while (body.type === "TSModuleDeclaration") {
this.token(".");
this.print(body.id, body);
body = body.body;
}
this.space();
this.print(body, node);
}
function TSModuleBlock(node) {
this.tsPrintBraced(node.body, node);
}
function TSImportType(node) {
const {
argument,
qualifier,
typeParameters
} = node;
this.word("import");
this.token("(");
this.print(argument, node);
this.token(")");
if (qualifier) {
this.token(".");
this.print(qualifier, node);
}
if (typeParameters) {
this.print(typeParameters, node);
}
}
function TSImportEqualsDeclaration(node) {
const {
isExport,
id,
moduleReference
} = node;
if (isExport) {
this.word("export");
this.space();
}
this.word("import");
this.space();
this.print(id, node);
this.space();
this.token("=");
this.space();
this.print(moduleReference, node);
this.token(";");
}
function TSExternalModuleReference(node) {
this.token("require(");
this.print(node.expression, node);
this.token(")");
}
function TSNonNullExpression(node) {
this.print(node.expression, node);
this.token("!");
}
function TSExportAssignment(node) {
this.word("export");
this.space();
this.token("=");
this.space();
this.print(node.expression, node);
this.token(";");
}
function TSNamespaceExportDeclaration(node) {
this.word("export");
this.space();
this.word("as");
this.space();
this.word("namespace");
this.space();
this.print(node.id, node);
}
function tsPrintSignatureDeclarationBase(node) {
const {
typeParameters,
parameters
} = node;
this.print(typeParameters, node);
this.token("(");
this._parameters(parameters, node);
this.token(")");
this.print(node.typeAnnotation, node);
} | {
"pile_set_name": "Github"
} |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-320-1.js
* @description Object.defineProperty - 'O' is an Arguments object of a function that has formal parameters, 'P' is own data property of 'O', test TypeError is thrown when updating the [[Configurable]] attribute value of 'P' which is not configurable (10.6 [[DefineOwnProperty]] step 4)
*/
function testcase() {
return (function (a, b, c) {
Object.defineProperty(arguments, "genericProperty", {
configurable: false
});
try {
Object.defineProperty(arguments, "genericProperty", {
configurable: true
});
} catch (e) {
return e instanceof TypeError &&
dataPropertyAttributesAreCorrect(arguments, "genericProperty", undefined, false, false, false);
}
return false;
}(1, 2, 3));
}
runTestCase(testcase);
| {
"pile_set_name": "Github"
} |
// #Regression #Conformance #ObjectOrientedTypes #InterfacesAndImplementations
type IFoo<'a> =
interface
abstract DoStuff : unit -> string
end
type Bar() =
interface IFoo<string> with
member this.DoStuff() = "IFoo<string>"
interface IFoo<int64> with
member this.DoStuff() = "IFoo<int64>"
| {
"pile_set_name": "Github"
} |
Bob,Jones,444223333,28
Tom,Allen,324001232,33
Jesse,Baker,555443333,21 | {
"pile_set_name": "Github"
} |
1
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
1 3 4 3 2 1 1
1 4 5 5 3 2 1 1
1 4 7 6 5 3 2 1 1
1 5 8 9 7 5 3 2 1 1
1 5 10 11 10 7 5 3 2 1 1
1 6 12 15 13 11 7 5 3 2 1 1
1 6 14 18 18 14 11 7 5 3 2 1 1
1 7 16 23 23 20 15 11 7 5 3 2 1 1
1 7 19 27 30 26 21 15 11 7 5 3 2 1 1
1 8 21 34 37 35 28 22 15 11 7 5 3 2 1 1
1 8 24 39 47 44 38 29 22 15 11 7 5 3 2 1 1
1 9 27 47 57 58 49 40 30 22 15 11 7 5 3 2 1 1
1 9 30 54 70 71 65 52 41 30 22 15 11 7 5 3 2 1 1
1 10 33 64 84 90 82 70 54 42 30 22 15 11 7 5 3 2 1 1
1255
2552338241
| {
"pile_set_name": "Github"
} |
/*
HydraBus/HydraNFC - Copyright (C) 2015 Nicolas OBERLI
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.
*/
#include "bsp_can.h"
#include "bsp_can_conf.h"
#include "stm32.h"
/*
Warning in order to use this driver all GPIOs peripherals shall be enabled.
*/
#define CANx_TIMEOUT_MAX (100000) // About 10sec (see common/chconf.h/CH_CFG_ST_FREQUENCY) can be aborted by UBTN too
#define NB_CAN (BSP_DEV_CAN_END)
static CAN_HandleTypeDef can_handle[NB_CAN];
static mode_config_proto_t* can_mode_conf[NB_CAN];
/**
* @brief Init low level hardware: GPIO, CLOCK, NVIC...
* @param dev_num: CAN dev num
* @retval None
*/
static void can_gpio_hw_init(bsp_dev_can_t dev_num)
{
GPIO_InitTypeDef GPIO_InitStructure;
__CAN1_CLK_ENABLE();
if(dev_num == BSP_DEV_CAN1) {
/* Enable the CAN peripheral */
GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;
GPIO_InitStructure.Pull = GPIO_NOPULL;
GPIO_InitStructure.Speed = BSP_CAN1_GPIO_SPEED;
GPIO_InitStructure.Alternate = BSP_CAN1_AF;
/* CAN1 TX pin configuration */
GPIO_InitStructure.Pin = BSP_CAN1_TX_PIN;
HAL_GPIO_Init(BSP_CAN1_TX_PORT, &GPIO_InitStructure);
/* CAN1 RX pin configuration */
GPIO_InitStructure.Pin = BSP_CAN1_RX_PIN;
HAL_GPIO_Init(BSP_CAN1_RX_PORT, &GPIO_InitStructure);
} else {
/* Enable the CAN peripheral */
__CAN2_CLK_ENABLE();
GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;
GPIO_InitStructure.Pull = GPIO_NOPULL;
GPIO_InitStructure.Speed = BSP_CAN2_GPIO_SPEED;
GPIO_InitStructure.Alternate = BSP_CAN2_AF;
/* CAN2 TX pin configuration */
GPIO_InitStructure.Pin = BSP_CAN2_TX_PIN;
HAL_GPIO_Init(BSP_CAN2_TX_PORT, &GPIO_InitStructure);
/* CAN2 RX pin configuration */
GPIO_InitStructure.Pin = BSP_CAN2_RX_PIN;
HAL_GPIO_Init(BSP_CAN2_RX_PORT, &GPIO_InitStructure);
}
}
/**
* @brief DeInit low level hardware: GPIO, CLOCK, NVIC...
* @param dev_num: CAN dev num
* @retval None
*/
static void can_gpio_hw_deinit(bsp_dev_can_t dev_num)
{
if(dev_num == BSP_DEV_CAN1) {
/* Reset peripherals */
__CAN1_FORCE_RESET();
__CAN1_RELEASE_RESET();
__CAN1_CLK_DISABLE();
/* Disable peripherals GPIO */
HAL_GPIO_DeInit(BSP_CAN1_TX_PORT, BSP_CAN1_TX_PIN);
HAL_GPIO_DeInit(BSP_CAN1_RX_PORT, BSP_CAN1_RX_PIN);
} else {
/* Reset peripherals */
__CAN2_FORCE_RESET();
__CAN2_RELEASE_RESET();
__CAN2_CLK_DISABLE();
/* Disable peripherals GPIO */
HAL_GPIO_DeInit(BSP_CAN2_TX_PORT, BSP_CAN2_TX_PIN);
HAL_GPIO_DeInit(BSP_CAN2_RX_PORT, BSP_CAN2_RX_PIN);
}
}
/**
* @brief CANx error treatment function.
* @param dev_num: CAN dev num
* @retval None
*/
static void can_error(bsp_dev_can_t dev_num)
{
if(bsp_can_deinit(dev_num) == BSP_OK) {
/* Re-Initialize the CAN comunication
* bus */
can_gpio_hw_init(dev_num);
bsp_can_init(dev_num, can_mode_conf[dev_num]);
bsp_can_init_filter(dev_num, can_mode_conf[dev_num]);
}
}
/**
* @brief CANx bus speed setting
* @param dev_num: CAN dev num
* @param speed: CAN dev speed in bps
* @retval status: status of the init.
*/
bsp_status_t bsp_can_set_speed(bsp_dev_can_t dev_num, uint32_t speed)
{
CAN_HandleTypeDef* hcan;
bsp_status_t status;
hcan = &can_handle[dev_num];
HAL_CAN_DeInit(hcan);
hcan->Init.Prescaler = 2000000/speed;
HAL_CAN_Stop(hcan);
status = (bsp_status_t) HAL_CAN_Init(hcan);
HAL_CAN_Start(hcan);
return status;
}
uint32_t bsp_can_get_speed(bsp_dev_can_t dev_num)
{
CAN_HandleTypeDef* hcan;
hcan = &can_handle[dev_num];
return 2000000/hcan->Init.Prescaler;
}
/**
* @brief CANx bus timing settings
* @param dev_num: CAN dev num
* @param ts1: Time setting 1
* @param ts2: Time setting 2
* @param sjw: Resynchronization Jump Width
* @retval status: status of the init.
*/
bsp_status_t bsp_can_set_timings(bsp_dev_can_t dev_num, mode_config_proto_t* mode_conf)
{
CAN_HandleTypeDef* hcan;
bsp_status_t status;
hcan = &can_handle[dev_num];
HAL_CAN_DeInit(hcan);
hcan->Init.TimeSeg1 = mode_conf->config.can.dev_timing&0xf0000;
hcan->Init.TimeSeg2 = mode_conf->config.can.dev_timing&0x700000;
hcan->Init.SyncJumpWidth = mode_conf->config.can.dev_timing&0x3000000;
HAL_CAN_Stop(hcan);
status = (bsp_status_t) HAL_CAN_Init(hcan);
HAL_CAN_Start(hcan);
return status;
}
bsp_status_t bsp_can_set_ts1(bsp_dev_can_t dev_num, mode_config_proto_t* mode_conf, uint8_t ts1)
{
CAN_HandleTypeDef* hcan;
bsp_status_t status;
hcan = &can_handle[dev_num];
HAL_CAN_DeInit(hcan);
hcan->Init.TimeSeg1 = (uint32_t)(ts1-1)<<16;
HAL_CAN_Stop(hcan);
status = (bsp_status_t) HAL_CAN_Init(hcan);
HAL_CAN_Start(hcan);
mode_conf->config.can.dev_timing = bsp_can_get_timings(dev_num);
return status;
}
bsp_status_t bsp_can_set_ts2(bsp_dev_can_t dev_num, mode_config_proto_t* mode_conf, uint8_t ts2)
{
CAN_HandleTypeDef* hcan;
bsp_status_t status;
hcan = &can_handle[dev_num];
HAL_CAN_DeInit(hcan);
hcan->Init.TimeSeg2 = (uint32_t)(ts2-1)<<20;
HAL_CAN_Stop(hcan);
status = (bsp_status_t) HAL_CAN_Init(hcan);
HAL_CAN_Start(hcan);
mode_conf->config.can.dev_timing = bsp_can_get_timings(dev_num);
return status;
}
bsp_status_t bsp_can_set_sjw(bsp_dev_can_t dev_num, mode_config_proto_t* mode_conf, uint8_t sjw)
{
CAN_HandleTypeDef* hcan;
bsp_status_t status;
hcan = &can_handle[dev_num];
HAL_CAN_DeInit(hcan);
hcan->Init.SyncJumpWidth = (uint32_t)(sjw-1)<<24;
HAL_CAN_Stop(hcan);
status = (bsp_status_t) HAL_CAN_Init(hcan);
HAL_CAN_Start(hcan);
mode_conf->config.can.dev_timing = bsp_can_get_timings(dev_num);
return status;
}
uint32_t bsp_can_get_timings(bsp_dev_can_t dev_num)
{
CAN_HandleTypeDef* hcan;
hcan = &can_handle[dev_num];
return hcan->Instance->BTR;
}
bsp_status_t bsp_can_mode_rw(bsp_dev_can_t dev_num, mode_config_proto_t* mode_conf)
{
CAN_HandleTypeDef* hcan;
bsp_status_t status;
hcan = &can_handle[dev_num];
HAL_CAN_DeInit(hcan);
mode_conf->config.can.dev_mode = BSP_CAN_MODE_RW;
hcan->Init.Mode = CAN_MODE_NORMAL;
status = (bsp_status_t) HAL_CAN_Init(hcan);
HAL_CAN_Start(hcan);
return status;
}
/**
* @brief Init CAN device.
* @param dev_num: CAN dev num.
* @param mode_conf: Mode config proto.
* @retval status: status of the init.
*/
bsp_status_t bsp_can_init(bsp_dev_can_t dev_num, mode_config_proto_t* mode_conf)
{
CAN_HandleTypeDef* hcan;
bsp_status_t status;
can_mode_conf[dev_num] = mode_conf;
hcan = &can_handle[dev_num];
can_gpio_hw_init(dev_num);
if(dev_num == BSP_DEV_CAN1) {
hcan->Instance = BSP_CAN1;
HAL_CAN_DeInit(hcan);
} else { /* CAN2 */
hcan->Instance = BSP_CAN2;
HAL_CAN_DeInit(hcan);
}
__HAL_CAN_RESET_HANDLE_STATE(hcan);
/* CAN cell init */
/* time triggered communication mode */
hcan->Init.TimeTriggeredMode = DISABLE;
/* automatic bus-off management */
hcan->Init.AutoBusOff = ENABLE;
/* automatic wake-up mode */
hcan->Init.AutoWakeUp = ENABLE;
/* non-automatic retransmission mode */
hcan->Init.AutoRetransmission = ENABLE;
/* receive FIFO Locked mode */
hcan->Init.ReceiveFifoLocked = DISABLE;
/* transmit FIFO priority */
hcan->Init.TransmitFifoPriority = DISABLE;
if(mode_conf->config.can.dev_mode == BSP_CAN_MODE_RO) {
hcan->Init.Mode = CAN_MODE_SILENT;
} else {
hcan->Init.Mode = CAN_MODE_NORMAL;
}
/* CAN timing values */
hcan->Init.TimeSeg1 = mode_conf->config.can.dev_timing&0xf0000;
hcan->Init.TimeSeg2 = mode_conf->config.can.dev_timing&0x700000;
hcan->Init.SyncJumpWidth = mode_conf->config.can.dev_timing&0x3000000;
/* CAN Baudrate */
hcan->Init.Prescaler = 2000000/mode_conf->config.can.dev_speed;
HAL_CAN_Stop(hcan);
status = (bsp_status_t) HAL_CAN_Init(hcan);
HAL_CAN_Start(hcan);
return status;
}
/**
* @brief Init CAN device filter to capture all
* @param dev_num: CAN dev num.
* @param mode_conf: Mode config proto.
* @retval status: status of the init.
*/
bsp_status_t bsp_can_init_filter(bsp_dev_can_t dev_num, mode_config_proto_t* mode_conf)
{
CAN_FilterTypeDef hcanfilter;
CAN_HandleTypeDef* hcan;
can_mode_conf[dev_num] = mode_conf;
hcan = &can_handle[dev_num];
bsp_status_t status;
hcanfilter.FilterIdLow = 0;
hcanfilter.FilterIdHigh = 0;
hcanfilter.FilterMaskIdHigh = 0;
hcanfilter.FilterMaskIdLow = 0;
hcanfilter.FilterFIFOAssignment = CAN_FILTER_FIFO0;
hcanfilter.FilterBank = 14*dev_num;
hcanfilter.FilterMode = CAN_FILTERMODE_IDMASK;
hcanfilter.FilterScale = CAN_FILTERSCALE_16BIT;
hcanfilter.FilterActivation = ENABLE;
hcanfilter.SlaveStartFilterBank = 14;
HAL_CAN_Stop(hcan);
status = (bsp_status_t) HAL_CAN_ConfigFilter(hcan, &hcanfilter);
HAL_CAN_Start(hcan);
return status;
}
/**
* @brief Set CAN device filter by ID
* @param dev_num: CAN dev num.
* @param mode_conf: Mode config proto.
* @param id_low: Lower ID to capture
* @param id_high: Higher ID to capture
* @retval status: status of the init.
*/
bsp_status_t bsp_can_set_filter(bsp_dev_can_t dev_num,
mode_config_proto_t* mode_conf,
uint32_t id_low, uint32_t id_high)
{
CAN_FilterTypeDef hcanfilter;
CAN_HandleTypeDef* hcan;
can_mode_conf[dev_num] = mode_conf;
hcan = &can_handle[dev_num];
bsp_status_t status;
hcanfilter.FilterIdLow = id_low<<5;
hcanfilter.FilterIdHigh = id_high<<5;
hcanfilter.FilterMaskIdHigh = 0;
hcanfilter.FilterMaskIdLow = 0;
hcanfilter.FilterFIFOAssignment = CAN_FILTER_FIFO0;
hcanfilter.FilterBank = 14*dev_num;
hcanfilter.FilterMode = CAN_FILTERMODE_IDLIST;
hcanfilter.FilterScale = CAN_FILTERSCALE_16BIT;
hcanfilter.FilterActivation = ENABLE;
hcanfilter.SlaveStartFilterBank = 14;
status = (bsp_status_t) HAL_CAN_ConfigFilter(hcan, &hcanfilter);
return status;
}
/**
* @brief De-initialize the CAN comunication bus
* @param dev_num: CAN dev num.
* @retval status: status of the deinit.
*/
bsp_status_t bsp_can_deinit(bsp_dev_can_t dev_num)
{
CAN_HandleTypeDef* hcan;
bsp_status_t status;
hcan = &can_handle[dev_num];
/* Stop the CAN controller */
HAL_CAN_Stop(hcan);
/* De-initialize the CAN comunication bus */
status = (bsp_status_t) HAL_CAN_DeInit(hcan);
/* DeInit the low level hardware: GPIO, CLOCK, NVIC... */
can_gpio_hw_deinit(dev_num);
return status;
}
/**
* @brief Sends a message in blocking mode and return the status.
* @param dev_num: CAN dev num.
* @param tx_msg: Message to send
* @retval status of the transfer.
*/
bsp_status_t bsp_can_write(bsp_dev_can_t dev_num, can_tx_frame* tx_msg)
{
CAN_HandleTypeDef* hcan;
bsp_status_t status;
uint32_t dummy;
uint32_t start_time;
hcan = &can_handle[dev_num];
start_time = HAL_GetTick();
while(HAL_CAN_GetTxMailboxesFreeLevel(hcan) == 0) {
if((HAL_GetTick()-start_time) > CANx_TIMEOUT_MAX) {
return BSP_TIMEOUT;
}
}
status = (bsp_status_t) HAL_CAN_AddTxMessage(hcan, &(tx_msg->header), tx_msg->data, &dummy);
switch(status) {
case BSP_ERROR:
can_error(dev_num);
break;
case BSP_OK:
case BSP_TIMEOUT:
case BSP_BUSY:
default:
return status;
}
return status;
}
/**
* @brief Read a message in blocking mode and return the status.
* @param dev_num: CAN dev num.
* @param rx_msg: Message to receive.
* @retval status of the transfer.
*/
bsp_status_t bsp_can_read(bsp_dev_can_t dev_num, can_rx_frame* rx_msg)
{
CAN_HandleTypeDef* hcan;
bsp_status_t status;
uint32_t start_time;
hcan = &can_handle[dev_num];
start_time = HAL_GetTick();
while(HAL_CAN_GetRxFifoFillLevel(hcan, CAN_RX_FIFO0) == 0) {
if((HAL_GetTick()-start_time) > CANx_TIMEOUT_MAX) {
return BSP_TIMEOUT;
}
}
status = (bsp_status_t) HAL_CAN_GetRxMessage(hcan, CAN_RX_FIFO0, &(rx_msg->header), rx_msg->data);
switch(status) {
case BSP_ERROR:
can_error(dev_num);
break;
case BSP_OK:
case BSP_TIMEOUT:
case BSP_BUSY:
default:
return status;
}
return status;
}
/**
* @brief Checks if the CAN receive buffer is empty
* @retval Number of messages in the FIFO
*/
bsp_status_t bsp_can_rxne(bsp_dev_can_t dev_num)
{
CAN_HandleTypeDef* hcan;
hcan = &can_handle[dev_num];
return HAL_CAN_GetRxFifoFillLevel(hcan, CAN_RX_FIFO0);
}
| {
"pile_set_name": "Github"
} |
//递归求年龄
# include <iostream>
using namespace std;
int age(int n)
{
int c;
if(n==1) //递归结束的条件
return 10;
else
c=age(n-1)+2; //调用自身
return c;
}
int main()
{
cout<<age(5)<<' ';
system("pause");
return 0;
}
| {
"pile_set_name": "Github"
} |
import { InputValue } from '../inputValue/interface';
import { SdlDirective } from '../interface';
export enum SdlFieldType {
SCALAR = 'SCALAR',
CUSTOM_SCALAR = 'CUSTOM_SCALAR',
ENUM = 'ENUM',
OBJECT = 'OBJECT',
}
export interface SdlField {
getTypeName(): string;
getFieldType(): SdlFieldType;
isNonNull(): boolean;
isList(): boolean;
isItemNonNull(): boolean;
getDescription(): string;
getDirective(name: string): SdlDirective;
getDirectives(): Record<string, SdlDirective>;
}
| {
"pile_set_name": "Github"
} |
sat
| {
"pile_set_name": "Github"
} |
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file alias="qlua.png">images/torch.png</file>
</qresource>
</RCC>
| {
"pile_set_name": "Github"
} |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v1.0.6-b27-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.06.11 at 10:33:54 AM PDT
//
package com.sun.identity.liberty.ws.common.jaxb.soap;
/**
* Java content class for Fault element declaration.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/Users/allan/A-SVN/trunk/opensso/products/federation/library/xsd/liberty/soap.xsd line 127)
* <p>
* <pre>
* <element name="Fault" type="{http://schemas.xmlsoap.org/soap/envelope/}FaultType"/>
* </pre>
*
*/
public interface FaultElement
extends javax.xml.bind.Element, com.sun.identity.liberty.ws.common.jaxb.soap.FaultType
{
}
| {
"pile_set_name": "Github"
} |
var baseTimes = require('./_baseTimes'),
castFunction = require('./_castFunction'),
toInteger = require('./toInteger');
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Invokes the iteratee `n` times, returning an array of the results of
* each invocation. The iteratee is invoked with one argument; (index).
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of results.
* @example
*
* _.times(3, String);
* // => ['0', '1', '2']
*
* _.times(4, _.constant(0));
* // => [0, 0, 0, 0]
*/
function times(n, iteratee) {
n = toInteger(n);
if (n < 1 || n > MAX_SAFE_INTEGER) {
return [];
}
var index = MAX_ARRAY_LENGTH,
length = nativeMin(n, MAX_ARRAY_LENGTH);
iteratee = castFunction(iteratee);
n -= MAX_ARRAY_LENGTH;
var result = baseTimes(length, iteratee);
while (++index < n) {
iteratee(index);
}
return result;
}
module.exports = times;
| {
"pile_set_name": "Github"
} |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Api;
use Magento\Tax\Api\Data\TaxRateInterface;
/**
* Interface for managing tax rates.
* @api
* @since 100.0.2
*/
interface TaxRateManagementInterface
{
/**
* Get rates by customerTaxClassId and productTaxClassId
*
* @param int $customerTaxClassId
* @param int $productTaxClassId
* @return TaxRateInterface[]
*/
public function getRatesByCustomerAndProductTaxClassId($customerTaxClassId, $productTaxClassId);
}
| {
"pile_set_name": "Github"
} |
---
id: 5dbba70e6ef5fe3a704f8498
title: Part 130
challengeType: 0
isHidden: true
---
## Description
<section id='description'>
On every attack, there should be a small chance that the player's weapon breaks. At the end of the `attack` function, add an empty `if` expression with the condition `Math.random() <= .1`.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: See description above for instructions.
testString: assert(attack.toString().replace(/\s/g, '').includes('if(Math.random()<=.1){}') || isMonsterHit.toString().replace(/\s/g, '').includes('if(Math.random()<=0.1){}'));
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='html-seed'>
```html
<script>
let xp = 0;
let health = 100;
let gold = 50;
let currentWeapon = 0;
let fighting;
let monsterHealth;
let inventory = ["stick"];
const button1 = document.querySelector('#button1');
const button2 = document.querySelector("#button2");
const button3 = document.querySelector("#button3");
const text = document.querySelector("#text");
const xpText = document.querySelector("#xpText");
const healthText = document.querySelector("#healthText");
const goldText = document.querySelector("#goldText");
const monsterStats = document.querySelector("#monsterStats");
const monsterNameText = document.querySelector("#monsterName");
const monsterHealthText = document.querySelector("#monsterHealth");
const weapons = [
{
name: "stick",
power: 5
},
{
name: "dagger",
power: 30
},
{
name: "claw hammer",
power: 50
},
{
name: "sword",
power: 100
}
];
const monsters = [
{
name: "slime",
level: 2,
health: 15
},
{
name: "fanged beast",
level: 8,
health: 60
},
{
name: "dragon",
level: 20,
health: 300
}
];
const locations = [
{
name: "town square",
"button text": ["Go to store", "Go to cave", "Fight dragon"],
"button functions": [goStore, goCave, fightDragon],
text: "You are in the town square. You see a sign that says \"Store.\""
},
{
name: "store",
"button text": ["Buy 10 health (10 gold)", "Buy weapon (30 gold)", "Go to town square"],
"button functions": [buyHealth, buyWeapon, goTown],
text: "You enter the store."
},
{
name: "cave",
"button text": ["Fight slime", "Fight fanged beast", "Go to town square"],
"button functions": [fightSlime, fightBeast, goTown],
text: "You enter the cave. You see some monsters."
},
{
name: "fight",
"button text": ["Attack", "Dodge", "Run"],
"button functions": [attack, dodge, goTown],
text: "You are fighting a monster."
},
{
name: "kill monster",
"button text": ["Go to town square", "Go to town square", "Go to town square"],
"button functions": [goTown, goTown, goTown],
text: 'The monster screams "Arg!" as it dies. You gain experience points and find gold.'
},
{
name: "lose",
"button text": ["REPLAY?", "REPLAY?", "REPLAY?"],
"button functions": [restart, restart, restart],
text: "You die. ☠️"
},
{
name: "win",
"button text": ["Fight slime", "Fight fanged beast", "Go to town square"],
"button functions": [restart, restart, restart],
text: "You defeat the dragon! YOU WIN THE GAME! 🎉"
}
];
// initialize buttons
button1.onclick = goStore;
button2.onclick = goCave;
button3.onclick = fightDragon;
function update(location) {
monsterStats.style.display = "none";
button1.innerText = location["button text"][0];
button2.innerText = location["button text"][1];
button3.innerText = location["button text"][2];
button1.onclick = location["button functions"][0];
button2.onclick = location["button functions"][1];
button3.onclick = location["button functions"][2];
text.innerText = location.text;
}
function goTown() {
update(locations[0]);
}
function goStore() {
update(locations[1]);
}
function goCave() {
update(locations[2]);
}
function buyHealth() {
if (gold >= 10) {
gold -= 10;
health += 10;
goldText.innerText = gold;
healthText.innerText = health;
} else {
text.innerText = "You do not have enough gold to buy health.";
}
}
function buyWeapon() {
if (currentWeapon < weapons.length - 1) {
if (gold >= 30) {
gold -= 30;
currentWeapon++;
goldText.innerText = gold;
let newWeapon = weapons[currentWeapon].name;
text.innerText = "You now have a " + newWeapon + ".";
inventory.push(newWeapon);
text.innerText += " In your inventory you have: " + inventory;
} else {
text.innerText = "You do not have enough gold to buy a weapon.";
}
} else {
text.innerText = "You already have the most powerful weapon!";
button2.innerText = "Sell weapon for 15 gold";
button2.onclick = sellWeapon;
}
}
function sellWeapon() {
if (inventory.length > 1) {
gold += 15;
goldText.innerText = gold;
let currentWeapon = inventory.shift();
text.innerText = "You sold a " + currentWeapon + ".";
text.innerText += " In your inventory you have: " + inventory;
} else {
text.innerText = "Don't sell your only weapon!";
}
}
function fightSlime() {
fighting = 0;
goFight();
}
function fightBeast() {
fighting = 1;
goFight();
}
function fightDragon() {
fighting = 2;
goFight();
}
function goFight() {
update(locations[3]);
monsterHealth = monsters[fighting].health;
monsterStats.style.display = "block";
monsterNameText.innerText = monsters[fighting].name;
monsterHealthText.innerText = monsterHealth;
}
function attack() {
text.innerText = "The " + monsters[fighting].name + " attacks.";
text.innerText += " You attack it with your " + weapons[currentWeapon].name + ".";
health -= getMonsterAttackValue(monsters[fighting].level);
if (isMonsterHit()) {
monsterHealth -= weapons[currentWeapon].power + Math.floor(Math.random() * xp) + 1;
} else {
text.innerText += " You miss.";
}
healthText.innerText = health;
monsterHealthText.innerText = monsterHealth;
if (health <= 0) {
lose();
} else if (monsterHealth <= 0) {
fighting === 2 ? winGame() : defeatMonster();
}
}
function getMonsterAttackValue(level) {
const hit = (level * 5) - (Math.floor(Math.random() * xp));
console.log(hit);
return hit > 0 ? hit : 0;
}
function isMonsterHit() {
return Math.random() > .2 || health < 20;
}
function dodge() {
text.innerText = "You dodge the attack from the " + monsters[fighting].name + ".";
}
function defeatMonster() {
gold += Math.floor(monsters[fighting].level * 6.7);
xp += monsters[fighting].level;
goldText.innerText = gold;
xpText.innerText = xp;
update(locations[4]);
}
function lose() {
update(locations[5]);
}
function winGame() {
update(locations[6]);
}
function restart() {
xp = 0;
health = 100;
gold = 50;
currentWeapon = 0;
inventory = ["stick"];
goldText.innerText = gold;
healthText.innerText = health;
xpText.innerText = xp;
goTown();
}
</script>
```
</div>
### Before Test
<div id='html-setup'>
```html
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>RPG - Dragon Repeller</title>
<style>
body {
background-color: darkblue;
}
#text {
background-color: black;
color: white;
padding: 10px;
}
#game {
max-width: 500px;
max-height: 400px;
background-color: lightgray;
color: white;
margin: 0 auto;
padding: 10px;
}
#controls {
border: 1px black solid;
padding: 5px;
}
#stats {
border: 1px black solid;
color: black;
padding: 5px;
}
#monsterStats {
display: none;
border: 1px black solid;
color: white;
padding: 5px;
background-color: red;
}
.stat {
padding-right: 10px;
}
</style>
</head>
<body>
<div id="game">
<div id="stats">
<span class="stat">XP: <strong><span id="xpText">0</span></strong></span>
<span class="stat">Health: <strong><span id="healthText">100</span></strong></span>
<span class="stat">Gold: <strong><span id="goldText">50</span></strong></span>
</div>
<div id="controls">
<button id="button1">Go to store</button>
<button id="button2">Go to cave</button>
<button id="button3">Fight dragon</button>
</div>
<div id="monsterStats">
<span class="stat">Monster Name: <strong><span id="monsterName"></span></strong></span>
<span class="stat">Health: <strong><span id="monsterHealth"></span></strong></span>
</div>
<div id="text">Welcome to Dragon Repeller. You must defeat the dragon that is preventing people from leaving the town. You are in the town square. Where do you want to go? Use the buttons above.</div>
</div>
```
</div>
### After Test
<div id='html-teardown'>
```html
</body>
</html>
```
</div>
</section>
## Solution
<section id='solution'>
```html
<script>
let xp = 0;
let health = 100;
let gold = 50;
let currentWeapon = 0;
let fighting;
let monsterHealth;
let inventory = ["stick"];
const button1 = document.querySelector('#button1');
const button2 = document.querySelector("#button2");
const button3 = document.querySelector("#button3");
const text = document.querySelector("#text");
const xpText = document.querySelector("#xpText");
const healthText = document.querySelector("#healthText");
const goldText = document.querySelector("#goldText");
const monsterStats = document.querySelector("#monsterStats");
const monsterNameText = document.querySelector("#monsterName");
const monsterHealthText = document.querySelector("#monsterHealth");
const weapons = [
{
name: "stick",
power: 5
},
{
name: "dagger",
power: 30
},
{
name: "claw hammer",
power: 50
},
{
name: "sword",
power: 100
}
];
const monsters = [
{
name: "slime",
level: 2,
health: 15
},
{
name: "fanged beast",
level: 8,
health: 60
},
{
name: "dragon",
level: 20,
health: 300
}
];
const locations = [
{
name: "town square",
"button text": ["Go to store", "Go to cave", "Fight dragon"],
"button functions": [goStore, goCave, fightDragon],
text: "You are in the town square. You see a sign that says \"Store.\""
},
{
name: "store",
"button text": ["Buy 10 health (10 gold)", "Buy weapon (30 gold)", "Go to town square"],
"button functions": [buyHealth, buyWeapon, goTown],
text: "You enter the store."
},
{
name: "cave",
"button text": ["Fight slime", "Fight fanged beast", "Go to town square"],
"button functions": [fightSlime, fightBeast, goTown],
text: "You enter the cave. You see some monsters."
},
{
name: "fight",
"button text": ["Attack", "Dodge", "Run"],
"button functions": [attack, dodge, goTown],
text: "You are fighting a monster."
},
{
name: "kill monster",
"button text": ["Go to town square", "Go to town square", "Go to town square"],
"button functions": [goTown, goTown, goTown],
text: 'The monster screams "Arg!" as it dies. You gain experience points and find gold.'
},
{
name: "lose",
"button text": ["REPLAY?", "REPLAY?", "REPLAY?"],
"button functions": [restart, restart, restart],
text: "You die. ☠️"
},
{
name: "win",
"button text": ["Fight slime", "Fight fanged beast", "Go to town square"],
"button functions": [restart, restart, restart],
text: "You defeat the dragon! YOU WIN THE GAME! 🎉"
}
];
// initialize buttons
button1.onclick = goStore;
button2.onclick = goCave;
button3.onclick = fightDragon;
function update(location) {
monsterStats.style.display = "none";
button1.innerText = location["button text"][0];
button2.innerText = location["button text"][1];
button3.innerText = location["button text"][2];
button1.onclick = location["button functions"][0];
button2.onclick = location["button functions"][1];
button3.onclick = location["button functions"][2];
text.innerText = location.text;
}
function goTown() {
update(locations[0]);
}
function goStore() {
update(locations[1]);
}
function goCave() {
update(locations[2]);
}
function buyHealth() {
if (gold >= 10) {
gold -= 10;
health += 10;
goldText.innerText = gold;
healthText.innerText = health;
} else {
text.innerText = "You do not have enough gold to buy health.";
}
}
function buyWeapon() {
if (currentWeapon < weapons.length - 1) {
if (gold >= 30) {
gold -= 30;
currentWeapon++;
goldText.innerText = gold;
let newWeapon = weapons[currentWeapon].name;
text.innerText = "You now have a " + newWeapon + ".";
inventory.push(newWeapon);
text.innerText += " In your inventory you have: " + inventory;
} else {
text.innerText = "You do not have enough gold to buy a weapon.";
}
} else {
text.innerText = "You already have the most powerful weapon!";
button2.innerText = "Sell weapon for 15 gold";
button2.onclick = sellWeapon;
}
}
function sellWeapon() {
if (inventory.length > 1) {
gold += 15;
goldText.innerText = gold;
let currentWeapon = inventory.shift();
text.innerText = "You sold a " + currentWeapon + ".";
text.innerText += " In your inventory you have: " + inventory;
} else {
text.innerText = "Don't sell your only weapon!";
}
}
function fightSlime() {
fighting = 0;
goFight();
}
function fightBeast() {
fighting = 1;
goFight();
}
function fightDragon() {
fighting = 2;
goFight();
}
function goFight() {
update(locations[3]);
monsterHealth = monsters[fighting].health;
monsterStats.style.display = "block";
monsterNameText.innerText = monsters[fighting].name;
monsterHealthText.innerText = monsterHealth;
}
function attack() {
text.innerText = "The " + monsters[fighting].name + " attacks.";
text.innerText += " You attack it with your " + weapons[currentWeapon].name + ".";
health -= getMonsterAttackValue(monsters[fighting].level);
if (isMonsterHit()) {
monsterHealth -= weapons[currentWeapon].power + Math.floor(Math.random() * xp) + 1;
} else {
text.innerText += " You miss.";
}
healthText.innerText = health;
monsterHealthText.innerText = monsterHealth;
if (health <= 0) {
lose();
} else if (monsterHealth <= 0) {
fighting === 2 ? winGame() : defeatMonster();
}
if (Math.random() <= .1) {
}
}
function getMonsterAttackValue(level) {
const hit = (level * 5) - (Math.floor(Math.random() * xp));
return hit > 0 ? hit : 0;
}
function isMonsterHit() {
return Math.random() > .2 || health < 20;
}
function dodge() {
text.innerText = "You dodge the attack from the " + monsters[fighting].name + ".";
}
function defeatMonster() {
gold += Math.floor(monsters[fighting].level * 6.7);
xp += monsters[fighting].level;
goldText.innerText = gold;
xpText.innerText = xp;
update(locations[4]);
}
function lose() {
update(locations[5]);
}
function winGame() {
update(locations[6]);
}
function restart() {
xp = 0;
health = 100;
gold = 50;
currentWeapon = 0;
inventory = ["stick"];
goldText.innerText = gold;
healthText.innerText = health;
xpText.innerText = xp;
goTown();
}
</script>
```
</section>
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2018 Netflix, Inc.
*
* 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.
*/
package com.netflix.titus.master.agent;
import java.util.Map;
/**
* An entity containing information about a Titus agent.
*/
public class TitusAgent {
private final String id;
private final String ipAddress;
private final Map<String, String> attributes;
public TitusAgent(String id, String ipAddress, Map<String, String> attributes) {
this.id = id;
this.ipAddress = ipAddress;
this.attributes = attributes;
}
public String getId() {
return id;
}
public String getIpAddress() {
return ipAddress;
}
public Map<String, String> getAttributes() {
return attributes;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TitusAgent that = (TitusAgent) o;
if (id != null ? !id.equals(that.id) : that.id != null) {
return false;
}
if (ipAddress != null ? !ipAddress.equals(that.ipAddress) : that.ipAddress != null) {
return false;
}
return attributes != null ? attributes.equals(that.attributes) : that.attributes == null;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (ipAddress != null ? ipAddress.hashCode() : 0);
result = 31 * result + (attributes != null ? attributes.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "TitusAgent{" +
"id='" + id + '\'' +
", ipAddress='" + ipAddress + '\'' +
", attributes=" + attributes +
'}';
}
}
| {
"pile_set_name": "Github"
} |
<annotation>
<folder>widerface</folder>
<filename>28--Sports_Fan_28_Sports_Fan_Sports_Fan_28_465.jpg</filename>
<source>
<database>wider face Database</database>
<annotation>PASCAL VOC2007</annotation>
<image>flickr</image>
<flickrid>-1</flickrid>
</source>
<owner>
<flickrid>yanyu</flickrid>
<name>yanyu</name>
</owner>
<size>
<width>1024</width>
<height>1470</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>462</xmin>
<ymin>597</ymin>
<xmax>611</xmax>
<ymax>786</ymax>
</bndbox>
<lm>
<x1>489.688</x1>
<y1>660.125</y1>
<x2>552.625</x2>
<y2>655.375</y2>
<x3>522.938</x3>
<y3>676.75</y3>
<x4>494.438</x4>
<y4>717.125</y4>
<x5>558.562</x5>
<y5>707.625</y5>
<visible>0</visible>
<blur>0.6</blur>
</lm>
<has_lm>1</has_lm>
</object>
</annotation> | {
"pile_set_name": "Github"
} |
<?php
/*
* Copyright 2014 Google Inc.
*
* 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.
*/
/**
* The "clusters" collection of methods.
* Typical usage is:
* <code>
* $dataprocService = new Google_Service_Dataproc(...);
* $clusters = $dataprocService->clusters;
* </code>
*/
class Google_Service_Dataproc_Resource_ProjectsRegionsClusters extends Google_Service_Resource
{
/**
* Creates a cluster in a project. The returned Operation.metadata will be
* ClusterOperationMetadata (https://cloud.google.com/dataproc/docs/reference/rp
* c/google.cloud.dataproc.v1#clusteroperationmetadata). (clusters.create)
*
* @param string $projectId Required. The ID of the Google Cloud Platform
* project that the cluster belongs to.
* @param string $region Required. The Dataproc region in which to handle the
* request.
* @param Google_Service_Dataproc_Cluster $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string requestId Optional. A unique id used to identify the
* request. If the server receives two CreateClusterRequest requests with the
* same id, then the second request will be ignored and the first
* google.longrunning.Operation created and stored in the backend is returned.It
* is recommended to always set this value to a UUID
* (https://en.wikipedia.org/wiki/Universally_unique_identifier).The id must
* contain only letters (a-z, A-Z), numbers (0-9), underscores (_), and hyphens
* (-). The maximum length is 40 characters.
* @return Google_Service_Dataproc_Operation
*/
public function create($projectId, $region, Google_Service_Dataproc_Cluster $postBody, $optParams = array())
{
$params = array('projectId' => $projectId, 'region' => $region, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "Google_Service_Dataproc_Operation");
}
/**
* Deletes a cluster in a project. The returned Operation.metadata will be
* ClusterOperationMetadata (https://cloud.google.com/dataproc/docs/reference/rp
* c/google.cloud.dataproc.v1#clusteroperationmetadata). (clusters.delete)
*
* @param string $projectId Required. The ID of the Google Cloud Platform
* project that the cluster belongs to.
* @param string $region Required. The Dataproc region in which to handle the
* request.
* @param string $clusterName Required. The cluster name.
* @param array $optParams Optional parameters.
*
* @opt_param string requestId Optional. A unique id used to identify the
* request. If the server receives two DeleteClusterRequest requests with the
* same id, then the second request will be ignored and the first
* google.longrunning.Operation created and stored in the backend is returned.It
* is recommended to always set this value to a UUID
* (https://en.wikipedia.org/wiki/Universally_unique_identifier).The id must
* contain only letters (a-z, A-Z), numbers (0-9), underscores (_), and hyphens
* (-). The maximum length is 40 characters.
* @opt_param string clusterUuid Optional. Specifying the cluster_uuid means the
* RPC should fail (with error NOT_FOUND) if cluster with specified UUID does
* not exist.
* @return Google_Service_Dataproc_Operation
*/
public function delete($projectId, $region, $clusterName, $optParams = array())
{
$params = array('projectId' => $projectId, 'region' => $region, 'clusterName' => $clusterName);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params), "Google_Service_Dataproc_Operation");
}
/**
* Gets cluster diagnostic information. The returned Operation.metadata will be
* ClusterOperationMetadata (https://cloud.google.com/dataproc/docs/reference/rp
* c/google.cloud.dataproc.v1#clusteroperationmetadata). After the operation
* completes, Operation.response contains DiagnoseClusterResults (https://cloud.
* google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#diagnoseclust
* erresults). (clusters.diagnose)
*
* @param string $projectId Required. The ID of the Google Cloud Platform
* project that the cluster belongs to.
* @param string $region Required. The Dataproc region in which to handle the
* request.
* @param string $clusterName Required. The cluster name.
* @param Google_Service_Dataproc_DiagnoseClusterRequest $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_Dataproc_Operation
*/
public function diagnose($projectId, $region, $clusterName, Google_Service_Dataproc_DiagnoseClusterRequest $postBody, $optParams = array())
{
$params = array('projectId' => $projectId, 'region' => $region, 'clusterName' => $clusterName, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('diagnose', array($params), "Google_Service_Dataproc_Operation");
}
/**
* Gets the resource representation for a cluster in a project. (clusters.get)
*
* @param string $projectId Required. The ID of the Google Cloud Platform
* project that the cluster belongs to.
* @param string $region Required. The Dataproc region in which to handle the
* request.
* @param string $clusterName Required. The cluster name.
* @param array $optParams Optional parameters.
* @return Google_Service_Dataproc_Cluster
*/
public function get($projectId, $region, $clusterName, $optParams = array())
{
$params = array('projectId' => $projectId, 'region' => $region, 'clusterName' => $clusterName);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Dataproc_Cluster");
}
/**
* Gets the access control policy for a resource. Returns an empty policy if the
* resource exists and does not have a policy set. (clusters.getIamPolicy)
*
* @param string $resource REQUIRED: The resource for which the policy is being
* requested. See the operation documentation for the appropriate value for this
* field.
* @param Google_Service_Dataproc_GetIamPolicyRequest $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_Dataproc_Policy
*/
public function getIamPolicy($resource, Google_Service_Dataproc_GetIamPolicyRequest $postBody, $optParams = array())
{
$params = array('resource' => $resource, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('getIamPolicy', array($params), "Google_Service_Dataproc_Policy");
}
/**
* Lists all regions/{region}/clusters in a project alphabetically.
* (clusters.listProjectsRegionsClusters)
*
* @param string $projectId Required. The ID of the Google Cloud Platform
* project that the cluster belongs to.
* @param string $region Required. The Dataproc region in which to handle the
* request.
* @param array $optParams Optional parameters.
*
* @opt_param int pageSize Optional. The standard List page size.
* @opt_param string filter Optional. A filter constraining the clusters to
* list. Filters are case-sensitive and have the following syntax:field = value
* AND field = value ...where field is one of status.state, clusterName, or
* labels.[KEY], and [KEY] is a label key. value can be * to match all values.
* status.state can be one of the following: ACTIVE, INACTIVE, CREATING,
* RUNNING, ERROR, DELETING, or UPDATING. ACTIVE contains the CREATING,
* UPDATING, and RUNNING states. INACTIVE contains the DELETING and ERROR
* states. clusterName is the name of the cluster provided at creation time.
* Only the logical AND operator is supported; space-separated items are treated
* as having an implicit AND operator.Example filter:status.state = ACTIVE AND
* clusterName = mycluster AND labels.env = staging AND labels.starred = *
* @opt_param string pageToken Optional. The standard List page token.
* @return Google_Service_Dataproc_ListClustersResponse
*/
public function listProjectsRegionsClusters($projectId, $region, $optParams = array())
{
$params = array('projectId' => $projectId, 'region' => $region);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_Dataproc_ListClustersResponse");
}
/**
* Updates a cluster in a project. The returned Operation.metadata will be
* ClusterOperationMetadata (https://cloud.google.com/dataproc/docs/reference/rp
* c/google.cloud.dataproc.v1#clusteroperationmetadata). (clusters.patch)
*
* @param string $projectId Required. The ID of the Google Cloud Platform
* project the cluster belongs to.
* @param string $region Required. The Dataproc region in which to handle the
* request.
* @param string $clusterName Required. The cluster name.
* @param Google_Service_Dataproc_Cluster $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string updateMask Required. Specifies the path, relative to
* Cluster, of the field to update. For example, to change the number of workers
* in a cluster to 5, the update_mask parameter would be specified as
* config.worker_config.num_instances, and the PATCH request body would specify
* the new value, as follows: { "config":{ "workerConfig":{ "numInstances":"5" }
* } } Similarly, to change the number of preemptible workers in a cluster to 5,
* the update_mask parameter would be
* config.secondary_worker_config.num_instances, and the PATCH request body
* would be set as follows: { "config":{ "secondaryWorkerConfig":{
* "numInstances":"5" } } } *Note:* Currently, only the following fields can be
* updated: *Mask* *Purpose* *labels* Update labels
* *config.worker_config.num_instances* Resize primary worker group
* *config.secondary_worker_config.num_instances* Resize secondary worker group
* config.autoscaling_config.policy_uri Use, stop using, or change autoscaling
* policies
* @opt_param string gracefulDecommissionTimeout Optional. Timeout for graceful
* YARN decomissioning. Graceful decommissioning allows removing nodes from the
* cluster without interrupting jobs in progress. Timeout specifies how long to
* wait for jobs in progress to finish before forcefully removing nodes (and
* potentially interrupting jobs). Default timeout is 0 (for forceful
* decommission), and the maximum allowed timeout is 1 day. (see JSON
* representation of Duration (https://developers.google.com/protocol-
* buffers/docs/proto3#json)).Only supported on Dataproc image versions 1.2 and
* higher.
* @opt_param string requestId Optional. A unique id used to identify the
* request. If the server receives two UpdateClusterRequest requests with the
* same id, then the second request will be ignored and the first
* google.longrunning.Operation created and stored in the backend is returned.It
* is recommended to always set this value to a UUID
* (https://en.wikipedia.org/wiki/Universally_unique_identifier).The id must
* contain only letters (a-z, A-Z), numbers (0-9), underscores (_), and hyphens
* (-). The maximum length is 40 characters.
* @return Google_Service_Dataproc_Operation
*/
public function patch($projectId, $region, $clusterName, Google_Service_Dataproc_Cluster $postBody, $optParams = array())
{
$params = array('projectId' => $projectId, 'region' => $region, 'clusterName' => $clusterName, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('patch', array($params), "Google_Service_Dataproc_Operation");
}
/**
* Sets the access control policy on the specified resource. Replaces any
* existing policy.Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED
* errors. (clusters.setIamPolicy)
*
* @param string $resource REQUIRED: The resource for which the policy is being
* specified. See the operation documentation for the appropriate value for this
* field.
* @param Google_Service_Dataproc_SetIamPolicyRequest $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_Dataproc_Policy
*/
public function setIamPolicy($resource, Google_Service_Dataproc_SetIamPolicyRequest $postBody, $optParams = array())
{
$params = array('resource' => $resource, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('setIamPolicy', array($params), "Google_Service_Dataproc_Policy");
}
/**
* Returns permissions that a caller has on the specified resource. If the
* resource does not exist, this will return an empty set of permissions, not a
* NOT_FOUND error.Note: This operation is designed to be used for building
* permission-aware UIs and command-line tools, not for authorization checking.
* This operation may "fail open" without warning. (clusters.testIamPermissions)
*
* @param string $resource REQUIRED: The resource for which the policy detail is
* being requested. See the operation documentation for the appropriate value
* for this field.
* @param Google_Service_Dataproc_TestIamPermissionsRequest $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_Dataproc_TestIamPermissionsResponse
*/
public function testIamPermissions($resource, Google_Service_Dataproc_TestIamPermissionsRequest $postBody, $optParams = array())
{
$params = array('resource' => $resource, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('testIamPermissions', array($params), "Google_Service_Dataproc_TestIamPermissionsResponse");
}
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 2567401bb47fe5241b9a7917c362fcfb
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
// -*- C++ -*-
// Copyright (C) 2005-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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 3, or (at your option) any later
// version.
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file rb_tree_map_/erase_fn_imps.hpp
* Contains an implementation for rb_tree_.
*/
PB_DS_CLASS_T_DEC
inline bool
PB_DS_CLASS_C_DEC::
erase(key_const_reference r_key)
{
point_iterator it = this->find(r_key);
if (it == base_type::end())
return false;
erase(it);
return true;
}
PB_DS_CLASS_T_DEC
inline typename PB_DS_CLASS_C_DEC::iterator
PB_DS_CLASS_C_DEC::
erase(iterator it)
{
PB_DS_ASSERT_VALID((*this))
if (it == base_type::end())
return it;
iterator ret_it = it;
++ret_it;
erase_node(it.m_p_nd);
PB_DS_ASSERT_VALID((*this))
return ret_it;
}
PB_DS_CLASS_T_DEC
inline typename PB_DS_CLASS_C_DEC::reverse_iterator
PB_DS_CLASS_C_DEC::
erase(reverse_iterator it)
{
PB_DS_ASSERT_VALID((*this))
if (it.m_p_nd == base_type::m_p_head)
return it;
reverse_iterator ret_it = it;
++ret_it;
erase_node(it.m_p_nd);
PB_DS_ASSERT_VALID((*this))
return ret_it;
}
PB_DS_CLASS_T_DEC
template<typename Pred>
inline typename PB_DS_CLASS_C_DEC::size_type
PB_DS_CLASS_C_DEC::
erase_if(Pred pred)
{
PB_DS_ASSERT_VALID((*this))
size_type num_ersd = 0;
iterator it = base_type::begin();
while (it != base_type::end())
{
if (pred(*it))
{
++num_ersd;
it = erase(it);
}
else
++it;
}
PB_DS_ASSERT_VALID((*this))
return num_ersd;
}
PB_DS_CLASS_T_DEC
void
PB_DS_CLASS_C_DEC::
erase_node(node_pointer p_nd)
{
remove_node(p_nd);
base_type::actual_erase_node(p_nd);
PB_DS_ASSERT_VALID((*this))
}
PB_DS_CLASS_T_DEC
void
PB_DS_CLASS_C_DEC::
remove_node(node_pointer p_z)
{
this->update_min_max_for_erased_node(p_z);
node_pointer p_y = p_z;
node_pointer p_x = 0;
node_pointer p_new_x_parent = 0;
if (p_y->m_p_left == 0)
p_x = p_y->m_p_right;
else if (p_y->m_p_right == 0)
p_x = p_y->m_p_left;
else
{
p_y = p_y->m_p_right;
while (p_y->m_p_left != 0)
p_y = p_y->m_p_left;
p_x = p_y->m_p_right;
}
if (p_y == p_z)
{
p_new_x_parent = p_y->m_p_parent;
if (p_x != 0)
p_x->m_p_parent = p_y->m_p_parent;
if (base_type::m_p_head->m_p_parent == p_z)
base_type::m_p_head->m_p_parent = p_x;
else if (p_z->m_p_parent->m_p_left == p_z)
{
p_y->m_p_left = p_z->m_p_parent;
p_z->m_p_parent->m_p_left = p_x;
}
else
{
p_y->m_p_left = 0;
p_z->m_p_parent->m_p_right = p_x;
}
}
else
{
p_z->m_p_left->m_p_parent = p_y;
p_y->m_p_left = p_z->m_p_left;
if (p_y != p_z->m_p_right)
{
p_new_x_parent = p_y->m_p_parent;
if (p_x != 0)
p_x->m_p_parent = p_y->m_p_parent;
p_y->m_p_parent->m_p_left = p_x;
p_y->m_p_right = p_z->m_p_right;
p_z->m_p_right->m_p_parent = p_y;
}
else
p_new_x_parent = p_y;
if (base_type::m_p_head->m_p_parent == p_z)
base_type::m_p_head->m_p_parent = p_y;
else if (p_z->m_p_parent->m_p_left == p_z)
p_z->m_p_parent->m_p_left = p_y;
else
p_z->m_p_parent->m_p_right = p_y;
p_y->m_p_parent = p_z->m_p_parent;
std::swap(p_y->m_red, p_z->m_red);
p_y = p_z;
}
this->update_to_top(p_new_x_parent, (node_update* )this);
if (p_y->m_red)
return;
remove_fixup(p_x, p_new_x_parent);
}
PB_DS_CLASS_T_DEC
void
PB_DS_CLASS_C_DEC::
remove_fixup(node_pointer p_x, node_pointer p_new_x_parent)
{
_GLIBCXX_DEBUG_ASSERT(p_x == 0 || p_x->m_p_parent == p_new_x_parent);
while (p_x != base_type::m_p_head->m_p_parent && is_effectively_black(p_x))
if (p_x == p_new_x_parent->m_p_left)
{
node_pointer p_w = p_new_x_parent->m_p_right;
if (p_w->m_red)
{
p_w->m_red = false;
p_new_x_parent->m_red = true;
base_type::rotate_left(p_new_x_parent);
p_w = p_new_x_parent->m_p_right;
}
if (is_effectively_black(p_w->m_p_left)
&& is_effectively_black(p_w->m_p_right))
{
p_w->m_red = true;
p_x = p_new_x_parent;
p_new_x_parent = p_new_x_parent->m_p_parent;
}
else
{
if (is_effectively_black(p_w->m_p_right))
{
if (p_w->m_p_left != 0)
p_w->m_p_left->m_red = false;
p_w->m_red = true;
base_type::rotate_right(p_w);
p_w = p_new_x_parent->m_p_right;
}
p_w->m_red = p_new_x_parent->m_red;
p_new_x_parent->m_red = false;
if (p_w->m_p_right != 0)
p_w->m_p_right->m_red = false;
base_type::rotate_left(p_new_x_parent);
this->update_to_top(p_new_x_parent, (node_update* )this);
break;
}
}
else
{
node_pointer p_w = p_new_x_parent->m_p_left;
if (p_w->m_red == true)
{
p_w->m_red = false;
p_new_x_parent->m_red = true;
base_type::rotate_right(p_new_x_parent);
p_w = p_new_x_parent->m_p_left;
}
if (is_effectively_black(p_w->m_p_right)
&& is_effectively_black(p_w->m_p_left))
{
p_w->m_red = true;
p_x = p_new_x_parent;
p_new_x_parent = p_new_x_parent->m_p_parent;
}
else
{
if (is_effectively_black(p_w->m_p_left))
{
if (p_w->m_p_right != 0)
p_w->m_p_right->m_red = false;
p_w->m_red = true;
base_type::rotate_left(p_w);
p_w = p_new_x_parent->m_p_left;
}
p_w->m_red = p_new_x_parent->m_red;
p_new_x_parent->m_red = false;
if (p_w->m_p_left != 0)
p_w->m_p_left->m_red = false;
base_type::rotate_right(p_new_x_parent);
this->update_to_top(p_new_x_parent, (node_update* )this);
break;
}
}
if (p_x != 0)
p_x->m_red = false;
}
| {
"pile_set_name": "Github"
} |
# Mixed DDL-DML (CREATE ... SELECT ...) statements can only be
# replicated properly in statement-based replication.
# Currently statement based due to bug 12345
--source include/have_binlog_format_mixed_or_statement.inc
source include/master-slave.inc;
# Test replication of auto_increment
create table t1 (n int auto_increment primary key);
set insert_id = 2000;
insert into t1 values (NULL),(NULL),(NULL);
sync_slave_with_master;
select * from t1;
connection master;
--replace_result $SLAVE_MYPORT 9999
show slave hosts;
drop table t1;
sync_slave_with_master;
stop slave;
--source include/wait_for_slave_to_stop.inc
connection master;
# Test replication of timestamp
create table t2(id int auto_increment primary key, created datetime);
set timestamp=12345;
insert into t2 set created=now();
select * from t2;
# Test replication of CREATE .. LIKE (Bug #2557)
create table t3 like t2;
create temporary table t4 like t2;
create table t5 select * from t4;
save_master_pos;
connection slave;
start slave;
--source include/wait_for_slave_to_start.inc
sync_with_master;
select * from t2;
show create table t3;
show create table t5;
connection master;
drop table t2,t3,t5;
drop temporary table t4;
sync_slave_with_master;
# End of 4.1 tests
--source include/rpl_end.inc
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!-- This file was written by the internal XML-Handler of Y-Files.-->
<!DOCTYPE graphml SYSTEM "http://www.graphdrawing.org/dtds/graphml.dtd">
<graphml>
<graph id="G">
<node id="n0"/>
<node id="n1"/>
<node id="n2"/>
<node id="n3"/>
<node id="n4"/>
<node id="n5"/>
<node id="n6"/>
<node id="n7"/>
<node id="n8"/>
<node id="n9"/>
<node id="n10"/>
<edge id="e0" source="n0" target="n1"/>
<edge id="e1" source="n0" target="n2"/>
<edge id="e2" source="n1" target="n3"/>
<edge id="e3" source="n3" target="n4"/>
<edge id="e4" source="n3" target="n5"/>
<edge id="e5" source="n4" target="n6"/>
<edge id="e6" source="n4" target="n7"/>
<edge id="e7" source="n6" target="n8"/>
<edge id="e8" source="n5" target="n8"/>
<edge id="e9" source="n7" target="n6"/>
<edge id="e10" source="n2" target="n3"/>
<edge id="e11" source="n9" target="n10"/>
<edge id="e12" source="n0" target="n9"/>
</graph>
</graphml> | {
"pile_set_name": "Github"
} |
/*
Unix SMB/CIFS implementation.
implement the DRSUpdateRefs call
Copyright (C) Andrew Tridgell 2009
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 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "includes.h"
#include "rpc_server/dcerpc_server.h"
#include "dsdb/samdb/samdb.h"
#include "libcli/security/security.h"
#include "libcli/security/session.h"
#include "rpc_server/drsuapi/dcesrv_drsuapi.h"
#include "auth/session.h"
#include "librpc/gen_ndr/ndr_drsuapi.h"
struct repsTo {
uint32_t count;
struct repsFromToBlob *r;
};
/*
add a replication destination for a given partition GUID
*/
static WERROR uref_add_dest(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
struct ldb_dn *dn, struct repsFromTo1 *dest,
uint32_t options)
{
struct repsTo reps;
WERROR werr;
unsigned int i;
werr = dsdb_loadreps(sam_ctx, mem_ctx, dn, "repsTo", &reps.r, &reps.count);
if (!W_ERROR_IS_OK(werr)) {
return werr;
}
for (i=0; i<reps.count; i++) {
if (GUID_equal(&dest->source_dsa_obj_guid,
&reps.r[i].ctr.ctr1.source_dsa_obj_guid)) {
if (options & DRSUAPI_DRS_GETCHG_CHECK) {
return WERR_OK;
} else {
return WERR_DS_DRA_REF_ALREADY_EXISTS;
}
}
}
reps.r = talloc_realloc(mem_ctx, reps.r, struct repsFromToBlob, reps.count+1);
if (reps.r == NULL) {
return WERR_DS_DRA_INTERNAL_ERROR;
}
ZERO_STRUCT(reps.r[reps.count]);
reps.r[reps.count].version = 1;
reps.r[reps.count].ctr.ctr1 = *dest;
/* add the GCSPN flag if the client asked for it */
reps.r[reps.count].ctr.ctr1.replica_flags |= (options & DRSUAPI_DRS_REF_GCSPN);
reps.count++;
werr = dsdb_savereps(sam_ctx, mem_ctx, dn, "repsTo", reps.r, reps.count);
if (!W_ERROR_IS_OK(werr)) {
return werr;
}
return WERR_OK;
}
/*
delete a replication destination for a given partition GUID
*/
static WERROR uref_del_dest(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
struct ldb_dn *dn, struct GUID *dest_guid,
uint32_t options)
{
struct repsTo reps;
WERROR werr;
unsigned int i;
bool found = false;
werr = dsdb_loadreps(sam_ctx, mem_ctx, dn, "repsTo", &reps.r, &reps.count);
if (!W_ERROR_IS_OK(werr)) {
return werr;
}
for (i=0; i<reps.count; i++) {
if (GUID_equal(dest_guid,
&reps.r[i].ctr.ctr1.source_dsa_obj_guid)) {
if (i+1 < reps.count) {
memmove(&reps.r[i], &reps.r[i+1], sizeof(reps.r[i])*(reps.count-(i+1)));
}
reps.count--;
found = true;
}
}
werr = dsdb_savereps(sam_ctx, mem_ctx, dn, "repsTo", reps.r, reps.count);
if (!W_ERROR_IS_OK(werr)) {
return werr;
}
if (!found &&
!(options & DRSUAPI_DRS_GETCHG_CHECK) &&
!(options & DRSUAPI_DRS_ADD_REF)) {
return WERR_DS_DRA_REF_NOT_FOUND;
}
return WERR_OK;
}
/**
* @brief Update the references for the given NC and the destination DSA object
*
* This function is callable from non RPC functions (ie. getncchanges), it
* will validate the request to update reference and then will add/del a repsTo
* to the specified server referenced by its DSA GUID in the request.
*
* @param[in] b_state A bind_state object
*
* @param[in] mem_ctx A talloc context for memory allocation
*
* @param[in] req A drsuapi_DsReplicaUpdateRefsRequest1
* object which NC, which server and which
* action (add/delete) should be performed
*
* @return WERR_OK is success, different error
* otherwise.
*/
WERROR drsuapi_UpdateRefs(struct drsuapi_bind_state *b_state, TALLOC_CTX *mem_ctx,
struct drsuapi_DsReplicaUpdateRefsRequest1 *req)
{
WERROR werr;
int ret;
struct ldb_dn *dn;
struct ldb_dn *nc_root;
struct ldb_context *sam_ctx = b_state->sam_ctx_system?b_state->sam_ctx_system:b_state->sam_ctx;
DEBUG(4,("DsReplicaUpdateRefs for host '%s' with GUID %s options 0x%08x nc=%s\n",
req->dest_dsa_dns_name, GUID_string(mem_ctx, &req->dest_dsa_guid),
req->options,
drs_ObjectIdentifier_to_string(mem_ctx, req->naming_context)));
/*
* 4.1.26.2 Server Behavior of the IDL_DRSUpdateRefs Method
* Implements the input validation checks
*/
if (GUID_all_zero(&req->dest_dsa_guid)) {
return WERR_DS_DRA_INVALID_PARAMETER;
}
/* FIXME it seems that we should check the length of the stuff too*/
if (req->dest_dsa_dns_name == NULL) {
return WERR_DS_DRA_INVALID_PARAMETER;
}
if (!(req->options & (DRSUAPI_DRS_DEL_REF|DRSUAPI_DRS_ADD_REF))) {
return WERR_DS_DRA_INVALID_PARAMETER;
}
dn = drs_ObjectIdentifier_to_dn(mem_ctx, sam_ctx, req->naming_context);
W_ERROR_HAVE_NO_MEMORY(dn);
ret = dsdb_find_nc_root(sam_ctx, dn, dn, &nc_root);
if (ret != LDB_SUCCESS) {
DEBUG(2, ("Didn't find a nc for %s\n", ldb_dn_get_linearized(dn)));
return WERR_DS_DRA_BAD_NC;
}
if (ldb_dn_compare(dn, nc_root) != 0) {
DEBUG(2, ("dn %s is not equal to %s\n", ldb_dn_get_linearized(dn), ldb_dn_get_linearized(nc_root)));
return WERR_DS_DRA_BAD_NC;
}
if (ldb_transaction_start(sam_ctx) != LDB_SUCCESS) {
DEBUG(0,(__location__ ": Failed to start transaction on samdb: %s\n",
ldb_errstring(sam_ctx)));
return WERR_DS_DRA_INTERNAL_ERROR;
}
if (req->options & DRSUAPI_DRS_DEL_REF) {
werr = uref_del_dest(sam_ctx, mem_ctx, dn, &req->dest_dsa_guid, req->options);
if (!W_ERROR_IS_OK(werr)) {
DEBUG(0,("Failed to delete repsTo for %s: %s\n",
GUID_string(mem_ctx, &req->dest_dsa_guid),
win_errstr(werr)));
goto failed;
}
}
if (req->options & DRSUAPI_DRS_ADD_REF) {
struct repsFromTo1 dest;
struct repsFromTo1OtherInfo oi;
ZERO_STRUCT(dest);
ZERO_STRUCT(oi);
oi.dns_name = req->dest_dsa_dns_name;
dest.other_info = &oi;
dest.source_dsa_obj_guid = req->dest_dsa_guid;
dest.replica_flags = req->options;
werr = uref_add_dest(sam_ctx, mem_ctx, dn, &dest, req->options);
if (!W_ERROR_IS_OK(werr)) {
DEBUG(0,("Failed to add repsTo for %s: %s\n",
GUID_string(mem_ctx, &dest.source_dsa_obj_guid),
win_errstr(werr)));
goto failed;
}
}
if (ldb_transaction_commit(sam_ctx) != LDB_SUCCESS) {
DEBUG(0,(__location__ ": Failed to commit transaction on samdb: %s\n",
ldb_errstring(sam_ctx)));
return WERR_DS_DRA_INTERNAL_ERROR;
}
return WERR_OK;
failed:
ldb_transaction_cancel(sam_ctx);
return werr;
}
/*
drsuapi_DsReplicaUpdateRefs
*/
WERROR dcesrv_drsuapi_DsReplicaUpdateRefs(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
struct drsuapi_DsReplicaUpdateRefs *r)
{
struct dcesrv_handle *h;
struct drsuapi_bind_state *b_state;
struct drsuapi_DsReplicaUpdateRefsRequest1 *req;
WERROR werr;
int ret;
enum security_user_level security_level;
DCESRV_PULL_HANDLE_WERR(h, r->in.bind_handle, DRSUAPI_BIND_HANDLE);
b_state = h->data;
if (r->in.level != 1) {
DEBUG(0,("DrReplicUpdateRefs - unsupported level %u\n", r->in.level));
return WERR_DS_DRA_INVALID_PARAMETER;
}
req = &r->in.req.req1;
werr = drs_security_access_check(b_state->sam_ctx,
mem_ctx,
dce_call->conn->auth_state.session_info->security_token,
req->naming_context,
GUID_DRS_MANAGE_TOPOLOGY);
if (!W_ERROR_IS_OK(werr)) {
return werr;
}
security_level = security_session_user_level(dce_call->conn->auth_state.session_info, NULL);
if (security_level < SECURITY_ADMINISTRATOR) {
/* check that they are using an DSA objectGUID that they own */
ret = dsdb_validate_dsa_guid(b_state->sam_ctx,
&req->dest_dsa_guid,
&dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX]);
if (ret != LDB_SUCCESS) {
DEBUG(0,(__location__ ": Refusing DsReplicaUpdateRefs for sid %s with GUID %s\n",
dom_sid_string(mem_ctx,
&dce_call->conn->auth_state.session_info->security_token->sids[PRIMARY_USER_SID_INDEX]),
GUID_string(mem_ctx, &req->dest_dsa_guid)));
return WERR_DS_DRA_ACCESS_DENIED;
}
}
werr = drsuapi_UpdateRefs(b_state, mem_ctx, req);
#if 0
NDR_PRINT_FUNCTION_DEBUG(drsuapi_DsReplicaUpdateRefs, NDR_BOTH, r);
#endif
return werr;
}
| {
"pile_set_name": "Github"
} |
--TEST--
Test function @return hinting
--FILE--
<?php
/**
*
* @return DateTime[]
*/
function test_function() {
return array ();
}
function ok() {
test_function()[0]->f|
}
--EXPECT--
method(format) | {
"pile_set_name": "Github"
} |
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/engines/scene.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <babylon/layers/highlight_layer.h>
#include <babylon/lights/point_light.h>
#include <babylon/materials/image_processing_configuration.h>
#include <babylon/materials/pbr/pbr_material.h>
#include <babylon/materials/textures/hdr_cube_texture.h>
#include <babylon/materials/textures/texture.h>
#include <babylon/materials/textures/texture_constants.h>
#include <babylon/meshes/builders/mesh_builder_options.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/mesh_builder.h>
#include <babylon/samples/babylon_register_sample.h>
namespace BABYLON {
namespace Samples {
/**
* @brief Highlight layer scene. Example demonstrating how to highlight a mesh.
* @see https://www.babylonjs-playground.com/#7EESGZ#0
* @see https://doc.babylonjs.com/how_to/highlight_layer
*/
class HighlightLayerScene : public IRenderableScene {
public:
HighlightLayerScene(ICanvas* iCanvas) : IRenderableScene(iCanvas), _alpha{0.01f}, _hl{nullptr}
{
}
~HighlightLayerScene() override = default;
const char* getName() override
{
return "Highlight Layer Scene";
}
void initializeScene(ICanvas* canvas, Scene* scene) override
{
auto camera
= ArcRotateCamera::New("Camera", -Math::PI_4, Math::PI / 2.5f, 200.f, Vector3::Zero(), scene);
camera->attachControl(canvas, true);
camera->minZ = 0.1f;
// Light
auto light = PointLight::New("point", Vector3(0.f, 40.f, 0.f), scene);
light->intensity = 0.98f;
// Environment Texture
auto hdrTexture = HDRCubeTexture::New("/textures/room.hdr", scene, 512);
// Skybox
auto hdrSkybox = Mesh::CreateBox("hdrSkyBox", 1000.f, scene);
auto hdrSkyboxMaterial = PBRMaterial::New("skyBox", scene);
hdrSkyboxMaterial->backFaceCulling = false;
hdrSkyboxMaterial->reflectionTexture = hdrTexture->clone();
hdrSkyboxMaterial->reflectionTexture()->coordinatesMode = TextureConstants::SKYBOX_MODE;
hdrSkyboxMaterial->microSurface = 1.f;
hdrSkyboxMaterial->cameraExposure = 0.6f;
hdrSkyboxMaterial->cameraContrast = 1.6f;
hdrSkyboxMaterial->disableLighting = true;
hdrSkybox->material = hdrSkyboxMaterial;
hdrSkybox->infiniteDistance = true;
// Create meshes
auto sphereGlass = Mesh::CreateSphere("sphereGlass", 48, 30.f, scene);
sphereGlass->translate(Vector3(1.f, 0.f, 0.f), -60.f);
auto sphereMetal = Mesh::CreateSphere("sphereMetal", 48, 30.f, scene);
sphereMetal->translate(Vector3(1.f, 0.f, 0.f), 60.f);
auto spherePlastic = Mesh::CreateSphere("spherePlastic", 48, 30.f, scene);
spherePlastic->translate(Vector3(0.f, 0.f, 1.f), -60.f);
BoxOptions woodPlankOptions;
woodPlankOptions.width = 65.f;
woodPlankOptions.height = 1.f;
woodPlankOptions.depth = 65.f;
auto woodPlank = MeshBuilder::CreateBox("plane", woodPlankOptions, scene);
// Create materials
auto glass = PBRMaterial::New("glass", scene);
glass->reflectionTexture = hdrTexture;
glass->refractionTexture = hdrTexture;
glass->linkRefractionWithTransparency = true;
glass->indexOfRefraction = 0.52f;
glass->alpha = 0.f;
glass->directIntensity = 0.f;
glass->environmentIntensity = 0.5f;
glass->cameraExposure = 0.5f;
glass->cameraContrast = 1.7f;
glass->microSurface = 1.f;
glass->reflectivityColor = Color3(0.2f, 0.2f, 0.2f);
glass->albedoColor = Color3(0.95f, 0.95f, 0.95f);
sphereGlass->material = glass;
auto metal = PBRMaterial::New("metal", scene);
metal->reflectionTexture = hdrTexture;
metal->directIntensity = 0.3f;
metal->environmentIntensity = 0.7f;
metal->cameraExposure = 0.55f;
metal->cameraContrast = 1.6f;
metal->microSurface = 0.96f;
metal->reflectivityColor = Color3(0.9f, 0.9f, 0.9f);
metal->albedoColor = Color3(1.f, 1.f, 1.f);
sphereMetal->material = metal;
auto plastic = PBRMaterial::New("plastic", scene);
plastic->reflectionTexture = hdrTexture;
plastic->directIntensity = 0.6f;
plastic->environmentIntensity = 0.7f;
plastic->cameraExposure = 0.6f;
plastic->cameraContrast = 1.6f;
plastic->microSurface = 0.96f;
plastic->albedoColor = Color3(0.206f, 0.94f, 1.f);
plastic->reflectivityColor = Color3(0.05f, 0.05f, 0.05f);
spherePlastic->material = plastic;
auto wood = PBRMaterial::New("wood", scene);
wood->reflectionTexture = hdrTexture;
wood->directIntensity = 1.5f;
wood->environmentIntensity = 0.5f;
wood->specularIntensity = 0.3f;
wood->cameraExposure = 0.9f;
wood->cameraContrast = 1.6f;
wood->reflectivityTexture = Texture::New("textures/reflectivity.png", scene);
wood->useMicroSurfaceFromReflectivityMapAlpha = true;
wood->albedoColor = Color3::White();
wood->albedoTexture = Texture::New("textures/albedo.png", scene);
woodPlank->material = wood;
_hl = HighlightLayer::New("hl", scene);
_hl->addMesh(sphereMetal, Color3::White());
auto hl2 = HighlightLayer::New("hl", scene);
hl2->addMesh(spherePlastic, Color3::Green());
auto hl3 = HighlightLayer::New("hl", scene);
hl3->addMesh(sphereGlass, Color3::Red());
_scene->registerBeforeRender([this](Scene*, EventState&) {
_hl->blurHorizontalSize = 0.4f + std::cos(_alpha);
_hl->blurVerticalSize = 0.4f + std::cos(_alpha);
_alpha += 0.01f;
});
}
private:
float _alpha;
HighlightLayerPtr _hl;
}; // end of class HighlightLayerScene
BABYLON_REGISTER_SAMPLE("Special FX", HighlightLayerScene)
} // end of namespace Samples
} // end of namespace BABYLON
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* 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.
*/
package com.afwsamples.testdpc;
import static com.afwsamples.testdpc.common.Util.Q_VERSION_CODE;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build.VERSION_CODES;
@TargetApi(Q_VERSION_CODE)
public class DelegatedAdminReceiver extends android.app.admin.DelegatedAdminReceiver {
@Override
public String onChoosePrivateKeyAlias(Context context, Intent intent, int uid, Uri uri,
String alias) {
return CommonReceiverOperations.onChoosePrivateKeyAlias(context, uid);
}
@Override
public void onNetworkLogsAvailable(Context context, Intent intent, long batchToken,
int networkLogsCount) {
CommonReceiverOperations.onNetworkLogsAvailable(context, null, batchToken,
networkLogsCount);
}
}
| {
"pile_set_name": "Github"
} |
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import "UIView.h"
@class NSArray, NSMutableArray, SULinkControl;
@interface SUDownloadsGridFooterView : UIView
{
SULinkControl *_linkControl;
NSMutableArray *_nativeButtons;
NSArray *_scriptButtons;
}
@property(retain, nonatomic) NSArray *scriptButtons; // @synthesize scriptButtons=_scriptButtons;
- (void)_reloadNativeButtons;
- (id)_newNativeButton;
- (float)_maximumButtonHeight;
- (void)_linkControlAction:(id)arg1;
- (void)sizeToFit;
- (void)layoutSubviews;
- (id)hitTest:(struct CGPoint)arg1 withEvent:(id)arg2;
- (void)dealloc;
- (id)initWithFrame:(struct CGRect)arg1;
@end
| {
"pile_set_name": "Github"
} |
<?php
/**
* Mail English lexicon topic
*
* @language en
* @package modx
* @subpackage lexicon
*/
$_lang['mail_err_address_ns'] = 'You must provide an email address to send to.';
$_lang['mail_err_derive_getmailer'] = 'Attempt to call abstract function _getMailer() in modMail class. You must implement this function in a derivative of modMail.';
$_lang['mail_err_attr_nv'] = '[[+attr]] is not a valid PHPMailer attribute and is being ignored by the implementation.';
$_lang['mail_err_unset_spec'] = 'modPHPMailer does not support unsetting specific addresses. Use reset() to clear all recipients and add back the ones you want to send to.'; | {
"pile_set_name": "Github"
} |
version https://git-lfs.github.com/spec/v1
oid sha256:edf6ff417de00d9f11142e7867c6d04cbc1c09955ad8ab16bb506daa93afa450
size 3409
| {
"pile_set_name": "Github"
} |
# /usr/bin/env python3.5
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2020, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# SPDX-License-Identifier: BSD-3-Clause
#
# @@-COPYRIGHT-END-@@
# =============================================================================
import unittest
import torch
from aimet_common.polyslice import PolySlice
from aimet_torch.winnow.winnow_utils import reduce_tensor
def tensor_contains(tensor, value):
return (tensor == value).nonzero().numel() > 0
class TestTrainingExtensionsTensorReduction(unittest.TestCase):
def test_tensor_reduction(self):
shape = [3, 2, 4]
tensor = torch.zeros(shape, dtype=torch.int8)
view = tensor.reshape([-1])
for i in range(tensor.numel()):
view[i] = 101 + i
reduct = PolySlice(dim=0, index=1)
result = reduce_tensor(tensor, reduct)
assert list(result.shape) == [2, 2, 4]
assert tensor_contains(result, 101)
assert tensor_contains(result, 108)
assert not tensor_contains(result, 109)
assert not tensor_contains(result, 116)
assert tensor_contains(result, 117)
assert tensor_contains(result, 124)
reduct.set(dim=2, index=[0])
reduct.add(dim=2, index=3)
result = reduce_tensor(tensor, reduct)
assert list(result.shape) == [2, 2, 2]
assert not tensor_contains(result, 101)
assert tensor_contains(result, 102)
assert tensor_contains(result, 103)
assert not tensor_contains(result, 104)
assert not tensor_contains(result, 117)
assert not tensor_contains(result, 121)
assert tensor_contains(result, 122)
assert tensor_contains(result, 123)
assert not tensor_contains(result, 124)
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=macro.info.html">
</head>
<body>
<p>Redirecting to <a href="macro.info.html">macro.info.html</a>...</p>
<script>location.replace("macro.info.html" + location.search + location.hash);</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
"""
==============================
tests.test_markdown_extensions
==============================
Test proper work of various Markdown extensions.
"""
import sys
import unittest
from flask import Flask
from flask_flatpages import FlatPages
from flask_flatpages.compat import IS_PY3
from markdown.extensions.toc import TocExtension
class TestMarkdownExtensions(unittest.TestCase):
def check_toc_page(self, pages):
toc = pages.get('toc')
self.assertEqual(
toc.html,
'<div class="toc">\n<ul>\n<li><a href="#page-header">Page '
'Header</a><ul>\n<li><a href="#paragraph-header">Paragraph '
'Header</a></li>\n</ul>\n</li>\n</ul>\n</div>\n'
'<h1 id="page-header">Page Header</h1>\n'
'<h2 id="paragraph-header">Paragraph Header</h2>\n'
'<p>Text</p>'
)
def check_default_codehilite_page(self, pages):
codehilite = pages.get('codehilite') #Test codehilite loaded by default
#by pygmented_markdown
fixture = (
'<div class="codehilite"><pre><span></span>'
'<code><span class="nb">print</span>'
'<span class="p">(</span><span class="s1">'Hello, world!''
'</span><span class="p">)</span>\n</code></pre></div>'
)
if not IS_PY3:
fixture = (
'<div class="codehilite"><pre><span></span>'
'<span class="nb">print</span>'
'<span class="p">(</span><span class="s1">'Hello, world!''
'</span><span class="p">)</span>\n</pre></div>'
)
elif sys.version_info[1] == 4:
fixture = (
'<div class="codehilite"><pre><span></span>'
'<span class="k">print</span>'
'<span class="p">(</span><span class="s1">'Hello, world!''
'</span><span class="p">)</span>\n</pre></div>'
)
self.assertEqual(
codehilite.html,
fixture
)
def check_codehilite_with_linenums(self, pages):
codehilite = pages.get('codehilite')
fixture = (
'<table class="codehilitetable"><tr><td class="linenos">'
'<div class="linenodiv"><pre>1</pre></div></td><td class="code">'
'<div class="codehilite"><pre><span></span><code>'
'<span class="nb">print</span>'
'<span class="p">(</span><span class="s1">'Hello, world!''
'</span><span class="p">)</span>\n'
'</code></pre></div>\n</td></tr></table>'
)
if not IS_PY3:
fixture = (
'<table class="codehilitetable"><tr><td class="linenos">'
'<div class="linenodiv"><pre>1</pre></div></td><td class="code">'
'<div class="codehilite"><pre><span></span>'
'<span class="nb">print</span>'
'<span class="p">(</span><span class="s1">'Hello, world!''
'</span><span class="p">)</span>\n'
'</pre></div>\n</td></tr></table>'
)
elif sys.version_info[1] == 4:
fixture = (
'<table class="codehilitetable"><tr><td class="linenos">'
'<div class="linenodiv"><pre>1</pre></div></td><td class="code">'
'<div class="codehilite"><pre><span></span>'
'<span class="k">print</span>'
'<span class="p">(</span><span class="s1">'Hello, world!''
'</span><span class="p">)</span>\n'
'</pre></div>\n</td></tr></table>'
)
self.assertEqual(
codehilite.html,
fixture
)
def check_extra(self, pages):
extra_sep = '\n' if sys.version_info[:2] > (2, 6) else '\n\n'
extra = pages.get('extra')
self.assertEqual(
extra.html,
'<p>This is <em>true</em> markdown text.</p>\n'
'<div>{0}'
'<p>This is <em>true</em> markdown text.</p>\n'
'</div>'.format(extra_sep)
)
def test_basic(self):
pages = FlatPages(Flask(__name__))
hello = pages.get('headerid')
self.assertEqual(
hello.html,
u'<h1>Page Header</h1>\n<h2>Paragraph Header</h2>\n<p>Text</p>'
)
pages.app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = []
pages.reload()
pages._file_cache = {}
hello = pages.get('headerid')
self.assertEqual(
hello.html,
u'<h1>Page Header</h1>\n<h2>Paragraph Header</h2>\n<p>Text</p>'
)
self.check_default_codehilite_page(pages)
def test_codehilite_linenums_disabled(self):
#Test explicity disabled
app = Flask(__name__)
app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = ['codehilite']
pages = FlatPages(app)
self.check_default_codehilite_page(pages)
#Test explicity disabled
pages.app.config['FLATPAGES_EXTENSION_CONFIGS'] = {
'codehilite': {
'linenums': 'False'
}
}
pages.reload()
pages._file_cache = {}
self.check_default_codehilite_page(pages)
def test_codehilite_linenums_enabled(self):
app = Flask(__name__)
app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = ['codehilite']
app.config['FLATPAGES_EXTENSION_CONFIGS'] = {
'codehilite': {
'linenums': 'True'
}
}
pages = FlatPages(app)
self.check_codehilite_with_linenums(pages)
def test_extra(self):
app = Flask(__name__)
app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = ['extra']
pages = FlatPages(app)
self.check_extra(pages)
def test_toc(self):
app = Flask(__name__)
app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = ['toc']
pages = FlatPages(app)
self.check_toc_page(pages)
def test_headerid_with_toc(self):
app = Flask(__name__)
pages = FlatPages(app)
pages.app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = [
'codehilite', 'toc' #headerid is deprecated in Markdown 3.0
]
pages.reload()
pages._file_cache = {}
hello = pages.get('headerid')
self.assertEqual(
hello.html,
'<h1 id="page-header">Page Header</h1>\n'
'<h2 id="paragraph-header">Paragraph Header</h2>\n'
'<p>Text</p>'
)
self.check_default_codehilite_page(pages) #test codehilite also loaded
def test_extension_importpath(self):
app = Flask(__name__)
app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = [
'markdown.extensions.codehilite:CodeHiliteExtension'
]
pages = FlatPages(app)
self.check_default_codehilite_page(pages)
app.config['FLATPAGES_EXTENSION_CONFIGS'] = { #Markdown 3 style config
'markdown.extensions.codehilite:CodeHiliteExtension': {
'linenums': True
}
}
pages.reload()
pages._file_cache = {}
self.check_codehilite_with_linenums(pages)
def test_extension_object(self):
app = Flask(__name__)
from markdown.extensions.codehilite import CodeHiliteExtension
codehilite = CodeHiliteExtension()
app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = [codehilite]
pages = FlatPages(app)
self.check_default_codehilite_page(pages)
codehilite = CodeHiliteExtension(linenums='True') #Check config applies
app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = [codehilite]
pages.reload()
pages._file_cache = {}
self.check_codehilite_with_linenums(pages)
def test_mixed_extension_types(self):
app = Flask(__name__)
from markdown.extensions.toc import TocExtension
toc = TocExtension()
app.config['FLATPAGES_MARKDOWN_EXTENSIONS'] = [
toc,
'codehilite',
'markdown.extensions.extra:ExtraExtension'
]
pages = FlatPages(app)
self.check_toc_page(pages)
self.check_default_codehilite_page(pages)
self.check_extra(pages)
app.config['FLATPAGES_EXTENSION_CONFIGS'] = {
'codehilite': {
'linenums': 'True'
}
}
pages.reload()
pages._file_cache = {}
self.check_toc_page(pages)
self.check_extra(pages)
self.check_codehilite_with_linenums(pages)
| {
"pile_set_name": "Github"
} |
/*
Copyright 2014 The Kubernetes 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.
*/
package flowcontrol
import (
"context"
"errors"
"sync"
"time"
"golang.org/x/time/rate"
)
type RateLimiter interface {
// TryAccept returns true if a token is taken immediately. Otherwise,
// it returns false.
TryAccept() bool
// Accept returns once a token becomes available.
Accept()
// Stop stops the rate limiter, subsequent calls to CanAccept will return false
Stop()
// QPS returns QPS of this rate limiter
QPS() float32
// Wait returns nil if a token is taken before the Context is done.
Wait(ctx context.Context) error
}
type tokenBucketRateLimiter struct {
limiter *rate.Limiter
clock Clock
qps float32
}
// NewTokenBucketRateLimiter creates a rate limiter which implements a token bucket approach.
// The rate limiter allows bursts of up to 'burst' to exceed the QPS, while still maintaining a
// smoothed qps rate of 'qps'.
// The bucket is initially filled with 'burst' tokens, and refills at a rate of 'qps'.
// The maximum number of tokens in the bucket is capped at 'burst'.
func NewTokenBucketRateLimiter(qps float32, burst int) RateLimiter {
limiter := rate.NewLimiter(rate.Limit(qps), burst)
return newTokenBucketRateLimiter(limiter, realClock{}, qps)
}
// An injectable, mockable clock interface.
type Clock interface {
Now() time.Time
Sleep(time.Duration)
}
type realClock struct{}
func (realClock) Now() time.Time {
return time.Now()
}
func (realClock) Sleep(d time.Duration) {
time.Sleep(d)
}
// NewTokenBucketRateLimiterWithClock is identical to NewTokenBucketRateLimiter
// but allows an injectable clock, for testing.
func NewTokenBucketRateLimiterWithClock(qps float32, burst int, c Clock) RateLimiter {
limiter := rate.NewLimiter(rate.Limit(qps), burst)
return newTokenBucketRateLimiter(limiter, c, qps)
}
func newTokenBucketRateLimiter(limiter *rate.Limiter, c Clock, qps float32) RateLimiter {
return &tokenBucketRateLimiter{
limiter: limiter,
clock: c,
qps: qps,
}
}
func (t *tokenBucketRateLimiter) TryAccept() bool {
return t.limiter.AllowN(t.clock.Now(), 1)
}
// Accept will block until a token becomes available
func (t *tokenBucketRateLimiter) Accept() {
now := t.clock.Now()
t.clock.Sleep(t.limiter.ReserveN(now, 1).DelayFrom(now))
}
func (t *tokenBucketRateLimiter) Stop() {
}
func (t *tokenBucketRateLimiter) QPS() float32 {
return t.qps
}
func (t *tokenBucketRateLimiter) Wait(ctx context.Context) error {
return t.limiter.Wait(ctx)
}
type fakeAlwaysRateLimiter struct{}
func NewFakeAlwaysRateLimiter() RateLimiter {
return &fakeAlwaysRateLimiter{}
}
func (t *fakeAlwaysRateLimiter) TryAccept() bool {
return true
}
func (t *fakeAlwaysRateLimiter) Stop() {}
func (t *fakeAlwaysRateLimiter) Accept() {}
func (t *fakeAlwaysRateLimiter) QPS() float32 {
return 1
}
func (t *fakeAlwaysRateLimiter) Wait(ctx context.Context) error {
return nil
}
type fakeNeverRateLimiter struct {
wg sync.WaitGroup
}
func NewFakeNeverRateLimiter() RateLimiter {
rl := fakeNeverRateLimiter{}
rl.wg.Add(1)
return &rl
}
func (t *fakeNeverRateLimiter) TryAccept() bool {
return false
}
func (t *fakeNeverRateLimiter) Stop() {
t.wg.Done()
}
func (t *fakeNeverRateLimiter) Accept() {
t.wg.Wait()
}
func (t *fakeNeverRateLimiter) QPS() float32 {
return 1
}
func (t *fakeNeverRateLimiter) Wait(ctx context.Context) error {
return errors.New("can not be accept")
}
| {
"pile_set_name": "Github"
} |
#if IOS
using LibVLCSharp.Forms.Platforms.iOS;
using LibVLCSharp.Forms.Shared;
using UIKit;
using Xamarin.Forms;
[assembly: Dependency(typeof(PowerManager))]
namespace LibVLCSharp.Forms.Platforms.iOS
{
/// <summary>
/// Power manager.
/// </summary>
internal class PowerManager : IPowerManager
{
/// <summary>
/// Gets or sets a value indicating whether the screen should be kept on.
/// </summary>
public bool KeepScreenOn
{
get => UIApplication.SharedApplication.IdleTimerDisabled;
set => UIApplication.SharedApplication.IdleTimerDisabled = value;
}
}
}
#endif
| {
"pile_set_name": "Github"
} |
Copyright (c) 2017
Glyph Lefkowitz
Itamar Turner-Trauring
Jean Paul Calderone
Adi Roiban
Amber Hawkie Brown
Mahmoud Hashemi
and others that have contributed code to the public domain.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | {
"pile_set_name": "Github"
} |
package slack
import (
"context"
"errors"
"net/url"
"strconv"
"strings"
)
// Conversation is the foundation for IM and BaseGroupConversation
type conversation struct {
ID string `json:"id"`
Created JSONTime `json:"created"`
IsOpen bool `json:"is_open"`
LastRead string `json:"last_read,omitempty"`
Latest *Message `json:"latest,omitempty"`
UnreadCount int `json:"unread_count,omitempty"`
UnreadCountDisplay int `json:"unread_count_display,omitempty"`
IsGroup bool `json:"is_group"`
IsShared bool `json:"is_shared"`
IsIM bool `json:"is_im"`
IsExtShared bool `json:"is_ext_shared"`
IsOrgShared bool `json:"is_org_shared"`
IsPendingExtShared bool `json:"is_pending_ext_shared"`
IsPrivate bool `json:"is_private"`
IsMpIM bool `json:"is_mpim"`
Unlinked int `json:"unlinked"`
NameNormalized string `json:"name_normalized"`
NumMembers int `json:"num_members"`
Priority float64 `json:"priority"`
User string `json:"user"`
// TODO support pending_shared
// TODO support previous_names
}
// GroupConversation is the foundation for Group and Channel
type groupConversation struct {
conversation
Name string `json:"name"`
Creator string `json:"creator"`
IsArchived bool `json:"is_archived"`
Members []string `json:"members"`
Topic Topic `json:"topic"`
Purpose Purpose `json:"purpose"`
}
// Topic contains information about the topic
type Topic struct {
Value string `json:"value"`
Creator string `json:"creator"`
LastSet JSONTime `json:"last_set"`
}
// Purpose contains information about the purpose
type Purpose struct {
Value string `json:"value"`
Creator string `json:"creator"`
LastSet JSONTime `json:"last_set"`
}
type GetUsersInConversationParameters struct {
ChannelID string
Cursor string
Limit int
}
type GetConversationsForUserParameters struct {
UserID string
Cursor string
Types []string
Limit int
}
type responseMetaData struct {
NextCursor string `json:"next_cursor"`
}
// GetUsersInConversation returns the list of users in a conversation
func (api *Client) GetUsersInConversation(params *GetUsersInConversationParameters) ([]string, string, error) {
return api.GetUsersInConversationContext(context.Background(), params)
}
// GetUsersInConversationContext returns the list of users in a conversation with a custom context
func (api *Client) GetUsersInConversationContext(ctx context.Context, params *GetUsersInConversationParameters) ([]string, string, error) {
values := url.Values{
"token": {api.token},
"channel": {params.ChannelID},
}
if params.Cursor != "" {
values.Add("cursor", params.Cursor)
}
if params.Limit != 0 {
values.Add("limit", strconv.Itoa(params.Limit))
}
response := struct {
Members []string `json:"members"`
ResponseMetaData responseMetaData `json:"response_metadata"`
SlackResponse
}{}
err := postSlackMethod(ctx, api.httpclient, "conversations.members", values, &response, api)
if err != nil {
return nil, "", err
}
if !response.Ok {
return nil, "", errors.New(response.Error)
}
return response.Members, response.ResponseMetaData.NextCursor, nil
}
// GetConversationsForUser returns the list conversations for a given user
func (api *Client) GetConversationsForUser(params *GetConversationsForUserParameters) (channels []Channel, nextCursor string, err error) {
return api.GetConversationsForUserContext(context.Background(), params)
}
// GetConversationsForUserContext returns the list conversations for a given user with a custom context
func (api *Client) GetConversationsForUserContext(ctx context.Context, params *GetConversationsForUserParameters) (channels []Channel, nextCursor string, err error) {
values := url.Values{
"token": {api.token},
}
if params.UserID != "" {
values.Add("user", params.UserID)
}
if params.Cursor != "" {
values.Add("cursor", params.Cursor)
}
if params.Limit != 0 {
values.Add("limit", strconv.Itoa(params.Limit))
}
if params.Types != nil {
values.Add("types", strings.Join(params.Types, ","))
}
response := struct {
Channels []Channel `json:"channels"`
ResponseMetaData responseMetaData `json:"response_metadata"`
SlackResponse
}{}
err = postSlackMethod(ctx, api.httpclient, "users.conversations", values, &response, api)
if err != nil {
return nil, "", err
}
return response.Channels, response.ResponseMetaData.NextCursor, response.Err()
}
// ArchiveConversation archives a conversation
func (api *Client) ArchiveConversation(channelID string) error {
return api.ArchiveConversationContext(context.Background(), channelID)
}
// ArchiveConversationContext archives a conversation with a custom context
func (api *Client) ArchiveConversationContext(ctx context.Context, channelID string) error {
values := url.Values{
"token": {api.token},
"channel": {channelID},
}
response := SlackResponse{}
err := postSlackMethod(ctx, api.httpclient, "conversations.archive", values, &response, api)
if err != nil {
return err
}
return response.Err()
}
// UnArchiveConversation reverses conversation archival
func (api *Client) UnArchiveConversation(channelID string) error {
return api.UnArchiveConversationContext(context.Background(), channelID)
}
// UnArchiveConversationContext reverses conversation archival with a custom context
func (api *Client) UnArchiveConversationContext(ctx context.Context, channelID string) error {
values := url.Values{
"token": {api.token},
"channel": {channelID},
}
response := SlackResponse{}
err := postSlackMethod(ctx, api.httpclient, "conversations.unarchive", values, &response, api)
if err != nil {
return err
}
return response.Err()
}
// SetTopicOfConversation sets the topic for a conversation
func (api *Client) SetTopicOfConversation(channelID, topic string) (*Channel, error) {
return api.SetTopicOfConversationContext(context.Background(), channelID, topic)
}
// SetTopicOfConversationContext sets the topic for a conversation with a custom context
func (api *Client) SetTopicOfConversationContext(ctx context.Context, channelID, topic string) (*Channel, error) {
values := url.Values{
"token": {api.token},
"channel": {channelID},
"topic": {topic},
}
response := struct {
SlackResponse
Channel *Channel `json:"channel"`
}{}
err := postSlackMethod(ctx, api.httpclient, "conversations.setTopic", values, &response, api)
if err != nil {
return nil, err
}
return response.Channel, response.Err()
}
// SetPurposeOfConversation sets the purpose for a conversation
func (api *Client) SetPurposeOfConversation(channelID, purpose string) (*Channel, error) {
return api.SetPurposeOfConversationContext(context.Background(), channelID, purpose)
}
// SetPurposeOfConversationContext sets the purpose for a conversation with a custom context
func (api *Client) SetPurposeOfConversationContext(ctx context.Context, channelID, purpose string) (*Channel, error) {
values := url.Values{
"token": {api.token},
"channel": {channelID},
"purpose": {purpose},
}
response := struct {
SlackResponse
Channel *Channel `json:"channel"`
}{}
err := postSlackMethod(ctx, api.httpclient, "conversations.setPurpose", values, &response, api)
if err != nil {
return nil, err
}
return response.Channel, response.Err()
}
// RenameConversation renames a conversation
func (api *Client) RenameConversation(channelID, channelName string) (*Channel, error) {
return api.RenameConversationContext(context.Background(), channelID, channelName)
}
// RenameConversationContext renames a conversation with a custom context
func (api *Client) RenameConversationContext(ctx context.Context, channelID, channelName string) (*Channel, error) {
values := url.Values{
"token": {api.token},
"channel": {channelID},
"name": {channelName},
}
response := struct {
SlackResponse
Channel *Channel `json:"channel"`
}{}
err := postSlackMethod(ctx, api.httpclient, "conversations.rename", values, &response, api)
if err != nil {
return nil, err
}
return response.Channel, response.Err()
}
// InviteUsersToConversation invites users to a channel
func (api *Client) InviteUsersToConversation(channelID string, users ...string) (*Channel, error) {
return api.InviteUsersToConversationContext(context.Background(), channelID, users...)
}
// InviteUsersToConversationContext invites users to a channel with a custom context
func (api *Client) InviteUsersToConversationContext(ctx context.Context, channelID string, users ...string) (*Channel, error) {
values := url.Values{
"token": {api.token},
"channel": {channelID},
"users": {strings.Join(users, ",")},
}
response := struct {
SlackResponse
Channel *Channel `json:"channel"`
}{}
err := postSlackMethod(ctx, api.httpclient, "conversations.invite", values, &response, api)
if err != nil {
return nil, err
}
return response.Channel, response.Err()
}
// KickUserFromConversation removes a user from a conversation
func (api *Client) KickUserFromConversation(channelID string, user string) error {
return api.KickUserFromConversationContext(context.Background(), channelID, user)
}
// KickUserFromConversationContext removes a user from a conversation with a custom context
func (api *Client) KickUserFromConversationContext(ctx context.Context, channelID string, user string) error {
values := url.Values{
"token": {api.token},
"channel": {channelID},
"user": {user},
}
response := SlackResponse{}
err := postSlackMethod(ctx, api.httpclient, "conversations.kick", values, &response, api)
if err != nil {
return err
}
return response.Err()
}
// CloseConversation closes a direct message or multi-person direct message
func (api *Client) CloseConversation(channelID string) (noOp bool, alreadyClosed bool, err error) {
return api.CloseConversationContext(context.Background(), channelID)
}
// CloseConversationContext closes a direct message or multi-person direct message with a custom context
func (api *Client) CloseConversationContext(ctx context.Context, channelID string) (noOp bool, alreadyClosed bool, err error) {
values := url.Values{
"token": {api.token},
"channel": {channelID},
}
response := struct {
SlackResponse
NoOp bool `json:"no_op"`
AlreadyClosed bool `json:"already_closed"`
}{}
err = postSlackMethod(ctx, api.httpclient, "conversations.close", values, &response, api)
if err != nil {
return false, false, err
}
return response.NoOp, response.AlreadyClosed, response.Err()
}
// CreateConversation initiates a public or private channel-based conversation
func (api *Client) CreateConversation(channelName string, isPrivate bool) (*Channel, error) {
return api.CreateConversationContext(context.Background(), channelName, isPrivate)
}
// CreateConversationContext initiates a public or private channel-based conversation with a custom context
func (api *Client) CreateConversationContext(ctx context.Context, channelName string, isPrivate bool) (*Channel, error) {
values := url.Values{
"token": {api.token},
"name": {channelName},
"is_private": {strconv.FormatBool(isPrivate)},
}
response, err := channelRequest(
ctx, api.httpclient, "conversations.create", values, api)
if err != nil {
return nil, err
}
return &response.Channel, response.Err()
}
// GetConversationInfo retrieves information about a conversation
func (api *Client) GetConversationInfo(channelID string, includeLocale bool) (*Channel, error) {
return api.GetConversationInfoContext(context.Background(), channelID, includeLocale)
}
// GetConversationInfoContext retrieves information about a conversation with a custom context
func (api *Client) GetConversationInfoContext(ctx context.Context, channelID string, includeLocale bool) (*Channel, error) {
values := url.Values{
"token": {api.token},
"channel": {channelID},
"include_locale": {strconv.FormatBool(includeLocale)},
}
response, err := channelRequest(
ctx, api.httpclient, "conversations.info", values, api)
if err != nil {
return nil, err
}
return &response.Channel, response.Err()
}
// LeaveConversation leaves a conversation
func (api *Client) LeaveConversation(channelID string) (bool, error) {
return api.LeaveConversationContext(context.Background(), channelID)
}
// LeaveConversationContext leaves a conversation with a custom context
func (api *Client) LeaveConversationContext(ctx context.Context, channelID string) (bool, error) {
values := url.Values{
"token": {api.token},
"channel": {channelID},
}
response, err := channelRequest(ctx, api.httpclient, "conversations.leave", values, api)
if err != nil {
return false, err
}
return response.NotInChannel, err
}
type GetConversationRepliesParameters struct {
ChannelID string
Timestamp string
Cursor string
Inclusive bool
Latest string
Limit int
Oldest string
}
// GetConversationReplies retrieves a thread of messages posted to a conversation
func (api *Client) GetConversationReplies(params *GetConversationRepliesParameters) (msgs []Message, hasMore bool, nextCursor string, err error) {
return api.GetConversationRepliesContext(context.Background(), params)
}
// GetConversationRepliesContext retrieves a thread of messages posted to a conversation with a custom context
func (api *Client) GetConversationRepliesContext(ctx context.Context, params *GetConversationRepliesParameters) (msgs []Message, hasMore bool, nextCursor string, err error) {
values := url.Values{
"token": {api.token},
"channel": {params.ChannelID},
"ts": {params.Timestamp},
}
if params.Cursor != "" {
values.Add("cursor", params.Cursor)
}
if params.Latest != "" {
values.Add("latest", params.Latest)
}
if params.Limit != 0 {
values.Add("limit", strconv.Itoa(params.Limit))
}
if params.Oldest != "" {
values.Add("oldest", params.Oldest)
}
if params.Inclusive {
values.Add("inclusive", "1")
} else {
values.Add("inclusive", "0")
}
response := struct {
SlackResponse
HasMore bool `json:"has_more"`
ResponseMetaData struct {
NextCursor string `json:"next_cursor"`
} `json:"response_metadata"`
Messages []Message `json:"messages"`
}{}
err = postSlackMethod(ctx, api.httpclient, "conversations.replies", values, &response, api)
if err != nil {
return nil, false, "", err
}
return response.Messages, response.HasMore, response.ResponseMetaData.NextCursor, response.Err()
}
type GetConversationsParameters struct {
Cursor string
ExcludeArchived string
Limit int
Types []string
}
// GetConversations returns the list of channels in a Slack team
func (api *Client) GetConversations(params *GetConversationsParameters) (channels []Channel, nextCursor string, err error) {
return api.GetConversationsContext(context.Background(), params)
}
// GetConversationsContext returns the list of channels in a Slack team with a custom context
func (api *Client) GetConversationsContext(ctx context.Context, params *GetConversationsParameters) (channels []Channel, nextCursor string, err error) {
values := url.Values{
"token": {api.token},
"exclude_archived": {params.ExcludeArchived},
}
if params.Cursor != "" {
values.Add("cursor", params.Cursor)
}
if params.Limit != 0 {
values.Add("limit", strconv.Itoa(params.Limit))
}
if params.Types != nil {
values.Add("types", strings.Join(params.Types, ","))
}
response := struct {
Channels []Channel `json:"channels"`
ResponseMetaData responseMetaData `json:"response_metadata"`
SlackResponse
}{}
err = postSlackMethod(ctx, api.httpclient, "conversations.list", values, &response, api)
if err != nil {
return nil, "", err
}
return response.Channels, response.ResponseMetaData.NextCursor, response.Err()
}
type OpenConversationParameters struct {
ChannelID string
ReturnIM bool
Users []string
}
// OpenConversation opens or resumes a direct message or multi-person direct message
func (api *Client) OpenConversation(params *OpenConversationParameters) (*Channel, bool, bool, error) {
return api.OpenConversationContext(context.Background(), params)
}
// OpenConversationContext opens or resumes a direct message or multi-person direct message with a custom context
func (api *Client) OpenConversationContext(ctx context.Context, params *OpenConversationParameters) (*Channel, bool, bool, error) {
values := url.Values{
"token": {api.token},
"return_im": {strconv.FormatBool(params.ReturnIM)},
}
if params.ChannelID != "" {
values.Add("channel", params.ChannelID)
}
if params.Users != nil {
values.Add("users", strings.Join(params.Users, ","))
}
response := struct {
Channel *Channel `json:"channel"`
NoOp bool `json:"no_op"`
AlreadyOpen bool `json:"already_open"`
SlackResponse
}{}
err := postSlackMethod(ctx, api.httpclient, "conversations.open", values, &response, api)
if err != nil {
return nil, false, false, err
}
return response.Channel, response.NoOp, response.AlreadyOpen, response.Err()
}
// JoinConversation joins an existing conversation
func (api *Client) JoinConversation(channelID string) (*Channel, string, []string, error) {
return api.JoinConversationContext(context.Background(), channelID)
}
// JoinConversationContext joins an existing conversation with a custom context
func (api *Client) JoinConversationContext(ctx context.Context, channelID string) (*Channel, string, []string, error) {
values := url.Values{"token": {api.token}, "channel": {channelID}}
response := struct {
Channel *Channel `json:"channel"`
Warning string `json:"warning"`
ResponseMetaData *struct {
Warnings []string `json:"warnings"`
} `json:"response_metadata"`
SlackResponse
}{}
err := postSlackMethod(ctx, api.httpclient, "conversations.join", values, &response, api)
if err != nil {
return nil, "", nil, err
}
if response.Err() != nil {
return nil, "", nil, response.Err()
}
var warnings []string
if response.ResponseMetaData != nil {
warnings = response.ResponseMetaData.Warnings
}
return response.Channel, response.Warning, warnings, nil
}
type GetConversationHistoryParameters struct {
ChannelID string
Cursor string
Inclusive bool
Latest string
Limit int
Oldest string
}
type GetConversationHistoryResponse struct {
SlackResponse
HasMore bool `json:"has_more"`
PinCount int `json:"pin_count"`
Latest string `json:"latest"`
ResponseMetaData struct {
NextCursor string `json:"next_cursor"`
} `json:"response_metadata"`
Messages []Message `json:"messages"`
}
// GetConversationHistory joins an existing conversation
func (api *Client) GetConversationHistory(params *GetConversationHistoryParameters) (*GetConversationHistoryResponse, error) {
return api.GetConversationHistoryContext(context.Background(), params)
}
// GetConversationHistoryContext joins an existing conversation with a custom context
func (api *Client) GetConversationHistoryContext(ctx context.Context, params *GetConversationHistoryParameters) (*GetConversationHistoryResponse, error) {
values := url.Values{"token": {api.token}, "channel": {params.ChannelID}}
if params.Cursor != "" {
values.Add("cursor", params.Cursor)
}
if params.Inclusive {
values.Add("inclusive", "1")
} else {
values.Add("inclusive", "0")
}
if params.Latest != "" {
values.Add("latest", params.Latest)
}
if params.Limit != 0 {
values.Add("limit", strconv.Itoa(params.Limit))
}
if params.Oldest != "" {
values.Add("oldest", params.Oldest)
}
response := GetConversationHistoryResponse{}
err := postSlackMethod(ctx, api.httpclient, "conversations.history", values, &response, api)
if err != nil {
return nil, err
}
return &response, response.Err()
}
| {
"pile_set_name": "Github"
} |
<noscript><meta http-equiv="refresh" content="0; url=/zend-stratigility/v3/creating-middleware/"></noscript>
<script>
document.addEventListener("DOMContentLoaded", function (event) {
var uri = new URL(window.location.href);
uri.pathname = '/zend-stratigility/v3/creating-middleware/';
window.location = uri.href;
});
</script>
| {
"pile_set_name": "Github"
} |
<!--
// 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.
-->
<div class="well well-small form-inline">
<input type="text" placeholder="Search" class="input-medium search-query" ng-model="search.name">
<modal-form form-details="addAccountForm">
<button class="btn">Add Account</button>
</modal-form>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th ng-repeat="attribute in toDisplay"> {{dictionary.labels[attribute]}} </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="model in collection">
<td ng-repeat="attribute in toDisplay">{{model[attribute]}}</td>
</tr>
</tbody>
</table>
| {
"pile_set_name": "Github"
} |
// Copyright 2013 MongoDB, Inc.
//
// 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.
// author tolsen
// author-github https://github.com/tolsen
//
// repository-name gojsonschema
// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
//
// description Implements a persistent (immutable w/ shared structure) singly-linked list of strings for the purpose of storing a json context
//
// created 04-09-2013
package gojsonschema
import "bytes"
// JsonContext implements a persistent linked-list of strings
type JsonContext struct {
head string
tail *JsonContext
}
// NewJsonContext creates a new JsonContext
func NewJsonContext(head string, tail *JsonContext) *JsonContext {
return &JsonContext{head, tail}
}
// String displays the context in reverse.
// This plays well with the data structure's persistent nature with
// Cons and a json document's tree structure.
func (c *JsonContext) String(del ...string) string {
byteArr := make([]byte, 0, c.stringLen())
buf := bytes.NewBuffer(byteArr)
c.writeStringToBuffer(buf, del)
return buf.String()
}
func (c *JsonContext) stringLen() int {
length := 0
if c.tail != nil {
length = c.tail.stringLen() + 1 // add 1 for "."
}
length += len(c.head)
return length
}
func (c *JsonContext) writeStringToBuffer(buf *bytes.Buffer, del []string) {
if c.tail != nil {
c.tail.writeStringToBuffer(buf, del)
if len(del) > 0 {
buf.WriteString(del[0])
} else {
buf.WriteString(".")
}
}
buf.WriteString(c.head)
}
| {
"pile_set_name": "Github"
} |
SELECT
r.oid, r.rolname, r.rolcanlogin, r.rolsuper
FROM
pg_roles r
{% if rid %}
WHERE r.oid = {{ rid|qtLiteral }}::oid
{% endif %}
ORDER BY r.rolcanlogin, r.rolname
| {
"pile_set_name": "Github"
} |
#ifdef HAVE_CONFIG_H
#include "../ext_config.h"
#endif
#include <php.h>
#include "../php_ext.h"
#include "../ext.h"
#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>
#include "kernel/main.h"
#include "kernel/string.h"
#include "kernel/memory.h"
#include "kernel/array.h"
#include "kernel/operators.h"
#include "kernel/math.h"
#include "kernel/object.h"
#include "kernel/concat.h"
#include "kernel/fcall.h"
ZEPHIR_INIT_CLASS(Stub_Fasta) {
ZEPHIR_REGISTER_CLASS(Stub, Fasta, stub, fasta, stub_fasta_method_entry, 0);
return SUCCESS;
}
PHP_METHOD(Stub_Fasta, fastaRepeat) {
zval _2, _5;
zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
zend_long ZEPHIR_LAST_CALL_STATUS, seqi, i = 0;
zval seq;
zval *n, n_sub, *seq_param = NULL, len, j, k, l, block, str, lines, _0, _1, _3, _4, _9, _10, _6$$3, _7$$3, _8$$3, _11$$6, _12$$7, _13$$7, _14$$7, _15$$7;
zval *this_ptr = getThis();
ZVAL_UNDEF(&n_sub);
ZVAL_UNDEF(&len);
ZVAL_UNDEF(&j);
ZVAL_UNDEF(&k);
ZVAL_UNDEF(&l);
ZVAL_UNDEF(&block);
ZVAL_UNDEF(&str);
ZVAL_UNDEF(&lines);
ZVAL_UNDEF(&_0);
ZVAL_UNDEF(&_1);
ZVAL_UNDEF(&_3);
ZVAL_UNDEF(&_4);
ZVAL_UNDEF(&_9);
ZVAL_UNDEF(&_10);
ZVAL_UNDEF(&_6$$3);
ZVAL_UNDEF(&_7$$3);
ZVAL_UNDEF(&_8$$3);
ZVAL_UNDEF(&_11$$6);
ZVAL_UNDEF(&_12$$7);
ZVAL_UNDEF(&_13$$7);
ZVAL_UNDEF(&_14$$7);
ZVAL_UNDEF(&_15$$7);
ZVAL_UNDEF(&seq);
ZVAL_UNDEF(&_2);
ZVAL_UNDEF(&_5);
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 2, 0, &n, &seq_param);
zephir_get_strval(&seq, seq_param);
seqi = 0;
ZEPHIR_INIT_VAR(&len);
ZVAL_LONG(&len, zephir_fast_strlen_ev(&seq));
ZEPHIR_INIT_VAR(&_0);
ZVAL_LONG(&_1, ((zephir_get_numberval(&len) * 60) + 1));
zephir_create_array(&_0, zephir_get_intval(&_1), 1);
zephir_get_arrval(&_2, &_0);
ZEPHIR_INIT_VAR(&str);
zephir_fast_join(&str, &seq, &_2);
ZEPHIR_INIT_VAR(&_3);
ZEPHIR_INIT_VAR(&_4);
mul_function(&_4, &len, &len);
zephir_create_array(&_3, zephir_get_intval(&_4), 1);
zephir_get_arrval(&_5, &_3);
ZEPHIR_CPY_WRT(&lines, &_5);
ZEPHIR_INIT_VAR(&j);
mul_function(&j, &len, &len);
i = zephir_get_numberval(&j);
while (1) {
if (ZEPHIR_LE_LONG(&j, -1)) {
break;
}
ZEPHIR_SEPARATE(&j);
zephir_decrement(&j);
ZVAL_LONG(&_6$$3, (60 * zephir_get_numberval(&j)));
ZVAL_LONG(&_7$$3, 60);
ZEPHIR_INIT_NVAR(&_8$$3);
zephir_substr(&_8$$3, &str, zephir_get_intval(&_6$$3), 60 , 0);
zephir_array_update_zval(&lines, &j, &_8$$3, PH_COPY | PH_SEPARATE);
}
ZEPHIR_INIT_NVAR(&j);
ZVAL_LONG(&j, 0);
ZVAL_DOUBLE(&_9, zephir_safe_div_zval_long(n, 60));
ZEPHIR_INIT_VAR(&l);
ZVAL_DOUBLE(&l, zephir_floor(&_9));
ZVAL_DOUBLE(&_10, zephir_safe_div_zval_long(&l, i));
ZEPHIR_INIT_VAR(&k);
ZVAL_DOUBLE(&k, zephir_floor(&_10));
ZEPHIR_INIT_VAR(&block);
zephir_fast_join_str(&block, SL("\n"), &lines);
while (1) {
if (!(ZEPHIR_LT(&j, &k))) {
break;
}
zend_print_zval(&block, 0);
ZEPHIR_SEPARATE(&j);
zephir_increment(&j);
}
ZEPHIR_INIT_NVAR(&j);
ZVAL_LONG(&j, 0);
ZEPHIR_INIT_NVAR(&k);
ZVAL_DOUBLE(&k, zephir_safe_mod_zval_long(&l, i));
while (1) {
if (!(ZEPHIR_LT(&j, &k))) {
break;
}
zephir_array_fetch(&_11$$6, &lines, &j, PH_NOISY | PH_READONLY, "stub/fasta.zep", 38);
zend_print_zval(&_11$$6, 0);
ZEPHIR_SEPARATE(&j);
zephir_increment(&j);
}
if (zephir_safe_mod_zval_long(n, 60) > 0) {
zephir_array_fetch(&_12$$7, &lines, &k, PH_NOISY | PH_READONLY, "stub/fasta.zep", 43);
ZVAL_LONG(&_13$$7, 0);
ZVAL_DOUBLE(&_14$$7, zephir_safe_mod_zval_long(n, 60));
ZEPHIR_INIT_VAR(&_15$$7);
zephir_substr(&_15$$7, &_12$$7, 0 , zephir_get_intval(&_14$$7), 0);
zend_print_zval(&_15$$7, 0);
}
ZEPHIR_MM_RESTORE();
}
PHP_METHOD(Stub_Fasta, fastRandom) {
zval *this_ptr = getThis();
}
PHP_METHOD(Stub_Fasta, main) {
zval _0;
zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
zend_long ZEPHIR_LAST_CALL_STATUS;
zval *n, n_sub, alu, iub, homoSap, _1;
zval *this_ptr = getThis();
ZVAL_UNDEF(&n_sub);
ZVAL_UNDEF(&alu);
ZVAL_UNDEF(&iub);
ZVAL_UNDEF(&homoSap);
ZVAL_UNDEF(&_1);
ZVAL_UNDEF(&_0);
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &n);
ZEPHIR_INIT_VAR(&_0);
ZEPHIR_CONCAT_SSSSSSS(&_0, "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG", "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA", "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT", "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA", "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG", "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC", "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA");
ZEPHIR_CPY_WRT(&alu, &_0);
ZEPHIR_INIT_VAR(&iub);
zephir_create_array(&iub, 15, 0);
add_assoc_double_ex(&iub, SL("a"), 0.27);
add_assoc_double_ex(&iub, SL("c"), 0.12);
add_assoc_double_ex(&iub, SL("g"), 0.12);
add_assoc_double_ex(&iub, SL("t"), 0.27);
add_assoc_double_ex(&iub, SL("B"), 0.02);
add_assoc_double_ex(&iub, SL("D"), 0.02);
add_assoc_double_ex(&iub, SL("H"), 0.02);
add_assoc_double_ex(&iub, SL("K"), 0.02);
add_assoc_double_ex(&iub, SL("M"), 0.02);
add_assoc_double_ex(&iub, SL("N"), 0.02);
add_assoc_double_ex(&iub, SL("R"), 0.02);
add_assoc_double_ex(&iub, SL("S"), 0.02);
add_assoc_double_ex(&iub, SL("V"), 0.02);
add_assoc_double_ex(&iub, SL("W"), 0.02);
add_assoc_double_ex(&iub, SL("Y"), 0.02);
ZEPHIR_INIT_VAR(&homoSap);
zephir_create_array(&homoSap, 4, 0);
add_assoc_double_ex(&homoSap, SL("a"), 0.3029549426680);
add_assoc_double_ex(&homoSap, SL("c"), 0.1979883004921);
add_assoc_double_ex(&homoSap, SL("g"), 0.1975473066391);
add_assoc_double_ex(&homoSap, SL("t"), 0.3015094502008);
php_printf("%s", ">ONE Homo sapiens alu");
ZVAL_LONG(&_1, (2 * zephir_get_numberval(n)));
ZEPHIR_CALL_METHOD(NULL, this_ptr, "fastarepeat", NULL, 0, &_1, &alu);
zephir_check_call_status();
ZEPHIR_MM_RESTORE();
}
| {
"pile_set_name": "Github"
} |
"use strict";
var helpers = require("../../../helpers/helpers");
exports["America/Indiana/Knox"] = {
"guess:by:offset" : helpers.makeTestGuess("America/Indiana/Knox", { offset: true, expect: "America/Chicago" }),
"guess:by:abbr" : helpers.makeTestGuess("America/Indiana/Knox", { abbr: true, expect: "America/Chicago" }),
"1918" : helpers.makeTestYear("America/Indiana/Knox", [
["1918-03-31T07:59:59+00:00", "01:59:59", "CST", 360],
["1918-03-31T08:00:00+00:00", "03:00:00", "CDT", 300],
["1918-10-27T06:59:59+00:00", "01:59:59", "CDT", 300],
["1918-10-27T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1919" : helpers.makeTestYear("America/Indiana/Knox", [
["1919-03-30T07:59:59+00:00", "01:59:59", "CST", 360],
["1919-03-30T08:00:00+00:00", "03:00:00", "CDT", 300],
["1919-10-26T06:59:59+00:00", "01:59:59", "CDT", 300],
["1919-10-26T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1942" : helpers.makeTestYear("America/Indiana/Knox", [
["1942-02-09T07:59:59+00:00", "01:59:59", "CST", 360],
["1942-02-09T08:00:00+00:00", "03:00:00", "CWT", 300]
]),
"1945" : helpers.makeTestYear("America/Indiana/Knox", [
["1945-08-14T22:59:59+00:00", "17:59:59", "CWT", 300],
["1945-08-14T23:00:00+00:00", "18:00:00", "CPT", 300],
["1945-09-30T06:59:59+00:00", "01:59:59", "CPT", 300],
["1945-09-30T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1947" : helpers.makeTestYear("America/Indiana/Knox", [
["1947-04-27T07:59:59+00:00", "01:59:59", "CST", 360],
["1947-04-27T08:00:00+00:00", "03:00:00", "CDT", 300],
["1947-09-28T06:59:59+00:00", "01:59:59", "CDT", 300],
["1947-09-28T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1948" : helpers.makeTestYear("America/Indiana/Knox", [
["1948-04-25T07:59:59+00:00", "01:59:59", "CST", 360],
["1948-04-25T08:00:00+00:00", "03:00:00", "CDT", 300],
["1948-09-26T06:59:59+00:00", "01:59:59", "CDT", 300],
["1948-09-26T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1949" : helpers.makeTestYear("America/Indiana/Knox", [
["1949-04-24T07:59:59+00:00", "01:59:59", "CST", 360],
["1949-04-24T08:00:00+00:00", "03:00:00", "CDT", 300],
["1949-09-25T06:59:59+00:00", "01:59:59", "CDT", 300],
["1949-09-25T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1950" : helpers.makeTestYear("America/Indiana/Knox", [
["1950-04-30T07:59:59+00:00", "01:59:59", "CST", 360],
["1950-04-30T08:00:00+00:00", "03:00:00", "CDT", 300],
["1950-09-24T06:59:59+00:00", "01:59:59", "CDT", 300],
["1950-09-24T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1951" : helpers.makeTestYear("America/Indiana/Knox", [
["1951-04-29T07:59:59+00:00", "01:59:59", "CST", 360],
["1951-04-29T08:00:00+00:00", "03:00:00", "CDT", 300],
["1951-09-30T06:59:59+00:00", "01:59:59", "CDT", 300],
["1951-09-30T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1952" : helpers.makeTestYear("America/Indiana/Knox", [
["1952-04-27T07:59:59+00:00", "01:59:59", "CST", 360],
["1952-04-27T08:00:00+00:00", "03:00:00", "CDT", 300],
["1952-09-28T06:59:59+00:00", "01:59:59", "CDT", 300],
["1952-09-28T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1953" : helpers.makeTestYear("America/Indiana/Knox", [
["1953-04-26T07:59:59+00:00", "01:59:59", "CST", 360],
["1953-04-26T08:00:00+00:00", "03:00:00", "CDT", 300],
["1953-09-27T06:59:59+00:00", "01:59:59", "CDT", 300],
["1953-09-27T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1954" : helpers.makeTestYear("America/Indiana/Knox", [
["1954-04-25T07:59:59+00:00", "01:59:59", "CST", 360],
["1954-04-25T08:00:00+00:00", "03:00:00", "CDT", 300],
["1954-09-26T06:59:59+00:00", "01:59:59", "CDT", 300],
["1954-09-26T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1955" : helpers.makeTestYear("America/Indiana/Knox", [
["1955-04-24T07:59:59+00:00", "01:59:59", "CST", 360],
["1955-04-24T08:00:00+00:00", "03:00:00", "CDT", 300],
["1955-10-30T06:59:59+00:00", "01:59:59", "CDT", 300],
["1955-10-30T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1956" : helpers.makeTestYear("America/Indiana/Knox", [
["1956-04-29T07:59:59+00:00", "01:59:59", "CST", 360],
["1956-04-29T08:00:00+00:00", "03:00:00", "CDT", 300],
["1956-10-28T06:59:59+00:00", "01:59:59", "CDT", 300],
["1956-10-28T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1957" : helpers.makeTestYear("America/Indiana/Knox", [
["1957-04-28T07:59:59+00:00", "01:59:59", "CST", 360],
["1957-04-28T08:00:00+00:00", "03:00:00", "CDT", 300],
["1957-09-29T06:59:59+00:00", "01:59:59", "CDT", 300],
["1957-09-29T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1958" : helpers.makeTestYear("America/Indiana/Knox", [
["1958-04-27T07:59:59+00:00", "01:59:59", "CST", 360],
["1958-04-27T08:00:00+00:00", "03:00:00", "CDT", 300],
["1958-09-28T06:59:59+00:00", "01:59:59", "CDT", 300],
["1958-09-28T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1959" : helpers.makeTestYear("America/Indiana/Knox", [
["1959-04-26T07:59:59+00:00", "01:59:59", "CST", 360],
["1959-04-26T08:00:00+00:00", "03:00:00", "CDT", 300],
["1959-10-25T06:59:59+00:00", "01:59:59", "CDT", 300],
["1959-10-25T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1960" : helpers.makeTestYear("America/Indiana/Knox", [
["1960-04-24T07:59:59+00:00", "01:59:59", "CST", 360],
["1960-04-24T08:00:00+00:00", "03:00:00", "CDT", 300],
["1960-10-30T06:59:59+00:00", "01:59:59", "CDT", 300],
["1960-10-30T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1961" : helpers.makeTestYear("America/Indiana/Knox", [
["1961-04-30T07:59:59+00:00", "01:59:59", "CST", 360],
["1961-04-30T08:00:00+00:00", "03:00:00", "CDT", 300],
["1961-10-29T06:59:59+00:00", "01:59:59", "CDT", 300],
["1961-10-29T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1962" : helpers.makeTestYear("America/Indiana/Knox", [
["1962-04-29T07:59:59+00:00", "01:59:59", "CST", 360],
["1962-04-29T08:00:00+00:00", "03:00:00", "EST", 300]
]),
"1963" : helpers.makeTestYear("America/Indiana/Knox", [
["1963-10-27T06:59:59+00:00", "01:59:59", "EST", 300],
["1963-10-27T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1967" : helpers.makeTestYear("America/Indiana/Knox", [
["1967-04-30T07:59:59+00:00", "01:59:59", "CST", 360],
["1967-04-30T08:00:00+00:00", "03:00:00", "CDT", 300],
["1967-10-29T06:59:59+00:00", "01:59:59", "CDT", 300],
["1967-10-29T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1968" : helpers.makeTestYear("America/Indiana/Knox", [
["1968-04-28T07:59:59+00:00", "01:59:59", "CST", 360],
["1968-04-28T08:00:00+00:00", "03:00:00", "CDT", 300],
["1968-10-27T06:59:59+00:00", "01:59:59", "CDT", 300],
["1968-10-27T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1969" : helpers.makeTestYear("America/Indiana/Knox", [
["1969-04-27T07:59:59+00:00", "01:59:59", "CST", 360],
["1969-04-27T08:00:00+00:00", "03:00:00", "CDT", 300],
["1969-10-26T06:59:59+00:00", "01:59:59", "CDT", 300],
["1969-10-26T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1970" : helpers.makeTestYear("America/Indiana/Knox", [
["1970-04-26T07:59:59+00:00", "01:59:59", "CST", 360],
["1970-04-26T08:00:00+00:00", "03:00:00", "CDT", 300],
["1970-10-25T06:59:59+00:00", "01:59:59", "CDT", 300],
["1970-10-25T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1971" : helpers.makeTestYear("America/Indiana/Knox", [
["1971-04-25T07:59:59+00:00", "01:59:59", "CST", 360],
["1971-04-25T08:00:00+00:00", "03:00:00", "CDT", 300],
["1971-10-31T06:59:59+00:00", "01:59:59", "CDT", 300],
["1971-10-31T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1972" : helpers.makeTestYear("America/Indiana/Knox", [
["1972-04-30T07:59:59+00:00", "01:59:59", "CST", 360],
["1972-04-30T08:00:00+00:00", "03:00:00", "CDT", 300],
["1972-10-29T06:59:59+00:00", "01:59:59", "CDT", 300],
["1972-10-29T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1973" : helpers.makeTestYear("America/Indiana/Knox", [
["1973-04-29T07:59:59+00:00", "01:59:59", "CST", 360],
["1973-04-29T08:00:00+00:00", "03:00:00", "CDT", 300],
["1973-10-28T06:59:59+00:00", "01:59:59", "CDT", 300],
["1973-10-28T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1974" : helpers.makeTestYear("America/Indiana/Knox", [
["1974-01-06T07:59:59+00:00", "01:59:59", "CST", 360],
["1974-01-06T08:00:00+00:00", "03:00:00", "CDT", 300],
["1974-10-27T06:59:59+00:00", "01:59:59", "CDT", 300],
["1974-10-27T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1975" : helpers.makeTestYear("America/Indiana/Knox", [
["1975-02-23T07:59:59+00:00", "01:59:59", "CST", 360],
["1975-02-23T08:00:00+00:00", "03:00:00", "CDT", 300],
["1975-10-26T06:59:59+00:00", "01:59:59", "CDT", 300],
["1975-10-26T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1976" : helpers.makeTestYear("America/Indiana/Knox", [
["1976-04-25T07:59:59+00:00", "01:59:59", "CST", 360],
["1976-04-25T08:00:00+00:00", "03:00:00", "CDT", 300],
["1976-10-31T06:59:59+00:00", "01:59:59", "CDT", 300],
["1976-10-31T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1977" : helpers.makeTestYear("America/Indiana/Knox", [
["1977-04-24T07:59:59+00:00", "01:59:59", "CST", 360],
["1977-04-24T08:00:00+00:00", "03:00:00", "CDT", 300],
["1977-10-30T06:59:59+00:00", "01:59:59", "CDT", 300],
["1977-10-30T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1978" : helpers.makeTestYear("America/Indiana/Knox", [
["1978-04-30T07:59:59+00:00", "01:59:59", "CST", 360],
["1978-04-30T08:00:00+00:00", "03:00:00", "CDT", 300],
["1978-10-29T06:59:59+00:00", "01:59:59", "CDT", 300],
["1978-10-29T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1979" : helpers.makeTestYear("America/Indiana/Knox", [
["1979-04-29T07:59:59+00:00", "01:59:59", "CST", 360],
["1979-04-29T08:00:00+00:00", "03:00:00", "CDT", 300],
["1979-10-28T06:59:59+00:00", "01:59:59", "CDT", 300],
["1979-10-28T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1980" : helpers.makeTestYear("America/Indiana/Knox", [
["1980-04-27T07:59:59+00:00", "01:59:59", "CST", 360],
["1980-04-27T08:00:00+00:00", "03:00:00", "CDT", 300],
["1980-10-26T06:59:59+00:00", "01:59:59", "CDT", 300],
["1980-10-26T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1981" : helpers.makeTestYear("America/Indiana/Knox", [
["1981-04-26T07:59:59+00:00", "01:59:59", "CST", 360],
["1981-04-26T08:00:00+00:00", "03:00:00", "CDT", 300],
["1981-10-25T06:59:59+00:00", "01:59:59", "CDT", 300],
["1981-10-25T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1982" : helpers.makeTestYear("America/Indiana/Knox", [
["1982-04-25T07:59:59+00:00", "01:59:59", "CST", 360],
["1982-04-25T08:00:00+00:00", "03:00:00", "CDT", 300],
["1982-10-31T06:59:59+00:00", "01:59:59", "CDT", 300],
["1982-10-31T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1983" : helpers.makeTestYear("America/Indiana/Knox", [
["1983-04-24T07:59:59+00:00", "01:59:59", "CST", 360],
["1983-04-24T08:00:00+00:00", "03:00:00", "CDT", 300],
["1983-10-30T06:59:59+00:00", "01:59:59", "CDT", 300],
["1983-10-30T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1984" : helpers.makeTestYear("America/Indiana/Knox", [
["1984-04-29T07:59:59+00:00", "01:59:59", "CST", 360],
["1984-04-29T08:00:00+00:00", "03:00:00", "CDT", 300],
["1984-10-28T06:59:59+00:00", "01:59:59", "CDT", 300],
["1984-10-28T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1985" : helpers.makeTestYear("America/Indiana/Knox", [
["1985-04-28T07:59:59+00:00", "01:59:59", "CST", 360],
["1985-04-28T08:00:00+00:00", "03:00:00", "CDT", 300],
["1985-10-27T06:59:59+00:00", "01:59:59", "CDT", 300],
["1985-10-27T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1986" : helpers.makeTestYear("America/Indiana/Knox", [
["1986-04-27T07:59:59+00:00", "01:59:59", "CST", 360],
["1986-04-27T08:00:00+00:00", "03:00:00", "CDT", 300],
["1986-10-26T06:59:59+00:00", "01:59:59", "CDT", 300],
["1986-10-26T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1987" : helpers.makeTestYear("America/Indiana/Knox", [
["1987-04-05T07:59:59+00:00", "01:59:59", "CST", 360],
["1987-04-05T08:00:00+00:00", "03:00:00", "CDT", 300],
["1987-10-25T06:59:59+00:00", "01:59:59", "CDT", 300],
["1987-10-25T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1988" : helpers.makeTestYear("America/Indiana/Knox", [
["1988-04-03T07:59:59+00:00", "01:59:59", "CST", 360],
["1988-04-03T08:00:00+00:00", "03:00:00", "CDT", 300],
["1988-10-30T06:59:59+00:00", "01:59:59", "CDT", 300],
["1988-10-30T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1989" : helpers.makeTestYear("America/Indiana/Knox", [
["1989-04-02T07:59:59+00:00", "01:59:59", "CST", 360],
["1989-04-02T08:00:00+00:00", "03:00:00", "CDT", 300],
["1989-10-29T06:59:59+00:00", "01:59:59", "CDT", 300],
["1989-10-29T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1990" : helpers.makeTestYear("America/Indiana/Knox", [
["1990-04-01T07:59:59+00:00", "01:59:59", "CST", 360],
["1990-04-01T08:00:00+00:00", "03:00:00", "CDT", 300],
["1990-10-28T06:59:59+00:00", "01:59:59", "CDT", 300],
["1990-10-28T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"1991" : helpers.makeTestYear("America/Indiana/Knox", [
["1991-04-07T07:59:59+00:00", "01:59:59", "CST", 360],
["1991-04-07T08:00:00+00:00", "03:00:00", "CDT", 300],
["1991-10-27T06:59:59+00:00", "01:59:59", "CDT", 300],
["1991-10-27T07:00:00+00:00", "02:00:00", "EST", 300]
]),
"2006" : helpers.makeTestYear("America/Indiana/Knox", [
["2006-04-02T06:59:59+00:00", "01:59:59", "EST", 300],
["2006-04-02T07:00:00+00:00", "02:00:00", "CDT", 300],
["2006-10-29T06:59:59+00:00", "01:59:59", "CDT", 300],
["2006-10-29T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2007" : helpers.makeTestYear("America/Indiana/Knox", [
["2007-03-11T07:59:59+00:00", "01:59:59", "CST", 360],
["2007-03-11T08:00:00+00:00", "03:00:00", "CDT", 300],
["2007-11-04T06:59:59+00:00", "01:59:59", "CDT", 300],
["2007-11-04T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2008" : helpers.makeTestYear("America/Indiana/Knox", [
["2008-03-09T07:59:59+00:00", "01:59:59", "CST", 360],
["2008-03-09T08:00:00+00:00", "03:00:00", "CDT", 300],
["2008-11-02T06:59:59+00:00", "01:59:59", "CDT", 300],
["2008-11-02T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2009" : helpers.makeTestYear("America/Indiana/Knox", [
["2009-03-08T07:59:59+00:00", "01:59:59", "CST", 360],
["2009-03-08T08:00:00+00:00", "03:00:00", "CDT", 300],
["2009-11-01T06:59:59+00:00", "01:59:59", "CDT", 300],
["2009-11-01T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2010" : helpers.makeTestYear("America/Indiana/Knox", [
["2010-03-14T07:59:59+00:00", "01:59:59", "CST", 360],
["2010-03-14T08:00:00+00:00", "03:00:00", "CDT", 300],
["2010-11-07T06:59:59+00:00", "01:59:59", "CDT", 300],
["2010-11-07T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2011" : helpers.makeTestYear("America/Indiana/Knox", [
["2011-03-13T07:59:59+00:00", "01:59:59", "CST", 360],
["2011-03-13T08:00:00+00:00", "03:00:00", "CDT", 300],
["2011-11-06T06:59:59+00:00", "01:59:59", "CDT", 300],
["2011-11-06T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2012" : helpers.makeTestYear("America/Indiana/Knox", [
["2012-03-11T07:59:59+00:00", "01:59:59", "CST", 360],
["2012-03-11T08:00:00+00:00", "03:00:00", "CDT", 300],
["2012-11-04T06:59:59+00:00", "01:59:59", "CDT", 300],
["2012-11-04T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2013" : helpers.makeTestYear("America/Indiana/Knox", [
["2013-03-10T07:59:59+00:00", "01:59:59", "CST", 360],
["2013-03-10T08:00:00+00:00", "03:00:00", "CDT", 300],
["2013-11-03T06:59:59+00:00", "01:59:59", "CDT", 300],
["2013-11-03T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2014" : helpers.makeTestYear("America/Indiana/Knox", [
["2014-03-09T07:59:59+00:00", "01:59:59", "CST", 360],
["2014-03-09T08:00:00+00:00", "03:00:00", "CDT", 300],
["2014-11-02T06:59:59+00:00", "01:59:59", "CDT", 300],
["2014-11-02T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2015" : helpers.makeTestYear("America/Indiana/Knox", [
["2015-03-08T07:59:59+00:00", "01:59:59", "CST", 360],
["2015-03-08T08:00:00+00:00", "03:00:00", "CDT", 300],
["2015-11-01T06:59:59+00:00", "01:59:59", "CDT", 300],
["2015-11-01T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2016" : helpers.makeTestYear("America/Indiana/Knox", [
["2016-03-13T07:59:59+00:00", "01:59:59", "CST", 360],
["2016-03-13T08:00:00+00:00", "03:00:00", "CDT", 300],
["2016-11-06T06:59:59+00:00", "01:59:59", "CDT", 300],
["2016-11-06T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2017" : helpers.makeTestYear("America/Indiana/Knox", [
["2017-03-12T07:59:59+00:00", "01:59:59", "CST", 360],
["2017-03-12T08:00:00+00:00", "03:00:00", "CDT", 300],
["2017-11-05T06:59:59+00:00", "01:59:59", "CDT", 300],
["2017-11-05T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2018" : helpers.makeTestYear("America/Indiana/Knox", [
["2018-03-11T07:59:59+00:00", "01:59:59", "CST", 360],
["2018-03-11T08:00:00+00:00", "03:00:00", "CDT", 300],
["2018-11-04T06:59:59+00:00", "01:59:59", "CDT", 300],
["2018-11-04T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2019" : helpers.makeTestYear("America/Indiana/Knox", [
["2019-03-10T07:59:59+00:00", "01:59:59", "CST", 360],
["2019-03-10T08:00:00+00:00", "03:00:00", "CDT", 300],
["2019-11-03T06:59:59+00:00", "01:59:59", "CDT", 300],
["2019-11-03T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2020" : helpers.makeTestYear("America/Indiana/Knox", [
["2020-03-08T07:59:59+00:00", "01:59:59", "CST", 360],
["2020-03-08T08:00:00+00:00", "03:00:00", "CDT", 300],
["2020-11-01T06:59:59+00:00", "01:59:59", "CDT", 300],
["2020-11-01T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2021" : helpers.makeTestYear("America/Indiana/Knox", [
["2021-03-14T07:59:59+00:00", "01:59:59", "CST", 360],
["2021-03-14T08:00:00+00:00", "03:00:00", "CDT", 300],
["2021-11-07T06:59:59+00:00", "01:59:59", "CDT", 300],
["2021-11-07T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2022" : helpers.makeTestYear("America/Indiana/Knox", [
["2022-03-13T07:59:59+00:00", "01:59:59", "CST", 360],
["2022-03-13T08:00:00+00:00", "03:00:00", "CDT", 300],
["2022-11-06T06:59:59+00:00", "01:59:59", "CDT", 300],
["2022-11-06T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2023" : helpers.makeTestYear("America/Indiana/Knox", [
["2023-03-12T07:59:59+00:00", "01:59:59", "CST", 360],
["2023-03-12T08:00:00+00:00", "03:00:00", "CDT", 300],
["2023-11-05T06:59:59+00:00", "01:59:59", "CDT", 300],
["2023-11-05T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2024" : helpers.makeTestYear("America/Indiana/Knox", [
["2024-03-10T07:59:59+00:00", "01:59:59", "CST", 360],
["2024-03-10T08:00:00+00:00", "03:00:00", "CDT", 300],
["2024-11-03T06:59:59+00:00", "01:59:59", "CDT", 300],
["2024-11-03T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2025" : helpers.makeTestYear("America/Indiana/Knox", [
["2025-03-09T07:59:59+00:00", "01:59:59", "CST", 360],
["2025-03-09T08:00:00+00:00", "03:00:00", "CDT", 300],
["2025-11-02T06:59:59+00:00", "01:59:59", "CDT", 300],
["2025-11-02T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2026" : helpers.makeTestYear("America/Indiana/Knox", [
["2026-03-08T07:59:59+00:00", "01:59:59", "CST", 360],
["2026-03-08T08:00:00+00:00", "03:00:00", "CDT", 300],
["2026-11-01T06:59:59+00:00", "01:59:59", "CDT", 300],
["2026-11-01T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2027" : helpers.makeTestYear("America/Indiana/Knox", [
["2027-03-14T07:59:59+00:00", "01:59:59", "CST", 360],
["2027-03-14T08:00:00+00:00", "03:00:00", "CDT", 300],
["2027-11-07T06:59:59+00:00", "01:59:59", "CDT", 300],
["2027-11-07T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2028" : helpers.makeTestYear("America/Indiana/Knox", [
["2028-03-12T07:59:59+00:00", "01:59:59", "CST", 360],
["2028-03-12T08:00:00+00:00", "03:00:00", "CDT", 300],
["2028-11-05T06:59:59+00:00", "01:59:59", "CDT", 300],
["2028-11-05T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2029" : helpers.makeTestYear("America/Indiana/Knox", [
["2029-03-11T07:59:59+00:00", "01:59:59", "CST", 360],
["2029-03-11T08:00:00+00:00", "03:00:00", "CDT", 300],
["2029-11-04T06:59:59+00:00", "01:59:59", "CDT", 300],
["2029-11-04T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2030" : helpers.makeTestYear("America/Indiana/Knox", [
["2030-03-10T07:59:59+00:00", "01:59:59", "CST", 360],
["2030-03-10T08:00:00+00:00", "03:00:00", "CDT", 300],
["2030-11-03T06:59:59+00:00", "01:59:59", "CDT", 300],
["2030-11-03T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2031" : helpers.makeTestYear("America/Indiana/Knox", [
["2031-03-09T07:59:59+00:00", "01:59:59", "CST", 360],
["2031-03-09T08:00:00+00:00", "03:00:00", "CDT", 300],
["2031-11-02T06:59:59+00:00", "01:59:59", "CDT", 300],
["2031-11-02T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2032" : helpers.makeTestYear("America/Indiana/Knox", [
["2032-03-14T07:59:59+00:00", "01:59:59", "CST", 360],
["2032-03-14T08:00:00+00:00", "03:00:00", "CDT", 300],
["2032-11-07T06:59:59+00:00", "01:59:59", "CDT", 300],
["2032-11-07T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2033" : helpers.makeTestYear("America/Indiana/Knox", [
["2033-03-13T07:59:59+00:00", "01:59:59", "CST", 360],
["2033-03-13T08:00:00+00:00", "03:00:00", "CDT", 300],
["2033-11-06T06:59:59+00:00", "01:59:59", "CDT", 300],
["2033-11-06T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2034" : helpers.makeTestYear("America/Indiana/Knox", [
["2034-03-12T07:59:59+00:00", "01:59:59", "CST", 360],
["2034-03-12T08:00:00+00:00", "03:00:00", "CDT", 300],
["2034-11-05T06:59:59+00:00", "01:59:59", "CDT", 300],
["2034-11-05T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2035" : helpers.makeTestYear("America/Indiana/Knox", [
["2035-03-11T07:59:59+00:00", "01:59:59", "CST", 360],
["2035-03-11T08:00:00+00:00", "03:00:00", "CDT", 300],
["2035-11-04T06:59:59+00:00", "01:59:59", "CDT", 300],
["2035-11-04T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2036" : helpers.makeTestYear("America/Indiana/Knox", [
["2036-03-09T07:59:59+00:00", "01:59:59", "CST", 360],
["2036-03-09T08:00:00+00:00", "03:00:00", "CDT", 300],
["2036-11-02T06:59:59+00:00", "01:59:59", "CDT", 300],
["2036-11-02T07:00:00+00:00", "01:00:00", "CST", 360]
]),
"2037" : helpers.makeTestYear("America/Indiana/Knox", [
["2037-03-08T07:59:59+00:00", "01:59:59", "CST", 360],
["2037-03-08T08:00:00+00:00", "03:00:00", "CDT", 300],
["2037-11-01T06:59:59+00:00", "01:59:59", "CDT", 300],
["2037-11-01T07:00:00+00:00", "01:00:00", "CST", 360]
])
}; | {
"pile_set_name": "Github"
} |
import numpy as np
import pytest
from matplotlib.testing.decorators import image_comparison
import matplotlib.pyplot as plt
import matplotlib.patheffects as path_effects
@image_comparison(baseline_images=['patheffect1'], remove_text=True)
def test_patheffect1():
ax1 = plt.subplot(111)
ax1.imshow([[1, 2], [2, 3]])
txt = ax1.annotate("test", (1., 1.), (0., 0),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle3", lw=2),
size=20, ha="center",
path_effects=[path_effects.withStroke(linewidth=3,
foreground="w")])
txt.arrow_patch.set_path_effects([path_effects.Stroke(linewidth=5,
foreground="w"),
path_effects.Normal()])
pe = [path_effects.withStroke(linewidth=3, foreground="w")]
ax1.grid(True, linestyle="-", path_effects=pe)
@image_comparison(baseline_images=['patheffect2'], remove_text=True,
style='mpl20')
def test_patheffect2():
ax2 = plt.subplot(111)
arr = np.arange(25).reshape((5, 5))
ax2.imshow(arr)
cntr = ax2.contour(arr, colors="k")
plt.setp(cntr.collections,
path_effects=[path_effects.withStroke(linewidth=3,
foreground="w")])
clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
plt.setp(clbls,
path_effects=[path_effects.withStroke(linewidth=3,
foreground="w")])
@image_comparison(baseline_images=['patheffect3'])
def test_patheffect3():
p1, = plt.plot([1, 3, 5, 4, 3], 'o-b', lw=4)
p1.set_path_effects([path_effects.SimpleLineShadow(),
path_effects.Normal()])
plt.title(r'testing$^{123}$',
path_effects=[path_effects.withStroke(linewidth=1, foreground="r")])
leg = plt.legend([p1], [r'Line 1$^2$'], fancybox=True, loc='upper left')
leg.legendPatch.set_path_effects([path_effects.withSimplePatchShadow()])
text = plt.text(2, 3, 'Drop test', color='white',
bbox={'boxstyle': 'circle,pad=0.1', 'color': 'red'})
pe = [path_effects.Stroke(linewidth=3.75, foreground='k'),
path_effects.withSimplePatchShadow((6, -3), shadow_rgbFace='blue')]
text.set_path_effects(pe)
text.get_bbox_patch().set_path_effects(pe)
pe = [path_effects.PathPatchEffect(offset=(4, -4), hatch='xxxx',
facecolor='gray'),
path_effects.PathPatchEffect(edgecolor='white', facecolor='black',
lw=1.1)]
t = plt.gcf().text(0.02, 0.1, 'Hatch shadow', fontsize=75, weight=1000,
va='center')
t.set_path_effects(pe)
@image_comparison(baseline_images=['stroked_text'], extensions=['png'])
def test_patheffects_stroked_text():
text_chunks = [
'A B C D E F G H I J K L',
'M N O P Q R S T U V W',
'X Y Z a b c d e f g h i j',
'k l m n o p q r s t u v',
'w x y z 0123456789',
r"!@#$%^&*()-=_+[]\;'",
',./{}|:"<>?'
]
font_size = 50
ax = plt.axes([0, 0, 1, 1])
for i, chunk in enumerate(text_chunks):
text = ax.text(x=0.01, y=(0.9 - i * 0.13), s=chunk,
fontdict={'ha': 'left', 'va': 'center',
'size': font_size, 'color': 'white'})
text.set_path_effects([path_effects.Stroke(linewidth=font_size / 10,
foreground='black'),
path_effects.Normal()])
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.axis('off')
@pytest.mark.xfail
def test_PathEffect_points_to_pixels():
fig = plt.figure(dpi=150)
p1, = plt.plot(range(10))
p1.set_path_effects([path_effects.SimpleLineShadow(),
path_effects.Normal()])
renderer = fig.canvas.get_renderer()
pe_renderer = path_effects.SimpleLineShadow().get_proxy_renderer(renderer)
assert isinstance(pe_renderer, path_effects.PathEffectRenderer)
# Confirm that using a path effects renderer maintains point sizes
# appropriately. Otherwise rendered font would be the wrong size.
assert renderer.points_to_pixels(15) == pe_renderer.points_to_pixels(15)
def test_SimplePatchShadow_offset():
pe = path_effects.SimplePatchShadow(offset=(4, 5))
assert pe._offset == (4, 5)
@image_comparison(baseline_images=['collection'], tol=0.02, style='mpl20')
def test_collection():
x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100))
data = np.sin(x) + np.cos(y)
cs = plt.contour(data)
pe = [path_effects.PathPatchEffect(edgecolor='black', facecolor='none',
linewidth=12),
path_effects.Stroke(linewidth=5)]
for collection in cs.collections:
collection.set_path_effects(pe)
for text in plt.clabel(cs, colors='white'):
text.set_path_effects([path_effects.withStroke(foreground='k',
linewidth=3)])
text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none',
'edgecolor': 'blue'})
| {
"pile_set_name": "Github"
} |
## Crypto 50 (crypto, 50p)
### PL
[ENG](#eng-version)
Bardzo przyjemne (dla autora tego writeupa) zadanie. Dostajemy 10 tekstów zaszyfrowanych tym samym stream cipher (z tym samym IV/kluczem), i mamy za zadanie rozszyfrować 11.
Teksty w pliku [input.txt](input.txt)
Orientujemy się od razu, że to sytuacja podobna do tego gdy wszystkie teksty zostały zaszyfrowane tym samym one time padem. A na to są sposoby.
Oczywiście jeden sposób to napisanie masę skomplikowanego kodu bruteforcującego różne możliwości i wybierający najlepszy plaintext (np. taki który mieści sie w wymaganym charsecie). To rozwiązanie dobre do specjalistycznych zastosowań/mechanicznego łamania, ale my mamy znacznie _zabawniejszy_ sposób, do zapisania w kilkunastu linijkach pythona:
dat = open('input.txt').readlines()
dat = [x.strip().decode('hex') for x in dat]
def xor(a, b):
return ''.join(chr(ord(ac) ^ ord(bc)) for ac, bc in zip(a, b))
def interactive_hack(xored):
while True:
print ">",
i = raw_input()
for x in xored:
print " -> ", xor(i, x)
xored = [xor(dat[0], d) for d in dat[1:]]
interactive_hack(xored)
I tyle. Co nam to daje? Otóż możemy zgadywać w ten sposób hasło "interaktywnie" - Na przykład jest spore prawdopodobieństwo że któryś z plaintextów zaczyna się od "You" - spróbujmy więc:
> You
-> {&j&
-> nn`h
-> nnl;
-> {&v<
-> {&v<
-> sh%)
-> s`)h
-> {hj<
-> xok)
-> mn`&
Meh. To może "The "?
> The
-> v!z&
-> ciph
-> ci|;
-> v!f<
-> v!f<
-> ~o5)
-> ~g9h
-> voz<
-> uh{)
-> `ip&
Strzał w dziesiątkę. Widać początek słowa "cipher", więc próbujemy:
> cipher
-> A one-'
-> The ke*
-> This m2
-> A stre2
-> A stre2
-> In a s*
-> If, ho$
-> Anothe!
-> Binarys
-> When u
Ostatni znak nie ma sensu nigdzie, więc podejrzewamy że to jednak miało być inne słowo (np. ciphers). Ale idziemy dalej, i tak aż do końca:

Flaga: `When using a stream cipher, never use the key more than once!`
### ENG version
Very nice (at least for the auther of the writeup) task. We get 10 ciphertexts encoded with the same stream cipher (with the same IV and key) and we have to decode 11th.
Input texts in [input.txt](input.txt)
We realise that this is a similar case to encoding all the texts with the same one time pad. But this can be handled.
Of course we could have written a lot of complex brute-force code testing multiple possibilities and choosing the best plaintext (eg. the one that fits into selected charset). This is a good task for automatic code breaking, but we came up with a more `fun` idea, which could have been written in just few lines of code:
dat = open('input.txt').readlines()
dat = [x.strip().decode('hex') for x in dat]
def xor(a, b):
return ''.join(chr(ord(ac) ^ ord(bc)) for ac, bc in zip(a, b))
def interactive_hack(xored):
while True:
print ">",
i = raw_input()
for x in xored:
print " -> ", xor(i, x)
xored = [xor(dat[0], d) for d in dat[1:]]
interactive_hack(xored)
And that's it. What does it give us? We can try to break the code in an "interactive" way. We just try to guess the begining of one of the plaintexts - we assume that there is possibility that it starts with "You" so we try:
> You
-> {&j&
-> nn`h
-> nnl;
-> {&v<
-> {&v<
-> sh%)
-> s`)h
-> {hj<
-> xok)
-> mn`&
Not this time, so maybe "The "?
> The
-> v!z&
-> ciph
-> ci|;
-> v!f<
-> v!f<
-> ~o5)
-> ~g9h
-> voz<
-> uh{)
-> `ip&
Bingo! We can see a "ciph" word prefix so we try "cipher":
> cipher
-> A one-'
-> The ke*
-> This m2
-> A stre2
-> A stre2
-> In a s*
-> If, ho$
-> Anothe!
-> Binarys
-> When u
Last character does not make sense so we assume this must be a different word (eg. ciphers). We proceed until the end:

Flaga: `When using a stream cipher, never use the key more than once!` | {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
@class NSMutableDictionary, NSString, QDBDatabase, QDBStatement;
@interface QDBResultSet : NSObject
{
QDBDatabase *_parentDB;
QDBStatement *_statement;
NSString *_query;
NSMutableDictionary *_columnNameToIndexMap;
}
+ (id)resultSetWithStatement:(id)arg1 usingParentDatabase:(id)arg2;
@property(retain) QDBStatement *statement; // @synthesize statement=_statement;
@property(retain) NSString *query; // @synthesize query=_query;
- (void).cxx_destruct;
- (id)dataForColumnIndex:(int)arg1;
- (id)dataForColumn:(id)arg1;
- (id)stringForColumnIndex:(int)arg1;
- (id)stringForColumn:(id)arg1;
- (int)intForColumnIndex:(int)arg1;
- (int)intForColumn:(id)arg1;
- (int)columnIndexForName:(id)arg1;
@property(readonly) NSMutableDictionary *columnNameToIndexMap;
- (_Bool)nextWithError:(id *)arg1;
- (_Bool)next;
- (int)columnCount;
- (void)setParentDB:(id)arg1;
- (void)close;
- (void)dealloc;
@end
| {
"pile_set_name": "Github"
} |
# Predict with pre-trained models
This tutorial explains how to recognize objects in an image with a
pre-trained model, and how to perform feature extraction.
## Prerequisites
To complete this tutorial, we need:
- MXNet. See the instructions for your operating system in [Setup and Installation](http://mxnet.io/install/index.html)
- [Python Requests](http://docs.python-requests.org/en/master/), [Matplotlib](https://matplotlib.org/) and [Jupyter Notebook](http://jupyter.org/index.html).
```
$ pip install requests matplotlib jupyter opencv-python
```
## Loading
We first download a pre-trained ResNet 152 layer that is trained on the full
ImageNet dataset with over 10 million images and 10 thousand classes. A
pre-trained model contains two parts, a json file containing the model
definition and a binary file containing the parameters. In addition, there may be
a text file for the labels.
```python
import mxnet as mx
path='http://data.mxnet.io/models/imagenet-11k/'
[mx.test_utils.download(path+'resnet-152/resnet-152-symbol.json'),
mx.test_utils.download(path+'resnet-152/resnet-152-0000.params'),
mx.test_utils.download(path+'synset.txt')]
```
Next, we load the downloaded model. *Note:* If GPU is available, we can replace all
occurrences of `mx.cpu()` with `mx.gpu()` to accelerate the computation.
```python
sym, arg_params, aux_params = mx.model.load_checkpoint('resnet-152', 0)
mod = mx.mod.Module(symbol=sym, context=mx.cpu(), label_names=None)
mod.bind(for_training=False, data_shapes=[('data', (1,3,224,224))],
label_shapes=mod._label_shapes)
mod.set_params(arg_params, aux_params, allow_missing=True)
with open('synset.txt', 'r') as f:
labels = [l.rstrip() for l in f]
```
## Predicting
We first define helper functions for downloading an image and performing the
prediction:
```python
%matplotlib inline
import matplotlib.pyplot as plt
import cv2
import numpy as np
# define a simple data batch
from collections import namedtuple
Batch = namedtuple('Batch', ['data'])
def get_image(url, show=False):
# download and show the image
fname = mx.test_utils.download(url)
img = cv2.cvtColor(cv2.imread(fname), cv2.COLOR_BGR2RGB)
if img is None:
return None
if show:
plt.imshow(img)
plt.axis('off')
# convert into format (batch, RGB, width, height)
img = cv2.resize(img, (224, 224))
img = np.swapaxes(img, 0, 2)
img = np.swapaxes(img, 1, 2)
img = img[np.newaxis, :]
return img
def predict(url):
img = get_image(url, show=True)
# compute the predict probabilities
mod.forward(Batch([mx.nd.array(img)]))
prob = mod.get_outputs()[0].asnumpy()
# print the top-5
prob = np.squeeze(prob)
a = np.argsort(prob)[::-1]
for i in a[0:5]:
print('probability=%f, class=%s' %(prob[i], labels[i]))
```
Now, we can perform prediction with any downloadable URL:
```python
predict('http://writm.com/wp-content/uploads/2016/08/Cat-hd-wallpapers.jpg')
```
```python
predict('http://thenotoriouspug.com/wp-content/uploads/2015/01/Pug-Cookie-1920x1080-1024x576.jpg')
```
## Feature extraction
By feature extraction, we mean presenting the input images by the output of an
internal layer rather than the last softmax layer. These outputs, which can be
viewed as the feature of the raw input image, can then be used by other
applications such as object detection.
We can use the ``get_internals`` method to get all internal layers from a
Symbol.
```python
# list the last 10 layers
all_layers = sym.get_internals()
all_layers.list_outputs()[-10:]
```
An often used layer for feature extraction is the one before the last fully
connected layer. For ResNet, and also Inception, it is the flattened layer with
name `flatten0` which reshapes the 4-D convolutional layer output into 2-D for
the fully connected layer. The following source code extracts a new Symbol which
outputs the flattened layer and creates a model.
```python
fe_sym = all_layers['flatten0_output']
fe_mod = mx.mod.Module(symbol=fe_sym, context=mx.cpu(), label_names=None)
fe_mod.bind(for_training=False, data_shapes=[('data', (1,3,224,224))])
fe_mod.set_params(arg_params, aux_params)
```
We can now invoke `forward` to obtain the features:
```python
img = get_image('http://writm.com/wp-content/uploads/2016/08/Cat-hd-wallpapers.jpg')
fe_mod.forward(Batch([mx.nd.array(img)]))
features = fe_mod.get_outputs()[0].asnumpy()
print(features)
assert features.shape == (1, 2048)
```
<!-- INSERT SOURCE DOWNLOAD BUTTONS -->
| {
"pile_set_name": "Github"
} |
#N canvas 218 94 842 634 10;
#X obj 63 84 t a a;
#X obj 63 241 spigot;
#X obj 102 149 bang;
#X obj 102 168 1;
#X obj 223 149 route bang;
#X obj 183 150 bang;
#X obj 183 169 0;
#X obj 102 114 list split 2;
#X obj 232 379 list split;
#X obj 299 328 list length;
#X obj 299 350 >> 1;
#X obj 63 260 t a a a a;
#X obj 63 446 list split;
#X obj 130 398 list length;
#X obj 130 423 >> 1;
#X obj 31 19 inlet;
#X obj 290 175 outlet;
#X text 73 19 Copyright 2009 by Mathieu Bouchard;
#X obj 31 53 t b a;
#X obj 465 119 outlet;
#X text 520 121 signal end of list;
#X text 381 23 made compatible with [list-drip]: fbar 2009;
#N canvas 228 198 627 317 LICENSE-BSD 0;
#X text 121 56 This software is copyrighted by Miller Puckette \, Reality
Jockey Ltd. and others. The terms (the "Standard Improved BSD License")
apply to all files associated with the software unless explicitly disclaimed
in individual files.;
#X text 123 148 See the file LICENSE.txt for the full license text.
;
#X restore 523 60 pd LICENSE-BSD;
#X connect 0 0 1 0;
#X connect 0 1 7 0;
#X connect 1 0 11 0;
#X connect 2 0 3 0;
#X connect 3 0 1 1;
#X connect 4 1 16 0;
#X connect 5 0 6 0;
#X connect 6 0 1 1;
#X connect 7 0 2 0;
#X connect 7 2 4 0;
#X connect 7 2 5 0;
#X connect 8 0 0 0;
#X connect 9 0 10 0;
#X connect 10 0 8 1;
#X connect 11 0 12 0;
#X connect 11 1 13 0;
#X connect 11 2 8 0;
#X connect 11 3 9 0;
#X connect 12 1 0 0;
#X connect 13 0 14 0;
#X connect 14 0 12 1;
#X connect 15 0 18 0;
#X connect 18 0 19 0;
#X connect 18 1 0 0;
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
#
# Copyright 2014-2020 BigML
#
# 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.
"""Centroid structure for the BigML local Cluster
This module defines an auxiliary Centroid predicate structure that is used
in the cluster.
"""
import math
import sys
INDENT = " " * 4
STATISTIC_MEASURES = [
'Minimum', 'Mean', 'Median', 'Maximum', 'Standard deviation', 'Sum',
'Sum squares', 'Variance']
def cosine_distance2(terms, centroid_terms, scale):
"""Returns the distance defined by cosine similarity
"""
# Centroid values for the field can be an empty list.
# Then the distance for an empty input is 1
# (before applying the scale factor).
if not terms and not centroid_terms:
return 0
if not terms or not centroid_terms:
return scale ** 2
input_count = 0
for term in centroid_terms:
if term in terms:
input_count += 1
cosine_similarity = input_count / math.sqrt(
len(terms) * len(centroid_terms))
similarity_distance = scale * (1 - cosine_similarity)
return similarity_distance ** 2
class Centroid():
"""A Centroid.
"""
def __init__(self, centroid_info):
self.center = centroid_info.get('center', {})
self.count = centroid_info.get('count', 0)
self.centroid_id = centroid_info.get(
'id', centroid_info.get("centroid_id", None))
self.name = centroid_info.get('name', None)
self.distance = centroid_info.get('distance', {})
def distance2(self, input_data, term_sets, scales, stop_distance2=None):
"""Squared Distance from the given input data to the centroid
"""
distance2 = 0.0
for field_id, value in list(self.center.items()):
if isinstance(value, list):
# text field
terms = ([] if field_id not in term_sets else
term_sets[field_id])
distance2 += cosine_distance2(terms, value, scales[field_id])
elif isinstance(value, str):
if field_id not in input_data or input_data[field_id] != value:
distance2 += 1 * scales[field_id] ** 2
else:
distance2 += ((input_data[field_id] - value) *
scales[field_id]) ** 2
if stop_distance2 is not None and distance2 >= stop_distance2:
return None
return distance2
def print_statistics(self, out=sys.stdout):
"""Print the statistics for the training data clustered around the
centroid
"""
out.write("%s%s:\n" % (INDENT, self.name))
literal = "%s%s: %s\n"
for measure_title in STATISTIC_MEASURES:
measure = measure_title.lower().replace(" ", "_")
out.write(literal % (INDENT * 2, measure_title,
self.distance[measure]))
out.write("\n")
| {
"pile_set_name": "Github"
} |
{ "translations": {
"Server to server sharing is not enabled on this server" : "שיתוף שרת לשרת לא מופעל בשרת זה",
"The mountpoint name contains invalid characters." : "שם ה- mountpoint מכיל תווים לא חוקיים.",
"Not allowed to create a federated share with the same user server" : "יצירת שיתוף מאוגד עם אותו שרת משתמש אסורה",
"Invalid or untrusted SSL certificate" : "תעודת SSL לא חוקית או לא בטוחה",
"Could not authenticate to remote share, password might be wrong" : "לא ניתן לאמת שיתוף חיצוני, ייתכן שהסיסמא שגוייה",
"Storage not valid" : "אחסון לא חוקי",
"Couldn't add remote share" : "לא ניתן להוסיף שיתוף חיצוני",
"Shared with you" : "שיתף/שיתפה אתך",
"Shared with others" : "משותף עם אחרים",
"Shared by link" : "משותף עם קישור",
"Anonymous upload" : "העלאה אנונימית",
"Click to select files or use drag & drop to upload" : "ניתן ללחוץ לבחירת קבצים או להשתמש בגרירה ועזיבה לצורך העלאה",
"Uploaded files" : "קבצים שהועלו",
"Uploading..." : "העלאה...",
"Nothing shared with you yet" : "עדיין לא שיתפו אתך דבר",
"Files and folders others share with you will show up here" : "קבצים ותיקיות שאחרים שיתפו אתך יוצגו כאן",
"Nothing shared yet" : "עדיין לא שותף דבר",
"Files and folders you share will show up here" : "קבצים ותיקיות ששיתפת יוצגו כאן",
"No shared links" : "אין קישורים משותפים",
"Files and folders you share by link will show up here" : "קבצים ותיקיות ששיתפת עם קישור יוצגו כאן",
"An error occurred while updating share state: {message}" : "אירעה שגיאה בזמן עדכון של מצב שיתוף: {message}",
"Accept Share" : "אישור שיתוף",
"Decline Share" : "דחיית שיתוף",
"Do you want to add the remote share {name} from {owner}@{remote}?" : "האם לשתף את השיתוף החיצוני {name} שהתקבל מ- {owner}@{remote}?",
"Remote share" : "שיתוף חיצוני",
"Remote share password" : "סיסמת שיתוף חיצוני",
"Cancel" : "ביטול",
"Add remote share" : "הוספת שיתוף חיצוני",
"You can upload into this folder" : "ניתן להעלות לתיקייה זו",
"No ownCloud installation (7 or higher) found at {remote}" : "לא נמצאה התקנת ownCloud (גרסה 7 ומעלה) ב- {remote}",
"Invalid ownCloud url" : "נתיב ownCloud לא חוקי",
"Share" : "שיתוף",
"No expiration date set" : "לא הוגדר תאריך תפוגה",
"Declined" : "נדחה",
"Pending" : "ממתין",
"Shared by" : "שותף על־ידי",
"Sharing" : "שיתוף",
"A file or folder has been <strong>shared</strong>" : "קובץ או תיקייה <strong>שותפו<strong/>",
"A file or folder was shared from <strong>another server</strong>" : "קובץ או תיקייה שותפו מ- <strong>שרת אחר</strong>",
"A public shared file or folder was <strong>downloaded</strong>" : "קובץ או תיקייה עם שיתוף ציבורי <strong>הורדו</strong>",
"You received a new remote share %2$s from %1$s" : "קבלת שיתוף חיצוני חדש %2$s מאת %1$s",
"You received a new remote share from %s" : "קבלת שיתוף חיצוני חדש מאת %s",
"%1$s accepted remote share %2$s" : "%1$s אישר/אישרה שיתוף חיצוני %2$s",
"%1$s declined remote share %2$s" : "%1$s סירב/סירבה שיתוף חיצוני %2$s",
"%1$s unshared %2$s from you" : "%1$s ביטל/ביטלה שיתוף %2$s אתך",
"Public shared folder %1$s was downloaded" : "תיקיית שיתוף ציבורית %1$s הורדה",
"Public shared file %1$s was downloaded" : "קובץ שיתוף ציבורי %1$s הורד",
"You shared %1$s with %2$s" : "שיתפת %1$s עם %2$s",
"%2$s shared %1$s with %3$s" : "%2$s שיתף/שיתפה %1$s עם %3$s",
"You removed the share of %2$s for %1$s" : "הסרת את השיתוף של %2$s עבור %1$s",
"%2$s removed the share of %3$s for %1$s" : "%2$s הסיר/ה את השיתוף של %3$s עבור %1$s",
"You unshared %1$s shared by %2$s from self" : "ביטלת את השיתוף %1$s ששותף על ידי %2$s עם עצמך",
"You shared %1$s with group %2$s" : "שיתפת %1$s עם קבוצת %2$s",
"%2$s shared %1$s with group %3$s" : "%2$s שיתף/שיתפה %1$s עם קבוצה %3$s",
"You removed the share of group %2$s for %1$s" : "הסרת את השיתוף לקבוצה %2$s עבור %1$s",
"%2$s removed the share of group %3$s for %1$s" : "%2$s הסיר/ה את השיתוף לקבוצה %3$s עבור %1$s",
"%2$s shared %1$s via link" : "%2$s שיתף/שיתפה %1$s על ידי קישור",
"You shared %1$s via link" : "שיתפת %1$s על בסיס קישור",
"You removed the public link for %1$s" : "הסרת את הקישור הציבורי של %1$s",
"%2$s removed the public link for %1$s" : "%2$s הסיר/ה את הקישור הציבורי של %1$s",
"Your public link for %1$s expired" : "הקישור הציבורי של %1$s פג תוקף",
"The public link of %2$s for %1$s expired" : "הקישור הציבורי של %2$s עבור %1$s פג תוקף",
"%2$s shared %1$s with you" : "%2$s שיתפו %1$s אתך",
"%2$s removed the share for %1$s" : "%2$s הסיר/ה את השיתוף של %1$s",
"Downloaded via public link" : "הורד על בסיס קישור ציבורי",
"Shared with %2$s" : "שיתף/שיתפה עם %2$s",
"Shared with %3$s by %2$s" : "שיתף/שיתפה עם %3$s על ידי %2$s",
"Removed share for %2$s" : "הסיר/ה שיתוף של %2$s",
"%2$s removed share for %3$s" : "%2$s הסיר/ה שיתוף של %3$s",
"Unshared %1$s from self" : "ביטלת את השיתוף של %1$s עם עצמך",
"Shared with group %2$s" : "שיתף/שיתפה עם קבוצה %2$s",
"Shared with group %3$s by %2$s" : "שיתף/שיתפה עם קבוצה %3$s על ידי %2$s",
"Removed share of group %2$s" : "הסיר/ה שיתוף של קבוצה %2$s",
"%2$s removed share of group %3$s" : "%2$s הסיר/ה שיתוף של קבוצה %3$s",
"Shared via link by %2$s" : "שיתף/שיתפה על בסיס קישור על ידי %2$s",
"Shared via public link" : "משותף על בסיס קישור ציבורי",
"Removed public link" : "הסיר/ה קישור ציבורי",
"%2$s removed public link" : "%2$s הסיר/ה קישור ציבורי",
"Public link expired" : "קישור ציבורי פג תוקף",
"Public link of %2$s expired" : "קישור ציבורי של %2$s פג תוקף",
"Shared by %2$s" : "שיתף/שיתפה על ידי %2$s",
"Shares" : "שיתופים",
"File sharing" : "שיתוף קובץ",
"Public link" : "קישור ציבורי",
"Couldn't send mail to following recipient(s): %s " : "נא ניתן לשלוח דוא״ל לנמענים הבאים: %s",
"Share API is disabled" : "שיתוף API מנוטרל",
"Wrong share ID, share doesn't exist" : "מספר זיהוי שיתוף שגוי, שיתוף אינו קיים",
"Could not delete share" : "לא ניתן היה למחוק את השיתוף",
"Please specify a file or folder path" : "יש לספק נתיב לקובץ או תיקייה",
"Wrong path, file/folder doesn't exist" : "נתיב שגוי, קובץ/תיקייה אינם קיימים",
"Invalid date, date format must be YYYY-MM-DD" : "תאריך לא חוקי, תבנית התאריך חייבת להיות YYYY-MM-DD",
"Please specify a valid user" : "יש לספק משתמש חוקי",
"Group sharing is disabled by the administrator" : "שיתוף קבוצתי מנוטרל על ידי המנהל",
"Please specify a valid group" : "יש לספק קבוצה חוקית",
"The group is blacklisted for sharing" : "הקבוצה משויכת לרשימה שחורה לשיתוף",
"Public link sharing is disabled by the administrator" : "שיתוף ציבורי מנוטרל על ידי המנהל",
"Public upload disabled by the administrator" : "שיתוף ציבורי מנוטרל על ידי המנהל",
"Public upload is only possible for publicly shared folders" : "העלאה ציבורית אפשרית רק אל תיקיות משותפות ציבוריות",
"Sharing %s failed because the back end does not allow shares from type %s" : "שיתוף %s נכשל כיוון שהצד האחרוי ינו מאפשר שיתוף מסוג %s",
"shareWith parameter must be a string" : "פרמטר shareWith חייב להיות מחרוזת",
"Unknown share type" : "סוג שיתוף אינו מוכר",
"Not a directory" : "אינה תיקייה",
"Could not lock path" : "לא ניתן היה לנעול נתיב",
"Could not update share" : "לא ניתן היה לעדכן את השיתוף",
"Can't change permissions for public share links" : "לא ניתן לשנות הרשאות לקישורי שיתוף ציבוריים",
"Only recipient can change accepted state" : "רק נמענים יכולים לשנות המצב המקובל",
"\"%1$s\" shared \"%3$s\" with you (on behalf of \"%2$s\")" : "\"%1$s\" משתף \"%3$s\" אתך (בשם \"%2$s\")",
"\"%1$s\" shared \"%3$s\" with you" : "\"%1$s\" משתף \"%3$s\" אתך",
"\"%1$s\" invited you to view \"%3$s\" (on behalf of \"%2$s\")" : "\"%1$s\" מזמין אותך לצפות ב- \"%3$s\" (בשם \"%2$s\")",
"\"%1$s\" invited you to view \"%3$s\"" : "\"%1$s\" מזמין אותך לצפות ב- \"%3$s\"",
"Accept" : "אישור",
"Decline" : "סירוב",
"Automatically accept new incoming local user shares" : "קבלה אוטומטית של שיתופי משתמש מקומי חדשים",
"Allow finding you via autocomplete in share dialog. If this is disabled the full username needs to be entered." : "אפשר השלמה אוטומטית של שמות משתמש בתפריט שיתוף. אם תכונה זו מנוטרלת יש להכניס שם משתמש מלא.",
"This share is password-protected" : "שיתוף זה מוגן סיסמא",
"The password is wrong. Try again." : "הסיסמא שגויה. יש לנסות שנית.",
"Password" : "סיסמא",
"No entries found in this folder" : "לא נמצאו כניסות לתיקייה זו",
"Name" : "שם",
"State" : "מצב",
"Share time" : "זמן שיתוף",
"Expiration date" : "תאריך התפוגה",
"Sorry, this link doesn’t seem to work anymore." : "מצטערים, לא נראה שקישור זה עובד יותר. ",
"Reasons might be:" : "הסיבות יכולות להיות:",
"the item was removed" : "הפריט הוסר",
"the link expired" : "הקישור פג תוקף",
"sharing is disabled" : "השיתוף נוטרל",
"For more info, please ask the person who sent this link." : "למידע נוסף, יש לפנות לשולח קישור זה.",
"%s is publicly shared" : "%s בשיתוף ציבורי",
"Download" : "הורדה",
"Download %s" : "הורדה %s",
"Direct link" : "קישור ישיר",
"Nothing to configure." : "אין שום דבר להגדיר.",
"Group Sharing Blacklist" : "רשימה שחורה לשיתוף קבוצות",
"Exclude groups from receiving shares" : "מניעת קבוצות מלקבל שיתופים",
"These groups will not be available to share with. Members of the group are not restricted in initiating shares and can receive shares with other groups they are a member of as usual." : "קבוצות אלו לא יהיו זמינות עבור שיתוף אליהן. החברים בקבוצות אלו לא מוגבלות ביצירת שיתופים, ויכולים לקבל שיתופים דרך קבוצות אחרות שהן חברים בהן."
},"pluralForm" :"nplurals=4; plural=(n == 1 && n % 1 == 0) ? 0 : (n == 2 && n % 1 == 0) ? 1: (n % 10 == 0 && n % 1 == 0 && n > 10) ? 2 : 3;"
} | {
"pile_set_name": "Github"
} |
#!/bin/sh
#
# $FreeBSD$
#
# PROVIDE: flowd_aggregate
# REQUIRE: SERVERS
# KEYWORD: shutdown
#
. /etc/rc.subr
name=flowd_aggregate
rcvar=flowd_aggregate_enable
command=/usr/local/opnsense/scripts/netflow/flowd_aggregate.py
command_interpreter=/usr/local/bin/python3
pidfile="/var/run/${name}.pid"
load_rc_config $name
# Set defaults
: ${flowd_aggregate_enable:=NO}
stop_cmd=flowd_aggregate_stop
# kill configd
flowd_aggregate_stop()
{
if [ -z "$rc_pid" ]; then
[ -n "$rc_fast" ] && return 0
_run_rc_notrunning
return 1
fi
echo -n "Stopping ${name}."
# first ask gently to exit
kill -15 ${rc_pid}
# wait max 5 seconds for gentle exit
for i in $(seq 1 50);
do
if [ -z "`/bin/ps -ax | /usr/bin/awk '{print $1;}' | /usr/bin/grep "^${rc_pid}"`" ]; then
break
fi
sleep 0.1
done
# kill any remaining configd processes (if still running)
for flowd_aggregate_pid in `/bin/ps -ax | grep 'flowd_aggregate.py' | /usr/bin/awk '{print $1;}' `
do
kill -9 $flowd_aggregate_pid >/dev/null 2>&1
done
echo "..done"
}
run_rc_command $1
| {
"pile_set_name": "Github"
} |
/* s_gen.c
*
* Micropolis, Unix Version. This game was released for the Unix platform
* in or about 1990 and has been modified for inclusion in the One Laptop
* Per Child program. Copyright (C) 1989 - 2007 Electronic Arts Inc. If
* you need assistance with this program, you may contact:
* http://wiki.laptop.org/go/Micropolis or email [email protected].
*
* 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 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
* General Public License for more details. You should have received a
* copy of the GNU General Public License along with this program. If
* not, see <http://www.gnu.org/licenses/>.
*
* ADDITIONAL TERMS per GNU GPL Section 7
*
* No trademark or publicity rights are granted. This license does NOT
* give you any right, title or interest in the trademark SimCity or any
* other Electronic Arts trademark. You may not distribute any
* modification of this program using the trademark SimCity or claim any
* affliation or association with Electronic Arts Inc. or its employees.
*
* Any propagation or conveyance of this program must include this
* copyright notice and these terms.
*
* If you convey this program (or any modifications of it) and assume
* contractual liability for the program to recipients of it, you agree
* to indemnify Electronic Arts for any liability that those contractual
* assumptions impose on Electronic Arts.
*
* You may not misrepresent the origins of this program; modified
* versions of the program must be marked as such and not identified as
* the original program.
*
* This disclaimer supplements the one included in the General Public
* License. TO THE FULLEST EXTENT PERMISSIBLE UNDER APPLICABLE LAW, THIS
* PROGRAM IS PROVIDED TO YOU "AS IS," WITH ALL FAULTS, WITHOUT WARRANTY
* OF ANY KIND, AND YOUR USE IS AT YOUR SOLE RISK. THE ENTIRE RISK OF
* SATISFACTORY QUALITY AND PERFORMANCE RESIDES WITH YOU. ELECTRONIC ARTS
* DISCLAIMS ANY AND ALL EXPRESS, IMPLIED OR STATUTORY WARRANTIES,
* INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY, SATISFACTORY QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT OF THIRD PARTY
* RIGHTS, AND WARRANTIES (IF ANY) ARISING FROM A COURSE OF DEALING,
* USAGE, OR TRADE PRACTICE. ELECTRONIC ARTS DOES NOT WARRANT AGAINST
* INTERFERENCE WITH YOUR ENJOYMENT OF THE PROGRAM; THAT THE PROGRAM WILL
* MEET YOUR REQUIREMENTS; THAT OPERATION OF THE PROGRAM WILL BE
* UNINTERRUPTED OR ERROR-FREE, OR THAT THE PROGRAM WILL BE COMPATIBLE
* WITH THIRD PARTY SOFTWARE OR THAT ANY ERRORS IN THE PROGRAM WILL BE
* CORRECTED. NO ORAL OR WRITTEN ADVICE PROVIDED BY ELECTRONIC ARTS OR
* ANY AUTHORIZED REPRESENTATIVE SHALL CREATE A WARRANTY. SOME
* JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF OR LIMITATIONS ON IMPLIED
* WARRANTIES OR THE LIMITATIONS ON THE APPLICABLE STATUTORY RIGHTS OF A
* CONSUMER, SO SOME OR ALL OF THE ABOVE EXCLUSIONS AND LIMITATIONS MAY
* NOT APPLY TO YOU.
*/
#include "sim.h"
/* Generate Map */
#define WATER_LOW RIVER /* 2 */
#define WATER_HIGH LASTRIVEDGE /* 20 */
#define WOODS_LOW TREEBASE /* 21 */
#define WOODS_HIGH UNUSED_TRASH2 /* 39 */
short XStart, YStart, MapX, MapY;
short Dir, LastDir;
int TreeLevel = -1; /* level for tree creation */
int LakeLevel = -1; /* level for lake creation */
int CurveLevel = -1; /* level for river curviness */
int CreateIsland = -1; /* -1 => 10%, 0 => never, 1 => always */
GenerateNewCity(void)
{
GenerateSomeCity(Rand16());
}
GenerateSomeCity(int r)
{
if (CityFileName != NULL) {
ckfree(CityFileName);
CityFileName = NULL;
}
gettimeofday(&start_time, NULL);
GenerateMap(r);
ScenarioID = 0;
CityTime = 0;
InitSimLoad = 2;
DoInitialEval = 0;
InitWillStuff();
ResetMapState();
ResetEditorState();
InvalidateEditors();
InvalidateMaps();
UpdateFunds();
DoSimInit();
Eval("UIDidGenerateNewCity");
Kick();
}
ERand(short limit)
{
short x, z;
z = Rand(limit);
x = Rand(limit);
if (z < x)
return (z);
return (x);
}
GenerateMap(int r)
{
SeedRand(r);
if (CreateIsland < 0) {
if (Rand(100) < 10) { /* chance that island is generated */
MakeIsland();
return;
}
}
if (CreateIsland == 1) {
MakeNakedIsland();
} else {
ClearMap();
}
GetRandStart();
if (CurveLevel != 0) {
DoRivers();
}
if (LakeLevel != 0) {
MakeLakes();
}
SmoothRiver();
if (TreeLevel != 0) {
DoTrees();
}
RandomlySeedRand();
}
ClearMap(void)
{
register short x, y;
for (x = 0; x < WORLD_X; x++)
for (y = 0; y < WORLD_Y; y++)
Map[x][y] = DIRT;
}
ClearUnnatural(void)
{
register short x, y;
for (x = 0; x < WORLD_X; x++) {
for (y = 0; y < WORLD_Y; y++) {
if (Map[x][y] > WOODS) {
Map[x][y] = DIRT;
}
}
}
}
#define RADIUS 18
MakeNakedIsland()
{
register int x, y;
for (x = 0; x < WORLD_X; x++)
for (y = 0; y < WORLD_Y; y++)
Map[x][y] = RIVER;
for (x = 5; x < WORLD_X - 5; x++)
for (y = 5; y < WORLD_Y - 5; y++)
Map[x][y] = DIRT;
for (x = 0; x < WORLD_X - 5; x += 2) {
MapX = x ;
MapY = ERand(RADIUS);
BRivPlop();
MapY = (WORLD_Y - 10) - ERand(RADIUS);
BRivPlop();
MapY = 0;
SRivPlop();
MapY = (WORLD_Y - 6);
SRivPlop();
}
for (y = 0; y < WORLD_Y - 5; y += 2) {
MapY = y ;
MapX = ERand(RADIUS);
BRivPlop();
MapX = (WORLD_X - 10) - ERand(RADIUS);
BRivPlop();
MapX = 0;
SRivPlop();
MapX = (WORLD_X - 6);
SRivPlop();
}
}
MakeIsland(void)
{
MakeNakedIsland();
SmoothRiver();
DoTrees();
}
MakeLakes(void)
{
short Lim1, Lim2, t, z;
register short x, y;
if (LakeLevel < 0) {
Lim1 = Rand(10);
} else {
Lim1 = LakeLevel / 2;
}
for (t = 0; t < Lim1; t++) {
x = Rand(WORLD_X - 21) + 10;
y = Rand(WORLD_Y - 20) + 10;
Lim2 = Rand(12) + 2;
for (z = 0; z < Lim2; z++) {
MapX = x - 6 + Rand(12);
MapY = y - 6 + Rand(12);
if (Rand(4))
SRivPlop();
else
BRivPlop();
}
}
}
GetRandStart(void)
{
XStart = 40 + Rand(WORLD_X - 80);
YStart = 33 + Rand(WORLD_Y - 67);
MapX = XStart;
MapY = YStart;
}
MoveMap(short dir)
{
static short DirTab[2][8] = { { 0, 1, 1, 1, 0, -1, -1, -1},
{-1,-1, 0, 1, 1, 1, 0, -1} };
dir = dir & 7;
MapX += DirTab[0][dir];
MapY += DirTab[1][dir];
}
TreeSplash(short xloc, short yloc)
{
short dis, dir;
register short xoff, yoff, z;
if (TreeLevel < 0) {
dis = Rand(150) + 50;
} else {
dis = Rand(100 + (TreeLevel * 2)) + 50;
}
MapX = xloc;
MapY = yloc;
for (z = 0; z < dis; z++) {
dir = Rand(7);
MoveMap(dir);
if (!(TestBounds(MapX, MapY)))
return;
if ((Map[MapX][MapY] & LOMASK) == DIRT)
Map[MapX][MapY] = WOODS + BLBNBIT;
}
}
DoTrees(void)
{
short Amount, x, xloc, yloc;
if (TreeLevel < 0) {
Amount = Rand(100) + 50;
} else {
Amount = TreeLevel + 3;
}
for(x = 0; x < Amount; x++) {
xloc = Rand(WORLD_X - 1);
yloc = Rand(WORLD_Y - 1);
TreeSplash(xloc, yloc);
}
SmoothTrees();
SmoothTrees();
}
SmoothRiver(void)
{
static short DX[4] = {-1, 0, 1, 0};
static short DY[4] = { 0, 1, 0,-1};
static short REdTab[16] = {
13+BULLBIT, 13+BULLBIT, 17+BULLBIT, 15+BULLBIT,
5+BULLBIT, 2, 19+BULLBIT, 17+BULLBIT,
9+BULLBIT, 11+BULLBIT, 2, 13+BULLBIT,
7+BULLBIT, 9+BULLBIT, 5+BULLBIT, 2 };
short bitindex, z, Xtem, Ytem;
register short temp, MapX, MapY;
for (MapX = 0; MapX < WORLD_X; MapX++) {
for (MapY = 0; MapY < WORLD_Y; MapY++) {
if (Map[MapX][MapY] == REDGE) {
bitindex = 0;
for (z = 0; z < 4; z++) {
bitindex = bitindex << 1;
Xtem = MapX + DX[z];
Ytem = MapY + DY[z];
if (TestBounds(Xtem, Ytem) &&
((Map[Xtem][Ytem] & LOMASK) != DIRT) &&
(((Map[Xtem][Ytem]&LOMASK) < WOODS_LOW) ||
((Map[Xtem][Ytem]&LOMASK) > WOODS_HIGH)))
bitindex++;
}
temp = REdTab[bitindex & 15];
if ((temp != RIVER) && (Rand(1)))
temp++;
Map[MapX][MapY] = temp;
}
}
}
}
IsTree(int cell)
{
if (((cell & LOMASK) >= WOODS_LOW) &&
((cell & LOMASK) <= WOODS_HIGH))
return TRUE;
return FALSE;
}
SmoothTrees(void)
{
static short DX[4] = {-1, 0, 1, 0};
static short DY[4] = { 0, 1, 0,-1};
static short TEdTab[16] = { 0, 0, 0, 34,
0, 0, 36, 35,
0, 32, 0, 33,
30, 31, 29, 37 };
short bitindex, z, Xtem, Ytem;
register short temp, MapX, MapY;
for (MapX = 0; MapX < WORLD_X; MapX++) {
for (MapY = 0; MapY < WORLD_Y; MapY++) {
if (IsTree(Map[MapX][MapY])) {
bitindex = 0;
for (z = 0; z < 4; z++) {
bitindex = bitindex << 1;
Xtem = MapX + DX[z];
Ytem = MapY + DY[z];
if (TestBounds(Xtem, Ytem) &&
IsTree(Map[Xtem][Ytem])) {
bitindex++;
}
}
temp = TEdTab[bitindex & 15];
if (temp) {
if (temp != WOODS)
if ((MapX + MapY) & 1)
temp = temp - 8;
Map[MapX][MapY] = temp + BLBNBIT;
}
else Map[MapX][MapY] = temp;
}
}
}
}
DoRivers(void)
{
LastDir = Rand(3);
Dir = LastDir;
DoBRiv();
MapX = XStart;
MapY = YStart;
LastDir = LastDir ^ 4;
Dir = LastDir;
DoBRiv();
MapX = XStart;
MapY = YStart;
LastDir = Rand(3);
DoSRiv();
}
DoBRiv(void)
{
int r1, r2;
if (CurveLevel < 0) {
r1 = 100;
r2 = 200;
} else {
r1 = CurveLevel + 10;
r2 = CurveLevel + 100;
}
while (TestBounds (MapX + 4, MapY + 4)) {
BRivPlop();
if (Rand(r1) < 10) {
Dir = LastDir;
} else {
if (Rand(r2) > 90) Dir++;
if (Rand(r2) > 90) Dir--;
}
MoveMap(Dir);
}
}
DoSRiv(void)
{
int r1, r2;
if (CurveLevel < 0) {
r1 = 100;
r2 = 200;
} else {
r1 = CurveLevel + 10;
r2 = CurveLevel + 100;
}
while (TestBounds (MapX + 3, MapY + 3)) {
SRivPlop();
if (Rand(r1) < 10) {
Dir = LastDir;
} else {
if (Rand(r2) > 90) Dir++;
if (Rand(r2) > 90) Dir--;
}
MoveMap(Dir);
}
}
PutOnMap(short Mchar, short Xoff, short Yoff)
{
register short Xloc, Yloc, temp;
if (Mchar == 0)
return;
Xloc = MapX + Xoff;
Yloc = MapY + Yoff;
if (TestBounds(Xloc, Yloc) == FALSE)
return;
if (temp = Map[Xloc][Yloc]) {
temp = temp & LOMASK;
if (temp == RIVER)
if (Mchar != CHANNEL)
return;
if (temp == CHANNEL)
return;
}
Map[Xloc][Yloc] = Mchar;
}
BRivPlop(void)
{
static short BRMatrix[9][9] = {
{ 0, 0, 0, 3, 3, 3, 0, 0, 0 },
{ 0, 0, 3, 2, 2, 2, 3, 0, 0 },
{ 0, 3, 2, 2, 2, 2, 2, 3, 0 },
{ 3, 2, 2, 2, 2, 2, 2, 2, 3 },
{ 3, 2, 2, 2, 4, 2, 2, 2, 3 },
{ 3, 2, 2, 2, 2, 2, 2, 2, 3 },
{ 0, 3, 2, 2, 2, 2, 2, 3, 0 },
{ 0, 0, 3, 2, 2, 2, 3, 0, 0 },
{ 0, 0, 0, 3, 3, 3, 0, 0, 0 } };
short x, y;
for (x = 0; x < 9; x++)
for (y = 0; y < 9; y++)
PutOnMap(BRMatrix[y][x], x, y);
}
SRivPlop(void)
{
static short SRMatrix[6][6] = {
{ 0, 0, 3, 3, 0, 0 },
{ 0, 3, 2, 2, 3, 0 },
{ 3, 2, 2, 2, 2, 3 },
{ 3, 2, 2, 2, 2, 3 },
{ 0, 3, 2, 2, 3, 0 },
{ 0, 0, 3, 3, 0, 0 } };
short x, y;
for (x = 0; x < 6; x++)
for (y = 0; y < 6; y++)
PutOnMap(SRMatrix[y][x], x, y);
}
SmoothWater()
{
int x, y;
for(x = 0; x < WORLD_X; x++) {
for(y = 0; y < WORLD_Y; y++) {
/* If water: */
if (((Map[x][y] & LOMASK) >= WATER_LOW) &&
((Map[x][y] & LOMASK) <= WATER_HIGH)) {
if (x > 0) {
/* If nearest object is not water: */
if (((Map[x - 1][y] & LOMASK) < WATER_LOW) ||
((Map[x - 1][y] & LOMASK) > WATER_HIGH)) {
goto edge;
}
}
if (x < (WORLD_X - 1)) {
/* If nearest object is not water: */
if (((Map[x+1][y]&LOMASK) < WATER_LOW) ||
((Map[x+1][y]&LOMASK) > WATER_HIGH)) {
goto edge;
}
}
if (y > 0) {
/* If nearest object is not water: */
if (((Map[x][y - 1] & LOMASK) < WATER_LOW) ||
((Map[x][y-1]&LOMASK) > WATER_HIGH)) {
goto edge;
}
}
if (y < (WORLD_Y - 1)) {
/* If nearest object is not water: */
if (((Map[x][y + 1] & LOMASK) < WATER_LOW) ||
((Map[x][y + 1] & LOMASK) > WATER_HIGH)) {
edge:
Map[x][y]=REDGE; /* set river edge */
continue;
}
}
}
}
}
for (x = 0; x < WORLD_X; x++) {
for (y = 0; y < WORLD_Y; y++) {
/* If water which is not a channel: */
if (((Map[x][y] & LOMASK) != CHANNEL) &&
((Map[x][y] & LOMASK) >= WATER_LOW) &&
((Map[x][y] & LOMASK) <= WATER_HIGH)) {
if (x > 0) {
/* If nearest object is not water; */
if (((Map[x - 1][y] & LOMASK) < WATER_LOW) ||
((Map[x - 1][y] & LOMASK) > WATER_HIGH)) {
continue;
}
}
if (x < (WORLD_X - 1)) {
/* If nearest object is not water: */
if (((Map[x + 1][y] & LOMASK) < WATER_LOW) ||
((Map[x + 1][y] & LOMASK) > WATER_HIGH)) {
continue;
}
}
if (y > 0) {
/* If nearest object is not water: */
if (((Map[x][y - 1] & LOMASK) < WATER_LOW) ||
((Map[x][y - 1] & LOMASK) > WATER_HIGH)) {
continue;
}
}
if (y < (WORLD_Y - 1)) {
/* If nearest object is not water: */
if (((Map[x][y + 1] & LOMASK) < WATER_LOW) ||
((Map[x][y + 1] & LOMASK) > WATER_HIGH)) {
continue;
}
}
Map[x][y] = RIVER; /* make it a river */
}
}
}
for (x = 0; x < WORLD_X; x++) {
for (y = 0; y < WORLD_Y; y++) {
/* If woods: */
if (((Map[x][y] & LOMASK) >= WOODS_LOW) &&
((Map[x][y] & LOMASK) <= WOODS_HIGH)) {
if (x > 0) {
/* If nearest object is water: */
if ((Map[x - 1][y] == RIVER) ||
(Map[x - 1][y] == CHANNEL)) {
Map[x][y] = REDGE; /* make it water's edge */
continue;
}
}
if (x < (WORLD_X - 1)) {
/* If nearest object is water: */
if ((Map[x + 1][y] == RIVER) ||
(Map[x + 1][y] == CHANNEL)) {
Map[x][y] = REDGE; /* make it water's edge */
continue;
}
}
if (y > 0) {
/* If nearest object is water: */
if ((Map[x][y - 1] == RIVER) ||
(Map[x][y - 1] == CHANNEL)) {
Map[x][y] = REDGE; /* make it water's edge */
continue;
}
}
if (y < (WORLD_Y - 1)) {
/* If nearest object is water; */
if ((Map[x][y + 1] == RIVER) ||
(Map[x][y + 1] == CHANNEL)) {
Map[x][y] = REDGE; /* make it water's edge */
continue;
}
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
// Copyright (C) 2009 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#undef DLIB_TYPE_SAFE_UNION_KERNEl_ABSTRACT_
#ifdef DLIB_TYPE_SAFE_UNION_KERNEl_ABSTRACT_
#include "../algs.h"
#include "../noncopyable.h"
namespace dlib
{
// ----------------------------------------------------------------------------------------
class bad_type_safe_union_cast : public std::bad_cast
{
/*!
This is the exception object thrown by type_safe_union::cast_to() if the
type_safe_union does not contain the type of object being requested.
!*/
};
// ----------------------------------------------------------------------------------------
template <
typename T1,
typename T2 = _void, // _void indicates parameter not used.
typename T3 = _void,
typename T4 = _void,
typename T5 = _void,
typename T6 = _void,
typename T7 = _void,
typename T8 = _void,
typename T9 = _void,
typename T10 = _void,
typename T11 = _void,
typename T12 = _void,
typename T13 = _void,
typename T14 = _void,
typename T15 = _void,
typename T16 = _void,
typename T17 = _void,
typename T18 = _void,
typename T19 = _void,
typename T20 = _void
>
class type_safe_union : noncopyable
{
/*!
REQUIREMENTS ON ALL TEMPLATE ARGUMENTS
All template arguments must be default constructable and have
a global swap.
INITIAL VALUE
- is_empty() == true
- contains<U>() == false, for all possible values of U
WHAT THIS OBJECT REPRESENTS
This object is a type safe analogue of the classic C union object.
The type_safe_union, unlike a union, can contain non-POD types such
as std::string.
For example:
union my_union
{
int a;
std::string b; // Error, std::string isn't a POD
};
type_safe_union<int,std::string> my_type_safe_union; // No error
!*/
public:
typedef T1 type1;
typedef T2 type2;
typedef T3 type3;
typedef T4 type4;
typedef T5 type5;
typedef T6 type6;
typedef T7 type7;
typedef T8 type8;
typedef T9 type9;
typedef T10 type10;
typedef T11 type11;
typedef T12 type12;
typedef T13 type13;
typedef T14 type14;
typedef T15 type15;
typedef T16 type16;
typedef T17 type17;
typedef T18 type18;
typedef T19 type19;
typedef T20 type20;
type_safe_union(
);
/*!
ensures
- this object is properly initialized
!*/
template <typename T>
type_safe_union (
const T& item
);
/*!
requires
- T must be one of the types given to this object's template arguments
ensures
- this object is properly initialized
- #get<T>() == item
(i.e. this object will contain a copy of item)
!*/
~type_safe_union(
);
/*!
ensures
- all resources associated with this object have been freed
!*/
template <typename T>
static int get_type_id (
);
/*!
ensures
- if (T is the same type as one of the template arguments) then
- returns a number indicating which template argument it is.
(e.g. if T is the same type as T3 then this function returns 3)
- else
- returns -1
!*/
template <typename T>
bool contains (
) const;
/*!
ensures
- if (this type_safe_union currently contains an object of type T) then
- returns true
- else
- returns false
!*/
bool is_empty (
) const;
/*!
ensures
- if (this type_safe_union currently contains any object at all) then
- returns true
- else
- returns false
!*/
template <typename T>
void apply_to_contents (
T& obj
);
/*!
requires
- obj is a function object capable of operating on all the types contained
in this type_safe_union. I.e. obj(this->get<U>()) must be a valid
expression for all the possible U types.
ensures
- if (is_empty() == false) then
- Let U denote the type of object currently contained in this type_safe_union
- calls obj(this->get<U>())
- The object returned by this->get<U>() will be non-const
!*/
template <typename T>
void apply_to_contents (
const T& obj
);
/*!
requires
- obj is a function object capable of operating on all the types contained
in this type_safe_union. I.e. obj(this->get<U>()) must be a valid
expression for all the possible U types.
ensures
- if (is_empty() == false) then
- Let U denote the type of object currently contained in this type_safe_union
- calls obj(this->get<U>())
- The object returned by this->get<U>() will be non-const
!*/
template <typename T>
void apply_to_contents (
T& obj
) const;
/*!
requires
- obj is a function object capable of operating on all the types contained
in this type_safe_union. I.e. obj(this->get<U>()) must be a valid
expression for all the possible U types.
ensures
- if (is_empty() == false) then
- Let U denote the type of object currently contained in this type_safe_union
- calls obj(this->get<U>())
- The object returned by this->get<U>() will be const
!*/
template <typename T>
void apply_to_contents (
const T& obj
) const;
/*!
requires
- obj is a function object capable of operating on all the types contained
in this type_safe_union. I.e. obj(this->get<U>()) must be a valid
expression for all the possible U types.
ensures
- if (is_empty() == false) then
- Let U denote the type of object currently contained in this type_safe_union
- calls obj(this->get<U>())
- The object returned by this->get<U>() will be const
!*/
template <typename T>
T& get(
);
/*!
requires
- T must be one of the types given to this object's template arguments
ensures
- #is_empty() == false
- #contains<T>() == true
- if (contains<T>() == true)
- returns a non-const reference to the object contained in this type_safe_union.
- else
- Constructs an object of type T inside *this
- Any previous object stored in this type_safe_union is destructed and its
state is lost.
- returns a non-const reference to the newly created T object.
!*/
template <typename T>
const T& cast_to (
) const;
/*!
requires
- T must be one of the types given to this object's template arguments
ensures
- if (contains<T>() == true) then
- returns a const reference to the object contained in this type_safe_union.
- else
- throws bad_type_safe_union_cast
!*/
template <typename T>
T& cast_to (
);
/*!
requires
- T must be one of the types given to this object's template arguments
ensures
- if (contains<T>() == true) then
- returns a non-const reference to the object contained in this type_safe_union.
- else
- throws bad_type_safe_union_cast
!*/
template <typename T>
type_safe_union& operator= (
const T& item
);
/*!
requires
- T must be one of the types given to this object's template arguments
ensures
- #get<T>() == item
(i.e. this object will contain a copy of item)
- returns *this
!*/
void swap (
type_safe_union& item
);
/*!
ensures
- swaps *this and item
!*/
};
// ----------------------------------------------------------------------------------------
template < ... >
inline void swap (
type_safe_union<...>& a,
type_safe_union<...>& b
) { a.swap(b); }
/*!
provides a global swap function
!*/
// ----------------------------------------------------------------------------------------
template < ... >
void serialize (
const type_safe_union<...>& item,
std::ostream& out
);
/*!
provides serialization support
Note that type_safe_union objects are serialized as follows:
- if (item.is_empty()) then
- perform: serialize(0, out)
- else
- perform: serialize(item.get_type_id<type_of_object_in_item>(), out);
serialize(item.get<type_of_object_in_item>(), out);
!*/
template < ... >
void deserialize (
type_safe_union<...>& item,
std::istream& in
);
/*!
provides deserialization support
!*/
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_TYPE_SAFE_UNION_KERNEl_ABSTRACT_
| {
"pile_set_name": "Github"
} |
/*
* This file is part of the OregonCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Zulaman
SD%Complete: 90
SDComment: Forest Frog will turn into different NPC's. Workaround to prevent new entry from running this script
SDCategory: Zul'Aman
EndScriptData */
/* ContentData
npc_forest_frog
EndContentData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "zulaman.h"
#include "ScriptedGossip.h"
/*######
## npc_forest_frog
######*/
enum //Misc
{
SPELL_REMOVE_AMANI_CURSE = 43732,
SPELL_PUSH_MOJO = 43923,
ENTRY_FOREST_FROG = 24396
};
struct npc_forest_frogAI : public ScriptedAI
{
npc_forest_frogAI(Creature* c) : ScriptedAI(c)
{
pInstance = (ScriptedInstance*)c->GetInstanceData();
}
ScriptedInstance* pInstance;
void Reset() {}
void EnterCombat(Unit* /*who*/) {}
void DoSpawnRandom()
{
if (pInstance)
{
uint32 cEntry = 0;
switch (rand() % 10)
{
case 0:
cEntry = 24397;
break; //Mannuth
case 1:
cEntry = 24403;
break; //Deez
case 2:
cEntry = 24404;
break; //Galathryn
case 3:
cEntry = 24405;
break; //Adarrah
case 4:
cEntry = 24406;
break; //Fudgerick
case 5:
cEntry = 24407;
break; //Darwen
case 6:
cEntry = 24445;
break; //Mitzi
case 7:
cEntry = 24448;
break; //Christian
case 8:
cEntry = 24453;
break; //Brennan
case 9:
cEntry = 24455;
break; //Hollee
}
if (!pInstance->GetData(ENCOUNTER_RAND_VENDOR_1))
if (rand() % 10 == 1) cEntry = 24408; //Gunter
if (!pInstance->GetData(ENCOUNTER_RAND_VENDOR_2))
if (rand() % 10 == 1) cEntry = 24409; //Kyren
if (cEntry) me->UpdateEntry(cEntry);
if (cEntry == 24408) pInstance->SetData(ENCOUNTER_RAND_VENDOR_1, DONE);
if (cEntry == 24409) pInstance->SetData(ENCOUNTER_RAND_VENDOR_2, DONE);
}
}
void SpellHit(Unit* caster, const SpellEntry* spell)
{
if (spell->Id == SPELL_REMOVE_AMANI_CURSE && caster->GetTypeId() == TYPEID_PLAYER && me->GetEntry() == ENTRY_FOREST_FROG)
{
//increase or decrease chance of mojo?
if (rand() % 99 == 50) DoCast(caster, SPELL_PUSH_MOJO, true);
else DoSpawnRandom();
}
}
};
CreatureAI* GetAI_npc_forest_frog(Creature* pCreature)
{
return new npc_forest_frogAI (pCreature);
}
/*######
## npc_zulaman_hostage
######*/
static char GOSSIP_HOSTAGE1[] = "I am glad to have helped you.";
static uint32 HostageEntry[] = {23790, 23999, 24001, 24024};
static uint32 ChestEntry[] = {186648, 187021, 186672, 186667};
struct npc_zulaman_hostageAI : public ScriptedAI
{
npc_zulaman_hostageAI(Creature* c) : ScriptedAI(c)
{
IsLoot = false;
}
bool IsLoot;
uint64 PlayerGUID;
void Reset() {}
void EnterCombat(Unit* /*who*/) {}
void JustDied(Unit* /*who*/)
{
Player* pPlayer = Unit::GetPlayer(*me, PlayerGUID);
if (pPlayer) pPlayer->SendLoot(me->GetGUID(), LOOT_CORPSE);
}
void UpdateAI(const uint32 /*diff*/)
{
if (IsLoot)
DoCast(me, 7, false);
}
};
bool GossipHello_npc_zulaman_hostage(Player* pPlayer, Creature* pCreature)
{
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HOSTAGE1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
pPlayer->SEND_GOSSIP_MENU(pPlayer->GetGossipTextId(pCreature), pCreature->GetGUID());
return true;
}
bool GossipSelect_npc_zulaman_hostage(Player* pPlayer, Creature* pCreature, uint32 /*uiSender*/, uint32 uiAction)
{
if (uiAction == GOSSIP_ACTION_INFO_DEF + 1)
pPlayer->CLOSE_GOSSIP_MENU();
if (!pCreature->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP))
return true;
pCreature->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
ScriptedInstance* pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
if (pInstance)
{
uint8 progress = pInstance->GetData(ENCOUNTER_CHESTLOOTED);
pInstance->SetData(ENCOUNTER_CHESTLOOTED, progress + 1);
float x, y, z;
pCreature->GetPosition(x, y, z);
uint32 entry = pCreature->GetEntry();
for (uint8 i = 0; i < 4; ++i)
{
if (HostageEntry[i] == entry)
{
pCreature->SummonGameObject(ChestEntry[i], x - 2, y, z, 0, 0, 0, 0, 0, 0);
break;
}
}
/*Creature* summon = pCreature->SummonCreature(HostageInfo[progress], x-2, y, z, 0, TEMPSUMMON_DEAD_DESPAWN, 0);
if (summon)
{
CAST_AI(npc_zulaman_hostageAI, summon->AI())->PlayerGUID = pPlayer->GetGUID();
CAST_AI(npc_zulaman_hostageAI, summon->AI())->IsLoot = true;
summon->SetDisplayId(10056);
summon->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
summon->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
}*/
}
return true;
}
CreatureAI* GetAI_npc_zulaman_hostage(Creature* pCreature)
{
return new npc_zulaman_hostageAI(pCreature);
}
/* npc_harrison_jones */
static char GOSSIP_HARRISON[] = "Tooltip Missing";
static char SAY_HARRISON_UNK0[] = "Puzzling. They're clearly harnessing great power from their sacrifices. But for what?";
static char YELL_HARRISON_FOLLOWME[] = "Suit yourself. At least five of you must assist me if we're to get inside. Follow me...";
static char YELL_HARRISON_UNK1[] = "According to my calculations, if enough of us bang the gong at once the seal on these doors will break and we can enter.";
static char YELL_HARRISON_UNK2[] = "I've researched this site extensively and I won't allow any dim-witted treasure hunters to swoop in and steal what belongs in a museum. I'll lead this charge.";
static char YELL_HARRISON_UNK3[] = "In fact, it would be best if you just stay here. You'd only get in my way....";
static float HarrisonsWay[3] = { 131.81f, 1642.91f, 42.021595f };
struct npc_harrison_jonesAI : public ScriptedAI
{
npc_harrison_jonesAI(Creature* pCreature) : ScriptedAI(pCreature)
{
instance = (ScriptedInstance*)pCreature->GetInstanceData();
handleGossips = !!instance;
if (handleGossips)
{
me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
me->SetSpeed(MOVE_RUN, 1);
//me->RemoveUnitMovementFlag(MOVEMENTFLAG_WALK_MODE);
}
}
bool GossipHello(Player* player)
{
if (!handleGossips)
return false;
Group* group = player->GetGroup();
if (!group || group->IsLeader(player->GetGUID()) || player->IsGameMaster())
{
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HARRISON, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
player->SEND_GOSSIP_MENU(player->GetGossipTextId(me), me->GetGUID());
}
return true;
}
bool GossipSelect()
{
me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
me->GetMotionMaster()->MovePoint(0, HarrisonsWay[0], HarrisonsWay[1], HarrisonsWay[2]);
me->MonsterYell(YELL_HARRISON_FOLLOWME, LANG_UNIVERSAL, 0);
return true;
}
void MovementInform(uint32 type, uint32 id)
{
if (type != POINT_MOTION_TYPE || id != 0)
return;
me->Say("Gong Event is not implemented, yet. Skipping the event...", LANG_UNIVERSAL, 0);
instance->SetData(ENCOUNTER_GONG, DONE);
}
void Update(uint32 /*diff*/)
{
}
ScriptedInstance* instance;
bool handleGossips;
};
static bool GossipHello_npc_harrison_jones(Player* pPlayer, Creature* pCreature)
{
if (npc_harrison_jonesAI* ai = dynamic_cast <npc_harrison_jonesAI*> (pCreature->AI()))
return ai->GossipHello(pPlayer);
return false;
}
static bool GossipSelect_npc_harrison_jones(Player* pPlayer, Creature* pCreature, uint32 /*uiSender*/, uint32 uiAction)
{
if (npc_harrison_jonesAI* ai = dynamic_cast <npc_harrison_jonesAI*> (pCreature->AI()))
return ai->GossipSelect();
return false;
}
CreatureAI* GetAI_npc_harrison_jones(Creature* pCreature)
{
return new npc_harrison_jonesAI(pCreature);
}
void AddSC_zulaman()
{
Script* newscript;
newscript = new Script;
newscript->Name = "npc_forest_frog";
newscript->GetAI = &GetAI_npc_forest_frog;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "npc_zulaman_hostage";
newscript->GetAI = &GetAI_npc_zulaman_hostage;
newscript->pGossipHello = &GossipHello_npc_zulaman_hostage;
newscript->pGossipSelect = &GossipSelect_npc_zulaman_hostage;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "npc_harrison_jones";
newscript->GetAI = &GetAI_npc_harrison_jones;
newscript->pGossipHello = &GossipHello_npc_harrison_jones;
newscript->pGossipSelect = &GossipSelect_npc_harrison_jones;
newscript->RegisterSelf();
}
| {
"pile_set_name": "Github"
} |
#pragma once
/*
* Copyright 2010-2016 OpenXcom Developers.
*
* This file is part of OpenXcom.
*
* OpenXcom 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 3 of the License, or
* (at your option) any later version.
*
* OpenXcom 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 OpenXcom. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../Engine/State.h"
#include <SDL.h>
#include <string>
#include "OptionsBaseState.h"
#include "../Savegame/SavedGame.h"
namespace OpenXcom
{
class Text;
class SavedGame;
/**
* Loads a saved game, with an optional message.
*/
class LoadGameState : public State
{
private:
int _firstRun;
OptionsOrigin _origin;
Text *_txtStatus;
std::string _filename;
public:
/// Creates the Load Game state.
LoadGameState(OptionsOrigin origin, const std::string &filename, SDL_Color *palette);
/// Creates the Load Game state.
LoadGameState(OptionsOrigin origin, SaveType type, SDL_Color *palette);
/// Cleans up the Load Game state.
~LoadGameState();
/// Creates the interface.
void buildUi(SDL_Color *palette);
/// Validates game.
void init();
/// Loads the game.
void think();
/// Shows an error message.
void error(const std::string &msg, SavedGame *save);
};
}
| {
"pile_set_name": "Github"
} |
config BR2_PACKAGE_PYTHON_HIREDIS
bool "python-hiredis"
help
Python wrapper for hiredis.
https://github.com/redis/hiredis-py
| {
"pile_set_name": "Github"
} |
import png from './file.png';
export default '<img alt="test" src="' + png + '" />';
| {
"pile_set_name": "Github"
} |
//
// The MIT License
//
// Copyright (c) 2011 - 2013, Mirek Rusin <mirek [at] me [dot] com>
// http://github.com/mirek/CoreWebSocket
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#include "WebSocketClient.h"
//#include <CoreWebSocket/WebSocketClient.h>
#define if_self if (self)
#pragma mark Write
// Internal, write provided buffer as websocket frame [0x00 buffer 0xff]
CFIndex
__WebSocketClientWriteFrameWithData (WebSocketClientRef client, WebSocketFrameOpCode opCode, Boolean isMasked, UInt8 *maskingKey, CFDataRef payload) {
CFIndex result = 0;
WebSocketFrameRef frame = WebSocketFrameCreateWithPayloadData(client->allocator, opCode, isMasked, maskingKey, payload);
if (frame != NULL) {
CFIndex length = CFDataGetLength(frame->data);
while (CFWriteStreamCanAcceptBytes(client->write) && (result < length)) {
CFIndex didWrite = CFWriteStreamWrite(client->write, WebSocketFrameGetBytesPtr(frame) + result, length - result);
if (didWrite > 0) {
result += didWrite;
}
}
WebSocketFrameDealloc(frame);
}
return result;
}
// Write data as websocket frame (with binary frame opcode).
CFIndex
WebSocketClientWriteWithData (WebSocketClientRef self, CFDataRef value) {
return __WebSocketClientWriteFrameWithData(self, kWebSocketFrameOpCodeBinary, FALSE, NULL, value);
}
// Write UTF-8 encoded string as a websocket frame (with text frame opcode).
CFIndex
WebSocketClientWriteWithString (WebSocketClientRef self, CFStringRef value) {
CFIndex result = -1;
if_self {
if (value) {
CFDataRef data = CFStringCreateExternalRepresentation(self->allocator, value, kCFStringEncodingUTF8, 0);
if (data) {
result = __WebSocketClientWriteFrameWithData(self, kWebSocketFrameOpCodeText, FALSE, NULL, data);
CFRelease(data);
}
}
}
return result;
}
// Write UTF-8 encoded string as a websocket frame (with text frame opcode).
CFIndex
WebSocketClientWriteWithFormat (WebSocketClientRef self, CFStringRef fmt, ...) {
CFIndex result = -1;
if_self if (fmt != NULL) {
va_list args;
va_start(args, fmt);
CFStringRef string = CFStringCreateWithFormatAndArguments(self->allocator, NULL, fmt, args);
va_end(args);
if (string != NULL) {
result = WebSocketClientWriteWithString(self, string);
CFRelease(string);
}
}
return result;
}
#pragma mark Read callback
Boolean
__WebSocketClientWriteHandShake (WebSocketClientRef client);
void
__WebSocketClientReadFrame (WebSocketClientRef self, CFReadStreamRef stream) {
// Reset last frame if it has been completed.
if (WebSocketFrameGetState(self->frame) == kWebSocketFrameStateReady) {
WebSocketFrameReset(self->frame);
}
// Did handshake already and there are bytes to read.
// It's an incomming message.
{
CFIndex size = 64 * 1024;
UInt8 *buffer = (UInt8 *) CFAllocatorAllocate(self->allocator, size, 0);
if (buffer != NULL) {
CFIndex didRead = 0;
while (CFReadStreamHasBytesAvailable(self->read)) {
if ((didRead = CFReadStreamRead(stream, buffer, size)) != -1) {
WebSocketFrameAppend(self->frame, buffer, didRead);
} else {
break;
}
}
CFAllocatorDeallocate(self->allocator, buffer);
}
}
if (WebSocketFrameParse(self->frame) == kWebSocketFrameStateReady) {
CFStringRef string = WebSocketFrameCopyPayloadString(self->frame, kCFStringEncodingUTF8);
if (string) {
self->webSocket->callbacks.didClientReadCallback(self->webSocket, self, string);
CFRelease(string);
}
}
}
void
__WebSocketClientReadCallBack (CFReadStreamRef stream, CFStreamEventType eventType, void *info) {
WebSocketClientRef self = (WebSocketClientRef) info;
if (self) {
switch (eventType) {
case kCFStreamEventOpenCompleted:
break;
case kCFStreamEventHasBytesAvailable:
if (!self->didReadHandShake) {
if (__WebSocketClientReadHandShake(self)) {
if (!self->didWriteHandShake) {
if (CFWriteStreamCanAcceptBytes(self->write)) {
if (__WebSocketClientWriteHandShake(self)) {
// printf("Successfully written handshake\n");
} else {
printf("TODO: Error writting handshake\n");
}
} else {
// printf("TODO: Didn't handshake and client doesn't accept bytes yet. Write callback will handle writting handshake as soon as we can write.\n");
}
} else {
printf("TODO: Just read handshake and handshake already written, shouldn't happen, fault?\n");
}
__WebSocketAppendClient(self->webSocket, self);
} else {
printf("TODO: Didn't read handshake and __WebSocketClientReadHandShake failed.\n");
}
} else {
__WebSocketClientReadFrame(self, stream);
}
break;
case kCFStreamEventErrorOccurred:
break;
case kCFStreamEventEndEncountered:
break;
default:
break;
}
}
}
Boolean
__WebSocketClientWriteWithHTTPMessage (WebSocketClientRef client, CFHTTPMessageRef message) {
Boolean result = FALSE;
if (client && message) {
CFDataRef data = CFHTTPMessageCopySerializedMessage(message);
if (data) {
CFIndex written = CFWriteStreamWrite(client->write, CFDataGetBytePtr(data), CFDataGetLength(data));
if (written == CFDataGetLength(data)) {
result = TRUE; // TODO: do it properly
}
client->didWriteHandShake = 1;
CFRelease(data);
}
}
return result;
}
Boolean
__WebSocketClientWriteHandShakeDraftIETF_HYBI_00 (WebSocketClientRef client) {
Boolean result = FALSE;
if (client) {
if (client->protocol == kWebSocketProtocolDraftIETF_HYBI_00) {
CFStringRef key1 = CFHTTPMessageCopyHeaderFieldValue(client->handShakeRequestHTTPMessage, CFSTR("Sec-Websocket-Key1"));
CFStringRef key2 = CFHTTPMessageCopyHeaderFieldValue(client->handShakeRequestHTTPMessage, CFSTR("Sec-Websocket-Key2"));
CFDataRef key3 = CFHTTPMessageCopyBody(client->handShakeRequestHTTPMessage);
CFStringRef origin = CFHTTPMessageCopyHeaderFieldValue(client->handShakeRequestHTTPMessage, CFSTR("Origin"));
CFStringRef host = CFHTTPMessageCopyHeaderFieldValue(client->handShakeRequestHTTPMessage, CFSTR("Host"));
CFHTTPMessageRef response = CFHTTPMessageCreateEmpty(NULL, 0);
CFHTTPMessageAppendBytes(response, (const UInt8 *)"HTTP/1.1 101 Web Socket Protocol Handshake\r\n", 44);
CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Upgrade"), CFSTR("WebSocket"));
CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Connection"), CFSTR("Upgrade"));
CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Sec-Websocket-Origin"), origin);
CFMutableStringRef location = CFStringCreateMutable(client->allocator, 0);
CFStringAppend(location, CFSTR("ws://"));
CFStringAppend(location, host);
CFStringAppend(location, CFSTR("/"));
CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Sec-Websocket-Location"), location);
CFRelease(location);
// Set MD5 hash
{
CFMutableDataRef mutable = CFDataCreateMutable(client->allocator, 0);
__WebSocketDataAppendMagickNumberWithKeyValueString(mutable, key1);
__WebSocketDataAppendMagickNumberWithKeyValueString(mutable, key2);
CFDataAppendBytes(mutable, CFDataGetBytePtr(key3), CFDataGetLength(key3));
CFDataRef data = __WebSocketCreateMD5Data(client->allocator, mutable);
CFHTTPMessageSetBody(response, data);
CFRelease(mutable);
CFRelease(data);
}
result = __WebSocketClientWriteWithHTTPMessage(client, response) ? TRUE : FALSE;
CFRelease(response);
CFRelease(host);
CFRelease(origin);
CFRelease(key3);
CFRelease(key2);
CFRelease(key1);
}
}
return result;
}
// The source code has been copied and modified from
// http://www.opensource.apple.com/source/CFNetwork/CFNetwork-128/HTTP/CFHTTPAuthentication.c
// See _CFEncodeBase64 function. The source code has been released under
// Apple Public Source License Version 2.0 http://www.opensource.apple.com/apsl/
CFStringRef
__WebSocketCreateBase64StringWithData (CFAllocatorRef allocator, CFDataRef inputData) {
unsigned outDataLen;
CFStringRef result = NULL;
unsigned char *outData = cuEnc64(CFDataGetBytePtr(inputData), (unsigned int)CFDataGetLength(inputData), &outDataLen);
if(outData) {
// current cuEnc64 appends \n and NULL, trim them
unsigned char *c = outData + outDataLen - 1;
while((*c == '\n') || (*c == '\0')) {
c--;
outDataLen--;
}
result = CFStringCreateWithBytes(allocator, outData, outDataLen, kCFStringEncodingASCII, FALSE);
free(outData);
}
return result;
}
Boolean
__WebSocketClientWriteHandShakeDraftIETF_HYBI_06 (WebSocketClientRef client) {
Boolean success = 0;
if (client) {
if (client->protocol == kWebSocketProtocolDraftIETF_HYBI_06) {
CFStringRef key = CFHTTPMessageCopyHeaderFieldValue(client->handShakeRequestHTTPMessage, CFSTR("Sec-WebSocket-Key"));
CFStringRef keyWithMagick = CFStringCreateWithFormat(client->allocator, NULL, CFSTR("%@%@"), key, CFSTR("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
CFDataRef keyWithMagickSHA1 = __WebSocketCreateSHA1DataWithString(client->allocator, keyWithMagick, kCFStringEncodingUTF8);
CFStringRef keyWithMagickSHA1Base64 = __WebSocketCreateBase64StringWithData(client->allocator, keyWithMagickSHA1);
CFStringRef origin = CFHTTPMessageCopyHeaderFieldValue(client->handShakeRequestHTTPMessage, CFSTR("Sec-WebSocket-Origin"));
CFStringRef host = CFHTTPMessageCopyHeaderFieldValue(client->handShakeRequestHTTPMessage, CFSTR("Host"));
CFHTTPMessageRef response = CFHTTPMessageCreateEmpty(NULL, 0);
CFHTTPMessageAppendBytes(response, (const UInt8 *)"HTTP/1.1 101 Switching Protocols\r\n", 44);
CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Upgrade"), CFSTR("websocket"));
CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Connection"), CFSTR("Upgrade"));
CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Sec-WebSocket-Accept"), keyWithMagickSHA1Base64);
success = __WebSocketClientWriteWithHTTPMessage(client, response);
CFRelease(response);
CFRelease(keyWithMagickSHA1Base64);
CFRelease(keyWithMagickSHA1);
CFRelease(keyWithMagick);
CFRelease(key);
CFRelease(origin);
CFRelease(host);
}
}
return success;
}
Boolean
__WebSocketClientWriteHandShakeRFC6455_13 (WebSocketClientRef client) {
Boolean success = 0;
if (client) {
if (client->protocol == kWebSocketProtocol_RFC6455_13) {
CFStringRef key = CFHTTPMessageCopyHeaderFieldValue(client->handShakeRequestHTTPMessage, CFSTR("Sec-WebSocket-Key"));
CFStringRef keyWithMagick = CFStringCreateWithFormat(client->allocator, NULL, CFSTR("%@%@"), key, CFSTR("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
CFDataRef keyWithMagickSHA1 = __WebSocketCreateSHA1DataWithString(client->allocator, keyWithMagick, kCFStringEncodingUTF8);
CFStringRef keyWithMagickSHA1Base64 = __WebSocketCreateBase64StringWithData(client->allocator, keyWithMagickSHA1);
// CFStringRef host = CFHTTPMessageCopyHeaderFieldValue(client->handShakeRequestHTTPMessage, CFSTR("Host"));
CFHTTPMessageRef response = CFHTTPMessageCreateEmpty(NULL, 0);
CFHTTPMessageAppendBytes(response, (const UInt8 *)"HTTP/1.1 101 Switching Protocols\r\n", 44);
CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Upgrade"), CFSTR("websocket"));
CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Connection"), CFSTR("Upgrade"));
CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Sec-WebSocket-Accept"), keyWithMagickSHA1Base64);
success = __WebSocketClientWriteWithHTTPMessage(client, response);
CFRelease(response);
CFRelease(keyWithMagickSHA1Base64);
CFRelease(keyWithMagickSHA1);
CFRelease(keyWithMagick);
CFRelease(key);
// CFRelease(host);
}
}
return success;
}
Boolean
__WebSocketClientWriteHandShake (WebSocketClientRef self) {
Boolean success = 0;
if (self->didReadHandShake) {
if (!self->didWriteHandShake) {
switch (self->protocol) {
case kWebSocketProtocolDraftIETF_HYBI_00:
success = __WebSocketClientWriteHandShakeDraftIETF_HYBI_00(self);
break;
case kWebSocketProtocolDraftIETF_HYBI_06:
success = __WebSocketClientWriteHandShakeDraftIETF_HYBI_06(self);
break;
case kWebSocketProtocol_RFC6455_13:
success = __WebSocketClientWriteHandShakeRFC6455_13(self);
break;
default:
printf("Unknown protocol, can't write handshake. TODO: disconnect\n");
// Unknown protocol, can't write handshake
break;
}
}
}
return success;
}
void
__WebSocketClientWriteCallBack (CFWriteStreamRef stream, CFStreamEventType eventType, void *info) {
WebSocketClientRef client = info;
if (client) {
switch (eventType) {
case kCFStreamEventCanAcceptBytes:
if (!client->didWriteHandShake && client->didReadHandShake)
__WebSocketClientWriteHandShake(client);
break;
case kCFStreamEventEndEncountered:
break;
case kCFStreamEventErrorOccurred:
printf("kCFStreamEventErrorOccurred (write)\n");
CFErrorRef error = CFWriteStreamCopyError(stream);
if (error) {
CFShow(error);
CFRelease(error);
}
break;
default:
break;
}
}
}
#pragma mark Lifecycle
WebSocketClientRef
WebSocketClientCreate (WebSocketRef webSocket, CFSocketNativeHandle handle) {
WebSocketClientRef self = NULL;
if (webSocket) {
self = CFAllocatorAllocate(webSocket->allocator, sizeof(WebSocketClient), 0);
if (self) {
self->allocator = webSocket->allocator ? CFRetain(webSocket->allocator) : NULL;
self->retainCount = 1;
WebSocketRetain(webSocket), self->webSocket = webSocket;
self->handle = handle;
self->frame = WebSocketFrameCreate(self->allocator);
self->read = NULL;
self->write = NULL;
self->context.version = 0;
self->context.info = self;
self->context.copyDescription = NULL;
self->context.retain = NULL;
self->context.release = NULL;
self->handShakeRequestHTTPMessage = NULL;
self->didReadHandShake = 0;
self->didWriteHandShake = 0;
self->protocol = kWebSocketProtocolUnknown;
CFStreamCreatePairWithSocket(self->allocator, handle, &self->read, &self->write);
if (!self->read || !self->write) {
close(handle);
fprintf(stderr, "CFStreamCreatePairWithSocket() failed, %p, %p\n", read, write);
} else {
// printf("ok\n");
}
CFOptionFlags flags = kCFStreamEventOpenCompleted | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;
CFReadStreamSetClient(self->read, flags | kCFStreamEventHasBytesAvailable, __WebSocketClientReadCallBack, &self->context);
CFWriteStreamSetClient(self->write, flags | kCFStreamEventCanAcceptBytes, __WebSocketClientWriteCallBack, &self->context);
CFReadStreamScheduleWithRunLoop(self->read, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
CFWriteStreamScheduleWithRunLoop(self->write, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
if (!CFReadStreamOpen(self->read)) {
printf("couldn't open read stream\n");
} else {
// printf("opened read stream\n");
}
if (!CFWriteStreamOpen(self->write)) {
printf("couldn't open write stream\n");
} else {
// printf("opened write stream\n");
}
}
}
return self;
}
void
WebSocketClientRetain (WebSocketClientRef self) {
if_self {
++self->retainCount;
}
}
void
WebSocketClientRelease (WebSocketClientRef self) {
if_self {
if (--self->retainCount == 0) {
CFAllocatorRef allocator = self->allocator;
if (self->read) {
if (CFReadStreamGetStatus(self->read) != kCFStreamStatusClosed)
CFReadStreamClose(self->read);
CFRelease(self->read);
self->read = NULL;
}
if (self->write) {
if (CFWriteStreamGetStatus(self->write) != kCFStreamStatusClosed)
CFWriteStreamClose(self->write);
CFRelease(self->write);
self->write = NULL;
}
if (self->frame != NULL) {
WebSocketFrameRelease(self->frame), self->frame = NULL;
}
CFAllocatorDeallocate(allocator, self);
self = NULL;
if (allocator)
CFRelease(allocator);
}
}
}
#pragma Handshake
// Return magic number for the key needed to generate handshake hash
uint32_t
__WebSocketGetMagicNumberWithKeyValueString (CFStringRef string) {
uint32_t magick = -1;
if (string) {
UInt8 buffer[__WebSocketMaxHeaderKeyLength];
CFIndex usedBufferLength = 0;
char numberBuffer[__WebSocketMaxHeaderKeyLength];
memset(numberBuffer, 0, sizeof(numberBuffer));
CFIndex usedNumberBufferLength = 0;
CFStringGetBytes(string, CFRangeMake(0, CFStringGetLength(string)), kCFStringEncodingASCII, 0, 0, buffer, sizeof(buffer), &usedBufferLength);
UInt32 number = 0;
UInt32 spaces = 0;
for (int i = 0; i < usedBufferLength; i++) {
if (buffer[i] >= '0' && buffer[i] <= '9')
numberBuffer[usedNumberBufferLength++] = buffer[i];
if (buffer[i] == ' ')
spaces++;
}
if (spaces > 0) {
number = (UInt32)strtoul(numberBuffer, NULL, 10);
magick = number / spaces;
}
}
return magick;
}
// Appends big-endian uint32 magic number with key string to the mutable data
Boolean
__WebSocketDataAppendMagickNumberWithKeyValueString (CFMutableDataRef data, CFStringRef string) {
Boolean success = 0;
if (data && string) {
uint32_t magick = __WebSocketGetMagicNumberWithKeyValueString(string);
uint32_t swapped = CFSwapInt32HostToBig(magick);
CFDataAppendBytes(data, (const void *)&swapped, sizeof(swapped));
success = 1;
}
return success;
}
CFDataRef
__WebSocketCreateMD5Data (CFAllocatorRef allocator, CFDataRef value) {
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5((unsigned char *)CFDataGetBytePtr(value), (CC_LONG)CFDataGetLength(value), digest);
return CFDataCreate(allocator, digest, CC_MD5_DIGEST_LENGTH);
}
CFDataRef
__WebSocketCreateSHA1DataWithData (CFAllocatorRef allocator, CFDataRef value) {
unsigned char digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1((unsigned char *)CFDataGetBytePtr(value), (CC_LONG)CFDataGetLength(value), digest);
return CFDataCreate(allocator, digest, CC_SHA1_DIGEST_LENGTH);
}
CFDataRef
__WebSocketCreateSHA1DataWithString (CFAllocatorRef allocator, CFStringRef value, CFStringEncoding encoding) {
CFDataRef data = NULL;
if (value) {
CFDataRef valueData = CFStringCreateExternalRepresentation(allocator, value, encoding, 0);
if (valueData) {
data = __WebSocketCreateSHA1DataWithData(allocator, valueData);
CFRelease(valueData);
}
}
return data;
}
Boolean
__WebSocketClientHandShakeConsumeHTTPMessage (WebSocketClientRef client) {
Boolean success = 0;
if (client) {
UInt8 buffer[4096];
CFIndex bytes = 0;
client->handShakeRequestHTTPMessage = CFHTTPMessageCreateEmpty(client->allocator, 1);
while (CFReadStreamHasBytesAvailable(client->read)) {
if ((bytes = CFReadStreamRead(client->read, buffer, sizeof(buffer))) > 0) {
CFHTTPMessageAppendBytes(client->handShakeRequestHTTPMessage, buffer, bytes);
} else if (bytes < 0) {
CFErrorRef error = CFReadStreamCopyError(client->read);
CFShow(error);
CFRelease(error);
goto fin;
}
}
success = 1;
}
fin:
return success;
}
// Private method
Boolean
__WebSocketClientHandShakeUpdateProtocolBasedOnHTTPMessage (WebSocketClientRef self) {
Boolean result = FALSE;
if (self) {
// Get the protocol version
self->protocol = kWebSocketProtocolUnknown;
// Is Upgrade header available? It has to for ws...
CFStringRef upgrade = CFHTTPMessageCopyHeaderFieldValue(self->handShakeRequestHTTPMessage, CFSTR("Upgrade"));
if (upgrade) {
if (CFStringCompare(CFSTR("WebSocket"), upgrade, kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
CFStringRef version = CFHTTPMessageCopyHeaderFieldValue(self->handShakeRequestHTTPMessage, CFSTR("Sec-WebSocket-Version"));
if (version) {
if (CFStringCompare(CFSTR("6"), version, kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
self->protocol = kWebSocketProtocolDraftIETF_HYBI_06;
result = TRUE;
} else if (CFStringCompare(CFSTR("13"), version, kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
self->protocol = kWebSocketProtocol_RFC6455_13;
result = TRUE;
} else {
// Version different than 6, we don't know of any other, leave the protocol as unknown
}
CFRelease(version);
} else {
// Sec-WebSocket-Version header field is missing.
// It may be 00 protocol, which doesn't have this field.
// 00 protocol has to have Sec-WebSocket-Key1 and Sec-WebSocket-Key2
// fields - let's check for those.
CFStringRef key1 = CFHTTPMessageCopyHeaderFieldValue(self->handShakeRequestHTTPMessage, CFSTR("Sec-WebSocket-Key1"));
if (key1) {
CFStringRef key2 = CFHTTPMessageCopyHeaderFieldValue(self->handShakeRequestHTTPMessage, CFSTR("Sec-WebSocket-Key2"));
if (key2) {
self->protocol = kWebSocketProtocolDraftIETF_HYBI_00;
result = TRUE;
CFRelease(key2);
}
CFRelease(key1);
} else {
// Key2 missing, no version specified = unknown protocol
}
}
} else {
// Upgrade HTTP field seems to be different from "WebSocket" (case ignored)
}
CFRelease(upgrade);
} else {
// Upgrade HTTP field seems to be absent
}
}
return result;
}
Boolean
__WebSocketClientReadHandShake (WebSocketClientRef self) {
Boolean result = FALSE;
if_self {
if ((result = __WebSocketClientHandShakeConsumeHTTPMessage(self))) {
if ((result = __WebSocketClientHandShakeUpdateProtocolBasedOnHTTPMessage(self))) {
// Dump http message:
//
// CFDictionaryRef headerFields = CFHTTPMessageCopyAllHeaderFields(self->handShakeRequestHTTPMessage);
// if (headerFields) {
// CFRelease(headerFields);
// }
}
}
self->didReadHandShake = TRUE;
}
return result;
}
| {
"pile_set_name": "Github"
} |
//
// SafariView.swift
// ACHNBrowserUI
//
// Created by Thomas Ricouard on 17/04/2020.
// Copyright © 2020 Thomas Ricouard. All rights reserved.
//
import Foundation
import SwiftUI
#if !os(tvOS)
import SafariServices
public struct SafariView: UIViewControllerRepresentable {
public let url: URL
public init(url: URL) {
self.url = url
}
public func makeUIViewController(context: UIViewControllerRepresentableContext<SafariView>) -> SFSafariViewController {
let vc = SFSafariViewController(url: url)
vc.configuration.barCollapsingEnabled = false
return vc
}
public func updateUIViewController(_ uiViewController: SFSafariViewController,
context: UIViewControllerRepresentableContext<SafariView>) {
}
}
#endif
| {
"pile_set_name": "Github"
} |
===============
Troubleshooting
===============
Installation Problems
---------------------
Problem: Pip Fails
~~~~~~~~~~~~~~~~~~~~
Don't worry if `pip` fails like this::
$ pip install complexity
...
error: could not create '/Library/Python/2.7/site-packages/complexity':
Permission denied
We've got a couple of solutions for that.
Best Solution: Use Virtualenv
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Install virtualenv systemwide with `pip`::
$ sudo pip install virtualenv
2. Create a virtualenv for Complexity::
$ virtualenv complexity-env
$ source complexity-env/bin/activate
(or complexity-env/Scripts/activate.bat on Windows)
(complexity-env) $
3. Install Complexity into the virtualenv::
(complexity-env) $ pip install complexity
Alternate Solution: Install Systemwide
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Install Complexity systemwide with `pip`::
$ sudo pip install complexity
2. If that doesn't work, you can use `easy_install` instead::
$ sudo easy_install complexity
Site Generation Problems
------------------------
Problem: Site Generation Fails
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you get an error like this::
jinja2.exceptions.TemplateSyntaxError: Unexpected end of template. Jinja
was looking for the following tags: 'endblock'. The innermost block that
needs to be closed is 'block'.
Then check your templates carefully and make sure that you've closed all
blocks properly with `{% endblock %}`.
Still Having Problems?
----------------------
`File an issue here`_ with the following info:
* Your operating system name and version.
* Any details about your local setup that might be helpful in troubleshooting.
* Detailed steps to reproduce the problems.
.. _`File an issue here`: https://github.com/audreyr/complexity/issues/new
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of Jitamin.
*
* Copyright (C) Jitamin Team
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require_once __DIR__.'/../Base.php';
use Jitamin\Group\LdapBackendGroupProvider;
class LdapBackendGroupProviderTest extends Base
{
public function testGetLdapGroupPattern()
{
$this->setExpectedException('LogicException', 'LDAP group filter empty, check the parameter LDAP_GROUP_FILTER');
$backend = new LdapBackendGroupProvider($this->container);
$backend->getLdapGroupPattern('test');
}
}
| {
"pile_set_name": "Github"
} |
/*PLEASE DO NOT EDIT THIS CODE*/
/*This code was generated using the UMPLE 1.21.0.4666 modeling language!*/
/**
* Abstract
*/
// line 38 "DMMOverview.ump"
// line 89 "DMMOverview.ump"
public class Relationship
{
//------------------------
// MEMBER VARIABLES
//------------------------
//------------------------
// CONSTRUCTOR
//------------------------
public Relationship()
{}
//------------------------
// INTERFACE
//------------------------
public void delete()
{}
} | {
"pile_set_name": "Github"
} |
from django.db import models
from websiteFunctions.models import Websites
from datetime import datetime
class IncJob(models.Model):
website = models.ForeignKey(Websites, on_delete=models.CASCADE)
date = models.DateTimeField(default=datetime.now, blank=True)
class JobSnapshots(models.Model):
job = models.ForeignKey(IncJob, on_delete=models.CASCADE)
type = models.CharField(max_length=300)
snapshotid = models.CharField(max_length=50)
destination = models.CharField(max_length=200, default='')
class BackupJob(models.Model):
destination = models.CharField(max_length=300)
frequency = models.CharField(max_length=50)
websiteData = models.IntegerField()
websiteDatabases = models.IntegerField()
websiteDataEmails = models.IntegerField()
class JobSites(models.Model):
job = models.ForeignKey(BackupJob, on_delete=models.CASCADE)
website = models.CharField(max_length=300)
| {
"pile_set_name": "Github"
} |
/*
Copyright (C) 2005, 2006 Apple Inc. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
Some useful definitions needed for laying out elements
*/
#pragma once
#include "LayoutRect.h"
namespace WebCore {
struct GapRects {
const LayoutRect& left() const { return m_left; }
const LayoutRect& center() const { return m_center; }
const LayoutRect& right() const { return m_right; }
void uniteLeft(const LayoutRect& r) { m_left.unite(r); }
void uniteCenter(const LayoutRect& r) { m_center.unite(r); }
void uniteRight(const LayoutRect& r) { m_right.unite(r); }
void unite(const GapRects& o) { uniteLeft(o.left()); uniteCenter(o.center()); uniteRight(o.right()); }
operator LayoutRect() const
{
LayoutRect result = m_left;
result.unite(m_center);
result.unite(m_right);
return result;
}
bool operator==(const GapRects& other)
{
return m_left == other.left() && m_center == other.center() && m_right == other.right();
}
bool operator!=(const GapRects& other) { return !(*this == other); }
private:
LayoutRect m_left;
LayoutRect m_center;
LayoutRect m_right;
};
} // namespace WebCore
| {
"pile_set_name": "Github"
} |
/**
* @license
* Copyright 2019 Google LLC
*
* 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
*
* https://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.
*/
/**
* Clamps a number between `min` and `max` values. Both `min` and `max` are
* optional.
*
* ```javascript
* clamp(100, 0, 40); // 40.
* ```
*/
export function clamp(value: number,
min = Number.NEGATIVE_INFINITY,
max = Number.POSITIVE_INFINITY) {
return Math.max(min, Math.min(max, value));
}
| {
"pile_set_name": "Github"
} |
@extends('account.layouts.default')
@section('account.content')
<div class="card">
<div class="card-body">
<h4 class="card-title">Manage team</h4>
<form method="POST" action="{{ route('account.subscription.team.update') }}">
{{ csrf_field() }}
{{ method_field('PUT') }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" class="control-label">Team name</label>
<input id="name" type="text"
class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}"
name="name"
value="{{ old('name', $team->name) }}" required>
@if ($errors->has('name'))
<div class="invalid-feedback">
<strong>{{ $errors->first('name') }}</strong>
</div>
@endif
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">
Update
</button>
</div>
</form>
</div>
</div>
<div class="card mt-3">
<div class="card-body">
<div class="card-title">
<div class="flex-column align-items-start">
<div class="d-flex w-100 justify-content-between">
<h4>Team members</h4>
</div>
</div>
</div>
<form action="{{ route('account.subscription.team.member.store') }}" method="POST" id="member-form">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="control-label">Add member by email address</label>
<input id="email" type="email"
class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}"
name="email"
value="{{ old('email') }}" required>
@if ($errors->has('email'))
<div class="invalid-feedback">
<strong>{{ $errors->first('email') }}</strong>
</div>
@endif
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">
Add member
</button>
</div>
</form>
</div>
<div class="list-group list-group-flush">
@forelse($team->users as $user)
<div class="list-group-item flex-column align-items-start">
<div class="d-flex w-100 justify-content-between">
<h5>{{ $user->name }}</h5>
<div>
Joined {{ $user->pivot->created_at->toDateString() }}
</div>
</div>
<p>{{ $user->email }}</p>
<!-- Meta -->
<ul class="list-inline">
<li class="list-inline-item">
<a href="{{ route('account.subscription.team.member.destroy', $user) }}"
data-toggle="modal"
data-target="#destroy-member-modal-{{ $user->id }}">
Delete
</a>
<form action="{{ route('account.subscription.team.member.destroy', $user) }}"
method="POST"
style="display: none" id="member-destroy-form-{{ $user->id }}">
{{ csrf_field() }}
{{ method_field('DELETE') }}
</form>
</li>
</ul>
</div>
@include('layouts.partials.modals._confirm_modal', [
'modalId' => "destroy-member-modal-{$user->id}",
'type' => 'danger',
'title' => 'Delete member confirmation',
'message' => "Are you sure you want to remove '{$user->name}' from the team?",
'action' => "member-destroy-form-{$user->id}"
])
@empty
<div class="list-group-item">You have not added any team members yet.</div>
@endforelse
</div>
</div>
@endsection
| {
"pile_set_name": "Github"
} |
package com.aviary.android.feather;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import com.aviary.android.feather.library.log.LoggerFactory;
import com.aviary.android.feather.library.utils.SystemUtils;
// TODO: Auto-generated Javadoc
/**
* The Class Constants.
*/
public class Constants {
private static Boolean mEnableFastPreview;
/** The original bundle. */
private static Bundle mOriginalBundle = new Bundle();
/** Arbitrary number indicating a fast cpu. */
public static final int BOGO_CPU_FAST = 1400;
public static final int MHZ_CPU_FAST = 1000;
/** Arbitrary number indicating a medium fast cpu. */
public static final int BOGO_CPU_MEDIUM = 950;
public static final int ANDROID_SDK = android.os.Build.VERSION.SDK_INT;
private static final String LOG_TAG = "constants";
/** The original Intent */
private static Intent mOriginalIntent = new Intent();
/**
* Initialize the constant fields used in feather like the screen resolution, memory available, etc and copy all the extras field
* from the original activity's intent.
*
* @param activity
* the activity
*/
public static void init( Activity activity ) {
LoggerFactory.log( "ANDROID_SDK: " + ANDROID_SDK );
initContext( activity );
initIntent( activity.getIntent() );
}
/**
* Get if the fast preview mode is enabled. If the 'effect-enable-fast-preview' intent-extra has been passed within the original
* intent the intent value will be used, otherwise the device cpu speed will be used to determine the return value
*
* @return
*/
public static boolean getFastPreviewEnabled() {
if ( mEnableFastPreview == null ) {
boolean value = false;
if ( containsValue( EXTRA_EFFECTS_ENABLE_FAST_PREVIEW ) ) {
value = getValueFromIntent( EXTRA_EFFECTS_ENABLE_FAST_PREVIEW, false );
} else {
int mhz = SystemUtils.getCpuMhz();
LoggerFactory.log( "CPU MHZ: " + mhz );
if ( mhz > 0 ) {
value = mhz >= MHZ_CPU_FAST;
} else {
float speed = SystemUtils.getCpuSpeed();
value = speed >= BOGO_CPU_FAST;
}
}
mEnableFastPreview = value;
}
return mEnableFastPreview.booleanValue();
}
/**
* Return is external packs are enabled
*
* @return
*/
public static boolean getExternalPacksEnabled() {
return getValueFromIntent( EXTRA_EFFECTS_ENABLE_EXTERNAL_PACKS, true );
}
/**
* Inits the context.
*
* @param context
* the context
*/
private static void initContext( Context context ) {
final DisplayMetrics metrics = context.getResources().getDisplayMetrics();
SCREEN_WIDTH = metrics.widthPixels;
SCREEN_HEIGHT = metrics.heightPixels;
double[] mem = new double[3];
getMemoryInfo( mem );
MAX_MEMORY = mem[2];
}
/**
* Get information about device memory
* @param outValues
*/
public static void getMemoryInfo( double[] outValues ) {
double used = Double.valueOf( Runtime.getRuntime().totalMemory() ) / 1048576.0;
double total = Double.valueOf( Runtime.getRuntime().maxMemory() ) / 1048576.0;
double free = total - used;
Log.d( LOG_TAG, "memory: " + free + " of " + total );
outValues[0] = free;
outValues[1] = used;
outValues[2] = total;
}
public static void update( Context context ) {
final DisplayMetrics metrics = context.getResources().getDisplayMetrics();
SCREEN_WIDTH = metrics.widthPixels;
SCREEN_HEIGHT = metrics.heightPixels;
}
/**
* Register the original host {@link #android.content.Intent}.
*
* @param intent
* the intent
*/
private static void initIntent( Intent intent ) {
if ( intent != null ) {
Bundle extras = intent.getExtras();
if ( extras != null ) {
mOriginalBundle = (Bundle) extras.clone();
}
mOriginalIntent = new Intent( intent );
}
}
public static Intent getOriginalIntent() {
return mOriginalIntent;
}
public static Bundle getOriginalBundle() {
return mOriginalBundle;
}
/**
* Gets a value from the original intent.
*
* @param <T>
* the generic type
* @param key
* the key
* @param defaultValue
* the default value
* @return the value from intent
*/
@SuppressWarnings("unchecked")
public static <T> T getValueFromIntent( String key, T defaultValue ) {
if ( mOriginalBundle != null ) {
if ( mOriginalBundle.containsKey( key ) ) {
T value;
try {
value = (T) mOriginalBundle.get( key );
} catch ( ClassCastException e ) {
return defaultValue;
}
if ( value != null ) return value;
return defaultValue;
}
}
return defaultValue;
}
/**
* Check if the key string exists in the original bundle.
*
* @param key
* the key
* @return true, if successful
*/
public static boolean containsValue( String key ) {
if ( mOriginalBundle != null ) {
return mOriginalBundle.containsKey( key );
}
return false;
}
/**
* Return the maximum image size allowed for this device. Be careful if you want to modify the return value because it's easy to
* throw an {@link OutOfMemoryError} in android expecially when dealing with {@link Bitmap}.<br />
* Part of the application available memory has been already taken by the host application.
*
* @return the managed max image size
*/
public static final int getManagedMaxImageSize() {
if ( containsValue( EXTRA_MAX_IMAGE_SIZE ) ) {
int size = getValueFromIntent( EXTRA_MAX_IMAGE_SIZE, 0 );
if ( size > 0 ) {
return size;
}
}
final int screen_size = Math.max( SCREEN_HEIGHT, SCREEN_WIDTH );
if ( MAX_MEMORY >= 48 ) {
return Math.min( screen_size, 1280 );
} else if ( MAX_MEMORY >= 32 ) {
return Math.min( screen_size, 900 );
} else {
return Math.min( screen_size, 700 );
}
}
/**
* Return the max allowed heap size for application.
*
* @return the application max memory
*/
public static double getApplicationMaxMemory() {
return MAX_MEMORY;
}
/** The MAX image size */
static int MAX_IMAGE_SIZE_LOCAL = -1;
/** The max memory. */
static double MAX_MEMORY = -1;
/** The SCREEN width. */
public static int SCREEN_WIDTH = -1;
/** The SCREEN height. */
public static int SCREEN_HEIGHT = -1;
/** The Constant API_KEY. */
public static final String API_KEY = "API_KEY";
/** Result bitmap will be returned inline within the result Intent. */
public static final String EXTRA_RETURN_DATA = "return-data";
/** Define an output uri used by Feather to save the result bitmap in the specified location. */
public static final String EXTRA_OUTPUT = "output";
/**
* if an the EXTRA_OUTPUT is passed, this is used to determine the bitmap output format For valid values see
* Bitmap.CompressFormat
*
* @see Bitmap.CompressFormat
*/
public static final String EXTRA_OUTPUT_FORMAT = "output-format";
/**
* if EXTRA_OUTPUT is passed then this is used to determine the output quality ( if compress format is jpeg ) valid value: 0..100
*/
public static final String EXTRA_OUTPUT_QUALITY = "output-quality";
/**
* If tools-list is passed among the intent to Feather then only the selected list of tools will be shown Actually the list of
* tools: SHARPEN, BRIGHTNESS, CONTRAST, SATURATION, ROTATE, FLIP, BLUR, EFFECTS, COLORS, RED_EYE, CROP, WHITEN, DRAWING,
* STICKERS.
*/
public static final String EXTRA_TOOLS_LIST = "tools-list";
/**
* When the user click on the back-button and the image contains unsaved data a confirmation dialog appears by default. Setting
* this flag to true will hide that confirmation and the application will terminate.
*/
public static final String EXTRA_HIDE_EXIT_UNSAVE_CONFIRMATION = "hide-exit-unsave-confirmation";
/**
* Depending on the curremt image size and the current user device, some effects can take longer than expected to render the
* image. Passing in the caller intent this flag as boolean "true" will affect the behavior of some of the feather's panels, such
* as the effect panel. All the panels will use a small progress loader in the toolbar. Passing this value as "false" a modal
* progress loader will be used. If you omit this extra in the calling intent, Feather will determine this value reading the
* device cpu speed. Moreover the effect panel, when this value is "true", will create also an intermediate fast preview of the
* current selected effect while the full size preview is being loaded.
*/
public static final String EXTRA_EFFECTS_ENABLE_FAST_PREVIEW = "effect-enable-fast-preview";
/**
* By default feather offers to the final user the possibility to install external filters from the android market. If you want
* to disable this feature you can pass this extra boolean to the launching intent as "false". The default behavior is to enable
* the external filters.
*/
public static final String EXTRA_EFFECTS_ENABLE_EXTERNAL_PACKS = "effect-enable-external-pack";
/**
* By default feather offers to the final user the possibility to install external stickers from the android market. If you want
* to disable this feature you can pass this extra boolean to the launching intent as "false". The default behavior is to enable
* the external stickers.
*/
public static final String EXTRA_STICKERS_ENABLE_EXTERNAL_PACKS = "stickers-enable-external-pack";
/**
* By default Feather will resize the image loaded using the {@link Constants#getManagedMaxImageSize()} method based on the
* device memory. If you want to set at runtime the max image size allowed pass an integer value like this:<br />
*
* <pre>
* intent.putExtra( "max-image-size", 1024 );
* </pre>
*
* Remember that the available application memory is shared between the host application and the Aviary editor, so you should
* keep that in mind when setting the max image size.
*/
public static final String EXTRA_MAX_IMAGE_SIZE = "max-image-size";
/**
* If you want to enable the hi-res image post processing you need to pass a unique session id to the starting Intent. The
* session id string must be unique and must be 64 chars length
*/
public static final String EXTRA_OUTPUT_HIRES_SESSION_ID = "output-hires-session-id";
/**
* By default some our effects come with extra borders. If you want to disable those borders pass this extra as a boolan 'false'
*/
public static final String EXTRA_EFFECTS_BORDERS_ENABLED = "effect-enable-borders";
public static final String EXTRA_APP_ID = "app-id";
/**
* Passing this key in the calling intent, with any value, will disable the haptic vibration used in certain tools
*
* @since 2.1.5
*/
public static final String EXTRA_TOOLS_DISABLE_VIBRATION = "tools-vibration-disabled";
}
| {
"pile_set_name": "Github"
} |
/*
* This file is part of John the Ripper password cracker,
* Copyright (c) 1996-2001,2005,2012 by Solar Designer
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* There's ABSOLUTELY NO WARRANTY, express or implied.
*/
#include <string.h>
#include "arch.h"
#include "common.h"
#include "DES_std.h"
#include "memdbg.h"
#include "misc.h"
#if ARCH_BITS >= 64
#if !DES_ASM
static union {
double dummy;
struct {
DES_KS KS;
ARCH_WORD SPE_F[8][64];
#if DES_128K
ARCH_WORD SPE_W[4][64 * 64];
#endif
} data;
} CC_CACHE_ALIGN DES_all;
#else
extern ARCH_WORD DES_SPE_F[8][64];
#if DES_128K
extern ARCH_WORD DES_SPE_W[4][64 * 64];
#endif
#endif
static ARCH_WORD DES_SPE[8][64];
#else
#if !DES_ASM
static union {
double dummy;
struct {
DES_KS KS;
ARCH_WORD SPE_L[8][64];
ARCH_WORD cache_bank_shift;
ARCH_WORD SPE_H[8][64];
#if DES_128K
ARCH_WORD restore_double_word_alignment;
ARCH_WORD SPE_W[4][64 * 64][2];
#endif
} data;
} CC_CACHE_ALIGN DES_all;
#else
#if DES_X2
extern ARCH_WORD DES_SPE_F[8][64][2];
#else
extern ARCH_WORD DES_SPE_L[8][64], DES_SPE_H[8][64];
#endif
#if DES_128K
extern ARCH_WORD DES_SPE_W[4][64 * 64][2];
#endif
#endif
static ARCH_WORD DES_SPE[8][64][2];
#endif
#if !DES_ASM
#define DES_KS_copy DES_all.data.KS
#define DES_SPE_F DES_all.data.SPE_F
#define DES_SPE_L DES_all.data.SPE_L
#define DES_SPE_H DES_all.data.SPE_H
#define DES_SPE_W DES_all.data.SPE_W
DES_binary DES_IV;
ARCH_WORD DES_count;
DES_KS CC_CACHE_ALIGN DES_KS_current;
DES_KS CC_CACHE_ALIGN DES_KS_table[8][128];
#endif
static int DES_KS_updates;
static char DES_key[16];
#if DES_COPY
#if DES_ASM
extern DES_KS DES_KS_copy;
#endif
unsigned ARCH_WORD *DES_out;
#endif
extern DES_KS DES_KS_table[8][128];
#if ARCH_BITS >= 64
static ARCH_WORD DES_IP_E[8][16], DES_C_FP[16][16];
#else
static ARCH_WORD DES_IP_E[8][16][2], DES_C_FP[16][16][2];
#endif
/*
* Some architecture-dependent definitions follow. Be sure to use correct
* options while compiling, this might affect the performance a lot.
*/
#if (ARCH_BITS >= 64 && (DES_SCALE || !DES_MASK) || DES_128K) && \
DES_SIZE_FIX == 2
/*
* 64-bit architectures which can shift addresses left by 1 bit with no extra
* time required (for example by adding a register to itself).
*/
#define DES_INDEX(SPE, i) \
(*((ARCH_WORD *)(((unsigned char (*)[2])SPE) + (i))))
#else
#if DES_SIZE_FIX == 0
/*
* 64-bit architectures which can shift addresses left by 3 bits (but maybe
* not by 1) with no extra time required (for example by using the S8ADDQ
* instruction on DEC Alphas; we would need an ADDQ anyway).
*/
#define DES_INDEX(SPE, i) \
SPE[i]
#else
/*
* Architectures with no complicated addressing modes supported, or when those
* are not required.
*/
#define DES_INDEX(SPE, i) \
(*((ARCH_WORD *)(((unsigned char *)SPE) + (i))))
#if ARCH_BITS < 64 && DES_128K
#define DES_INDEX_L(SPE, i) \
(*((ARCH_WORD *)(((unsigned char *)&SPE[0][0]) + (i))))
#define DES_INDEX_H(SPE, i) \
(*((ARCH_WORD *)(((unsigned char *)&SPE[0][1]) + (i))))
#endif
#endif
#endif
/*
* You can choose between using shifts/masks, and using memory store and load
* instructions.
*/
#if DES_MASK
#if ARCH_BITS >= 64 && !DES_SCALE && DES_SIZE_FIX == 2
/*
* This method might be good for some 64-bit architectures with no complicated
* addressing modes supported. It would be the best one for DEC Alphas if they
* didn't have the S8ADDQ instruction.
*/
#define DES_MASK_6 (0x3F << 3)
#else
#if DES_EXTB
/*
* Masking whole bytes allows the compiler to use Move with Zero Extension
* instructions (where supported), like MOVZBL (MOVZX in Intel's syntax) on
* x86s, or EXTBL on DEC Alphas. It might only be reasonable to disable this
* if such instructions exist, but are slower than masks/shifts (as they are
* on Pentiums).
*/
#define DES_MASK_6 ((0x3F << DES_SIZE_FIX) | 0xFF)
#else
/*
* Forces using plain shifts/masks, sometimes it's the only choice. Note that
* you don't have to set DES_MASK if this is the case -- store/load method
* might be faster.
*/
#define DES_MASK_6 (0x3F << DES_SIZE_FIX)
#endif
#endif
#endif
#if !DES_COPY
#undef DES_KS_copy
#define DES_KS_copy KS
#endif
#define DES_KS_INDEX(i) (DES_KS_copy + (i * (16 / DES_SIZE)))
#define DES_24_TO_32(x) \
(((x) & 077) | \
(((x) & 07700) << 2) | \
(((x) & 0770000) << 4) | \
(((x) & 077000000) << 6))
#define DES_16_TO_32(x) \
((((x) & 0xF) << 1) | \
(((x) & 0xF0) << 5) | \
(((x) & 0xF00) << 9) | \
(((x) & 0xF000) << 13))
#if DES_128K
#define DES_UNDO_SIZE_FIX(x) \
((((x) >> 1) & 0xFF00FF00) | (((x) & 0x00FF00FF) >> 3))
#else
#define DES_UNDO_SIZE_FIX(x) \
((x) >> DES_SIZE_FIX)
#endif
static unsigned char DES_S[8][4][16] = {
{
{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7},
{0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},
{4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},
{15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}
}, {
{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10},
{3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},
{0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},
{13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}
}, {
{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8},
{13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1},
{13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7},
{1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}
}, {
{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15},
{13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9},
{10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4},
{3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}
}, {
{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9},
{14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6},
{4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14},
{11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}
}, {
{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11},
{10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8},
{9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6},
{4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}
}, {
{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1},
{13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6},
{1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2},
{6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}
}, {
{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7},
{1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2},
{7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8},
{2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}
}
};
static unsigned char DES_P[32] = {
15, 6, 19, 20,
28, 11, 27, 16,
0, 14, 22, 25,
4, 17, 30, 9,
1, 7, 23, 13,
31, 26, 2, 8,
18, 12, 29, 5,
21, 10, 3, 24
};
unsigned char DES_E[48] = {
31, 0, 1, 2, 3, 4,
3, 4, 5, 6, 7, 8,
7, 8, 9, 10, 11, 12,
11, 12, 13, 14, 15, 16,
15, 16, 17, 18, 19, 20,
19, 20, 21, 22, 23, 24,
23, 24, 25, 26, 27, 28,
27, 28, 29, 30, 31, 0
};
unsigned char DES_IP[64] = {
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7,
56, 48, 40, 32, 24, 16, 8, 0,
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6
};
static unsigned char DES_C[64] = {
0, 1, 2, 3, 16, 17, 18, 19,
4, 5, 6, 7, 20, 21, 22, 23,
8, 9, 10, 11, 24, 25, 26, 27,
12, 13, 14, 15, 28, 29, 30, 31,
32, 33, 34, 35, 48, 49, 50, 51,
36, 37, 38, 39, 52, 53, 54, 55,
40, 41, 42, 43, 56, 57, 58, 59,
44, 45, 46, 47, 60, 61, 62, 63
};
unsigned char DES_PC1[56] = {
56, 48, 40, 32, 24, 16, 8,
0, 57, 49, 41, 33, 25, 17,
9, 1, 58, 50, 42, 34, 26,
18, 10, 2, 59, 51, 43, 35,
62, 54, 46, 38, 30, 22, 14,
6, 61, 53, 45, 37, 29, 21,
13, 5, 60, 52, 44, 36, 28,
20, 12, 4, 27, 19, 11, 3
};
unsigned char DES_ROT[16] = {
1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
};
unsigned char DES_PC2[48] = {
13, 16, 10, 23, 0, 4,
2, 27, 14, 5, 20, 9,
22, 18, 11, 3, 25, 7,
15, 6, 26, 19, 12, 1,
40, 51, 30, 36, 46, 54,
29, 39, 50, 44, 32, 47,
43, 48, 38, 55, 33, 52,
45, 41, 49, 35, 28, 31
};
static void init_SPE(void)
{
int box, index, row, column, bit;
unsigned int mask, l, h;
for (box = 0; box < 8; box++)
for (index = 0; index < 64; index++) {
row =
((index & 1) << 1) |
(index >> 5);
column =
(((index >> 1) & 1) << 3) |
(((index >> 2) & 1) << 2) |
(((index >> 3) & 1) << 1) |
((index >> 4) & 1);
mask = (ARCH_WORD)DES_S[box][row][column] << ((7 - box) << 2);
h = l = 0;
for (bit = 0; bit < 24; bit++) {
if (((unsigned int)0x80000000 >>
DES_P[ARCH_INDEX(DES_E[bit])]) & mask)
l |= 1 << bit;
if (((unsigned int)0x80000000 >>
DES_P[ARCH_INDEX(DES_E[bit + 24])]) & mask)
h |= 1 << bit;
}
l = DES_24_TO_32(l); h = DES_24_TO_32(h);
#if ARCH_BITS >= 64
DES_SPE[box][index] =
DES_DO_SIZE_FIX(l) |
((unsigned ARCH_WORD)DES_DO_SIZE_FIX(h) << 32);
#else
DES_SPE[box][index][0] = DES_DO_SIZE_FIX(l);
DES_SPE[box][index][1] = DES_DO_SIZE_FIX(h);
#endif
}
}
static void init_IP_E(void)
{
int src, dst, dst1, dst2;
int chunk, mask, value;
memset(DES_IP_E, 0, sizeof(DES_IP_E));
for (dst1 = 0; dst1 < 8; dst1++)
for (dst2 = 0; dst2 < 6; dst2++) {
dst = (dst1 << 3) + dst2;
src = DES_IP[ARCH_INDEX(DES_E[dst1 * 6 + dst2])];
if (src >= 32) src -= 32; else src--;
src ^= 7;
chunk = src >> 2;
mask = 1 << (src & 3);
for (value = 0; value < 16; value++)
if (value & mask)
#if ARCH_BITS >= 64
DES_IP_E[chunk][value] |=
(unsigned ARCH_WORD)1 << dst;
#else
DES_IP_E[chunk][value][dst >> 5] |=
(unsigned ARCH_WORD)1 << (dst & 0x1F);
#endif
}
}
static void init_C_FP(void)
{
int src, dst;
int chunk, mask, value;
memset(DES_C_FP, 0, sizeof(DES_C_FP));
for (src = 0; src < 64; src++) {
dst = DES_IP[ARCH_INDEX(DES_C[src])] ^ 7;
chunk = src >> 2;
mask = 1 << (src & 3);
for (value = 0; value < 16; value++)
if (value & mask)
#if ARCH_BITS >= 64
DES_C_FP[chunk][value] |=
(unsigned ARCH_WORD)1 << dst;
#else
DES_C_FP[chunk][value][dst >> 5] |=
(unsigned ARCH_WORD)1 << (dst & 0x1F);
#endif
}
}
static void init_KS(void)
{
int pos, chr, round, bit, ofs;
unsigned char block[64];
ARCH_WORD value[2];
int k, p, q, r, s;
memset(block, 0, sizeof(block));
for (pos = 0; pos < 8; pos++)
for (chr = 0x7F; chr >= 0; chr--) {
for (bit = 0; bit < 7; bit++)
block[(pos << 3) + bit] = (chr >> (6 - bit)) & 1;
s = 0;
for (round = 0; round < 16; round++) {
s += DES_ROT[round];
value[0] = value[1] = 0;
k = 0;
for (ofs = 0; ofs < 64; ofs += 8)
for (bit = 0; bit < 6; bit++) {
p = DES_PC2[k++];
q = p < 28 ? 0 : 28;
p += s;
while (p >= 28) p -= 28;
r = DES_PC1[p + q];
value[ofs >> 5] |= (ARCH_WORD)block[r] <<
((ofs & 31) + bit);
}
#if ARCH_BITS >= 64
DES_KS_table[pos][chr][round] =
DES_DO_SIZE_FIX(value[0]) |
(DES_DO_SIZE_FIX(value[1]) << 32);
#else
DES_KS_table[pos][chr][round << 1] =
DES_DO_SIZE_FIX(value[0]);
DES_KS_table[pos][chr][(round << 1) + 1] =
DES_DO_SIZE_FIX(value[1]);
#endif
}
}
DES_KS_updates = 0;
memset(DES_key, 0, sizeof(DES_key));
memcpy(DES_KS_current, DES_KS_table, sizeof(DES_KS));
}
void DES_std_init(void)
{
init_SPE();
init_IP_E();
init_C_FP();
init_KS();
memset(DES_IV, 0, sizeof(DES_IV));
DES_count = 25;
}
void DES_std_set_salt(ARCH_WORD salt)
{
int box, index;
ARCH_WORD xor;
#if ARCH_BITS >= 64
unsigned ARCH_WORD src;
#else
ARCH_WORD l, h;
#endif
for (box = 0; box < 8; box++)
for (index = 0; index < 64; index++) {
#if ARCH_BITS >= 64
src = DES_SPE[box][index];
xor = (src ^ (src >> 32)) & salt;
DES_SPE_F[box][index] = src ^ (xor | (xor << 32));
#else
l = DES_SPE[box][index][0];
h = DES_SPE[box][index][1];
xor = (l ^ h) & salt;
#if DES_X2
DES_SPE_F[box][index][0] = l ^ xor;
DES_SPE_F[box][index][1] = h ^ xor;
#else
DES_SPE_L[box][index] = l ^ xor;
DES_SPE_H[box][index] = h ^ xor;
#endif
#endif
}
#if DES_128K
for (box = 0; box < 4; box++)
for (index = 0; index < 64 * 64; index++) {
#if ARCH_BITS >= 64
DES_SPE_W[box][index] =
DES_SPE_F[box << 1][index & 0x3F] ^
DES_SPE_F[(box << 1) + 1][index >> 6];
#else
DES_SPE_W[box][index][0] =
DES_SPE_L[box << 1][index & 0x3F] ^
DES_SPE_L[(box << 1) + 1][index >> 6];
DES_SPE_W[box][index][1] =
DES_SPE_H[box << 1][index & 0x3F] ^
DES_SPE_H[(box << 1) + 1][index >> 6];
#endif
}
#endif
}
/*
* The new DES_std_set_key() idea is originally by Roman Rusakov. I extended
* the original idea to detect whether it's faster to calculate from scratch
* or modify the previous key schedule. This code assumes that DES_xor_key1()
* is 1.5 times faster than DES_xor_key2().
*/
#if !DES_ASM
#define DES_xor1_1(ofs) \
DES_KS_current[ofs] ^= value1[ofs];
#define DES_xor1_4(ofs) \
DES_xor1_1(ofs); \
DES_xor1_1(ofs + 1); \
DES_xor1_1(ofs + 2); \
DES_xor1_1(ofs + 3);
#define DES_xor1_16(ofs) \
DES_xor1_4(ofs); \
DES_xor1_4(ofs + 4); \
DES_xor1_4(ofs + 8); \
DES_xor1_4(ofs + 12);
#if ARCH_BITS >= 64
#define DES_xor_key1(_value) { \
value1 = _value; \
DES_xor1_16(0); \
}
#else
#define DES_xor_key1(_value) { \
value1 = _value; \
DES_xor1_16(0); \
DES_xor1_16(16); \
}
#endif
#define DES_xor2_1(ofs) \
DES_KS_current[ofs] ^= value1[ofs] ^ value2[ofs];
#define DES_xor2_4(ofs) \
DES_xor2_1(ofs); \
DES_xor2_1(ofs + 1); \
DES_xor2_1(ofs + 2); \
DES_xor2_1(ofs + 3);
#define DES_xor2_16(ofs) \
DES_xor2_4(ofs); \
DES_xor2_4(ofs + 4); \
DES_xor2_4(ofs + 8); \
DES_xor2_4(ofs + 12);
#if ARCH_BITS >= 64
#define DES_xor_key2(_value1, _value2) { \
value1 = _value1; value2 = _value2; \
DES_xor2_16(0); \
}
#else
#define DES_xor_key2(_value1, _value2) { \
value1 = _value1; value2 = _value2; \
DES_xor2_16(0); \
DES_xor2_16(16); \
}
#endif
#else
extern void DES_xor_key1(ARCH_WORD *value);
extern void DES_xor_key2(ARCH_WORD *value1, ARCH_WORD *value2);
#endif
void DES_raw_set_key(char *key)
{
int i;
DES_KS *pos;
#if !DES_ASM
ARCH_WORD *value1;
#endif
memcpy(DES_KS_current,
DES_KS_table[0][ARCH_INDEX(DES_key[0] = key[0] & 0x7F)],
sizeof(DES_KS));
pos = (DES_KS *)DES_KS_table[1][0];
for (i = 1; i < 8; i++) {
DES_xor_key1(pos[ARCH_INDEX(DES_key[i] = key[i] & 0x7F)]);
pos += 128;
}
}
void DES_std_set_key(char *key)
{
unsigned i, j;
int k, l;
#if !DES_ASM
ARCH_WORD *value1, *value2;
#endif
j = key[0];
for (k = i = 0; (l = DES_key[i]) && (j = key[i]); i++)
if (j != l) k += 3;
if (j) {
while (i < 8 && key[i]) {
i++; k += 2;
}
j = i;
} else {
j = i;
while (DES_key[i++]) k += 2;
}
if ((k < (j << 1)) && (++DES_KS_updates & 0xFFF)) {
j = 0; l = 1;
for (i = 0; i < 8 && (k = key[i]); i++) {
if (l)
if (k == (l = DES_key[j++])) continue;
if (l) {
DES_xor_key2(DES_KS_table[i][l],
DES_KS_table[i][k & 0x7F]);
} else
DES_xor_key1(DES_KS_table[i][k & 0x7F]);
}
if (l)
for (; j < 8 && (l = DES_key[j]); j++)
DES_xor_key1(DES_KS_table[j][l]);
} else {
memcpy(DES_KS_current, DES_KS_table[0][(k = key[0]) & 0x7F],
sizeof(DES_KS));
if (k)
for (i = 1; i < 8 && (k = key[i]); i++)
DES_xor_key1(DES_KS_table[i][k & 0x7F]);
}
DES_key[0] = key[0] & 0x7F;
DES_key[1] = key[1] & 0x7F;
DES_key[2] = key[2] & 0x7F;
DES_key[3] = key[3] & 0x7F;
DES_key[4] = key[4] & 0x7F;
DES_key[5] = key[5] & 0x7F;
DES_key[6] = key[6] & 0x7F;
DES_key[7] = key[7] & 0x7F;
}
void DES_std_set_block(ARCH_WORD R, ARCH_WORD L)
{
ARCH_WORD Rl, Rh, Ll, Lh;
unsigned ARCH_WORD C;
#if ARCH_BITS >= 64
ARCH_WORD mask;
#else
ARCH_WORD *mask;
#endif
int chunk;
C = (R & 0xAAAAAAAA) | ((L & 0xAAAAAAAA) >> 1);
Rh = Rl = 0;
for (chunk = 0; chunk < 8; chunk++) {
mask = DES_IP_E[chunk][C & 0xF];
#if ARCH_BITS >= 64
Rl |= mask & 0xFFFFFFFF;
Rh |= mask >> 32;
#else
Rl |= mask[0];
Rh |= mask[1];
#endif
C >>= 4;
}
C = ((R & 0x55555555) << 1) | (L & 0x55555555);
Lh = Ll = 0;
for (chunk = 0; chunk < 8; chunk++) {
mask = DES_IP_E[chunk][C & 0xF];
#if ARCH_BITS >= 64
Ll |= mask & 0xFFFFFFFF;
Lh |= mask >> 32;
#else
Ll |= mask[0];
Lh |= mask[1];
#endif
C >>= 4;
}
Rl = DES_DO_SIZE_FIX(Rl);
Rh = DES_DO_SIZE_FIX(Rh);
Ll = DES_DO_SIZE_FIX(Ll);
Lh = DES_DO_SIZE_FIX(Lh);
#if ARCH_BITS >= 64
DES_IV[0] = Rl | (Rh << 32);
DES_IV[1] = Ll | (Lh << 32);
#else
DES_IV[0] = Rl;
DES_IV[1] = Rh;
DES_IV[2] = Ll;
DES_IV[3] = Lh;
#endif
}
void DES_std_get_block(DES_binary binary, unsigned ARCH_WORD out[2])
{
ARCH_WORD Rl, Rh, Ll, Lh;
ARCH_WORD R, L;
unsigned ARCH_WORD C;
#if ARCH_BITS >= 64
unsigned ARCH_WORD mask;
#else
ARCH_WORD *mask;
#endif
int chunk;
#if ARCH_BITS >= 64
Rl = binary[0];
Rh = binary[0] >> 32;
Ll = binary[1];
Lh = binary[1] >> 32;
#else
Rl = binary[0];
Rh = binary[1];
Ll = binary[2];
Lh = binary[3];
#endif
Rl = DES_UNDO_SIZE_FIX(Rl);
Rh = DES_UNDO_SIZE_FIX(Rh);
Ll = DES_UNDO_SIZE_FIX(Ll);
Lh = DES_UNDO_SIZE_FIX(Lh);
R = L = 0;
C = ((Ll >> 1) & 0x0F0F0F0F) | ((Lh << 3) & 0xF0F0F0F0);
for (chunk = 0; chunk < 16; chunk++) {
if (chunk == 8)
C = ((Rl >> 1) & 0x0F0F0F0F) | ((Rh << 3) & 0xF0F0F0F0);
mask = DES_C_FP[chunk][C & 0xF];
#if ARCH_BITS >= 64
R |= mask & 0xFFFFFFFF;
L |= mask >> 32;
#else
R |= mask[0];
L |= mask[1];
#endif
C >>= 4;
}
out[0] = R;
out[1] = L;
}
#if !DES_ASM
#if !DES_MASK
#define DES_D (DES_tmp.w)
#if ARCH_LITTLE_ENDIAN
#define DES_Dl (DES_tmp.w[0])
#define DES_Dh (DES_tmp.w[1])
#define DES_B0 (DES_tmp.b[0])
#define DES_B1 (DES_tmp.b[1])
#define DES_B2 (DES_tmp.b[2])
#define DES_B3 (DES_tmp.b[3])
#define DES_B4 (DES_tmp.b[4])
#define DES_B5 (DES_tmp.b[5])
#define DES_B6 (DES_tmp.b[6])
#define DES_B7 (DES_tmp.b[7])
#else
#define DES_Dl (DES_tmp.w[1])
#define DES_Dh (DES_tmp.w[0])
#if ARCH_BITS > 64
#define DES_START ARCH_SIZE
#else
#define DES_START 8
#endif
#define DES_B0 (DES_tmp.b[DES_START - 1])
#define DES_B1 (DES_tmp.b[DES_START - 2])
#define DES_B2 (DES_tmp.b[DES_START - 3])
#define DES_B3 (DES_tmp.b[DES_START - 4])
#define DES_B4 (DES_tmp.b[DES_START - 5])
#define DES_B5 (DES_tmp.b[DES_START - 6])
#define DES_B6 (DES_tmp.b[DES_START - 7])
#define DES_B7 (DES_tmp.b[DES_START - 8])
#endif
#endif
/*
* The code below is heavily optimized, looking at the assembly output for
* several architectures, enjoy the speed.
*/
#if ARCH_BITS >= 64
#if !DES_128K
/*
* An extra temporary register is used for better instruction scheduling.
*/
#if DES_MASK
#if DES_SCALE
/* 64-bit, 4K, mask, scale */
#define DES_ROUND(L, H, B) \
T = DES_INDEX(DES_SPE_F[0], DES_D & DES_MASK_6); \
B ^= DES_INDEX(DES_SPE_F[1], (DES_D >> 8) & DES_MASK_6); \
T ^= DES_INDEX(DES_SPE_F[2], (DES_D >> 16) & DES_MASK_6); \
B ^= DES_INDEX(DES_SPE_F[3], (DES_D >> 24) & DES_MASK_6); \
T ^= DES_INDEX(DES_SPE_F[4], (DES_D >> 32) & DES_MASK_6); \
B ^= DES_INDEX(DES_SPE_F[5], (DES_D >> 40) & DES_MASK_6); \
T ^= DES_INDEX(DES_SPE_F[6], (DES_D >> 48) & DES_MASK_6); \
B ^= T ^ DES_INDEX(DES_SPE_F[7], DES_D >> 56);
#else
/*
* This code assumes that the indices are already shifted left by 2, and still
* should be shifted left by 1 more bit. Weird shift counts allow doing this
* with only one extra shift, in the first line. By shifting the mask right
* (which is done at compile time), I moved the extra shift out of the mask,
* which allows doing this with special addressing modes, where possible.
*/
/* 64-bit, 4K, mask, no scale */
#define DES_ROUND(L, H, B) \
T = DES_INDEX(DES_SPE_F[0], (DES_D & (DES_MASK_6 >> 1)) << 1); \
B ^= DES_INDEX(DES_SPE_F[1], (DES_D >> 7) & DES_MASK_6); \
T ^= DES_INDEX(DES_SPE_F[2], (DES_D >> 15) & DES_MASK_6); \
B ^= DES_INDEX(DES_SPE_F[3], (DES_D >> 23) & DES_MASK_6); \
T ^= DES_INDEX(DES_SPE_F[4], (DES_D >> 31) & DES_MASK_6); \
B ^= DES_INDEX(DES_SPE_F[5], (DES_D >> 39) & DES_MASK_6); \
T ^= DES_INDEX(DES_SPE_F[6], (DES_D >> 47) & DES_MASK_6); \
B ^= T ^ DES_INDEX(DES_SPE_F[7], (DES_D >> 55) & DES_MASK_6);
#endif
#else
/* 64-bit, 4K, store/load, scale */
#define DES_ROUND(L, H, B) \
T = DES_INDEX(DES_SPE_F[0], DES_B0); \
B ^= DES_INDEX(DES_SPE_F[1], DES_B1); \
T ^= DES_INDEX(DES_SPE_F[2], DES_B2); \
B ^= DES_INDEX(DES_SPE_F[3], DES_B3); \
T ^= DES_INDEX(DES_SPE_F[4], DES_B4); \
B ^= DES_INDEX(DES_SPE_F[5], DES_B5); \
T ^= DES_INDEX(DES_SPE_F[6], DES_B6); \
B ^= T ^ DES_INDEX(DES_SPE_F[7], DES_B7);
#endif
#else
/* 64-bit, 128K, mask, no scale */
#define DES_ROUND(L, H, B) \
B ^= DES_INDEX(DES_SPE_W[0], DES_D & 0xFFFF); \
B ^= DES_INDEX(DES_SPE_W[1], (DES_D >>= 16) & 0xFFFF); \
B ^= DES_INDEX(DES_SPE_W[2], (DES_D >>= 16) & 0xFFFF); \
B ^= DES_INDEX(DES_SPE_W[3], DES_D >> 16);
#endif
#else
#if !DES_128K
#if DES_MASK
/* 32-bit, 4K, mask */
#define DES_ROUND(L, H, B) \
L ^= DES_INDEX(DES_SPE_L[0], DES_Dl & DES_MASK_6); \
H ^= DES_INDEX(DES_SPE_H[0], DES_Dl & DES_MASK_6); \
L ^= DES_INDEX(DES_SPE_L[1], (DES_Dl >>= 8) & DES_MASK_6); \
H ^= DES_INDEX(DES_SPE_H[1], DES_Dl & DES_MASK_6); \
L ^= DES_INDEX(DES_SPE_L[2], (DES_Dl >>= 8) & DES_MASK_6); \
H ^= DES_INDEX(DES_SPE_H[2], DES_Dl & DES_MASK_6); \
L ^= DES_INDEX(DES_SPE_L[3], (DES_Dl >>= 8) & DES_MASK_6); \
H ^= DES_INDEX(DES_SPE_H[3], DES_Dl & DES_MASK_6); \
L ^= DES_INDEX(DES_SPE_L[4], DES_Dh & DES_MASK_6); \
H ^= DES_INDEX(DES_SPE_H[4], DES_Dh & DES_MASK_6); \
L ^= DES_INDEX(DES_SPE_L[5], (DES_Dh >>= 8) & DES_MASK_6); \
H ^= DES_INDEX(DES_SPE_H[5], DES_Dh & DES_MASK_6); \
L ^= DES_INDEX(DES_SPE_L[6], (DES_Dh >>= 8) & DES_MASK_6); \
H ^= DES_INDEX(DES_SPE_H[6], DES_Dh & DES_MASK_6); \
L ^= DES_INDEX(DES_SPE_L[7], (DES_Dh >>= 8) & DES_MASK_6); \
H ^= DES_INDEX(DES_SPE_H[7], DES_Dh & DES_MASK_6);
#else
/* 32-bit, 4K, store/load */
#define DES_ROUND(L, H, B) \
L ^= DES_INDEX(DES_SPE_L[0], DES_B0); \
H ^= DES_INDEX(DES_SPE_H[0], DES_B0); \
L ^= DES_INDEX(DES_SPE_L[1], DES_B1); \
H ^= DES_INDEX(DES_SPE_H[1], DES_B1); \
L ^= DES_INDEX(DES_SPE_L[2], DES_B2); \
H ^= DES_INDEX(DES_SPE_H[2], DES_B2); \
L ^= DES_INDEX(DES_SPE_L[3], DES_B3); \
H ^= DES_INDEX(DES_SPE_H[3], DES_B3); \
L ^= DES_INDEX(DES_SPE_L[4], DES_B4); \
H ^= DES_INDEX(DES_SPE_H[4], DES_B4); \
L ^= DES_INDEX(DES_SPE_L[5], DES_B5); \
H ^= DES_INDEX(DES_SPE_H[5], DES_B5); \
L ^= DES_INDEX(DES_SPE_L[6], DES_B6); \
H ^= DES_INDEX(DES_SPE_H[6], DES_B6); \
L ^= DES_INDEX(DES_SPE_L[7], DES_B7); \
H ^= DES_INDEX(DES_SPE_H[7], DES_B7);
#endif
#else
/* 32-bit, 128K, mask */
#define DES_ROUND(L, H, B) \
L ^= DES_INDEX_L(DES_SPE_W[0], DES_Dl & 0xFFFF); \
H ^= DES_INDEX_H(DES_SPE_W[0], DES_Dl & 0xFFFF); \
L ^= DES_INDEX_L(DES_SPE_W[1], DES_Dl >>= 16); \
H ^= DES_INDEX_H(DES_SPE_W[1], DES_Dl); \
L ^= DES_INDEX_L(DES_SPE_W[2], DES_Dh & 0xFFFF); \
H ^= DES_INDEX_H(DES_SPE_W[2], DES_Dh & 0xFFFF); \
L ^= DES_INDEX_L(DES_SPE_W[3], DES_Dh >>= 16); \
H ^= DES_INDEX_H(DES_SPE_W[3], DES_Dh);
#endif
#endif
#if ARCH_BITS >= 64
#define DES_2_ROUNDS(KS) \
DES_D = R ^ KS[0]; \
DES_ROUND(Ll, Lh, L); \
DES_D = L ^ KS[1]; \
DES_ROUND(Rl, Rh, R);
#else
#define DES_2_ROUNDS(KS) \
DES_Dl = Rl ^ KS[0]; \
DES_Dh = Rh ^ KS[1]; \
DES_ROUND(Ll, Lh, L); \
DES_Dl = Ll ^ KS[2]; \
DES_Dh = Lh ^ KS[3]; \
DES_ROUND(Rl, Rh, R);
#endif
#if DES_COPY
static void crypt_body(void)
#else
void DES_std_crypt(DES_KS KS, DES_binary DES_out)
#endif
{
#if DES_MASK
#if ARCH_BITS >= 64
unsigned ARCH_WORD DES_D;
#else
unsigned ARCH_WORD DES_Dl, DES_Dh;
#endif
#else
union {
#if ARCH_BITS >= 64
ARCH_WORD w;
#else
ARCH_WORD w[2];
#endif
unsigned char b[8];
} DES_tmp;
#endif
#if ARCH_BITS >= 64
ARCH_WORD R, L;
#if !DES_128K
ARCH_WORD T;
#endif
#else
ARCH_WORD Rl, Rh, Ll, Lh;
#endif
int count;
#if ARCH_BITS >= 64
R = DES_IV[0];
L = DES_IV[1];
#else
Rl = DES_IV[0];
Rh = DES_IV[1];
Ll = DES_IV[2];
Lh = DES_IV[3];
#endif
count = DES_count;
do {
DES_2_ROUNDS(DES_KS_INDEX(0));
DES_2_ROUNDS(DES_KS_INDEX(1));
DES_2_ROUNDS(DES_KS_INDEX(2));
DES_2_ROUNDS(DES_KS_INDEX(3));
DES_2_ROUNDS(DES_KS_INDEX(4));
DES_2_ROUNDS(DES_KS_INDEX(5));
DES_2_ROUNDS(DES_KS_INDEX(6));
DES_2_ROUNDS(DES_KS_INDEX(7));
#if ARCH_BITS >= 64
L ^= R;
R ^= L;
L ^= R;
#else
Ll ^= Rl;
Lh ^= Rh;
Rl ^= Ll;
Rh ^= Lh;
Ll ^= Rl;
Lh ^= Rh;
#endif
} while (--count);
#if ARCH_BITS >= 64
DES_out[0] = R;
DES_out[1] = L;
#else
DES_out[0] = Rl;
DES_out[1] = Rh;
DES_out[2] = Ll;
DES_out[3] = Lh;
#endif
}
#if DES_COPY
void DES_std_crypt(DES_KS KS, DES_binary out)
{
memcpy(DES_KS_copy, KS, sizeof(DES_KS));
DES_out = out;
crypt_body();
}
#endif
#endif
static unsigned char DES_atoi64[0x100] = {
18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 0, 1,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 0, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 0, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 0, 1, 2, 3, 4
};
ARCH_WORD DES_raw_get_salt(char *ciphertext)
{
if (ciphertext[13]) return DES_atoi64[ARCH_INDEX(ciphertext[5])] |
((ARCH_WORD)DES_atoi64[ARCH_INDEX(ciphertext[6])] << 6) |
((ARCH_WORD)DES_atoi64[ARCH_INDEX(ciphertext[7])] << 12) |
((ARCH_WORD)DES_atoi64[ARCH_INDEX(ciphertext[8])] << 18);
else return DES_atoi64[ARCH_INDEX(ciphertext[0])] |
((ARCH_WORD)DES_atoi64[ARCH_INDEX(ciphertext[1])] << 6);
}
ARCH_WORD DES_std_get_salt(char *ciphertext)
{
unsigned int salt;
salt = DES_raw_get_salt(ciphertext);
salt = DES_24_TO_32(salt);
return (ARCH_WORD)DES_DO_SIZE_FIX(salt);
}
ARCH_WORD DES_raw_get_count(char *ciphertext)
{
if (ciphertext[13]) return DES_atoi64[ARCH_INDEX(ciphertext[1])] |
((ARCH_WORD)DES_atoi64[ARCH_INDEX(ciphertext[2])] << 6) |
((ARCH_WORD)DES_atoi64[ARCH_INDEX(ciphertext[3])] << 12) |
((ARCH_WORD)DES_atoi64[ARCH_INDEX(ciphertext[4])] << 18);
else return 25;
}
ARCH_WORD *DES_do_IP(ARCH_WORD in[2])
{
static ARCH_WORD out[2];
int src, dst;
out[0] = out[1] = 0;
for (dst = 0; dst < 64; dst++) {
src = DES_IP[dst ^ 0x20];
if (in[src >> 5] & ((unsigned ARCH_WORD)1 << (src & 0x1F)))
out[dst >> 5] |= (unsigned ARCH_WORD)1 << (dst & 0x1F);
}
return out;
}
ARCH_WORD *DES_do_FP(ARCH_WORD in[2])
{
static ARCH_WORD out[2];
int src, dst;
out[0] = out[1] = 0;
for (src = 0; src < 64; src++) {
dst = DES_IP[src ^ 0x20];
if (in[src >> 5] & ((unsigned ARCH_WORD)1 << (src & 0x1F)))
out[dst >> 5] |= (unsigned ARCH_WORD)1 << (dst & 0x1F);
}
return out;
}
ARCH_WORD *DES_raw_get_binary(char *ciphertext)
{
ARCH_WORD block[3];
ARCH_WORD mask;
int ofs, chr, src, dst, value;
if (ciphertext[13]) ofs = 9; else ofs = 2;
block[0] = block[1] = 0;
dst = 0;
for (chr = 0; chr < 11; chr++) {
value = DES_atoi64[ARCH_INDEX(ciphertext[chr + ofs])];
mask = 0x20;
for (src = 0; src < 6; src++) {
if (value & mask)
block[dst >> 5] |= (unsigned ARCH_WORD)1 << (dst & 0x1F);
mask >>= 1;
dst++;
}
}
return DES_do_IP(block);
}
ARCH_WORD *DES_std_get_binary(char *ciphertext)
{
static ARCH_WORD out[4];
ARCH_WORD *raw;
ARCH_WORD salt, mask;
raw = DES_raw_get_binary(ciphertext);
out[0] = DES_16_TO_32(raw[0]);
out[1] = DES_16_TO_32(raw[0] >> 16);
out[2] = DES_16_TO_32(raw[1]);
out[3] = DES_16_TO_32(raw[1] >> 16);
out[0] = DES_DO_SIZE_FIX(out[0]);
out[1] = DES_DO_SIZE_FIX(out[1]);
out[2] = DES_DO_SIZE_FIX(out[2]);
out[3] = DES_DO_SIZE_FIX(out[3]);
salt = DES_std_get_salt(ciphertext);
mask = (out[0] ^ out[1]) & salt;
out[0] ^= mask;
out[1] ^= mask;
mask = (out[2] ^ out[3]) & salt;
out[2] ^= mask;
out[3] ^= mask;
#if ARCH_BITS >= 64
out[0] |= out[1] << 32;
out[1] = out[2] | (out[3] << 32);
#endif
return out;
}
| {
"pile_set_name": "Github"
} |
[package]
name = "serde_json_test"
version = "0.0.0"
edition = "2018"
publish = false
[lib]
path = "test.rs"
[dependencies]
serde_json = { path = "../..", default-features = false }
[features]
default = ["std"]
std = ["serde_json/std"]
alloc = ["serde_json/alloc"]
preserve_order = ["serde_json/preserve_order"]
arbitrary_precision = ["serde_json/arbitrary_precision"]
raw_value = ["serde_json/raw_value"]
unbounded_depth = ["serde_json/unbounded_depth"]
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8" ?>
<vendors>
<vendor name="Ta Horng Musical Instrument" id="000074" />
<vendor name="e-Tek Labs (Forte Tech)" id="000075" />
<vendor name="Electro-Voice" id="000076" />
<vendor name="Midisoft Corporation" id="000077" />
<vendor name="QSound Labs" id="000078" />
<vendor name="Westrex" id="000079" />
<vendor name="Nvidia" id="00007A" />
<vendor name="ESS Technology" id="00007B" />
<vendor name="Media Trix Peripherals" id="00007C" />
<vendor name="Brooktree Corp" id="00007D" />
<vendor name="Otari Corp" id="00007E" />
<vendor name="Key Electronics" id="00007F" />
<vendor name="Shure incorporated" id="000100" />
<vendor name="AuraSound" id="000101" />
<vendor name="Crystal Semiconductor" id="000102" />
<vendor name="Conexant (Rockwell)" id="000103" />
<vendor name="Silicon Graphics" id="000104" />
<vendor name="M-Audio (Midiman)" id="000105" />
<vendor name="PreSonus" id="000106" />
<vendor name="Topaz Enterprises" id="000108" />
<vendor name="Cast Lighting" id="000109" />
<vendor name="Microsoft" id="00010A" />
<vendor name="Sonic Foundry" id="00010B" />
<vendor name="Line 6 (Fast Forward)" id="00010C" />
<vendor name="Beatnik Inc" id="00010D" />
<vendor name="Van Koevering Company" id="00010E" />
<vendor name="Altech Systems" id="00010F" />
<vendor name="S & S Research" id="000110" />
<vendor name="VLSI Technology" id="000111" />
<vendor name="Chromatic Research" id="000112" />
<vendor name="Sapphire" id="000113" />
<vendor name="IDRC" id="000114" />
<vendor name="Justonic Tuning" id="000115" />
<vendor name="TorComp Research Inc." id="000116" />
<vendor name="Newtek Inc." id="000117" />
<vendor name="Sound Sculpture" id="000118" />
<vendor name="Walker Technical" id="000119" />
<vendor name="Digital Harmony (PAVO)" id="00011A" />
<vendor name="InVision Interactive" id="00011B" />
<vendor name="T-Square Design" id="00011C" />
<vendor name="Nemesys Music Technology" id="00011D" />
<vendor name="DBX Professional (Harman Intl)" id="00011E" />
<vendor name="Syndyne Corporation" id="00011F" />
<vendor name="Bitheadz" id="000120" />
<vendor name="Cakewalk Music Software" id="000121" />
<vendor name="Analog Devices" id="000122" />
<vendor name="National Semiconductor" id="000123" />
<vendor name="Boom Theory / Adinolfi Alternative Percussion" id="000124" />
<vendor name="Virtual DSP Corporation" id="000125" />
<vendor name="Antares Systems" id="000126" />
<vendor name="Angel Software" id="000127" />
<vendor name="St Louis Music" id="000128" />
<vendor name="Lyrrus dba G-VOX" id="000129" />
<vendor name="Ashley Audio Inc." id="00012A" />
<vendor name="Vari-Lite Inc." id="00012B" />
<vendor name="Summit Audio Inc." id="00012C" />
<vendor name="Aureal Semiconductor Inc." id="00012D" />
<vendor name="SeaSound LLC" id="00012E" />
<vendor name="U.S. Robotics" id="00012F" />
<vendor name="Aurisis Research" id="000130" />
<vendor name="Nearfield Research" id="000131" />
<vendor name="FM7 Inc" id="000132" />
<vendor name="Swivel Systems" id="000133" />
<vendor name="Hyperactive Audio Systems" id="000134" />
<vendor name="MidiLite (Castle Studios Productions)" id="000135" />
<vendor name="Radikal Technologies" id="000136" />
<vendor name="Roger Linn Design" id="000137" />
<vendor name="TC-Helicon Vocal Technologies" id="000138" />
<vendor name="Event Electronics" id="000139" />
<vendor name="Sonic Network Inc" id="00013A" />
<vendor name="Realtime Music Solutions" id="00013B" />
<vendor name="Apogee Digital" id="00013C" />
<vendor name="Classical Organs" id="00013D" />
<vendor name="Microtools Inc." id="00013E" />
<vendor name="Numark Industries" id="00013F" />
<vendor name="Frontier Design Group" id="000140" />
<vendor name="Recordare LLC" id="000141" />
<vendor name="Starr Labs" id="000142" />
<vendor name="Voyager Sound Inc." id="000143" />
<vendor name="Manifold Labs" id="000144" />
<vendor name="Aviom Inc." id="000145" />
<vendor name="Mixmeister Technology" id="000146" />
<vendor name="Notation Software" id="000147" />
<vendor name="Mercurial Communications" id="000148" />
<vendor name="Wave Arts" id="000149" />
<vendor name="Logic Sequencing Devices" id="00014A" />
<vendor name="Axess Electronics" id="00014B" />
<vendor name="Muse Research" id="00014C" />
<vendor name="Open Labs" id="00014D" />
<vendor name="Guillemot R&D Inc" id="00014E" />
<vendor name="Samson Technologies" id="00014F" />
<vendor name="Electronic Theatre Controls" id="000150" />
<vendor name="Blackberry (RIM)" id="000151" />
<vendor name="Mobileer" id="000152" />
<vendor name="Synthogy" id="000153" />
<vendor name="Lynx Studio Technology Inc." id="000154" />
<vendor name="Damage Control Engineering LLC" id="000155" />
<vendor name="Yost Engineering" id="000156" />
<vendor name="Brooks & Forsman Designs LLC / DrumLite" id="000157" />
<vendor name="Infinite Response" id="000158" />
<vendor name="Garritan Corp" id="000159" />
<vendor name="Plogue Art et Technologie" id="00015A" />
<vendor name="RJM Music Technology" id="00015B" />
<vendor name=" Custom Solutions Software" id="00015C" />
<vendor name="Sonarcana LLC" id="00015D" />
<vendor name="Centrance" id="00015E" />
<vendor name="Kesumo LLC" id="00015F" />
<vendor name="Stanton (Gibson)" id="000160" />
<vendor name="Livid Instruments" id="000161" />
<vendor name="First Act / 745 Media" id="000162" />
<vendor name="Pygraphics" id="000163" />
<vendor name="Panadigm Innovations Ltd" id="000164" />
<vendor name="Avedis Zildjian Co" id="000165" />
<vendor name="Auvital Music Corp" id="000166" />
<vendor name="Inspired Instruments Inc" id="000167" />
<vendor name="Chris Grigg Designs" id="000168" />
<vendor name="Slate Digital LLC" id="000169" />
<vendor name="Mixware" id="00016A" />
<vendor name="Social Entropy" id="00016B" />
<vendor name="Source Audio LLC" id="00016C" />
<vendor name="Ernie Ball / Music Man" id="00016D" />
<vendor name="Fishman Transducers" id="00016E" />
<vendor name="Custom Audio Electronics" id="00016F" />
<vendor name="American Audio/DJ" id="000170" />
<vendor name="Mega Control Systems" id="000171" />
<vendor name="Kilpatrick Audio" id="000172" />
<vendor name="iConnectivity" id="000173" />
<vendor name="Fractal Audio" id="000174" />
<vendor name="NetLogic Microsystems" id="000175" />
<vendor name="Music Computing" id="000176" />
<vendor name="Nektar Technology Inc" id="000177" />
<vendor name="Zenph Sound Innovations" id="000178" />
<vendor name="DJTechTools.com" id="000179" />
<vendor name="Rezonance Labs" id="00017A" />
<vendor name="Decibel Eleven" id="00017B" />
<vendor name="Focusrite/Novation" id="002029" />
<vendor name="Samkyung Mechatronics" id="00202A" />
<vendor name="Medeli Electronics Co." id="00202B" />
<vendor name="Charlie Lab SRL" id="00202C" />
<vendor name="Blue Chip Music Technology" id="00202D" />
<vendor name="BEE OH Corp" id="00202E" />
<vendor name="LG Semicon America" id="00202F" />
<vendor name="TESI" id="002030" />
<vendor name="EMAGIC" id="002031" />
<vendor name="Behringer GmbH" id="002032" />
<vendor name="Access Music Electronics" id="002033" />
<vendor name="Synoptic" id="002034" />
<vendor name="Hanmesoft" id="002035" />
<vendor name="Terratec Electronic GmbH" id="002036" />
<vendor name="Proel SpA" id="002037" />
<vendor name="IBK MIDI" id="002038" />
<vendor name="IRCAM" id="002039" />
<vendor name="Propellerhead Software" id="00203A" />
<vendor name="Red Sound Systems Ltd" id="00203B" />
<vendor name="Elektron ESI AB" id="00203C" />
<vendor name="Sintefex Audio" id="00203D" />
<vendor name="MAM (Music and More)" id="00203E" />
<vendor name="Amsaro GmbH" id="00203F" />
<vendor name="CDS Advanced Technology BV" id="002040" />
<vendor name="Touched By Sound GmbH" id="002041" />
<vendor name="DSP Arts" id="002042" />
<vendor name="Phil Rees Music Tech" id="002043" />
<vendor name="Stamer Musikanlagen GmbH" id="002044" />
<vendor name="Musical Muntaner S.A. dba Soundart" id="002045" />
<vendor name="C-Mexx Software" id="002046" />
<vendor name="Klavis Technologies" id="002047" />
<vendor name="Noteheads AB" id="002048" />
<vendor name="Algorithmix" id="002049" />
<vendor name="Skrydstrup R&D" id="00204A" />
<vendor name="Professional Audio Company" id="00204B" />
<vendor name="NewWave Labs (MadWaves)" id="00204C" />
<vendor name="Vermona" id="00204D" />
<vendor name="Nokia" id="00204E" />
<vendor name="Wave Idea" id="00204F" />
<vendor name="Hartmann GmbH" id="002050" />
<vendor name="Lion's Tracs" id="002051" />
<vendor name="Analogue Systems" id="002052" />
<vendor name="Focal-JMlab" id="002053" />
<vendor name="Ringway Electronics (Chang-Zhou) Co Ltd" id="002054" />
<vendor name="Faith Technologies (Digiplug)" id="002055" />
<vendor name="Showworks" id="002056" />
<vendor name="Manikin Electronic" id="002057" />
<vendor name="1 Come Tech" id="002058" />
<vendor name="Phonic Corp" id="002059" />
<vendor name="Dolby Australia (Lake)" id="00205A" />
<vendor name="Silansys Technologies" id="00205B" />
<vendor name="Winbond Electronics" id="00205C" />
<vendor name="Cinetix Medien und Interface GmbH" id="00205D" />
<vendor name="A&G Soluzioni Digitali" id="00205E" />
<vendor name="Sequentix Music Systems" id="00205F" />
<vendor name="Oram Pro Audio" id="002060" />
<vendor name="Be4 Ltd" id="002061" />
<vendor name="Infection Music" id="002062" />
<vendor name="Central Music Co. (CME)" id="002063" />
<vendor name="genoQs Machines GmbH" id="002064" />
<vendor name="Medialon" id="002065" />
<vendor name="Waves Audio Ltd" id="002066" />
<vendor name="Jerash Labs" id="002067" />
<vendor name="Da Fact" id="002068" />
<vendor name="Elby Designs" id="002069" />
<vendor name="Spectral Audio" id="00206A" />
<vendor name="Arturia" id="00206B" />
<vendor name="Vixid" id="00206C" />
<vendor name="C-Thru Music" id="00206D" />
<vendor name="Ya Horng Electronic Co LTD" id="00206E" />
<vendor name="SM Pro Audio" id="00206F" />
<vendor name="OTO MACHINES" id="002070" />
<vendor name="ELZAB S.A." id="002071" />
<vendor name="Blackstar Amplification Ltd" id="002072" />
<vendor name="M3i Technologies GmbH" id="002073" />
<vendor name="Gemalto (from Xiring)" id="002074" />
<vendor name="Prostage SL" id="002075" />
<vendor name="Teenage Engineering" id="002076" />
<vendor name="Tobias Erichsen Consulting" id="002077" />
<vendor name="Nixer Ltd" id="002078" />
<vendor name="Hanpin Electron Co Ltd" id="002079" />
<vendor name="MIDI-hardware R.Sowa" id="00207A" />
<vendor name="Beyond Music Industrial Ltd" id="00207B" />
<vendor name="Kiss Box B.V." id="00207C" />
<vendor name="Misa Digital Technologies Ltd" id="00207D" />
<vendor name="AI Musics Technology Inc" id="00207E" />
<vendor name="Serato Inc LP" id="00207F" />
<vendor name="Limex Music Handles GmbH" id="002100" />
<vendor name="Kyodday/Tokai" id="002101" />
<vendor name="Mutable Instruments" id="002102" />
<vendor name="PreSonus Software Ltd" id="002103" />
<vendor name="Xiring" id="002104" />
<vendor name="Fairlight Instruments Pty Ltd" id="002105" />
<vendor name="Musicom Lab" id="002106" />
<vendor name="VacoLoco" id="002107" />
<vendor name="RWA (Hong Kong) Limited" id="002108" />
<vendor name="Native Instruments" id="002109" />
<vendor name="Naonext" id="00210A" />
<vendor name="MFB" id="00210B" />
<vendor name="Teknel Research" id="00210C" />
<vendor name="Ploytec GmbH" id="00210D" />
<vendor name="Surfin Kangaroo Studio" id="00210E" />
<vendor name="Crimson Technology Inc." id="004000" />
<vendor name="Softbank Mobile Corp" id="004001" />
<vendor name="D&M Holdings Inc." id="004003" />
<vendor name="Sequential Circuits" id="01" />
<vendor name="Big Briar" id="02" />
<vendor name="Octave / Plateau" id="03" />
<vendor name="Moog" id="04" />
<vendor name="Passport Designs" id="05" />
<vendor name="Lexicon" id="06" />
<vendor name="Kurzweil" id="07" />
<vendor name="Fender" id="08" />
<vendor name="Gulbransen" id="09" />
<vendor name="Delta Labs" id="0A" />
<vendor name="Sound Comp." id="0B" />
<vendor name="General Electro" id="0C" />
<vendor name="Techmar" id="0D" />
<vendor name="Matthews Research" id="0E" />
<vendor name="Oberheim" id="10" />
<vendor name="PAIA" id="11" />
<vendor name="Simmons" id="12" />
<vendor name="DigiDesign" id="13" />
<vendor name="Fairlight" id="14" />
<vendor name="Peavey" id="1B" />
<vendor name="JL Cooper" id="15" />
<vendor name="Lowery" id="16" />
<vendor name="Lin" id="17" />
<vendor name="Emu" id="18" />
<vendor name="Bon Tempi" id="20" />
<vendor name="S.I.E.L." id="21" />
<vendor name="SyntheAxe" id="23" />
<vendor name="Hohner" id="24" />
<vendor name="Crumar" id="25" />
<vendor name="Solton" id="26" />
<vendor name="Jellinghaus Ms" id="27" />
<vendor name="CTS" id="28" />
<vendor name="PPG" id="29" />
<vendor name="Elka" id="2F" />
<vendor name="Cheetah" id="36" />
<vendor name="Waldorf" id="3E" />
<vendor name="Kawai" id="40" />
<vendor name="Roland" id="41" />
<vendor name="Korg" id="42" />
<vendor name="Yamaha" id="43" />
<vendor name="Casio" id="44" />
<vendor name="Akai" id="45" />
<vendor name="Kawai Musical Instruments MFG. CO. Ltd" id="40" />
<vendor name="Roland Corporation" id="41" />
<vendor name="Korg Inc." id="42" />
<vendor name="Yamaha Corporation" id="43" />
<vendor name="Casio Computer Co. Ltd" id="44" />
<vendor name="Kamiya Studio Co. Ltd" id="46" />
<vendor name="Akai Electric Co. Ltd." id="47" />
<vendor name="Victor Company of Japan, Ltd." id="48" />
<vendor name="Fujitsu Limited" id="4B" />
<vendor name="Sony Corporation" id="4C" />
<vendor name="Teac Corporation" id="4E" />
<vendor name="Matsushita Electric Industrial Co. , Ltd" id="50" />
<vendor name="Fostex Corporation" id="51" />
<vendor name="Zoom Corporation" id="52" />
<vendor name="Matsushita Communication Industrial Co., Ltd." id="54" />
<vendor name="Suzuki Musical Instruments MFG. Co., Ltd." id="55" />
<vendor name="Fuji Sound Corporation Ltd." id="56" />
<vendor name="Acoustic Technical Laboratory, Inc." id="57" />
<vendor name="Faith, Inc." id="59" />
<vendor name="Internet Corporation" id="5A" />
<vendor name="Seekers Co. Ltd." id="5C" />
<vendor name="SD Card Association" id="5F" />
</vendors>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:gravity="center"
android:orientation="horizontal"
android:padding="5dip" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_dialog_alert" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="1dip"
android:layout_marginLeft="16dip"
android:text="@string/error_occured"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
</FrameLayout> | {
"pile_set_name": "Github"
} |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <GLES2/gl2.h>
#include <stddef.h>
#include <stdint.h>
#include "base/memory/shared_memory.h"
#include "base/message_loop/message_loop.h"
#include "build/build_config.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/ppb_video_decoder.h"
#include "ppapi/proxy/locking_resource_releaser.h"
#include "ppapi/proxy/plugin_message_filter.h"
#include "ppapi/proxy/ppapi_message_utils.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/proxy/ppapi_proxy_test.h"
#include "ppapi/proxy/ppb_graphics_3d_proxy.h"
#include "ppapi/proxy/video_decoder_constants.h"
#include "ppapi/proxy/video_decoder_resource.h"
#include "ppapi/shared_impl/proxy_lock.h"
#include "ppapi/thunk/thunk.h"
using ppapi::proxy::ResourceMessageTestSink;
namespace ppapi {
namespace proxy {
namespace {
const PP_Resource kGraphics3D = 7;
const uint32_t kShmSize = 256;
const size_t kDecodeBufferSize = 16;
const uint32_t kDecodeId = 5;
const uint32_t kTextureId1 = 1;
#if !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
const uint32_t kTextureId2 = 2;
#endif
const uint32_t kNumRequestedTextures = 2;
class MockCompletionCallback {
public:
MockCompletionCallback() : called_(false) {}
bool called() { return called_; }
int32_t result() { return result_; }
void Reset() { called_ = false; }
static void Callback(void* user_data, int32_t result) {
MockCompletionCallback* that =
reinterpret_cast<MockCompletionCallback*>(user_data);
that->called_ = true;
that->result_ = result;
}
private:
bool called_;
int32_t result_;
};
class VideoDecoderResourceTest : public PluginProxyTest {
public:
VideoDecoderResourceTest()
: decoder_iface_(thunk::GetPPB_VideoDecoder_1_1_Thunk()) {}
const PPB_VideoDecoder_1_1* decoder_iface() const { return decoder_iface_; }
void SendReply(const ResourceMessageCallParams& params,
int32_t result,
const IPC::Message& nested_message) {
ResourceMessageReplyParams reply_params(params.pp_resource(),
params.sequence());
reply_params.set_result(result);
PluginMessageFilter::DispatchResourceReplyForTest(reply_params,
nested_message);
}
void SendReplyWithHandle(const ResourceMessageCallParams& params,
int32_t result,
const IPC::Message& nested_message,
const SerializedHandle& handle) {
ResourceMessageReplyParams reply_params(params.pp_resource(),
params.sequence());
reply_params.set_result(result);
reply_params.AppendHandle(handle);
PluginMessageFilter::DispatchResourceReplyForTest(reply_params,
nested_message);
}
PP_Resource CreateDecoder() {
PP_Resource result = decoder_iface()->Create(pp_instance());
if (result) {
ProxyAutoLock lock;
ppapi::Resource* resource =
GetGlobals()->GetResourceTracker()->GetResource(result);
proxy::VideoDecoderResource* decoder =
static_cast<proxy::VideoDecoderResource*>(resource);
decoder->SetForTest();
}
return result;
}
PP_Resource CreateGraphics3d() {
ProxyAutoLock lock;
HostResource host_resource;
host_resource.SetHostResource(pp_instance(), kGraphics3D);
scoped_refptr<ppapi::proxy::Graphics3D> graphics_3d(
new ppapi::proxy::Graphics3D(host_resource, gfx::Size(640, 480)));
return graphics_3d->GetReference();
}
PP_Resource CreateAndInitializeDecoder() {
PP_Resource decoder = CreateDecoder();
LockingResourceReleaser graphics3d(CreateGraphics3d());
MockCompletionCallback cb;
int32_t result = decoder_iface()->Initialize(
decoder,
graphics3d.get(),
PP_VIDEOPROFILE_H264MAIN,
PP_HARDWAREACCELERATION_WITHFALLBACK,
0,
PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback,
&cb));
if (result != PP_OK_COMPLETIONPENDING)
return 0;
ResourceMessageCallParams params;
IPC::Message msg;
if (!sink().GetFirstResourceCallMatching(
PpapiHostMsg_VideoDecoder_Initialize::ID, ¶ms, &msg))
return 0;
sink().ClearMessages();
SendReply(params, PP_OK, PpapiPluginMsg_VideoDecoder_InitializeReply());
return decoder;
}
int32_t CallDecode(PP_Resource pp_decoder,
MockCompletionCallback* cb,
const PpapiHostMsg_VideoDecoder_GetShm* expected_shm_msg) {
// Set up a handler in case the resource sends a sync message to create
// shared memory.
PpapiPluginMsg_VideoDecoder_GetShmReply shm_msg_reply(kShmSize);
ResourceSyncCallHandler shm_msg_handler(
&sink(), PpapiHostMsg_VideoDecoder_GetShm::ID, PP_OK, shm_msg_reply);
sink().AddFilter(&shm_msg_handler);
base::SharedMemory shm;
if (expected_shm_msg) {
shm.CreateAnonymous(kShmSize);
base::SharedMemoryHandle shm_handle;
shm.ShareToProcess(base::GetCurrentProcessHandle(), &shm_handle);
SerializedHandle serialized_handle(shm_handle, kShmSize);
shm_msg_handler.set_serialized_handle(&serialized_handle);
}
memset(decode_buffer_, 0x55, kDecodeBufferSize);
int32_t result =
decoder_iface()->Decode(pp_decoder,
kDecodeId,
kDecodeBufferSize,
decode_buffer_,
PP_MakeOptionalCompletionCallback(
&MockCompletionCallback::Callback, cb));
if (expected_shm_msg) {
uint32_t shm_id, shm_size, expected_shm_id, expected_shm_size;
UnpackMessage<PpapiHostMsg_VideoDecoder_GetShm>(
*expected_shm_msg, &expected_shm_id, &expected_shm_size);
if (shm_msg_handler.last_handled_msg().type() == 0 ||
!UnpackMessage<PpapiHostMsg_VideoDecoder_GetShm>(
shm_msg_handler.last_handled_msg(), &shm_id, &shm_size) ||
shm_id != expected_shm_id ||
shm_size != expected_shm_size) {
// Signal that the expected shm message wasn't sent by failing.
result = PP_ERROR_FAILED;
}
}
sink().RemoveFilter(&shm_msg_handler);
return result;
}
int32_t CallGetPicture(PP_Resource pp_decoder,
PP_VideoPicture* picture,
MockCompletionCallback* cb) {
int32_t result =
decoder_iface()->GetPicture(pp_decoder,
picture,
PP_MakeOptionalCompletionCallback(
&MockCompletionCallback::Callback, cb));
return result;
}
void CallRecyclePicture(PP_Resource pp_decoder,
const PP_VideoPicture& picture) {
decoder_iface()->RecyclePicture(pp_decoder, &picture);
}
int32_t CallFlush(PP_Resource pp_decoder, MockCompletionCallback* cb) {
int32_t result =
decoder_iface()->Flush(pp_decoder,
PP_MakeOptionalCompletionCallback(
&MockCompletionCallback::Callback, cb));
return result;
}
int32_t CallReset(PP_Resource pp_decoder, MockCompletionCallback* cb) {
int32_t result =
decoder_iface()->Reset(pp_decoder,
PP_MakeOptionalCompletionCallback(
&MockCompletionCallback::Callback, cb));
return result;
}
void SendDecodeReply(const ResourceMessageCallParams& params,
uint32_t shm_id) {
SendReply(params, PP_OK, PpapiPluginMsg_VideoDecoder_DecodeReply(shm_id));
}
void SendPictureReady(const ResourceMessageCallParams& params,
uint32_t decode_count,
uint32_t texture_id) {
PP_Rect visible_rect = PP_MakeRectFromXYWH(0, 0, 640, 480);
SendReply(params, PP_OK, PpapiPluginMsg_VideoDecoder_PictureReady(
decode_count, texture_id, visible_rect));
}
void SendFlushReply(const ResourceMessageCallParams& params) {
SendReply(params, PP_OK, PpapiPluginMsg_VideoDecoder_FlushReply());
}
void SendResetReply(const ResourceMessageCallParams& params) {
SendReply(params, PP_OK, PpapiPluginMsg_VideoDecoder_ResetReply());
}
void SendRequestTextures(const ResourceMessageCallParams& params) {
SendReply(params,
PP_OK,
PpapiPluginMsg_VideoDecoder_RequestTextures(
kNumRequestedTextures,
PP_MakeSize(320, 240),
GL_TEXTURE_2D,
std::vector<gpu::Mailbox>()));
}
void SendNotifyError(const ResourceMessageCallParams& params, int32_t error) {
SendReply(params, PP_OK, PpapiPluginMsg_VideoDecoder_NotifyError(error));
}
bool CheckDecodeMsg(ResourceMessageCallParams* params,
uint32_t* shm_id,
uint32_t* size,
int32_t* decode_id) {
IPC::Message msg;
if (!sink().GetFirstResourceCallMatching(
PpapiHostMsg_VideoDecoder_Decode::ID, params, &msg))
return false;
sink().ClearMessages();
return UnpackMessage<PpapiHostMsg_VideoDecoder_Decode>(
msg, shm_id, size, decode_id);
}
bool CheckRecyclePictureMsg(ResourceMessageCallParams* params,
uint32_t* texture_id) {
IPC::Message msg;
if (!sink().GetFirstResourceCallMatching(
PpapiHostMsg_VideoDecoder_RecyclePicture::ID, params, &msg))
return false;
sink().ClearMessages();
return UnpackMessage<PpapiHostMsg_VideoDecoder_RecyclePicture>(msg,
texture_id);
}
bool CheckFlushMsg(ResourceMessageCallParams* params) {
return CheckMsg(params, PpapiHostMsg_VideoDecoder_Flush::ID);
}
bool CheckResetMsg(ResourceMessageCallParams* params) {
return CheckMsg(params, PpapiHostMsg_VideoDecoder_Reset::ID);
}
void ClearCallbacks(PP_Resource pp_decoder) {
ResourceMessageCallParams params;
MockCompletionCallback cb;
// Reset to abort Decode and GetPicture callbacks.
CallReset(pp_decoder, &cb);
// Initialize params so we can reply to the Reset.
CheckResetMsg(¶ms);
// Run the Reset callback.
SendResetReply(params);
}
private:
bool CheckMsg(ResourceMessageCallParams* params, int id) {
IPC::Message msg;
if (!sink().GetFirstResourceCallMatching(id, params, &msg))
return false;
sink().ClearMessages();
return true;
}
const PPB_VideoDecoder_1_1* decoder_iface_;
char decode_buffer_[kDecodeBufferSize];
};
} // namespace
TEST_F(VideoDecoderResourceTest, Initialize) {
// Initialize with 0 graphics3d_context should fail.
{
LockingResourceReleaser decoder(CreateDecoder());
MockCompletionCallback cb;
int32_t result = decoder_iface()->Initialize(
decoder.get(),
0 /* invalid 3d graphics */,
PP_VIDEOPROFILE_H264MAIN,
PP_HARDWAREACCELERATION_WITHFALLBACK,
0,
PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback,
&cb));
ASSERT_EQ(PP_ERROR_BADRESOURCE, result);
}
// Initialize with bad profile value should fail.
{
LockingResourceReleaser decoder(CreateDecoder());
MockCompletionCallback cb;
int32_t result = decoder_iface()->Initialize(
decoder.get(),
1 /* non-zero resource */,
static_cast<PP_VideoProfile>(-1),
PP_HARDWAREACCELERATION_WITHFALLBACK,
0,
PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback,
&cb));
ASSERT_EQ(PP_ERROR_BADARGUMENT, result);
}
// Initialize with valid graphics3d_context and profile should succeed.
{
LockingResourceReleaser decoder(CreateDecoder());
LockingResourceReleaser graphics3d(CreateGraphics3d());
MockCompletionCallback cb;
int32_t result = decoder_iface()->Initialize(
decoder.get(),
graphics3d.get(),
PP_VIDEOPROFILE_H264MAIN,
PP_HARDWAREACCELERATION_WITHFALLBACK,
0,
PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback,
&cb));
ASSERT_EQ(PP_OK_COMPLETIONPENDING, result);
ASSERT_TRUE(decoder_iface()->IsVideoDecoder(decoder.get()));
// Another attempt while pending should fail.
result = decoder_iface()->Initialize(
decoder.get(),
graphics3d.get(),
PP_VIDEOPROFILE_H264MAIN,
PP_HARDWAREACCELERATION_WITHFALLBACK,
0,
PP_MakeOptionalCompletionCallback(&MockCompletionCallback::Callback,
&cb));
ASSERT_EQ(PP_ERROR_INPROGRESS, result);
// Check for host message and send a reply to complete initialization.
ResourceMessageCallParams params;
IPC::Message msg;
ASSERT_TRUE(sink().GetFirstResourceCallMatching(
PpapiHostMsg_VideoDecoder_Initialize::ID, ¶ms, &msg));
sink().ClearMessages();
SendReply(params, PP_OK, PpapiPluginMsg_VideoDecoder_InitializeReply());
ASSERT_TRUE(cb.called());
ASSERT_EQ(PP_OK, cb.result());
}
}
TEST_F(VideoDecoderResourceTest, Uninitialized) {
// Operations on uninitialized decoders should fail.
LockingResourceReleaser decoder(CreateDecoder());
MockCompletionCallback uncalled_cb;
ASSERT_EQ(PP_ERROR_FAILED, CallDecode(decoder.get(), &uncalled_cb, NULL));
ASSERT_FALSE(uncalled_cb.called());
ASSERT_EQ(PP_ERROR_FAILED, CallGetPicture(decoder.get(), NULL, &uncalled_cb));
ASSERT_FALSE(uncalled_cb.called());
ASSERT_EQ(PP_ERROR_FAILED, CallFlush(decoder.get(), &uncalled_cb));
ASSERT_FALSE(uncalled_cb.called());
ASSERT_EQ(PP_ERROR_FAILED, CallReset(decoder.get(), &uncalled_cb));
ASSERT_FALSE(uncalled_cb.called());
}
// TODO(bbudge) Fix sync message testing on Windows 64 bit builds. The reply
// message for GetShm isn't received, causing Decode to fail.
// http://crbug.com/379260
#if !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
TEST_F(VideoDecoderResourceTest, DecodeAndGetPicture) {
LockingResourceReleaser decoder(CreateAndInitializeDecoder());
ResourceMessageCallParams params, params2;
MockCompletionCallback decode_cb, get_picture_cb, uncalled_cb;
uint32_t shm_id;
uint32_t decode_size;
int32_t decode_id;
// Call Decode until we have the maximum pending, minus one.
for (uint32_t i = 0; i < kMaximumPendingDecodes - 1; i++) {
PpapiHostMsg_VideoDecoder_GetShm shm_msg(i, kDecodeBufferSize);
ASSERT_EQ(PP_OK, CallDecode(decoder.get(), &uncalled_cb, &shm_msg));
ASSERT_FALSE(uncalled_cb.called());
CheckDecodeMsg(¶ms, &shm_id, &decode_size, &decode_id);
ASSERT_EQ(i, shm_id);
ASSERT_EQ(kDecodeBufferSize, decode_size);
// The resource generates uids internally, starting at 1.
int32_t uid = i + 1;
ASSERT_EQ(uid, decode_id);
}
// Once we've allocated the maximum number of buffers, we must wait.
PpapiHostMsg_VideoDecoder_GetShm shm_msg(7U, kDecodeBufferSize);
ASSERT_EQ(PP_OK_COMPLETIONPENDING,
CallDecode(decoder.get(), &decode_cb, &shm_msg));
CheckDecodeMsg(¶ms, &shm_id, &decode_size, &decode_id);
ASSERT_EQ(7U, shm_id);
ASSERT_EQ(kDecodeBufferSize, decode_size);
// Calling Decode when another Decode is pending should fail.
ASSERT_EQ(PP_ERROR_INPROGRESS, CallDecode(decoder.get(), &uncalled_cb, NULL));
ASSERT_FALSE(uncalled_cb.called());
// Free up the first decode buffer.
SendDecodeReply(params, 0U);
// The decoder should run the pending callback.
ASSERT_TRUE(decode_cb.called());
ASSERT_EQ(PP_OK, decode_cb.result());
decode_cb.Reset();
// Now try to get a picture. No picture ready message has been received yet.
PP_VideoPicture picture;
ASSERT_EQ(PP_OK_COMPLETIONPENDING,
CallGetPicture(decoder.get(), &picture, &get_picture_cb));
ASSERT_FALSE(get_picture_cb.called());
// Calling GetPicture when another GetPicture is pending should fail.
ASSERT_EQ(PP_ERROR_INPROGRESS,
CallGetPicture(decoder.get(), &picture, &uncalled_cb));
ASSERT_FALSE(uncalled_cb.called());
// Send 'request textures' message to initialize textures.
SendRequestTextures(params);
// Send a picture ready message for Decode call 1. The GetPicture callback
// should complete.
SendPictureReady(params, 1U, kTextureId1);
ASSERT_TRUE(get_picture_cb.called());
ASSERT_EQ(PP_OK, get_picture_cb.result());
ASSERT_EQ(kDecodeId, picture.decode_id);
get_picture_cb.Reset();
// Send a picture ready message for Decode call 2. Since there is no pending
// GetPicture call, the picture should be queued.
SendPictureReady(params, 2U, kTextureId2);
// The next GetPicture should return synchronously.
ASSERT_EQ(PP_OK, CallGetPicture(decoder.get(), &picture, &uncalled_cb));
ASSERT_FALSE(uncalled_cb.called());
ASSERT_EQ(kDecodeId, picture.decode_id);
}
#endif // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
// TODO(bbudge) Fix sync message testing on Windows 64 bit builds. The reply
// message for GetShm isn't received, causing Decode to fail.
// http://crbug.com/379260
#if !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
TEST_F(VideoDecoderResourceTest, RecyclePicture) {
LockingResourceReleaser decoder(CreateAndInitializeDecoder());
ResourceMessageCallParams params;
MockCompletionCallback decode_cb, get_picture_cb, uncalled_cb;
// Get to a state where we have a picture to recycle.
PpapiHostMsg_VideoDecoder_GetShm shm_msg(0U, kDecodeBufferSize);
ASSERT_EQ(PP_OK, CallDecode(decoder.get(), &decode_cb, &shm_msg));
uint32_t shm_id;
uint32_t decode_size;
int32_t decode_id;
CheckDecodeMsg(¶ms, &shm_id, &decode_size, &decode_id);
SendDecodeReply(params, 0U);
// Send 'request textures' message to initialize textures.
SendRequestTextures(params);
// Call GetPicture and send 'picture ready' message to get a picture to
// recycle.
PP_VideoPicture picture;
ASSERT_EQ(PP_OK_COMPLETIONPENDING,
CallGetPicture(decoder.get(), &picture, &get_picture_cb));
SendPictureReady(params, 0U, kTextureId1);
ASSERT_EQ(kTextureId1, picture.texture_id);
CallRecyclePicture(decoder.get(), picture);
uint32_t texture_id;
ASSERT_TRUE(CheckRecyclePictureMsg(¶ms, &texture_id));
ASSERT_EQ(kTextureId1, texture_id);
ClearCallbacks(decoder.get());
}
#endif // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
TEST_F(VideoDecoderResourceTest, Flush) {
LockingResourceReleaser decoder(CreateAndInitializeDecoder());
ResourceMessageCallParams params, params2;
MockCompletionCallback flush_cb, get_picture_cb, uncalled_cb;
ASSERT_EQ(PP_OK_COMPLETIONPENDING, CallFlush(decoder.get(), &flush_cb));
ASSERT_FALSE(flush_cb.called());
ASSERT_TRUE(CheckFlushMsg(¶ms));
ASSERT_EQ(PP_ERROR_FAILED, CallDecode(decoder.get(), &uncalled_cb, NULL));
ASSERT_FALSE(uncalled_cb.called());
// Plugin can call GetPicture while Flush is pending.
ASSERT_EQ(PP_OK_COMPLETIONPENDING,
CallGetPicture(decoder.get(), NULL, &get_picture_cb));
ASSERT_FALSE(get_picture_cb.called());
ASSERT_EQ(PP_ERROR_INPROGRESS, CallFlush(decoder.get(), &uncalled_cb));
ASSERT_FALSE(uncalled_cb.called());
ASSERT_EQ(PP_ERROR_FAILED, CallReset(decoder.get(), &uncalled_cb));
ASSERT_FALSE(uncalled_cb.called());
// Plugin can call RecyclePicture while Flush is pending.
PP_VideoPicture picture;
picture.texture_id = kTextureId1;
CallRecyclePicture(decoder.get(), picture);
uint32_t texture_id;
ASSERT_TRUE(CheckRecyclePictureMsg(¶ms2, &texture_id));
SendFlushReply(params);
// Any pending GetPicture call is aborted.
ASSERT_TRUE(get_picture_cb.called());
ASSERT_EQ(PP_ERROR_ABORTED, get_picture_cb.result());
ASSERT_TRUE(flush_cb.called());
ASSERT_EQ(PP_OK, flush_cb.result());
}
// TODO(bbudge) Test Reset when we can run the message loop to get aborted
// callbacks to run.
// TODO(bbudge) Fix sync message testing on Windows 64 bit builds. The reply
// message for GetShm isn't received, causing Decode to fail.
// http://crbug.com/379260
#if !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
TEST_F(VideoDecoderResourceTest, NotifyError) {
LockingResourceReleaser decoder(CreateAndInitializeDecoder());
ResourceMessageCallParams params;
MockCompletionCallback decode_cb, get_picture_cb, uncalled_cb;
// Call Decode and GetPicture to have some pending requests.
PpapiHostMsg_VideoDecoder_GetShm shm_msg(0U, kDecodeBufferSize);
ASSERT_EQ(PP_OK, CallDecode(decoder.get(), &decode_cb, &shm_msg));
ASSERT_FALSE(decode_cb.called());
ASSERT_EQ(PP_OK_COMPLETIONPENDING,
CallGetPicture(decoder.get(), NULL, &get_picture_cb));
ASSERT_FALSE(get_picture_cb.called());
// Send the decoder resource an unsolicited notify error message. We first
// need to initialize 'params' so the message is routed to the decoder.
uint32_t shm_id;
uint32_t decode_size;
int32_t decode_id;
CheckDecodeMsg(¶ms, &shm_id, &decode_size, &decode_id);
SendNotifyError(params, PP_ERROR_RESOURCE_FAILED);
// Any pending message should be run with the reported error.
ASSERT_TRUE(get_picture_cb.called());
ASSERT_EQ(PP_ERROR_RESOURCE_FAILED, get_picture_cb.result());
// All further calls return the reported error.
ASSERT_EQ(PP_ERROR_RESOURCE_FAILED,
CallDecode(decoder.get(), &uncalled_cb, NULL));
ASSERT_FALSE(uncalled_cb.called());
ASSERT_EQ(PP_ERROR_RESOURCE_FAILED,
CallGetPicture(decoder.get(), NULL, &uncalled_cb));
ASSERT_FALSE(uncalled_cb.called());
ASSERT_EQ(PP_ERROR_RESOURCE_FAILED, CallFlush(decoder.get(), &uncalled_cb));
ASSERT_FALSE(uncalled_cb.called());
ASSERT_EQ(PP_ERROR_RESOURCE_FAILED, CallReset(decoder.get(), &uncalled_cb));
ASSERT_FALSE(uncalled_cb.called());
}
#endif // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
} // namespace proxy
} // namespace ppapi
| {
"pile_set_name": "Github"
} |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
from azure.mgmt.core import ARMPipelineClient
from msrest import Deserializer, Serializer
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Optional
from azure.core.credentials import TokenCredential
from ._configuration import ComputeManagementClientConfiguration
from .operations import ResourceSkusOperations
from . import models
class ComputeManagementClient(object):
"""Compute Client.
:ivar resource_skus: ResourceSkusOperations operations
:vartype resource_skus: azure.mgmt.compute.v2019_04_01.operations.ResourceSkusOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.
:type subscription_id: str
:param str base_url: Service URL
"""
def __init__(
self,
credential, # type: "TokenCredential"
subscription_id, # type: str
base_url=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> None
if not base_url:
base_url = 'https://management.azure.com'
self._config = ComputeManagementClientConfiguration(credential, subscription_id, **kwargs)
self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._serialize.client_side_validation = False
self._deserialize = Deserializer(client_models)
self.resource_skus = ResourceSkusOperations(
self._client, self._config, self._serialize, self._deserialize)
def close(self):
# type: () -> None
self._client.close()
def __enter__(self):
# type: () -> ComputeManagementClient
self._client.__enter__()
return self
def __exit__(self, *exc_details):
# type: (Any) -> None
self._client.__exit__(*exc_details)
| {
"pile_set_name": "Github"
} |
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<a name="7.0.0"></a>
# [7.0.0](https://github.com/yargs/yargs-parser/compare/v6.0.1...v7.0.0) (2017-05-02)
### Chores
* revert populate-- logic ([#91](https://github.com/yargs/yargs-parser/issues/91)) ([6003e6d](https://github.com/yargs/yargs-parser/commit/6003e6d))
### BREAKING CHANGES
* populate-- now defaults to false.
<a name="6.0.1"></a>
## [6.0.1](https://github.com/yargs/yargs-parser/compare/v6.0.0...v6.0.1) (2017-05-01)
### Bug Fixes
* default '--' to undefined when not provided; this is closer to the array API ([#90](https://github.com/yargs/yargs-parser/issues/90)) ([4e739cc](https://github.com/yargs/yargs-parser/commit/4e739cc))
<a name="6.0.0"></a>
# [6.0.0](https://github.com/yargs/yargs-parser/compare/v4.2.1...v6.0.0) (2017-05-01)
### Bug Fixes
* environment variables should take precedence over config file ([#81](https://github.com/yargs/yargs-parser/issues/81)) ([76cee1f](https://github.com/yargs/yargs-parser/commit/76cee1f))
* parsing hints should apply for dot notation keys ([#86](https://github.com/yargs/yargs-parser/issues/86)) ([3e47d62](https://github.com/yargs/yargs-parser/commit/3e47d62))
### Chores
* upgrade to newest version of camelcase ([#87](https://github.com/yargs/yargs-parser/issues/87)) ([f1903aa](https://github.com/yargs/yargs-parser/commit/f1903aa))
### Features
* add -- option which allows arguments after the -- flag to be returned separated from positional arguments ([#84](https://github.com/yargs/yargs-parser/issues/84)) ([2572ca8](https://github.com/yargs/yargs-parser/commit/2572ca8))
* when parsing stops, we now populate "--" by default ([#88](https://github.com/yargs/yargs-parser/issues/88)) ([cd666db](https://github.com/yargs/yargs-parser/commit/cd666db))
### BREAKING CHANGES
* rather than placing arguments in "_", when parsing is stopped via "--"; we now populate an array called "--" by default.
* camelcase now requires Node 4+.
* environment variables will now override config files (args, env, config-file, config-object)
<a name="5.0.0"></a>
# [5.0.0](https://github.com/yargs/yargs-parser/compare/v4.2.1...v5.0.0) (2017-02-18)
### Bug Fixes
* environment variables should take precedence over config file ([#81](https://github.com/yargs/yargs-parser/issues/81)) ([76cee1f](https://github.com/yargs/yargs-parser/commit/76cee1f))
### BREAKING CHANGES
* environment variables will now override config files (args, env, config-file, config-object)
<a name="4.2.1"></a>
## [4.2.1](https://github.com/yargs/yargs-parser/compare/v4.2.0...v4.2.1) (2017-01-02)
### Bug Fixes
* flatten/duplicate regression ([#75](https://github.com/yargs/yargs-parser/issues/75)) ([68d68a0](https://github.com/yargs/yargs-parser/commit/68d68a0))
<a name="4.2.0"></a>
# [4.2.0](https://github.com/yargs/yargs-parser/compare/v4.1.0...v4.2.0) (2016-12-01)
### Bug Fixes
* inner objects in configs had their keys appended to top-level key when dot-notation was disabled ([#72](https://github.com/yargs/yargs-parser/issues/72)) ([0b1b5f9](https://github.com/yargs/yargs-parser/commit/0b1b5f9))
### Features
* allow multiple arrays to be provided, rather than always combining ([#71](https://github.com/yargs/yargs-parser/issues/71)) ([0f0fb2d](https://github.com/yargs/yargs-parser/commit/0f0fb2d))
<a name="4.1.0"></a>
# [4.1.0](https://github.com/yargs/yargs-parser/compare/v4.0.2...v4.1.0) (2016-11-07)
### Features
* apply coercions to default options ([#65](https://github.com/yargs/yargs-parser/issues/65)) ([c79052b](https://github.com/yargs/yargs-parser/commit/c79052b))
* handle dot notation boolean options ([#63](https://github.com/yargs/yargs-parser/issues/63)) ([02c3545](https://github.com/yargs/yargs-parser/commit/02c3545))
<a name="4.0.2"></a>
## [4.0.2](https://github.com/yargs/yargs-parser/compare/v4.0.1...v4.0.2) (2016-09-30)
### Bug Fixes
* whoops, let's make the assign not change the Object key order ([29d069a](https://github.com/yargs/yargs-parser/commit/29d069a))
<a name="4.0.1"></a>
## [4.0.1](https://github.com/yargs/yargs-parser/compare/v4.0.0...v4.0.1) (2016-09-30)
### Bug Fixes
* lodash.assign was deprecated ([#59](https://github.com/yargs/yargs-parser/issues/59)) ([5e7eb11](https://github.com/yargs/yargs-parser/commit/5e7eb11))
<a name="4.0.0"></a>
# [4.0.0](https://github.com/yargs/yargs-parser/compare/v3.2.0...v4.0.0) (2016-09-26)
### Bug Fixes
* coerce should be applied to the final objects and arrays created ([#57](https://github.com/yargs/yargs-parser/issues/57)) ([4ca69da](https://github.com/yargs/yargs-parser/commit/4ca69da))
### BREAKING CHANGES
* coerce is no longer applied to individual arguments in an implicit array.
<a name="3.2.0"></a>
# [3.2.0](https://github.com/yargs/yargs-parser/compare/v3.1.0...v3.2.0) (2016-08-13)
### Features
* coerce full array instead of each element ([#51](https://github.com/yargs/yargs-parser/issues/51)) ([cc4dc56](https://github.com/yargs/yargs-parser/commit/cc4dc56))
<a name="3.1.0"></a>
# [3.1.0](https://github.com/yargs/yargs-parser/compare/v3.0.0...v3.1.0) (2016-08-09)
### Bug Fixes
* address pkgConf parsing bug outlined in [#37](https://github.com/yargs/yargs-parser/issues/37) ([#45](https://github.com/yargs/yargs-parser/issues/45)) ([be76ee6](https://github.com/yargs/yargs-parser/commit/be76ee6))
* better parsing of negative values ([#44](https://github.com/yargs/yargs-parser/issues/44)) ([2e43692](https://github.com/yargs/yargs-parser/commit/2e43692))
* check aliases when guessing defaults for arguments fixes [#41](https://github.com/yargs/yargs-parser/issues/41) ([#43](https://github.com/yargs/yargs-parser/issues/43)) ([f3e4616](https://github.com/yargs/yargs-parser/commit/f3e4616))
### Features
* added coerce option, for providing specialized argument parsing ([#42](https://github.com/yargs/yargs-parser/issues/42)) ([7b49cd2](https://github.com/yargs/yargs-parser/commit/7b49cd2))
<a name="3.0.0"></a>
# [3.0.0](https://github.com/yargs/yargs-parser/compare/v2.4.1...v3.0.0) (2016-08-07)
### Bug Fixes
* parsing issue with numeric character in group of options ([#19](https://github.com/yargs/yargs-parser/issues/19)) ([f743236](https://github.com/yargs/yargs-parser/commit/f743236))
* upgraded lodash.assign ([5d7fdf4](https://github.com/yargs/yargs-parser/commit/5d7fdf4))
### BREAKING CHANGES
* subtle change to how values are parsed in a group of single-character arguments.
* _first released in 3.1.0, better handling of negative values should be considered a breaking change._
<a name="2.4.1"></a>
## [2.4.1](https://github.com/yargs/yargs-parser/compare/v2.4.0...v2.4.1) (2016-07-16)
### Bug Fixes
* **count:** do not increment a default value ([#39](https://github.com/yargs/yargs-parser/issues/39)) ([b04a189](https://github.com/yargs/yargs-parser/commit/b04a189))
<a name="2.4.0"></a>
# [2.4.0](https://github.com/yargs/yargs-parser/compare/v2.3.0...v2.4.0) (2016-04-11)
### Features
* **environment:** Support nested options in environment variables ([#26](https://github.com/yargs/yargs-parser/issues/26)) thanks [@elas7](https://github.com/elas7) \o/ ([020778b](https://github.com/yargs/yargs-parser/commit/020778b))
<a name="2.3.0"></a>
# [2.3.0](https://github.com/yargs/yargs-parser/compare/v2.2.0...v2.3.0) (2016-04-09)
### Bug Fixes
* **boolean:** fix for boolean options with non boolean defaults (#20) ([2dbe86b](https://github.com/yargs/yargs-parser/commit/2dbe86b)), closes [(#20](https://github.com/(/issues/20)
* **package:** remove tests from tarball ([0353c0d](https://github.com/yargs/yargs-parser/commit/0353c0d))
* **parsing:** handle calling short option with an empty string as the next value. ([a867165](https://github.com/yargs/yargs-parser/commit/a867165))
* boolean flag when next value contains the strings 'true' or 'false'. ([69941a6](https://github.com/yargs/yargs-parser/commit/69941a6))
* update dependencies; add standard-version bin for next release (#24) ([822d9d5](https://github.com/yargs/yargs-parser/commit/822d9d5))
### Features
* **configuration:** Allow to pass configuration objects to yargs-parser ([0780900](https://github.com/yargs/yargs-parser/commit/0780900))
* **normalize:** allow normalize to work with arrays ([e0eaa1a](https://github.com/yargs/yargs-parser/commit/e0eaa1a))
| {
"pile_set_name": "Github"
} |
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2015-2020 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/vectorfieldvisualizationgl/processors/2d/vector2ddivergence.h>
#include <modules/opengl/texture/textureunit.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/image/imagegl.h>
#include <modules/opengl/shader/shaderutils.h>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo Vector2DDivergence::processorInfo_{
"org.inviwo.Vector2DDivergence", // Class identifier
"Vector 2D Divergence", // Display name
"Vector Field Visualization", // Category
CodeState::Stable, // Code state
Tags::GL, // Tags
};
const ProcessorInfo Vector2DDivergence::getProcessorInfo() const { return processorInfo_; }
Vector2DDivergence::Vector2DDivergence()
: Processor()
, inport_("inport", true)
, outport_("outport", DataVec4Float32::get())
, shader_("vector2ddivergence.frag") {
addPort(inport_);
addPort(outport_);
}
void Vector2DDivergence::process() {
utilgl::activateAndClearTarget(outport_);
shader_.activate();
TextureUnitContainer units;
utilgl::bindAndSetUniforms(shader_, units, inport_, ImageType::ColorOnly);
utilgl::singleDrawImagePlaneRect();
shader_.deactivate();
utilgl::deactivateCurrentTarget();
}
} // namespace inviwo
| {
"pile_set_name": "Github"
} |
require 'puppet/util/checksums'
# Specify which checksum algorithm to use when checksumming
# files.
Puppet::Type.type(:file).newparam(:checksum) do
include Puppet::Util::Checksums
desc "The checksum type to use when determining whether to replace a file's contents.
The default checksum type is md5."
newvalues "md5", "md5lite", "sha256", "sha256lite", "mtime", "ctime", "none"
defaultto do
Puppet[:digest_algorithm].to_sym
end
def sum(content)
content = content.is_a?(Puppet::Pops::Types::PBinaryType::Binary) ? content.binary_buffer : content
type = digest_algorithm()
"{#{type}}" + send(type, content)
end
def sum_file(path)
type = digest_algorithm()
method = type.to_s + "_file"
"{#{type}}" + send(method, path).to_s
end
def sum_stream(&block)
type = digest_algorithm()
method = type.to_s + "_stream"
checksum = send(method, &block)
"{#{type}}#{checksum}"
end
private
# Return the appropriate digest algorithm with fallbacks in case puppet defaults have not
# been initialized.
def digest_algorithm
value || Puppet[:digest_algorithm].to_sym
end
end
| {
"pile_set_name": "Github"
} |
import { RendererLogger } from "./renderer-logger";
// tslint:disable:no-console
describe("RendererLogger", () => {
let logger: RendererLogger;
let ipcMainSendSpy: jasmine.Spy;
beforeEach(() => {
ipcMainSendSpy = jasmine.createSpy("ipcMain.send");
spyOn(console, "info");
spyOn(console, "error");
spyOn(console, "debug");
spyOn(console, "warn");
logger = new RendererLogger({
send: ipcMainSendSpy,
} as any);
});
it("calls console.info and send event when calling logger.", () => {
logger.info("Foo", "Bar", { val: 3 });
expect(console.info).toHaveBeenCalledOnce();
expect(console.info).toHaveBeenCalledWith("Foo", "Bar", { val: 3 });
expect(console.error).not.toHaveBeenCalled();
expect(console.warn).not.toHaveBeenCalled();
expect(console.debug).not.toHaveBeenCalled();
expect(ipcMainSendSpy).toHaveBeenCalledWith("SEND_LOG", {
level: "info",
message: "Foo", params: ["Bar", { val: 3 }],
});
});
it("calls console.debug and send event when calling logger.", () => {
logger.debug("Foo", "Bar", { val: 3 });
expect(console.debug).toHaveBeenCalledOnce();
expect(console.debug).toHaveBeenCalledWith("Foo", "Bar", { val: 3 });
expect(console.info).not.toHaveBeenCalled();
expect(console.error).not.toHaveBeenCalled();
expect(console.warn).not.toHaveBeenCalled();
expect(ipcMainSendSpy).toHaveBeenCalledWith("SEND_LOG", {
level: "debug",
message: "Foo", params: ["Bar", { val: 3 }],
});
});
it("calls console.error and send event when calling logger.", () => {
const error = new Error("Some error");
logger.error("Foo", error);
expect(console.error).toHaveBeenCalledOnce();
expect(console.error).toHaveBeenCalledWith("Foo", error);
expect(console.info).not.toHaveBeenCalled();
expect(console.debug).not.toHaveBeenCalled();
expect(console.warn).not.toHaveBeenCalled();
expect(ipcMainSendSpy).toHaveBeenCalledWith("SEND_LOG", {
level: "error",
message: "Foo", params: [error],
});
});
it("calls console.warn and send event when calling logger.", () => {
logger.warn("Foo", "Bar", { val: 3 });
expect(console.warn).toHaveBeenCalledOnce();
expect(console.warn).toHaveBeenCalledWith("Foo", "Bar", { val: 3 });
expect(console.info).not.toHaveBeenCalled();
expect(console.error).not.toHaveBeenCalled();
expect(console.debug).not.toHaveBeenCalled();
expect(ipcMainSendSpy).toHaveBeenCalledWith("SEND_LOG", {
level: "warn",
message: "Foo", params: ["Bar", { val: 3 }],
});
});
});
| {
"pile_set_name": "Github"
} |
# $Id$
# Authority: dag
# Upstream: Paul Seamons <perl$seamons,com>
%define perl_vendorlib %(eval "`%{__perl} -V:installvendorlib`"; echo $installvendorlib)
%define perl_vendorarch %(eval "`%{__perl} -V:installvendorarch`"; echo $installvendorarch)
%define real_name CGI-Ex
Summary: Perl module to make powerful application writing fun and easy
Name: perl-CGI-Ex
Version: 2.27
Release: 1%{?dist}
License: Artistic/GPL
Group: Applications/CPAN
URL: http://search.cpan.org/dist/CGI-Ex/
Source: http://www.cpan.org/modules/by-module/CGI/CGI-Ex-%{version}.tar.gz
BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root
BuildArch: noarch
BuildRequires: perl
BuildRequires: perl(ExtUtils::MakeMaker)
# From yaml requires
BuildRequires: perl(Template::Alloy) >= 1.004
%description
perl-CGI-Ex is a Perl module to make powerful application writing fun and easy.
%prep
%setup -n %{real_name}-%{version}
%build
%{__perl} Makefile.PL INSTALLDIRS="vendor" PREFIX="%{buildroot}%{_prefix}"
%{__make} %{?_smp_mflags}
%install
%{__rm} -rf %{buildroot}
%{__make} pure_install
### Clean up buildroot
find %{buildroot} -name .packlist -exec %{__rm} {} \;
### Clean up docs
find samples/ -type f -exec %{__chmod} a-x {} \;
%clean
%{__rm} -rf %{buildroot}
%files
%defattr(-, root, root, 0755)
%doc Changes MANIFEST MANIFEST.SKIP META.yml README samples/
%doc %{_mandir}/man3/CGI::Ex.3pm*
%doc %{_mandir}/man3/CGI::Ex::*.3pm*
%dir %{perl_vendorlib}/CGI/
%{perl_vendorlib}/CGI/Ex/
%{perl_vendorlib}/CGI/Ex.pm
%changelog
* Sat Aug 22 2009 Christoph Maser <[email protected]> - 2.27-1
- Updated to version 2.27.
* Thu Feb 28 2008 Dag Wieers <[email protected]> - 2.24-1
- Updated to release 2.24.
* Thu Dec 27 2007 Dag Wieers <[email protected]> - 2.23-1
- Updated to release 2.23.
* Wed Nov 07 2007 Dag Wieers <[email protected]> - 2.21-1
- Updated to release 2.21.
* Fri Aug 03 2007 Dag Wieers <[email protected]> - 2.18-1
- Initial package. (using DAR)
| {
"pile_set_name": "Github"
} |
#include "mutscan.h"
#include "fastqreader.h"
#include <iostream>
#include "htmlreporter.h"
#include "sescanner.h"
#include "pescanner.h"
#include "util.h"
#include "globalsettings.h"
MutScan::MutScan(string mutationFile, string refFile, string read1File, string read2File, string html, string json, int threadNum){
mRead1File = read1File;
mRead2File = read2File;
mMutationFile = mutationFile;
mRefFile = refFile;
mHtmlFile = html;
mJsonFile = json;
mThreadNum = threadNum;
}
bool MutScan::scan(){
if(mRead2File != ""){
//return scanPairEnd();
PairEndScanner pescanner( mMutationFile, mRefFile, mRead1File, mRead2File, mHtmlFile, mJsonFile, mThreadNum);
return pescanner.scan();
}
else{
//return scanSingleEnd();
SingleEndScanner sescanner( mMutationFile, mRefFile, mRead1File, mHtmlFile, mJsonFile, mThreadNum);
return sescanner.scan();
}
}
void MutScan::evaluateSimplifiedMode(string r1file, string r2file, int mutationNum) {
if(mutationNum < 10000) {
GlobalSettings::setSimplifiedMode(false);
return ;
}
// use another ifstream to not affect current reader
ifstream is(r1file);
is.seekg (0, is.end);
long bytes = is.tellg();
if(r2file != "")
bytes *= 2;
// here we consider gz file for FASTQ has a compression rate of 3
if(ends_with(r1file, ".gz"))
bytes *= 3;
// enable simplified mode for over 50G FASTQ + 10,000 mutations
if(bytes > 50L * 1024L * 1024L * 1024L) {
if(GlobalSettings::verbose)
cerr << "Simplified mode is enabled automatically..."<<endl;
GlobalSettings::setSimplifiedMode(true);
}
else {
GlobalSettings::setSimplifiedMode(false);
}
} | {
"pile_set_name": "Github"
} |
/*
* Copyright 2014 Google Inc.
*
* 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.
*/
package com.google.gwt.uibinder.test.client;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
/**
* Test class for checking UiBinder casting to a JsType interface like this one.
*/
@JsType(isNative = true)
public interface TestJsElementType {
@JsProperty
String getTagName();
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<Grid
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="StarWarsSample.Forms.UI.Components.InformationView"
Padding="16, 8, 16, 8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<Label
Grid.Column="0"
x:Name="Label"
HorizontalOptions="StartAndExpand"
VerticalOptions="Center"
TextColor="{StaticResource MenuTextColor}"/>
<Label
Grid.Column="1"
x:Name="Value"
HorizontalOptions="StartAndExpand"
VerticalOptions="Center"
FontAttributes="Bold"
TextColor="White"/>
</Grid>
| {
"pile_set_name": "Github"
} |
[PACKET]
codec_type=audio
stream_index=0
pts=0
pts_time=0.000000
dts=0
dts_time=0.000000
duration=1024
duration_time=0.023220
convergence_duration=N/A
convergence_duration_time=N/A
size=2048
pos=647
flags=K_
[/PACKET]
[FRAME]
media_type=audio
stream_index=0
key_frame=1
pkt_pts=0
pkt_pts_time=0.000000
pkt_dts=0
pkt_dts_time=0.000000
best_effort_timestamp=0
best_effort_timestamp_time=0.000000
pkt_duration=1024
pkt_duration_time=0.023220
pkt_pos=647
pkt_size=2048
sample_fmt=s16
nb_samples=1024
channels=1
channel_layout=unknown
[/FRAME]
[PACKET]
codec_type=video
stream_index=1
pts=0
pts_time=0.000000
dts=0
dts_time=0.000000
duration=2048
duration_time=0.040000
convergence_duration=N/A
convergence_duration_time=N/A
size=230400
pos=2722
flags=K_
[/PACKET]
[FRAME]
media_type=video
stream_index=1
key_frame=1
pkt_pts=0
pkt_pts_time=0.000000
pkt_dts=0
pkt_dts_time=0.000000
best_effort_timestamp=0
best_effort_timestamp_time=0.000000
pkt_duration=2048
pkt_duration_time=0.040000
pkt_pos=2722
pkt_size=230400
width=320
height=240
pix_fmt=rgb24
sample_aspect_ratio=1:1
pict_type=I
coded_picture_number=0
display_picture_number=0
interlaced_frame=0
top_field_first=0
repeat_pict=0
[/FRAME]
[PACKET]
codec_type=video
stream_index=2
pts=0
pts_time=0.000000
dts=0
dts_time=0.000000
duration=2048
duration_time=0.040000
convergence_duration=N/A
convergence_duration_time=N/A
size=30000
pos=233143
flags=K_
[/PACKET]
[FRAME]
media_type=video
stream_index=2
key_frame=1
pkt_pts=0
pkt_pts_time=0.000000
pkt_dts=0
pkt_dts_time=0.000000
best_effort_timestamp=0
best_effort_timestamp_time=0.000000
pkt_duration=2048
pkt_duration_time=0.040000
pkt_pos=233143
pkt_size=30000
width=100
height=100
pix_fmt=rgb24
sample_aspect_ratio=1:1
pict_type=I
coded_picture_number=0
display_picture_number=0
interlaced_frame=0
top_field_first=0
repeat_pict=0
[/FRAME]
[PACKET]
codec_type=audio
stream_index=0
pts=1024
pts_time=0.023220
dts=1024
dts_time=0.023220
duration=1024
duration_time=0.023220
convergence_duration=N/A
convergence_duration_time=N/A
size=2048
pos=263148
flags=K_
[/PACKET]
[FRAME]
media_type=audio
stream_index=0
key_frame=1
pkt_pts=1024
pkt_pts_time=0.023220
pkt_dts=1024
pkt_dts_time=0.023220
best_effort_timestamp=1024
best_effort_timestamp_time=0.023220
pkt_duration=1024
pkt_duration_time=0.023220
pkt_pos=263148
pkt_size=2048
sample_fmt=s16
nb_samples=1024
channels=1
channel_layout=unknown
[/FRAME]
[PACKET]
codec_type=video
stream_index=1
pts=2048
pts_time=0.040000
dts=2048
dts_time=0.040000
duration=2048
duration_time=0.040000
convergence_duration=N/A
convergence_duration_time=N/A
size=230400
pos=265226
flags=K_
[/PACKET]
[FRAME]
media_type=video
stream_index=1
key_frame=1
pkt_pts=2048
pkt_pts_time=0.040000
pkt_dts=2048
pkt_dts_time=0.040000
best_effort_timestamp=2048
best_effort_timestamp_time=0.040000
pkt_duration=2048
pkt_duration_time=0.040000
pkt_pos=265226
pkt_size=230400
width=320
height=240
pix_fmt=rgb24
sample_aspect_ratio=1:1
pict_type=I
coded_picture_number=0
display_picture_number=0
interlaced_frame=0
top_field_first=0
repeat_pict=0
[/FRAME]
[PACKET]
codec_type=video
stream_index=2
pts=2048
pts_time=0.040000
dts=2048
dts_time=0.040000
duration=2048
duration_time=0.040000
convergence_duration=N/A
convergence_duration_time=N/A
size=30000
pos=495650
flags=K_
[/PACKET]
[FRAME]
media_type=video
stream_index=2
key_frame=1
pkt_pts=2048
pkt_pts_time=0.040000
pkt_dts=2048
pkt_dts_time=0.040000
best_effort_timestamp=2048
best_effort_timestamp_time=0.040000
pkt_duration=2048
pkt_duration_time=0.040000
pkt_pos=495650
pkt_size=30000
width=100
height=100
pix_fmt=rgb24
sample_aspect_ratio=1:1
pict_type=I
coded_picture_number=0
display_picture_number=0
interlaced_frame=0
top_field_first=0
repeat_pict=0
[/FRAME]
[PACKET]
codec_type=audio
stream_index=0
pts=2048
pts_time=0.046440
dts=2048
dts_time=0.046440
duration=1024
duration_time=0.023220
convergence_duration=N/A
convergence_duration_time=N/A
size=2048
pos=525655
flags=K_
[/PACKET]
[FRAME]
media_type=audio
stream_index=0
key_frame=1
pkt_pts=2048
pkt_pts_time=0.046440
pkt_dts=2048
pkt_dts_time=0.046440
best_effort_timestamp=2048
best_effort_timestamp_time=0.046440
pkt_duration=1024
pkt_duration_time=0.023220
pkt_pos=525655
pkt_size=2048
sample_fmt=s16
nb_samples=1024
channels=1
channel_layout=unknown
[/FRAME]
[PACKET]
codec_type=audio
stream_index=0
pts=3072
pts_time=0.069660
dts=3072
dts_time=0.069660
duration=1024
duration_time=0.023220
convergence_duration=N/A
convergence_duration_time=N/A
size=2048
pos=527726
flags=K_
[/PACKET]
[FRAME]
media_type=audio
stream_index=0
key_frame=1
pkt_pts=3072
pkt_pts_time=0.069660
pkt_dts=3072
pkt_dts_time=0.069660
best_effort_timestamp=3072
best_effort_timestamp_time=0.069660
pkt_duration=1024
pkt_duration_time=0.023220
pkt_pos=527726
pkt_size=2048
sample_fmt=s16
nb_samples=1024
channels=1
channel_layout=unknown
[/FRAME]
[PACKET]
codec_type=video
stream_index=1
pts=4096
pts_time=0.080000
dts=4096
dts_time=0.080000
duration=2048
duration_time=0.040000
convergence_duration=N/A
convergence_duration_time=N/A
size=230400
pos=529804
flags=K_
[/PACKET]
[FRAME]
media_type=video
stream_index=1
key_frame=1
pkt_pts=4096
pkt_pts_time=0.080000
pkt_dts=4096
pkt_dts_time=0.080000
best_effort_timestamp=4096
best_effort_timestamp_time=0.080000
pkt_duration=2048
pkt_duration_time=0.040000
pkt_pos=529804
pkt_size=230400
width=320
height=240
pix_fmt=rgb24
sample_aspect_ratio=1:1
pict_type=I
coded_picture_number=0
display_picture_number=0
interlaced_frame=0
top_field_first=0
repeat_pict=0
[/FRAME]
[PACKET]
codec_type=video
stream_index=2
pts=4096
pts_time=0.080000
dts=4096
dts_time=0.080000
duration=2048
duration_time=0.040000
convergence_duration=N/A
convergence_duration_time=N/A
size=30000
pos=760228
flags=K_
[/PACKET]
[FRAME]
media_type=video
stream_index=2
key_frame=1
pkt_pts=4096
pkt_pts_time=0.080000
pkt_dts=4096
pkt_dts_time=0.080000
best_effort_timestamp=4096
best_effort_timestamp_time=0.080000
pkt_duration=2048
pkt_duration_time=0.040000
pkt_pos=760228
pkt_size=30000
width=100
height=100
pix_fmt=rgb24
sample_aspect_ratio=1:1
pict_type=I
coded_picture_number=0
display_picture_number=0
interlaced_frame=0
top_field_first=0
repeat_pict=0
[/FRAME]
[PACKET]
codec_type=audio
stream_index=0
pts=4096
pts_time=0.092880
dts=4096
dts_time=0.092880
duration=1024
duration_time=0.023220
convergence_duration=N/A
convergence_duration_time=N/A
size=2048
pos=790233
flags=K_
[/PACKET]
[FRAME]
media_type=audio
stream_index=0
key_frame=1
pkt_pts=4096
pkt_pts_time=0.092880
pkt_dts=4096
pkt_dts_time=0.092880
best_effort_timestamp=4096
best_effort_timestamp_time=0.092880
pkt_duration=1024
pkt_duration_time=0.023220
pkt_pos=790233
pkt_size=2048
sample_fmt=s16
nb_samples=1024
channels=1
channel_layout=unknown
[/FRAME]
[PACKET]
codec_type=audio
stream_index=0
pts=5120
pts_time=0.116100
dts=5120
dts_time=0.116100
duration=1024
duration_time=0.023220
convergence_duration=N/A
convergence_duration_time=N/A
size=2048
pos=792304
flags=K_
[/PACKET]
[FRAME]
media_type=audio
stream_index=0
key_frame=1
pkt_pts=5120
pkt_pts_time=0.116100
pkt_dts=5120
pkt_dts_time=0.116100
best_effort_timestamp=5120
best_effort_timestamp_time=0.116100
pkt_duration=1024
pkt_duration_time=0.023220
pkt_pos=792304
pkt_size=2048
sample_fmt=s16
nb_samples=1024
channels=1
channel_layout=unknown
[/FRAME]
[PACKET]
codec_type=video
stream_index=1
pts=6144
pts_time=0.120000
dts=6144
dts_time=0.120000
duration=2048
duration_time=0.040000
convergence_duration=N/A
convergence_duration_time=N/A
size=230400
pos=794382
flags=K_
[/PACKET]
[FRAME]
media_type=video
stream_index=1
key_frame=1
pkt_pts=6144
pkt_pts_time=0.120000
pkt_dts=6144
pkt_dts_time=0.120000
best_effort_timestamp=6144
best_effort_timestamp_time=0.120000
pkt_duration=2048
pkt_duration_time=0.040000
pkt_pos=794382
pkt_size=230400
width=320
height=240
pix_fmt=rgb24
sample_aspect_ratio=1:1
pict_type=I
coded_picture_number=0
display_picture_number=0
interlaced_frame=0
top_field_first=0
repeat_pict=0
[/FRAME]
[PACKET]
codec_type=video
stream_index=2
pts=6144
pts_time=0.120000
dts=6144
dts_time=0.120000
duration=2048
duration_time=0.040000
convergence_duration=N/A
convergence_duration_time=N/A
size=30000
pos=1024806
flags=K_
[/PACKET]
[FRAME]
media_type=video
stream_index=2
key_frame=1
pkt_pts=6144
pkt_pts_time=0.120000
pkt_dts=6144
pkt_dts_time=0.120000
best_effort_timestamp=6144
best_effort_timestamp_time=0.120000
pkt_duration=2048
pkt_duration_time=0.040000
pkt_pos=1024806
pkt_size=30000
width=100
height=100
pix_fmt=rgb24
sample_aspect_ratio=1:1
pict_type=I
coded_picture_number=0
display_picture_number=0
interlaced_frame=0
top_field_first=0
repeat_pict=0
[/FRAME]
[STREAM]
index=0
codec_name=pcm_s16le
profile=unknown
codec_type=audio
codec_time_base=1/44100
codec_tag_string=PSD[16]
codec_tag=0x10445350
sample_fmt=s16
sample_rate=44100
channels=1
channel_layout=unknown
bits_per_sample=16
id=N/A
r_frame_rate=0/0
avg_frame_rate=0/0
time_base=1/44100
start_pts=0
start_time=0.000000
duration_ts=N/A
duration=N/A
bit_rate=705600
max_bit_rate=N/A
bits_per_raw_sample=N/A
nb_frames=N/A
nb_read_frames=6
nb_read_packets=6
DISPOSITION:default=0
DISPOSITION:dub=0
DISPOSITION:original=0
DISPOSITION:comment=0
DISPOSITION:lyrics=0
DISPOSITION:karaoke=0
DISPOSITION:forced=0
DISPOSITION:hearing_impaired=0
DISPOSITION:visual_impaired=0
DISPOSITION:clean_effects=0
DISPOSITION:attached_pic=0
DISPOSITION:timed_thumbnails=0
TAG:E=mc²
TAG:encoder=Lavc pcm_s16le
[/STREAM]
[STREAM]
index=1
codec_name=rawvideo
profile=unknown
codec_type=video
codec_time_base=1/25
codec_tag_string=RGB[24]
codec_tag=0x18424752
width=320
height=240
coded_width=320
coded_height=240
has_b_frames=0
sample_aspect_ratio=1:1
display_aspect_ratio=4:3
pix_fmt=rgb24
level=-99
color_range=N/A
color_space=unknown
color_transfer=unknown
color_primaries=unknown
chroma_location=unspecified
field_order=unknown
timecode=N/A
refs=1
id=N/A
r_frame_rate=25/1
avg_frame_rate=25/1
time_base=1/51200
start_pts=0
start_time=0.000000
duration_ts=N/A
duration=N/A
bit_rate=N/A
max_bit_rate=N/A
bits_per_raw_sample=N/A
nb_frames=N/A
nb_read_frames=4
nb_read_packets=4
DISPOSITION:default=0
DISPOSITION:dub=0
DISPOSITION:original=0
DISPOSITION:comment=0
DISPOSITION:lyrics=0
DISPOSITION:karaoke=0
DISPOSITION:forced=0
DISPOSITION:hearing_impaired=0
DISPOSITION:visual_impaired=0
DISPOSITION:clean_effects=0
DISPOSITION:attached_pic=0
DISPOSITION:timed_thumbnails=0
TAG:title=foobar
TAG:duration_ts=field-and-tags-conflict-attempt
TAG:encoder=Lavc rawvideo
[/STREAM]
[STREAM]
index=2
codec_name=rawvideo
profile=unknown
codec_type=video
codec_time_base=1/25
codec_tag_string=RGB[24]
codec_tag=0x18424752
width=100
height=100
coded_width=100
coded_height=100
has_b_frames=0
sample_aspect_ratio=1:1
display_aspect_ratio=1:1
pix_fmt=rgb24
level=-99
color_range=N/A
color_space=unknown
color_transfer=unknown
color_primaries=unknown
chroma_location=unspecified
field_order=unknown
timecode=N/A
refs=1
id=N/A
r_frame_rate=25/1
avg_frame_rate=25/1
time_base=1/51200
start_pts=0
start_time=0.000000
duration_ts=N/A
duration=N/A
bit_rate=N/A
max_bit_rate=N/A
bits_per_raw_sample=N/A
nb_frames=N/A
nb_read_frames=4
nb_read_packets=4
DISPOSITION:default=0
DISPOSITION:dub=0
DISPOSITION:original=0
DISPOSITION:comment=0
DISPOSITION:lyrics=0
DISPOSITION:karaoke=0
DISPOSITION:forced=0
DISPOSITION:hearing_impaired=0
DISPOSITION:visual_impaired=0
DISPOSITION:clean_effects=0
DISPOSITION:attached_pic=0
DISPOSITION:timed_thumbnails=0
TAG:encoder=Lavc rawvideo
[/STREAM]
[FORMAT]
filename=tests/data/ffprobe-test.nut
nb_streams=3
nb_programs=0
format_name=nut
start_time=0.000000
duration=0.120000
size=1054887
bit_rate=70325800
probe_score=100
TAG:title=ffprobe test file
TAG:comment='A comment with CSV, XML & JSON special chars': <tag value="x">
TAG:comment2=I ♥ Üñîçød€
[/FORMAT]
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Changes some global preference settings in Swift Mailer.
*
* @package Swift
* @author Chris Corbyn
*/
class Swift_Preferences
{
/** Singleton instance */
private static $_instance = null;
/** Constructor not to be used */
private function __construct()
{
}
/**
* Gets the instance of Preferences.
*
* @return Swift_Preferences
*/
public static function getInstance()
{
if (!isset(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Set the default charset used.
*
* @param string $charset
*
* @return Swift_Preferences
*/
public function setCharset($charset)
{
Swift_DependencyContainer::getInstance()
->register('properties.charset')->asValue($charset);
return $this;
}
/**
* Set the directory where temporary files can be saved.
*
* @param string $dir
*
* @return Swift_Preferences
*/
public function setTempDir($dir)
{
Swift_DependencyContainer::getInstance()
->register('tempdir')->asValue($dir);
return $this;
}
/**
* Set the type of cache to use (i.e. "disk" or "array").
*
* @param string $type
*
* @return Swift_Preferences
*/
public function setCacheType($type)
{
Swift_DependencyContainer::getInstance()
->register('cache')->asAliasOf(sprintf('cache.%s', $type));
return $this;
}
/**
* Set the QuotedPrintable dot escaper preference.
*
* @param boolean $dotEscape
*
* @return Swift_Preferences
*/
public function setQPDotEscape($dotEscape)
{
$dotEscape = !empty($dotEscape);
Swift_DependencyContainer::getInstance()
-> register('mime.qpcontentencoder')
-> asNewInstanceOf('Swift_Mime_ContentEncoder_QpContentEncoder')
-> withDependencies(array('mime.charstream', 'mime.bytecanonicalizer'))
-> addConstructorValue($dotEscape);
return $this;
}
}
| {
"pile_set_name": "Github"
} |
.model IRF740 NMOS(Level=3 Gamma=0 Delta=0 Eta=0 Theta=0 Kappa=0.2 Vmax=0 Xj=0
+ Tox=100n Uo=600 Phi=.6 Rs=8.563m Kp=20.59u W=.78 L=2u Vto=3.657
+ Rd=.3915 Rds=1.778MEG Cbd=1.419n Pb=.8 Mj=.5 Fc=.5 Cgso=1.392n
+ Cgdo=146.6p Rg=.9088 Is=17.65p N=1 Tt=570n)
* IR pid=IRF740 case=TO220
| {
"pile_set_name": "Github"
} |
<div id="sidenav">
<div class="sidenav-holder clearfix">
<!-- <div class="widget clearfix"> -->
<!-- <p>Create an account or sign in for a tailor-made video experience</p> -->
<!-- <buttun class="btn btn-primary">Sign Up / Sign In</buttun> -->
<!-- </div> -->
<!-- <div class="widget clearfix">
<a href="#">Videos you might like</a>
</div> -->
<div class="panel-group clearfix widget" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne"><span class="caret"></span> Video Categories</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in">
{include file="$style_dir/blocks/category_list.html" type='video'}
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a href="{cblink(['name'=>'photos'])}">Photos</a>
</h4>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a href="{cblink(['name'=>'collections'])}">Collections</a>
</h4>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a href="{cblink(['name'=>'groups'])}">Groups</a>
</h4>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a href="{cblink(['name'=>'channels'])}">{lang code="View Channels"}</a>
</h4>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseTwo"><span class="caret"></span> Who to Follow</a>
</h4>
</div>
<div id="collapseThree" class="panel-collapse collapse in">
<ul class="panel-body">
{$users=get_users(["order"=>"subscribers DESC","limit" =>"3"])}
{foreach $users as $user}
<li>
<div class="avatar">
<a href="{$userquery->profile_link($user)}">
<img src="{avatar details=$user size='58x58'}">
</a>
</div>
<span class="user-name">
<a href="{$userquery->profile_link($user)}">{$user.username}</a>
</span>
</li>
{/foreach}
</ul>
</div>
</div>
</div>
</div>
</div> | {
"pile_set_name": "Github"
} |
<?php
class LtDbConnectionAdapterPdo implements LtDbConnectionAdapter
{
public function connect($connConf)
{
// $option = array(PDO::ATTR_PERSISTENT => true);
if (isset($connConf['pconnect']) && true == $connConf['pconnect'])
{
$option[PDO::ATTR_PERSISTENT] = true;
}
else
{
$option[PDO::ATTR_PERSISTENT] = false;
}
switch ($connConf['adapter'])
{
case "pdo_mysql":
$dsn = "mysql:host={$connConf['host']};dbname={$connConf['dbname']}";
break;
case "pdo_sqlite":
$connConf["host"] = rtrim($connConf["host"], '\\/') . DIRECTORY_SEPARATOR;
if (!is_dir($connConf["host"]))
{
if (!@mkdir($connConf["host"], 0777, true))
{
trigger_error("Can not create {$connConf['host']}");
}
}
$dsn = "{$connConf['sqlite_version']}:{$connConf['host']}{$connConf['dbname']}";
break;
case "pdo_pgsql":
$dsn = "pgsql:host={$connConf['host']} port={$connConf['port']} dbname={$connConf['dbname']} user={$connConf['username']} password={$connConf['password']}";
break;
case "odbc":
$dsn = "odbc:" . $connConf["host"];
break;
}
return new PDO($dsn, $connConf['username'], $connConf['password'], $option);
}
public function exec($sql, $connResource)
{
return $connResource->exec($sql);
}
public function query($sql, $connResource)
{
return $connResource->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}
/**
*
* @todo pgsql support
*/
public function lastInsertId($connResource)
{
return $connResource->lastInsertId();
}
public function escape($sql, $connResource)
{
// quote返回值带最前面和最后面的单引号, 这里去掉, DbHandler中加
return trim($connResource->quote($sql), "'");
}
}
| {
"pile_set_name": "Github"
} |
<template>
<default-setting :setting="setting" :errors="errors || []">
<template slot="setting">
<input
type="number"
:id="setting.key"
:value="setting.value"
@input="$emit('update', {
key: setting.key,
value: Number($event.target.value),
})"
:placeholder="setting.placeholder"
class="w-full form-control form-input form-input-bordered"
/>
</template>
</default-setting>
</template>
<script>
import DefaultSetting from './DefaultSetting'
export default {
components: { DefaultSetting },
props: {
setting: Object,
errors: Array,
},
}
</script>
| {
"pile_set_name": "Github"
} |
.. _quickstart-demos-ccloud:
On-Prem Kafka to Cloud
======================
This |ccloud| demo showcases a hybrid Kafka cluster: one cluster is a self-managed Kafka cluster running locally, the other is a |ccloud| cluster.
The use case is "Bridge to Cloud" as customers migrate from on premises to cloud.
.. figure:: images/services-in-cloud.jpg
:alt: image
========
Overview
========
The major components of the demo are:
* Two Kafka clusters: one cluster is a self-managed cluster running locally, the other is a |ccloud| cluster.
* |c3|: manages and monitors the deployment. Use it for topic inspection, viewing the schema, viewing and creating ksqlDB queries, streams monitoring, and more.
* ksqlDB: Confluent Cloud ksqlDB running queries on input topics `users` and `pageviews` in |ccloud|.
* Two Kafka Connect clusters: one cluster connects to the local self-managed cluster and one connects to the |ccloud| cluster. Both Connect worker processes themselves are running locally.
* One instance of `kafka-connect-datagen`: a source connector that produces mock data to prepopulate the topic `pageviews` locally
* One instance of `kafka-connect-datagen`: a source connector that produces mock data to prepopulate the topic `users` in the |ccloud| cluster
* Confluent Replicator: copies the topic `pageviews` from the local cluster to the |ccloud| cluster
* |sr-long|: the demo runs with Confluent Cloud Schema Registry, and the Kafka data is written in Avro format.
.. note:: This is a demo environment and has many services running on one host. Do not use this demo in production, and
do not use Confluent CLI in production. This is meant exclusively to easily demo the |cp| and |ccloud|.
.. include:: includes/ccloud-promo-code.rst
=======
Caution
=======
This demo uses real |ccloud| resources.
To avoid unexpected charges, carefully evaluate the cost of resources before launching the demo and ensure all resources are destroyed after you are done running it.
=============
Prerequisites
=============
#. An initialized `Confluent Cloud cluster <https://confluent.cloud/>`__
#. Local install of `Confluent Cloud CLI <https://docs.confluent.io/current/quickstart/cloud-quickstart/index.html#step-2-install-the-ccloud-cli>`__ v1.7.0 or later
#. `Download <https://www.confluent.io/download/>`__ |cp| if using the local install (not required for Docker)
#. .. include:: ../../docs/includes/demo-validation-env.rst
========
Run demo
========
Setup
-----
#. This demo creates a new |ccloud| environment with required resources to run this demo. As a reminder, this demo uses real |ccloud| resources and you may incur charges.
#. Clone the `examples GitHub repository <https://github.com/confluentinc/examples>`__ and check out the :litwithvars:`|release|-post` branch.
.. codewithvars:: bash
git clone https://github.com/confluentinc/examples
cd examples
git checkout |release|-post
#. Change directory to the |ccloud| demo.
.. sourcecode:: bash
cd ccloud
Run
---
#. Log in to |ccloud| with the command ``ccloud login``, and use your |ccloud| username and password. The ``--save`` argument saves your |ccloud| user login credentials or refresh token (in the case of SSO) to the local ``netrc`` file.
.. code:: shell
ccloud login --save
#. Start the entire demo by running a single command. You have two choices: using Docker Compose or a |cp| local install. This will take several minutes to complete as it creates new resources in |ccloud|.
.. sourcecode:: bash
# For Docker Compose
./start-docker.sh
.. sourcecode:: bash
# For Confluent Platform local
./start.sh
#. As part of this script run, it creates a new |ccloud| stack of fully managed resources and generates a local configuration file with all connection information, cluster IDs, and credentials, which is useful for other demos/automation. View this local configuration file, where ``SERVICE ACCOUNT ID`` is auto-generated by the script.
.. sourcecode:: bash
cat stack-configs/java-service-account-<SERVICE ACCOUNT ID>.config
Your output should resemble:
::
# ------------------------------
# Confluent Cloud connection information for demo purposes only
# Do not use in production
# ------------------------------
# ENVIRONMENT ID: <ENVIRONMENT ID>
# SERVICE ACCOUNT ID: <SERVICE ACCOUNT ID>
# KAFKA CLUSTER ID: <KAFKA CLUSTER ID>
# SCHEMA REGISTRY CLUSTER ID: <SCHEMA REGISTRY CLUSTER ID>
# KSQLDB APP ID: <KSQLDB APP ID>
# ------------------------------
ssl.endpoint.identification.algorithm=https
security.protocol=SASL_SSL
sasl.mechanism=PLAIN
bootstrap.servers=<BROKER ENDPOINT>
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username\="<API KEY>" password\="<API SECRET>";
basic.auth.credentials.source=USER_INFO
schema.registry.basic.auth.user.info=<SR API KEY>:<SR API SECRET>
schema.registry.url=https://<SR ENDPOINT>
ksql.endpoint=<KSQLDB ENDPOINT>
ksql.basic.auth.user.info=<KSQLDB API KEY>:<KSQLDB API SECRET>
#. Log into the Confluent Cloud UI at http://confluent.cloud .
#. Use Google Chrome to navigate to |c3| GUI at http://localhost:9021 .
========
Playbook
========
|ccloud| CLI
-------------------
#. Validate you can list topics in your cluster.
.. sourcecode:: bash
ccloud kafka topic list
#. View the ACLs associated to the service account <SERVICE ACCOUNT ID> that was created for this demo at the start. The resource name corresponds to the respective cluster, Kafka topic name, or consumer group name. Note: in production, you would not use the wildcard ``*``, this is included just for demo purposes.
.. sourcecode:: bash
ccloud kafka acl list --service-account <SERVICE ACCOUNT ID>
For example, if the service account ID were 69995, your output would resemble:
::
ServiceAccountId | Permission | Operation | Resource | Name | Type
+------------------+------------+------------------+----------+-----------------------+----------+
User:69995 | ALLOW | WRITE | TOPIC | _confluent-monitoring | PREFIXED
User:69995 | ALLOW | READ | TOPIC | _confluent-monitoring | PREFIXED
User:69995 | ALLOW | READ | TOPIC | _confluent-command | PREFIXED
User:69995 | ALLOW | WRITE | TOPIC | _confluent-command | PREFIXED
User:69995 | ALLOW | READ | TOPIC | _confluent | PREFIXED
User:69995 | ALLOW | CREATE | TOPIC | _confluent | PREFIXED
User:69995 | ALLOW | WRITE | TOPIC | _confluent | PREFIXED
User:69995 | ALLOW | CREATE | GROUP | * | LITERAL
User:69995 | ALLOW | WRITE | GROUP | * | LITERAL
User:69995 | ALLOW | READ | GROUP | * | LITERAL
User:69995 | ALLOW | WRITE | TOPIC | connect-demo-statuses | PREFIXED
User:69995 | ALLOW | READ | TOPIC | connect-demo-statuses | PREFIXED
User:69995 | ALLOW | READ | TOPIC | connect-demo-offsets | PREFIXED
User:69995 | ALLOW | WRITE | TOPIC | connect-demo-offsets | PREFIXED
User:69995 | ALLOW | DESCRIBE | TOPIC | pageviews | LITERAL
User:69995 | ALLOW | DESCRIBE_CONFIGS | TOPIC | pageviews | LITERAL
User:69995 | ALLOW | CREATE | TOPIC | pageviews | LITERAL
User:69995 | ALLOW | ALTER_CONFIGS | TOPIC | pageviews | LITERAL
User:69995 | ALLOW | READ | TOPIC | pageviews | LITERAL
User:69995 | ALLOW | WRITE | TOPIC | pageviews | LITERAL
User:69995 | ALLOW | WRITE | TOPIC | users | LITERAL
User:69995 | ALLOW | WRITE | TOPIC | * | LITERAL
User:69995 | ALLOW | CREATE | TOPIC | * | LITERAL
User:69995 | ALLOW | READ | TOPIC | * | LITERAL
User:69995 | ALLOW | DESCRIBE | TOPIC | * | LITERAL
User:69995 | ALLOW | DESCRIBE_CONFIGS | TOPIC | * | LITERAL
User:69995 | ALLOW | READ | GROUP | connect-cloud | LITERAL
User:69995 | ALLOW | DESCRIBE | CLUSTER | kafka-cluster | LITERAL
User:69995 | ALLOW | CREATE | CLUSTER | kafka-cluster | LITERAL
User:69995 | ALLOW | READ | GROUP | connect-replicator | LITERAL
User:69995 | ALLOW | WRITE | TOPIC | connect-demo-configs | PREFIXED
User:69995 | ALLOW | READ | TOPIC | connect-demo-configs | PREFIXED
User:69995 | ALLOW | WRITE | GROUP | _confluent | PREFIXED
User:69995 | ALLOW | READ | GROUP | _confluent | PREFIXED
User:69995 | ALLOW | CREATE | GROUP | _confluent | PREFIXED
kafka-connect-datagen
---------------------
#. In the demo, view :devx-examples:`this code|ccloud/connectors/submit_datagen_pageviews_config.sh` which automatically loads the ``kafka-connect-datagen`` connector for the Kafka topic ``pageviews`` into the ``connect-local`` cluster, which is later replicated by |crep| into |ccloud| (more on |crep| later).
.. literalinclude:: ../connectors/submit_datagen_pageviews_config.sh
:lines: 13-29
#. In |c3|, view the data in the ``pageviews`` topic in the local cluster.
.. figure:: images/topic_pageviews.png
:alt: image
#. In the demo, view :devx-examples:`this code|ccloud/connectors/submit_datagen_users_config.sh` which automatically loads the ``kafka-connect-datagen`` connector for the Kafka topic ``users`` into the ``connect-cloud`` cluster.
.. literalinclude:: ../connectors/submit_datagen_users_config.sh
:lines: 13-29
#. In |c3|, view the data in the ``users`` topic in |ccloud|.
.. figure:: images/topic_users.png
:alt: image
ksqlDB
------
#. In the demo, the Confluent Cloud ksqlDB queries are created from :devx-examples:`statements.sql|ccloud/statements.sql` (for ksqlDB version 0.10.0) using the REST API in :devx-examples:`this code|ccloud/create_ksqldb_app.sh` with proper credentials.
.. literalinclude:: ../create_ksqldb_app.sh
:lines: 31-52
#. From the Confluent Cloud UI, view the ksqlDB application flow.
.. figure:: images/ksqlDB_flow.png
:alt: image
#. Click on any stream to view its messages and its schema.
.. figure:: images/ksqlDB_stream_messages.png
:alt: image
Confluent Replicator
--------------------
Confluent Replicator copies data from a source Kafka cluster to a destination Kafka cluster.
In this demo, the source cluster is a local install of a self-managed cluster, and the destination cluster is |ccloud|.
|crep| is replicating a Kafka topic ``pageviews`` from the local install to |ccloud|, and it is running with Confluent Monitoring Interceptors for |c3| streams monitoring.
#. In the demo, view :devx-examples:`this code|ccloud/connectors/submit_replicator_docker_config.sh` which automatically loads the |crep| connector into the ``connect-cloud`` cluster. Notice that |crep| configuration sets ``confluent.topic.replication.factor=3``, which is required because the source cluster has ``replication.factor=1`` and |ccloud| requires ``replication.factor=3``:
.. literalinclude:: ../connectors/submit_replicator_docker_config.sh
:lines: 13-41
:emphasize-lines: 8
#. |c3| is configured to manage a locally running connect cluster called ``connect-cloud`` running on port 8087, which is running the ``kafka-connect-datagen`` (for the Kafka topic ``users``) connector and the |crep| connector. From the |c3| UI, view the connect clusters.
.. figure:: images/c3_clusters.png
:alt: image
#. In the demo, view :devx-examples:`this code|ccloud/docker-compose.yml` to see the ``connect-cloud`` connect cluster which is connected to |ccloud|.
.. literalinclude:: ../docker-compose.yml
:lines: 168-237
#. Click on `replicator` to view the |crep| configuration. Notice that it is replicating the topic ``pageviews`` from the local Kafka cluster to |ccloud|.
.. figure:: images/c3_replicator_config.png
:alt: image
#. Validate that messages are replicated from the local ``pageviews`` topic to the Confluent Cloud ``pageviews`` topic. From the Confluent Cloud UI, view messages in this topic.
.. figure:: images/cloud_pageviews_messages.png
:alt: image
#. View the Consumer Lag for |crep| from the |ccloud| UI. In ``Consumers`` view, click on ``connect-replicator``. Your output should resemble:
.. figure:: images/replicator_consumer_lag.png
:alt: image
Confluent Schema Registry
-------------------------
The connectors used in this demo are configured to automatically write Avro-formatted data, leveraging the |ccloud| |sr|.
#. View all the |sr| subjects.
.. sourcecode:: bash
# Confluent Cloud Schema Registry
curl -u <SR API KEY>:<SR API SECRET> https://<SR ENDPOINT>/subjects
#. From the Confluent Cloud UI, view the schema for the ``pageviews`` topic. The topic value is using a Schema registered with |sr| (the topic key is just a String).
.. figure:: images/topic_schema.png
:alt: image
#. If you need to migrate schemas from on-prem |sr| to |ccloud| |sr|, follow this :ref:`step-by-step guide <schemaregistry_migrate>`. Refer to the file :devx-examples:`submit_replicator_schema_migration_config.sh|ccloud/connectors/submit_replicator_schema_migration_config.sh#L13-L33>` for an example of a working Replicator configuration for schema migration.
===============================
Confluent Cloud Configurations
===============================
#. View the the template delta configuration for Confluent Platform components and clients to connect to Confluent Cloud:
.. sourcecode:: bash
ls template_delta_configs/
#. Generate the per-component delta configuration parameters, automatically derived from your Confluent Cloud configuration file:
.. sourcecode:: bash
./ccloud-generate-cp-configs.sh
#. If you ran this demo as `start-docker.sh`, configurations for all the |cp| components are available in the :devx-examples:`docker-compose.yml file|ccloud/docker-compose.yml`.
::
# For Docker Compose
cat docker-compose.yml
#. If you ran this demo as `start.sh` which uses Confluent CLI, it saves all configuration files and log files in the respective component subfolders in the current Confluent CLI temp directory (requires demo to be actively running):
.. sourcecode:: bash
# For Confluent Platform local install using Confluent CLI
ls `confluent local current | tail -1`
========================
Troubleshooting the demo
========================
#. If you ran with Docker, then run `docker-compose logs | grep ERROR`.
#. To view log files, look in the current Confluent CLI temp directory (requires demo to be actively running):
.. sourcecode:: bash
# View all files
ls `confluent local current | tail -1`
# View log file per service, e.g. for the Kafka broker
confluent local log kafka
=========
Stop Demo
=========
#. Stop the demo, destroy all resources in |ccloud| and local components.
.. sourcecode:: bash
# For Docker Compose
./stop-docker.sh
.. sourcecode:: bash
# For Confluent Platform local install using Confluent CLI
./stop.sh
#. Always verify that resources in |ccloud| have been destroyed.
====================
Additional Resources
====================
- To find additional |ccloud| demos, see :ref:`Confluent Cloud Demos Overview<ccloud-demos-overview>`.
| {
"pile_set_name": "Github"
} |
<div class="flex-header">
<div class="bhima-title">
<ol class="headercrumb">
<li class="static" translate>TREE.ADMIN</li>
<li class="title" translate>TREE.WEEKEND_CONFIGURATION</li>
</ol>
<div class="toolbar">
<div class="toolbar-item">
<button class="btn btn-default text-capitalize" ui-sref="configurationWeekend.create" data-method="create">
<span class="fa fa-plus"></span>
<span translate class="hidden-xs">FORM.BUTTONS.ADD_WEEKEND_CONFIGURATION</span>
</button>
</div>
<bh-filter-toggle
on-toggle="ConfigurationCtrl.toggleFilter()">
</bh-filter-toggle>
</div>
</div>
</div>
<!-- main content -->
<div class="flex-content">
<div class="container-fluid">
<div
id="weekend-config-grid"
class="grid-full-height"
ui-grid="ConfigurationCtrl.gridOptions"
ui-grid-auto-resize
ui-grid-resize-columns>
<bh-grid-loading-indicator
loading-state="ConfigurationCtrl.loading"
empty-state="ConfigurationCtrl.gridOptions.data.length === 0"
error-state="ConfigurationCtrl.hasError">
</bh-grid-loading-indicator>
</div>
</div>
</div>
| {
"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 (1.8.0_66) on Wed Jan 06 05:36:58 EST 2016 -->
<title>Uses of Interface wordcram.WordColorer (WordCram API)</title>
<meta name="date" content="2016-01-06">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface wordcram.WordColorer (WordCram API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<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><a href="../../wordcram/WordColorer.html" title="interface in wordcram">Class</a></li>
<li class="navBarCell1Rev">Use</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 class="aboutLanguage">WordCram 1.0.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?wordcram/class-use/WordColorer.html" target="_top">Frames</a></li>
<li><a href="WordColorer.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>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface wordcram.WordColorer" class="title">Uses of Interface<br>wordcram.WordColorer</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../wordcram/WordColorer.html" title="interface in wordcram">WordColorer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#wordcram">wordcram</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="wordcram">
<!-- -->
</a>
<h3>Uses of <a href="../../wordcram/WordColorer.html" title="interface in wordcram">WordColorer</a> in <a href="../../wordcram/package-summary.html">wordcram</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../wordcram/package-summary.html">wordcram</a> that return <a href="../../wordcram/WordColorer.html" title="interface in wordcram">WordColorer</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../wordcram/WordColorer.html" title="interface in wordcram">WordColorer</a></code></td>
<td class="colLast"><span class="typeNameLabel">Colorers.</span><code><span class="memberNameLink"><a href="../../wordcram/Colorers.html#alwaysUse-int-">alwaysUse</a></span>(int color)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../wordcram/WordColorer.html" title="interface in wordcram">WordColorer</a></code></td>
<td class="colLast"><span class="typeNameLabel">Colorers.</span><code><span class="memberNameLink"><a href="../../wordcram/Colorers.html#pickFrom-int...-">pickFrom</a></span>(int... colors)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../wordcram/WordColorer.html" title="interface in wordcram">WordColorer</a></code></td>
<td class="colLast"><span class="typeNameLabel">Colorers.</span><code><span class="memberNameLink"><a href="../../wordcram/Colorers.html#twoHuesRandomSats-processing.core.PApplet-">twoHuesRandomSats</a></span>(processing.core.PApplet host)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../wordcram/WordColorer.html" title="interface in wordcram">WordColorer</a></code></td>
<td class="colLast"><span class="typeNameLabel">Colorers.</span><code><span class="memberNameLink"><a href="../../wordcram/Colorers.html#twoHuesRandomSatsOnWhite-processing.core.PApplet-">twoHuesRandomSatsOnWhite</a></span>(processing.core.PApplet host)</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../wordcram/package-summary.html">wordcram</a> with parameters of type <a href="../../wordcram/WordColorer.html" title="interface in wordcram">WordColorer</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../wordcram/WordCram.html" title="class in wordcram">WordCram</a></code></td>
<td class="colLast"><span class="typeNameLabel">WordCram.</span><code><span class="memberNameLink"><a href="../../wordcram/WordCram.html#withColorer-wordcram.WordColorer-">withColorer</a></span>(<a href="../../wordcram/WordColorer.html" title="interface in wordcram">WordColorer</a> colorer)</code>
<div class="block">Use the given WordColorer to pick colors for each word.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<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><a href="../../wordcram/WordColorer.html" title="interface in wordcram">Class</a></li>
<li class="navBarCell1Rev">Use</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 class="aboutLanguage">WordCram 1.0.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?wordcram/class-use/WordColorer.html" target="_top">Frames</a></li>
<li><a href="WordColorer.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>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"pile_set_name": "Github"
} |
CONTAINER BJS_Standard_Material
{
NAME BJS_Standard_Material;
GROUP BJS_MATERIAL_SETTINGS
{
GROUP
{
STRING BJS_MATERIAL_NAME { }
}
SEPARATOR { LINE; }
STATICTEXT { NAME BJS_MATERIAL_COLOR_SECTION; }
GROUP
{
LAYOUTGROUP; COLUMNS 2;
GROUP
{
COLOR BJS_MATERIAL_COLOR_AMBIENT { PARENTCOLLAPSE; }
}
GROUP
{
COLOR BJS_MATERIAL_COLOR_DIFFUSE { PARENTCOLLAPSE; }
}
}
GROUP
{
LAYOUTGROUP; COLUMNS 2;
GROUP
{
COLOR BJS_MATERIAL_COLOR_EMISSIVE { PARENTCOLLAPSE; }
}
GROUP
{
COLOR BJS_MATERIAL_COLOR_SPECULAR { PARENTCOLLAPSE; }
}
}
}
} | {
"pile_set_name": "Github"
} |
# AUTOMATICALLY GENERATED
# DO NOT EDIT THIS FILE DIRECTLY, USE /templates/Gemfile.erb
source "https://rubygems.org"
gem "fluentd", "1.11.2"
gem "oj", "3.8.1"
gem "fluent-plugin-multi-format-parser", "~> 1.0.0"
gem "fluent-plugin-concat", "~> 2.4.0"
gem "fluent-plugin-grok-parser", "~> 2.6.0"
gem "fluent-plugin-prometheus", "~> 1.6.1"
gem 'fluent-plugin-json-in-json-2', ">= 1.0.2"
gem "fluent-plugin-record-modifier", "~> 2.0.0"
gem "fluent-plugin-detect-exceptions", "~> 0.0.12"
gem "fluent-plugin-rewrite-tag-filter", "~> 2.2.0"
gem "fluent-plugin-papertrail", "~> 0.2.6"
gem "fluent-plugin-kubernetes_metadata_filter", "~> 2.3.0"
gem "ffi"
gem "fluent-plugin-systemd", "~> 1.0.1"
| {
"pile_set_name": "Github"
} |
/*
* 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.
*/
package org.apache.drill.exec.expr.fn.impl.conv;
import org.apache.drill.exec.expr.DrillSimpleFunc;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.annotations.FunctionTemplate.FunctionScope;
import org.apache.drill.exec.expr.annotations.FunctionTemplate.NullHandling;
import org.apache.drill.exec.expr.annotations.Output;
import org.apache.drill.exec.expr.annotations.Param;
import org.apache.drill.exec.expr.holders.IntHolder;
import org.apache.drill.exec.expr.holders.VarBinaryHolder;
@FunctionTemplate(name = "convert_fromINT", scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL)
public class IntConvertFrom implements DrillSimpleFunc {
@Param VarBinaryHolder in;
@Output IntHolder out;
@Override
public void setup() { }
@Override
public void eval() {
org.apache.drill.exec.util.ByteBufUtil.checkBufferLength(in.buffer, in.start, in.end, 4);
in.buffer.readerIndex(in.start);
out.value = in.buffer.readInt();
}
}
| {
"pile_set_name": "Github"
} |
// Copyright Oliver Kowalke 2009.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_COROUTINES_COROUTINE_H
#define BOOST_COROUTINES_COROUTINE_H
#include <boost/coroutine/asymmetric_coroutine.hpp>
#include <boost/coroutine/symmetric_coroutine.hpp>
#endif // BOOST_COROUTINES_COROUTINE_H
| {
"pile_set_name": "Github"
} |
ij> --
-- 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.
--
-- tests for constant expression evaluation
autocommit off;
ij> -- create and populate a table
create table t1(c1 int);
0 rows inserted/updated/deleted
ij> insert into t1 values 1, 2, 3;
3 rows inserted/updated/deleted
ij> -- false constant expressions
select * from t1 where 1 <> 1;
C1
-----------
ij> select * from t1 where 1 = 1 and 1 = 0;
C1
-----------
ij> select * from t1 where 1 = (2 + 3 - 2);
C1
-----------
ij> select * from t1 where (case when 1 = 1 then 0 else 1 end) = 1;
C1
-----------
ij> select * from t1 where 1 in (2, 3, 4);
C1
-----------
ij> select * from t1 where 1 between 2 and 3;
C1
-----------
ij> prepare p1 as 'select * from t1 where ? = 1';
ij> prepare p2 as 'select * from t1 where cast(? as int) = 1';
ij> execute p1 using 'values 0';
C1
-----------
ij> execute p2 using 'values 0';
C1
-----------
ij> -- true constant expressions
select * from t1 where 1 = 1;
C1
-----------
1
2
3
ij> select * from t1 where 1 = 0 or 1 = 1;
C1
-----------
1
2
3
ij> select * from t1 where 1 + 2 = (2 + 3 - 2);
C1
-----------
1
2
3
ij> select * from t1 where (case when 1 = 1 then 1 else 0 end) = 1;
C1
-----------
1
2
3
ij> select * from t1 where 1 in (2, 3, 4, 4, 3, 2, 1);
C1
-----------
1
2
3
ij> select * from t1 where 1 + 1 between 0 and 3;
C1
-----------
1
2
3
ij> execute p1 using 'values 1';
C1
-----------
1
2
3
ij> execute p2 using 'values 1';
C1
-----------
1
2
3
ij> -- clean up
drop table t1;
0 rows inserted/updated/deleted
ij>
| {
"pile_set_name": "Github"
} |
/*
* XPath/XSLPattern query result node list implementation
*
* Copyright 2005 Mike McCormack
* Copyright 2007 Mikolaj Zalewski
* Copyright 2010 Adam Martinson for CodeWeavers
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#define COBJMACROS
#include "config.h"
#include <stdarg.h>
#ifdef HAVE_LIBXML2
# include <libxml/parser.h>
# include <libxml/xmlerror.h>
# include <libxml/xpath.h>
# include <libxml/xpathInternals.h>
#endif
#include "windef.h"
#include "winbase.h"
#include "winuser.h"
#include "ole2.h"
#include "msxml6.h"
#include "msxml2did.h"
#include "msxml_private.h"
#include "wine/debug.h"
/* This file implements the object returned by a XPath query. Note that this is
* not the IXMLDOMNodeList returned by childNodes - it's implemented in nodelist.c.
* They are different because the list returned by XPath queries:
* - is static - gives the results for the XML tree as it existed during the
* execution of the query
* - supports IXMLDOMSelection
*
*/
#ifdef HAVE_LIBXML2
WINE_DEFAULT_DEBUG_CHANNEL(msxml);
int registerNamespaces(xmlXPathContextPtr ctxt);
xmlChar* XSLPattern_to_XPath(xmlXPathContextPtr ctxt, xmlChar const* xslpat_str);
typedef struct
{
IEnumVARIANT IEnumVARIANT_iface;
LONG ref;
IUnknown *outer;
BOOL own;
LONG pos;
const struct enumvariant_funcs *funcs;
} enumvariant;
typedef struct
{
DispatchEx dispex;
IXMLDOMSelection IXMLDOMSelection_iface;
LONG ref;
xmlNodePtr node;
xmlXPathObjectPtr result;
int resultPos;
IEnumVARIANT *enumvariant;
} domselection;
static HRESULT selection_get_item(IUnknown *iface, LONG index, VARIANT* item)
{
V_VT(item) = VT_DISPATCH;
return IXMLDOMSelection_get_item((IXMLDOMSelection*)iface, index, (IXMLDOMNode**)&V_DISPATCH(item));
}
static HRESULT selection_next(IUnknown *iface)
{
IXMLDOMNode *node;
HRESULT hr = IXMLDOMSelection_nextNode((IXMLDOMSelection*)iface, &node);
if (hr == S_OK) IXMLDOMNode_Release(node);
return hr;
}
static const struct enumvariant_funcs selection_enumvariant = {
selection_get_item,
selection_next
};
static inline domselection *impl_from_IXMLDOMSelection( IXMLDOMSelection *iface )
{
return CONTAINING_RECORD(iface, domselection, IXMLDOMSelection_iface);
}
static inline enumvariant *impl_from_IEnumVARIANT( IEnumVARIANT *iface )
{
return CONTAINING_RECORD(iface, enumvariant, IEnumVARIANT_iface);
}
static HRESULT WINAPI domselection_QueryInterface(
IXMLDOMSelection *iface,
REFIID riid,
void** ppvObject )
{
domselection *This = impl_from_IXMLDOMSelection( iface );
TRACE("(%p)->(%s %p)\n", iface, debugstr_guid(riid), ppvObject);
if(!ppvObject)
return E_INVALIDARG;
if ( IsEqualGUID( riid, &IID_IUnknown ) ||
IsEqualGUID( riid, &IID_IXMLDOMNodeList ) ||
IsEqualGUID( riid, &IID_IXMLDOMSelection ))
{
*ppvObject = &This->IXMLDOMSelection_iface;
}
else if (IsEqualGUID( riid, &IID_IEnumVARIANT ))
{
if (!This->enumvariant)
{
HRESULT hr = create_enumvariant((IUnknown*)iface, FALSE, &selection_enumvariant, &This->enumvariant);
if (FAILED(hr)) return hr;
}
return IEnumVARIANT_QueryInterface(This->enumvariant, &IID_IEnumVARIANT, ppvObject);
}
else if (dispex_query_interface(&This->dispex, riid, ppvObject))
{
return *ppvObject ? S_OK : E_NOINTERFACE;
}
else
{
TRACE("interface %s not implemented\n", debugstr_guid(riid));
*ppvObject = NULL;
return E_NOINTERFACE;
}
IXMLDOMSelection_AddRef( iface );
return S_OK;
}
static ULONG WINAPI domselection_AddRef(
IXMLDOMSelection *iface )
{
domselection *This = impl_from_IXMLDOMSelection( iface );
ULONG ref = InterlockedIncrement( &This->ref );
TRACE("(%p)->(%d)\n", This, ref);
return ref;
}
static ULONG WINAPI domselection_Release(
IXMLDOMSelection *iface )
{
domselection *This = impl_from_IXMLDOMSelection( iface );
ULONG ref = InterlockedDecrement(&This->ref);
TRACE("(%p)->(%d)\n", This, ref);
if ( ref == 0 )
{
xmlXPathFreeObject(This->result);
xmldoc_release(This->node->doc);
if (This->enumvariant) IEnumVARIANT_Release(This->enumvariant);
heap_free(This);
}
return ref;
}
static HRESULT WINAPI domselection_GetTypeInfoCount(
IXMLDOMSelection *iface,
UINT* pctinfo )
{
domselection *This = impl_from_IXMLDOMSelection( iface );
return IDispatchEx_GetTypeInfoCount(&This->dispex.IDispatchEx_iface, pctinfo);
}
static HRESULT WINAPI domselection_GetTypeInfo(
IXMLDOMSelection *iface,
UINT iTInfo,
LCID lcid,
ITypeInfo** ppTInfo )
{
domselection *This = impl_from_IXMLDOMSelection( iface );
return IDispatchEx_GetTypeInfo(&This->dispex.IDispatchEx_iface,
iTInfo, lcid, ppTInfo);
}
static HRESULT WINAPI domselection_GetIDsOfNames(
IXMLDOMSelection *iface,
REFIID riid,
LPOLESTR* rgszNames,
UINT cNames,
LCID lcid,
DISPID* rgDispId )
{
domselection *This = impl_from_IXMLDOMSelection( iface );
return IDispatchEx_GetIDsOfNames(&This->dispex.IDispatchEx_iface,
riid, rgszNames, cNames, lcid, rgDispId);
}
static HRESULT WINAPI domselection_Invoke(
IXMLDOMSelection *iface,
DISPID dispIdMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS* pDispParams,
VARIANT* pVarResult,
EXCEPINFO* pExcepInfo,
UINT* puArgErr )
{
domselection *This = impl_from_IXMLDOMSelection( iface );
return IDispatchEx_Invoke(&This->dispex.IDispatchEx_iface,
dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
static HRESULT WINAPI domselection_get_item(
IXMLDOMSelection* iface,
LONG index,
IXMLDOMNode** listItem)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
TRACE("(%p)->(%d %p)\n", This, index, listItem);
if(!listItem)
return E_INVALIDARG;
*listItem = NULL;
if (index < 0 || index >= xmlXPathNodeSetGetLength(This->result->nodesetval))
return S_FALSE;
*listItem = create_node(xmlXPathNodeSetItem(This->result->nodesetval, index));
This->resultPos = index + 1;
return S_OK;
}
static HRESULT WINAPI domselection_get_length(
IXMLDOMSelection* iface,
LONG* listLength)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
TRACE("(%p)->(%p)\n", This, listLength);
if(!listLength)
return E_INVALIDARG;
*listLength = xmlXPathNodeSetGetLength(This->result->nodesetval);
return S_OK;
}
static HRESULT WINAPI domselection_nextNode(
IXMLDOMSelection* iface,
IXMLDOMNode** nextItem)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
TRACE("(%p)->(%p)\n", This, nextItem );
if(!nextItem)
return E_INVALIDARG;
*nextItem = NULL;
if (This->resultPos >= xmlXPathNodeSetGetLength(This->result->nodesetval))
return S_FALSE;
*nextItem = create_node(xmlXPathNodeSetItem(This->result->nodesetval, This->resultPos));
This->resultPos++;
return S_OK;
}
static HRESULT WINAPI domselection_reset(
IXMLDOMSelection* iface)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
TRACE("%p\n", This);
This->resultPos = 0;
return S_OK;
}
static HRESULT WINAPI domselection_get__newEnum(
IXMLDOMSelection* iface,
IUnknown** enumv)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
TRACE("(%p)->(%p)\n", This, enumv);
return create_enumvariant((IUnknown*)iface, TRUE, &selection_enumvariant, (IEnumVARIANT**)enumv);
}
static HRESULT WINAPI domselection_get_expr(
IXMLDOMSelection* iface,
BSTR *p)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI domselection_put_expr(
IXMLDOMSelection* iface,
BSTR p)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
FIXME("(%p)->(%s)\n", This, debugstr_w(p));
return E_NOTIMPL;
}
static HRESULT WINAPI domselection_get_context(
IXMLDOMSelection* iface,
IXMLDOMNode **node)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
FIXME("(%p)->(%p)\n", This, node);
return E_NOTIMPL;
}
static HRESULT WINAPI domselection_putref_context(
IXMLDOMSelection* iface,
IXMLDOMNode *node)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
FIXME("(%p)->(%p)\n", This, node);
return E_NOTIMPL;
}
static HRESULT WINAPI domselection_peekNode(
IXMLDOMSelection* iface,
IXMLDOMNode **node)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
FIXME("(%p)->(%p)\n", This, node);
return E_NOTIMPL;
}
static HRESULT WINAPI domselection_matches(
IXMLDOMSelection* iface,
IXMLDOMNode *node,
IXMLDOMNode **out_node)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
FIXME("(%p)->(%p %p)\n", This, node, out_node);
return E_NOTIMPL;
}
static HRESULT WINAPI domselection_removeNext(
IXMLDOMSelection* iface,
IXMLDOMNode **node)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
FIXME("(%p)->(%p)\n", This, node);
return E_NOTIMPL;
}
static HRESULT WINAPI domselection_removeAll(
IXMLDOMSelection* iface)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
FIXME("(%p)\n", This);
return E_NOTIMPL;
}
static HRESULT WINAPI domselection_clone(
IXMLDOMSelection* iface,
IXMLDOMSelection **node)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
FIXME("(%p)->(%p)\n", This, node);
return E_NOTIMPL;
}
static HRESULT WINAPI domselection_getProperty(
IXMLDOMSelection* iface,
BSTR p,
VARIANT *var)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
FIXME("(%p)->(%s %p)\n", This, debugstr_w(p), var);
return E_NOTIMPL;
}
static HRESULT WINAPI domselection_setProperty(
IXMLDOMSelection* iface,
BSTR p,
VARIANT var)
{
domselection *This = impl_from_IXMLDOMSelection( iface );
FIXME("(%p)->(%s %s)\n", This, debugstr_w(p), debugstr_variant(&var));
return E_NOTIMPL;
}
static const struct IXMLDOMSelectionVtbl domselection_vtbl =
{
domselection_QueryInterface,
domselection_AddRef,
domselection_Release,
domselection_GetTypeInfoCount,
domselection_GetTypeInfo,
domselection_GetIDsOfNames,
domselection_Invoke,
domselection_get_item,
domselection_get_length,
domselection_nextNode,
domselection_reset,
domselection_get__newEnum,
domselection_get_expr,
domselection_put_expr,
domselection_get_context,
domselection_putref_context,
domselection_peekNode,
domselection_matches,
domselection_removeNext,
domselection_removeAll,
domselection_clone,
domselection_getProperty,
domselection_setProperty
};
/* IEnumVARIANT support */
static HRESULT WINAPI enumvariant_QueryInterface(
IEnumVARIANT *iface,
REFIID riid,
void** ppvObject )
{
enumvariant *This = impl_from_IEnumVARIANT( iface );
TRACE("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppvObject);
*ppvObject = NULL;
if (IsEqualGUID( riid, &IID_IUnknown ))
{
if (This->own)
*ppvObject = &This->IEnumVARIANT_iface;
else
return IUnknown_QueryInterface(This->outer, riid, ppvObject);
}
else if (IsEqualGUID( riid, &IID_IEnumVARIANT ))
{
*ppvObject = &This->IEnumVARIANT_iface;
}
else
return IUnknown_QueryInterface(This->outer, riid, ppvObject);
IEnumVARIANT_AddRef( iface );
return S_OK;
}
static ULONG WINAPI enumvariant_AddRef(IEnumVARIANT *iface )
{
enumvariant *This = impl_from_IEnumVARIANT( iface );
ULONG ref = InterlockedIncrement( &This->ref );
TRACE("(%p)->(%d)\n", This, ref);
return ref;
}
static ULONG WINAPI enumvariant_Release(IEnumVARIANT *iface )
{
enumvariant *This = impl_from_IEnumVARIANT( iface );
ULONG ref = InterlockedDecrement(&This->ref);
TRACE("(%p)->(%d)\n", This, ref);
if ( ref == 0 )
{
if (This->own) IUnknown_Release(This->outer);
heap_free(This);
}
return ref;
}
static HRESULT WINAPI enumvariant_Next(
IEnumVARIANT *iface,
ULONG celt,
VARIANT *var,
ULONG *fetched)
{
enumvariant *This = impl_from_IEnumVARIANT( iface );
ULONG ret_count = 0;
TRACE("(%p)->(%u %p %p)\n", This, celt, var, fetched);
if (fetched) *fetched = 0;
if (celt && !var) return E_INVALIDARG;
for (; celt > 0; celt--, var++, This->pos++)
{
HRESULT hr = This->funcs->get_item(This->outer, This->pos, var);
if (hr != S_OK)
{
V_VT(var) = VT_EMPTY;
break;
}
ret_count++;
}
if (fetched) (*fetched)++;
/* we need to advance one step more for some reason */
if (ret_count)
{
if (This->funcs->next)
This->funcs->next(This->outer);
}
return celt == 0 ? S_OK : S_FALSE;
}
static HRESULT WINAPI enumvariant_Skip(
IEnumVARIANT *iface,
ULONG celt)
{
enumvariant *This = impl_from_IEnumVARIANT( iface );
FIXME("(%p)->(%u): stub\n", This, celt);
return E_NOTIMPL;
}
static HRESULT WINAPI enumvariant_Reset(IEnumVARIANT *iface)
{
enumvariant *This = impl_from_IEnumVARIANT( iface );
FIXME("(%p): stub\n", This);
return E_NOTIMPL;
}
static HRESULT WINAPI enumvariant_Clone(
IEnumVARIANT *iface, IEnumVARIANT **ppenum)
{
enumvariant *This = impl_from_IEnumVARIANT( iface );
FIXME("(%p)->(%p): stub\n", This, ppenum);
return E_NOTIMPL;
}
static const struct IEnumVARIANTVtbl EnumVARIANTVtbl =
{
enumvariant_QueryInterface,
enumvariant_AddRef,
enumvariant_Release,
enumvariant_Next,
enumvariant_Skip,
enumvariant_Reset,
enumvariant_Clone
};
HRESULT create_enumvariant(IUnknown *outer, BOOL own, const struct enumvariant_funcs *funcs, IEnumVARIANT **penum)
{
enumvariant *This;
This = heap_alloc(sizeof(enumvariant));
if (!This) return E_OUTOFMEMORY;
This->IEnumVARIANT_iface.lpVtbl = &EnumVARIANTVtbl;
This->ref = 0;
This->outer = outer;
This->own = own;
This->pos = 0;
This->funcs = funcs;
if (This->own)
IUnknown_AddRef(This->outer);
*penum = &This->IEnumVARIANT_iface;
IEnumVARIANT_AddRef(*penum);
return S_OK;
}
static HRESULT domselection_get_dispid(IUnknown *iface, BSTR name, DWORD flags, DISPID *dispid)
{
WCHAR *ptr;
int idx = 0;
for(ptr = name; *ptr && isdigitW(*ptr); ptr++)
idx = idx*10 + (*ptr-'0');
if(*ptr)
return DISP_E_UNKNOWNNAME;
*dispid = DISPID_DOM_COLLECTION_BASE + idx;
TRACE("ret %x\n", *dispid);
return S_OK;
}
static HRESULT domselection_invoke(IUnknown *iface, DISPID id, LCID lcid, WORD flags, DISPPARAMS *params,
VARIANT *res, EXCEPINFO *ei)
{
domselection *This = impl_from_IXMLDOMSelection( (IXMLDOMSelection*)iface );
TRACE("(%p)->(%x %x %x %p %p %p)\n", This, id, lcid, flags, params, res, ei);
V_VT(res) = VT_DISPATCH;
V_DISPATCH(res) = NULL;
if (id < DISPID_DOM_COLLECTION_BASE || id > DISPID_DOM_COLLECTION_MAX)
return DISP_E_UNKNOWNNAME;
switch(flags)
{
case INVOKE_PROPERTYGET:
{
IXMLDOMNode *disp = NULL;
IXMLDOMSelection_get_item(&This->IXMLDOMSelection_iface, id - DISPID_DOM_COLLECTION_BASE, &disp);
V_DISPATCH(res) = (IDispatch*)disp;
break;
}
default:
{
FIXME("unimplemented flags %x\n", flags);
break;
}
}
TRACE("ret %p\n", V_DISPATCH(res));
return S_OK;
}
static const dispex_static_data_vtbl_t domselection_dispex_vtbl = {
domselection_get_dispid,
domselection_invoke
};
static const tid_t domselection_iface_tids[] = {
IXMLDOMSelection_tid,
0
};
static dispex_static_data_t domselection_dispex = {
&domselection_dispex_vtbl,
IXMLDOMSelection_tid,
NULL,
domselection_iface_tids
};
#define XSLPATTERN_CHECK_ARGS(n) \
if (nargs != n) { \
FIXME("XSLPattern syntax error: Expected %i arguments, got %i\n", n, nargs); \
xmlXPathSetArityError(pctx); \
return; \
}
static void XSLPattern_index(xmlXPathParserContextPtr pctx, int nargs)
{
XSLPATTERN_CHECK_ARGS(0);
xmlXPathPositionFunction(pctx, 0);
xmlXPathReturnNumber(pctx, xmlXPathPopNumber(pctx) - 1.0);
}
static void XSLPattern_end(xmlXPathParserContextPtr pctx, int nargs)
{
double pos, last;
XSLPATTERN_CHECK_ARGS(0);
xmlXPathPositionFunction(pctx, 0);
pos = xmlXPathPopNumber(pctx);
xmlXPathLastFunction(pctx, 0);
last = xmlXPathPopNumber(pctx);
xmlXPathReturnBoolean(pctx, pos == last);
}
static void XSLPattern_nodeType(xmlXPathParserContextPtr pctx, int nargs)
{
XSLPATTERN_CHECK_ARGS(0);
xmlXPathReturnNumber(pctx, pctx->context->node->type);
}
static void XSLPattern_OP_IEq(xmlXPathParserContextPtr pctx, int nargs)
{
xmlChar *arg1, *arg2;
XSLPATTERN_CHECK_ARGS(2);
arg2 = xmlXPathPopString(pctx);
arg1 = xmlXPathPopString(pctx);
xmlXPathReturnBoolean(pctx, xmlStrcasecmp(arg1, arg2) == 0);
xmlFree(arg1);
xmlFree(arg2);
}
static void XSLPattern_OP_INEq(xmlXPathParserContextPtr pctx, int nargs)
{
xmlChar *arg1, *arg2;
XSLPATTERN_CHECK_ARGS(2);
arg2 = xmlXPathPopString(pctx);
arg1 = xmlXPathPopString(pctx);
xmlXPathReturnBoolean(pctx, xmlStrcasecmp(arg1, arg2) != 0);
xmlFree(arg1);
xmlFree(arg2);
}
static void XSLPattern_OP_ILt(xmlXPathParserContextPtr pctx, int nargs)
{
xmlChar *arg1, *arg2;
XSLPATTERN_CHECK_ARGS(2);
arg2 = xmlXPathPopString(pctx);
arg1 = xmlXPathPopString(pctx);
xmlXPathReturnBoolean(pctx, xmlStrcasecmp(arg1, arg2) < 0);
xmlFree(arg1);
xmlFree(arg2);
}
static void XSLPattern_OP_ILEq(xmlXPathParserContextPtr pctx, int nargs)
{
xmlChar *arg1, *arg2;
XSLPATTERN_CHECK_ARGS(2);
arg2 = xmlXPathPopString(pctx);
arg1 = xmlXPathPopString(pctx);
xmlXPathReturnBoolean(pctx, xmlStrcasecmp(arg1, arg2) <= 0);
xmlFree(arg1);
xmlFree(arg2);
}
static void XSLPattern_OP_IGt(xmlXPathParserContextPtr pctx, int nargs)
{
xmlChar *arg1, *arg2;
XSLPATTERN_CHECK_ARGS(2);
arg2 = xmlXPathPopString(pctx);
arg1 = xmlXPathPopString(pctx);
xmlXPathReturnBoolean(pctx, xmlStrcasecmp(arg1, arg2) > 0);
xmlFree(arg1);
xmlFree(arg2);
}
static void XSLPattern_OP_IGEq(xmlXPathParserContextPtr pctx, int nargs)
{
xmlChar *arg1, *arg2;
XSLPATTERN_CHECK_ARGS(2);
arg2 = xmlXPathPopString(pctx);
arg1 = xmlXPathPopString(pctx);
xmlXPathReturnBoolean(pctx, xmlStrcasecmp(arg1, arg2) >= 0);
xmlFree(arg1);
xmlFree(arg2);
}
static void query_serror(void* ctx, xmlErrorPtr err)
{
LIBXML2_CALLBACK_SERROR(domselection_create, err);
}
HRESULT create_selection(xmlNodePtr node, xmlChar* query, IXMLDOMNodeList **out)
{
domselection *This = heap_alloc(sizeof(domselection));
xmlXPathContextPtr ctxt = xmlXPathNewContext(node->doc);
HRESULT hr;
TRACE("(%p, %s, %p)\n", node, debugstr_a((char const*)query), out);
*out = NULL;
if (!This || !ctxt || !query)
{
xmlXPathFreeContext(ctxt);
heap_free(This);
return E_OUTOFMEMORY;
}
This->IXMLDOMSelection_iface.lpVtbl = &domselection_vtbl;
This->ref = 1;
This->resultPos = 0;
This->node = node;
This->enumvariant = NULL;
init_dispex(&This->dispex, (IUnknown*)&This->IXMLDOMSelection_iface, &domselection_dispex);
xmldoc_add_ref(This->node->doc);
ctxt->error = query_serror;
ctxt->node = node;
registerNamespaces(ctxt);
if (is_xpathmode(This->node->doc))
{
xmlXPathRegisterAllFunctions(ctxt);
This->result = xmlXPathEvalExpression(query, ctxt);
}
else
{
xmlChar* pattern_query = XSLPattern_to_XPath(ctxt, query);
xmlXPathRegisterFunc(ctxt, (xmlChar const*)"not", xmlXPathNotFunction);
xmlXPathRegisterFunc(ctxt, (xmlChar const*)"boolean", xmlXPathBooleanFunction);
xmlXPathRegisterFunc(ctxt, (xmlChar const*)"index", XSLPattern_index);
xmlXPathRegisterFunc(ctxt, (xmlChar const*)"end", XSLPattern_end);
xmlXPathRegisterFunc(ctxt, (xmlChar const*)"nodeType", XSLPattern_nodeType);
xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_IEq", XSLPattern_OP_IEq);
xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_INEq", XSLPattern_OP_INEq);
xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_ILt", XSLPattern_OP_ILt);
xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_ILEq", XSLPattern_OP_ILEq);
xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_IGt", XSLPattern_OP_IGt);
xmlXPathRegisterFunc(ctxt, (xmlChar const*)"OP_IGEq", XSLPattern_OP_IGEq);
This->result = xmlXPathEvalExpression(pattern_query, ctxt);
xmlFree(pattern_query);
}
if (!This->result || This->result->type != XPATH_NODESET)
{
hr = E_FAIL;
goto cleanup;
}
*out = (IXMLDOMNodeList*)&This->IXMLDOMSelection_iface;
hr = S_OK;
TRACE("found %d matches\n", xmlXPathNodeSetGetLength(This->result->nodesetval));
cleanup:
if (FAILED(hr))
IXMLDOMSelection_Release( &This->IXMLDOMSelection_iface );
xmlXPathFreeContext(ctxt);
return hr;
}
#endif
| {
"pile_set_name": "Github"
} |
{Listener} = require './listener'
##=======================================================================
# Collect all methods that start with "h_"s. These are handler
# hooks and will automatically assume a program with this function
exports.collect_hooks = collect_hooks = (proto) ->
re = /^h_(.*)$/
hooks = {}
for k,v of proto
if (m = k.match re)?
hooks[m[1]] = v
return hooks
##=======================================================================
exports.Server = class Server extends Listener
"""This server is connection-centric. When the handlers of the
passed programs are invoked, the 'this' object to the handler will
be the Transport that's handling that client. This server is available
via this.parent.
Note you can pass a TransportClass to use instead of the Transport.
It should be a subclass of Transport.
"""
#-----------------------------------------
constructor : (d) ->
super d
@programs = d.programs
#-----------------------------------------
got_new_connection : (c) ->
# c inherits from Dispatch, so it should have an add_programs
# method. We're just going to shove into it
c.add_programs @programs
##=======================================================================
exports.SimpleServer = class SimpleServer extends Listener
constructor : (d) ->
super d
@_program = d.program
got_new_connection : (c) ->
@_hooks = collect_hooks @
c.add_program @get_program_name(), @_hooks
set_program_name : (p) ->
@_program = p
get_program_name : () ->
r = @_program
throw new Error "No 'program' given" unless r?
return r
make_new_transport : (c) ->
x = super c
x.get_handler_this = (m) => @
return x
##=======================================================================
#
# Your class can be much cooler, maybe this is where you put all of your
# application logic.
#
# If you put hooks of the form:
#
# h_foo : (arg,res) ->
#
# Then they will be automatically rolled up into a program, handled by
# this class.
#
exports.Handler = class Handler
constructor : ({@transport, @server}) ->
# Collect all methods that start with "h_"s. These are handler
# hooks and will automatically assume a program with this function
@collect_hooks : () -> collect_hooks @prototype
##=======================================================================
exports.ContextualServer = class ContextualServer extends Listener
"""This exposes a slightly different object as `this` to RPC
handlers -- in this case, it a Handler object that points to be both
the parent server, and also the child transport. So both are accessible
via 'has-a' rather than 'is-a' relationships."""
constructor : (d) ->
super d
@programs = {}
@classes = d.classes
for n,klass of @classes
@programs[n] = klass.collect_hooks()
#-----------------------------------------
got_new_connection : (c) ->
# c inherits from Dispatch, so it should have an add_programs
# method. We're just going to shove into it
c.add_programs @programs
#-----------------------------------------
make_new_transport : (c) ->
x = super c
ctx = {}
for n,klass of @classes
ctx[n] = new klass { transport : x, server: @ }
# This is sort of a hack, but it should work and override the
# prototype. The alternative is to bubble classes up and down the
# class hierarchy, but this is much less code.
x.get_handler_this = (m) ->
pn = m.split(".")[0...-1].join(".")
# This really ought not happen
throw new Error "Couldn't find prog #{pn}" unless (obj = ctx[pn])?
return obj
return x
##=======================================================================
| {
"pile_set_name": "Github"
} |
/* err/gsl_message.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* 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 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
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MESSAGE_H__
#define __GSL_MESSAGE_H__
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* Provide a general messaging service for client use. Messages can
* be selectively turned off at compile time by defining an
* appropriate message mask. Client code which uses the GSL_MESSAGE()
* macro must provide a mask which is or'ed with the GSL_MESSAGE_MASK.
*
* The messaging service can be completely turned off
* by defining GSL_MESSAGING_OFF. */
void gsl_message(const char * message, const char * file, int line,
unsigned int mask);
#ifndef GSL_MESSAGE_MASK
#define GSL_MESSAGE_MASK 0xffffffffu /* default all messages allowed */
#endif
GSL_VAR unsigned int gsl_message_mask ;
/* Provide some symolic masks for client ease of use. */
enum {
GSL_MESSAGE_MASK_A = 1,
GSL_MESSAGE_MASK_B = 2,
GSL_MESSAGE_MASK_C = 4,
GSL_MESSAGE_MASK_D = 8,
GSL_MESSAGE_MASK_E = 16,
GSL_MESSAGE_MASK_F = 32,
GSL_MESSAGE_MASK_G = 64,
GSL_MESSAGE_MASK_H = 128
} ;
#ifdef GSL_MESSAGING_OFF /* throw away messages */
#define GSL_MESSAGE(message, mask) do { } while(0)
#else /* output all messages */
#define GSL_MESSAGE(message, mask) \
do { \
if (mask & GSL_MESSAGE_MASK) \
gsl_message (message, __FILE__, __LINE__, mask) ; \
} while (0)
#endif
__END_DECLS
#endif /* __GSL_MESSAGE_H__ */
| {
"pile_set_name": "Github"
} |
<!-- $Id: luac.man,v 1.28 2006/01/06 16:03:34 lhf Exp $ -->
<HTML>
<HEAD>
<TITLE>LUAC man page</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="lua.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<H2>NAME</H2>
luac - Lua compiler
<H2>SYNOPSIS</H2>
<B>luac</B>
[
<I>options</I>
] [
<I>filenames</I>
]
<H2>DESCRIPTION</H2>
<B>luac</B>
is the Lua compiler.
It translates programs written in the Lua programming language
into binary files that can be later loaded and executed.
<P>
The main advantages of precompiling chunks are:
faster loading,
protecting source code from accidental user changes,
and
off-line syntax checking.
<P>
Precompiling does not imply faster execution
because in Lua chunks are always compiled into bytecodes before being executed.
<B>luac</B>
simply allows those bytecodes to be saved in a file for later execution.
<P>
Precompiled chunks are not necessarily smaller than the corresponding source.
The main goal in precompiling is faster loading.
<P>
The binary files created by
<B>luac</B>
are portable only among architectures with the same word size and byte order.
<P>
<B>luac</B>
produces a single output file containing the bytecodes
for all source files given.
By default,
the output file is named
<B>luac.out</B>,
but you can change this with the
<B>-o</B>
option.
<P>
In the command line,
you can mix
text files containing Lua source and
binary files containing precompiled chunks.
This is useful because several precompiled chunks,
even from different (but compatible) platforms,
can be combined into a single precompiled chunk.
<P>
You can use
<B>'-'</B>
to indicate the standard input as a source file
and
<B>'--'</B>
to signal the end of options
(that is,
all remaining arguments will be treated as files even if they start with
<B>'-'</B>).
<P>
The internal format of the binary files produced by
<B>luac</B>
is likely to change when a new version of Lua is released.
So,
save the source files of all Lua programs that you precompile.
<P>
<H2>OPTIONS</H2>
Options must be separate.
<P>
<B>-l</B>
produce a listing of the compiled bytecode for Lua's virtual machine.
Listing bytecodes is useful to learn about Lua's virtual machine.
If no files are given, then
<B>luac</B>
loads
<B>luac.out</B>
and lists its contents.
<P>
<B>-o </B><I>file</I>
output to
<I>file</I>,
instead of the default
<B>luac.out</B>.
(You can use
<B>'-'</B>
for standard output,
but not on platforms that open standard output in text mode.)
The output file may be a source file because
all files are loaded before the output file is written.
Be careful not to overwrite precious files.
<P>
<B>-p</B>
load files but do not generate any output file.
Used mainly for syntax checking and for testing precompiled chunks:
corrupted files will probably generate errors when loaded.
Lua always performs a thorough integrity test on precompiled chunks.
Bytecode that passes this test is completely safe,
in the sense that it will not break the interpreter.
However,
there is no guarantee that such code does anything sensible.
(None can be given, because the halting problem is unsolvable.)
If no files are given, then
<B>luac</B>
loads
<B>luac.out</B>
and tests its contents.
No messages are displayed if the file passes the integrity test.
<P>
<B>-s</B>
strip debug information before writing the output file.
This saves some space in very large chunks,
but if errors occur when running a stripped chunk,
then the error messages may not contain the full information they usually do.
For instance,
line numbers and names of local variables are lost.
<P>
<B>-v</B>
show version information.
<H2>FILES</H2>
<P>
<B>luac.out</B>
default output file
<H2>SEE ALSO</H2>
<B>lua</B>(1)
<BR>
<A HREF="http://www.lua.org/">http://www.lua.org/</A>
<H2>DIAGNOSTICS</H2>
Error messages should be self explanatory.
<H2>AUTHORS</H2>
L. H. de Figueiredo,
R. Ierusalimschy and
W. Celes
<!-- EOF -->
</BODY>
</HTML>
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.