text
stringlengths
2
100k
meta
dict
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="bar_grey">#393a3e</color> <color name="black">#000000</color> <color name="white">#FFFFFF</color> <color name="blue">#7D7DFF</color> <color name="color_69">#999999</color> <color name="image_overlay_true">#80000000</color> <color name="image_overlay_false">#20000000</color> <color name="line_color">#EEEEEE</color> <color name="color_fa">#FAFAFA</color> <color name="tab_color_true">#FA632D</color> <color name="tab_color_false">#9b9b9b</color> <color name="color_f2">#F2F2F2</color> <color name="transparent">#00000000</color> <color name="transparent_white">#F0FFFFFF</color> <color name="transparent_db">#E0DBDBDB</color> <color name="color_53">#53575e</color> <color name="color_f0">#F0F0F0</color> <color name="bar_grey_90">#dd393a3e</color> <color name="color_4d">#4d4d4d</color> <color name="color_orange">#E0FF6100</color> </resources>
{ "pile_set_name": "Github" }
import { NamespaceDeclarationStructure, VariableStatementStructure, OptionalKind, StructureKind, VariableDeclarationStructure, ImportDeclarationStructure, ClassDeclarationStructure, ImportSpecifierStructure, EnumDeclarationStructure, InterfaceDeclarationStructure, FunctionDeclarationStructure, TypeAliasDeclarationStructure, PropertyDeclarationStructure, TypeParameterDeclarationStructure, ParameterDeclarationStructure, JSDocStructure, PropertySignatureStructure, MethodSignatureStructure, CallSignatureDeclarationStructure, IndexSignatureDeclarationStructure, ConstructSignatureDeclarationStructure, FunctionDeclarationOverloadStructure, EnumMemberStructure, MethodDeclarationStructure, MethodDeclarationOverloadStructure, SetAccessorDeclarationStructure, GetAccessorDeclarationStructure, DecoratorStructure, ConstructorDeclarationStructure, ConstructorDeclarationOverloadStructure, JSDocTagStructure } from "../../../structures"; import { NamespaceDeclarationKind, VariableDeclarationKind } from "../../../compiler"; // this file is incomplete... update accordingly as needed export namespace fillStructures { export function namespaceDeclaration(structure: OptionalKind<NamespaceDeclarationStructure>): NamespaceDeclarationStructure { setIfNull(structure, "declarationKind", NamespaceDeclarationKind.Namespace); setIfNull(structure, "docs", []); setIfNull(structure, "hasDeclareKeyword", false); setIfNull(structure, "isDefaultExport", false); setIfNull(structure, "isExported", false); fill(structure.docs!, jsDoc); setIfNull(structure, "kind", StructureKind.Namespace); return structure as NamespaceDeclarationStructure; } export function variableStatement(structure: OptionalKind<VariableStatementStructure>): VariableStatementStructure { setIfNull(structure, "declarationKind", VariableDeclarationKind.Let); setIfNull(structure, "docs", []); setIfNull(structure, "hasDeclareKeyword", false); setIfNull(structure, "isDefaultExport", false); setIfNull(structure, "isExported", false); fill(structure.docs!, jsDoc); fill(structure.declarations, variableDeclaration); setIfNull(structure, "kind", StructureKind.VariableStatement); return structure as VariableStatementStructure; } export function variableDeclaration(structure: OptionalKind<VariableDeclarationStructure>): VariableDeclarationStructure { setIfNull(structure, "hasExclamationToken", false); setIfNull(structure, "initializer", undefined); setIfNull(structure, "type", undefined); setIfNull(structure, "kind", StructureKind.VariableDeclaration); return structure as VariableDeclarationStructure; } export function importDeclaration(structure: OptionalKind<ImportDeclarationStructure>): ImportDeclarationStructure { setIfNull(structure, "isTypeOnly", false); setIfNull(structure, "defaultImport", undefined); setIfNull(structure, "namespaceImport", undefined); setIfNull(structure, "kind", StructureKind.ImportDeclaration); return structure as ImportDeclarationStructure; } export function importSpecifier(structure: OptionalKind<ImportSpecifierStructure>): ImportSpecifierStructure { setIfNull(structure, "alias", undefined); setIfNull(structure, "kind", StructureKind.ImportSpecifier); return structure as ImportSpecifierStructure; } export function classDeclaration(structure: OptionalKind<ClassDeclarationStructure>): ClassDeclarationStructure { setIfNull(structure, "hasDeclareKeyword", false); setIfNull(structure, "isAbstract", false); setIfNull(structure, "isDefaultExport", false); setIfNull(structure, "isExported", false); setIfNull(structure, "ctors", []); setIfNull(structure, "decorators", []); setIfNull(structure, "docs", []); setIfNull(structure, "extends", undefined); setIfNull(structure, "implements", []); setIfNull(structure, "getAccessors", []); setIfNull(structure, "methods", []); setIfNull(structure, "properties", []); setIfNull(structure, "setAccessors", []); setIfNull(structure, "typeParameters", []); fill(structure.docs!, jsDoc); fill(structure.decorators!, decorator); fill(structure.typeParameters!, typeParameter); fill(structure.ctors!, constructorDeclaration); fill(structure.methods!, method); fill(structure.properties!, property); fill(structure.getAccessors!, getAccessor); fill(structure.setAccessors!, setAccessor); setIfNull(structure, "kind", StructureKind.Class); return structure as ClassDeclarationStructure; } export function constructorDeclaration(structure: OptionalKind<ConstructorDeclarationStructure>): ConstructorDeclarationStructure { constructorBase(structure); setIfNull(structure, "statements", undefined); if (structure.overloads) fill(structure.overloads, constructorDeclarationOverload); setIfNull(structure, "kind", StructureKind.Constructor); return structure as ConstructorDeclarationStructure; } export function constructorDeclarationOverload(structure: OptionalKind<ConstructorDeclarationOverloadStructure>): ConstructorDeclarationOverloadStructure { constructorBase(structure); setIfNull(structure, "kind", StructureKind.ConstructorOverload); return structure as ConstructorDeclarationOverloadStructure; } function constructorBase(structure: OptionalKind<ConstructorDeclarationStructure | ConstructorDeclarationOverloadStructure>) { setIfNull(structure, "docs", []); setIfNull(structure, "parameters", []); setIfNull(structure, "typeParameters", []); setIfNull(structure, "scope", undefined); setIfNull(structure, "returnType", undefined); fill(structure.docs!, jsDoc); fill(structure.parameters!, parameter); fill(structure.typeParameters!, typeParameter); } export function enumDeclaration(structure: OptionalKind<EnumDeclarationStructure>): EnumDeclarationStructure { setIfNull(structure, "hasDeclareKeyword", false); setIfNull(structure, "isConst", false); setIfNull(structure, "isDefaultExport", false); setIfNull(structure, "docs", []); setIfNull(structure, "members", []); fill(structure.docs!, jsDoc); fill(structure.members!, enumMember); setIfNull(structure, "kind", StructureKind.Enum); return structure as EnumDeclarationStructure; } export function enumMember(structure: OptionalKind<EnumMemberStructure>): EnumMemberStructure { setIfNull(structure, "docs", []); setIfNull(structure, "initializer", undefined); setIfNull(structure, "value", undefined); fill(structure.docs!, jsDoc); setIfNull(structure, "kind", StructureKind.EnumMember); return structure as EnumMemberStructure; } export function interfaceDeclaration(structure: OptionalKind<InterfaceDeclarationStructure>): InterfaceDeclarationStructure { setIfNull(structure, "hasDeclareKeyword", false); setIfNull(structure, "isDefaultExport", false); setIfNull(structure, "isExported", false); setIfNull(structure, "docs", []); setIfNull(structure, "callSignatures", []); setIfNull(structure, "constructSignatures", []); setIfNull(structure, "extends", []); setIfNull(structure, "indexSignatures", []); setIfNull(structure, "properties", []); setIfNull(structure, "methods", []); setIfNull(structure, "typeParameters", []); fill(structure.docs!, jsDoc); fill(structure.typeParameters!, typeParameter); fill(structure.methods!, methodSignature); fill(structure.properties!, propertySignature); fill(structure.callSignatures!, callSignature); fill(structure.indexSignatures!, indexSignature); fill(structure.constructSignatures!, constructSignature); setIfNull(structure, "kind", StructureKind.Interface); return structure as InterfaceDeclarationStructure; } export function callSignature(structure: OptionalKind<CallSignatureDeclarationStructure>): CallSignatureDeclarationStructure { setIfNull(structure, "docs", []); setIfNull(structure, "parameters", []); setIfNull(structure, "typeParameters", []); fill(structure.docs!, jsDoc); fill(structure.parameters!, parameter); fill(structure.typeParameters!, typeParameter); setIfNull(structure, "kind", StructureKind.CallSignature); return structure as CallSignatureDeclarationStructure; } export function indexSignature(structure: OptionalKind<IndexSignatureDeclarationStructure>): IndexSignatureDeclarationStructure { setIfNull(structure, "docs", []); setIfNull(structure, "isReadonly", false); setIfNull(structure, "keyType", "string"); setIfNull(structure, "keyType", "string"); setIfNull(structure, "keyName", "key"); fill(structure.docs!, jsDoc); setIfNull(structure, "kind", StructureKind.IndexSignature); return structure as IndexSignatureDeclarationStructure; } export function constructSignature(structure: OptionalKind<ConstructSignatureDeclarationStructure>): ConstructSignatureDeclarationStructure { setIfNull(structure, "docs", []); setIfNull(structure, "parameters", []); setIfNull(structure, "typeParameters", []); fill(structure.docs!, jsDoc); fill(structure.parameters!, parameter); fill(structure.typeParameters!, typeParameter); setIfNull(structure, "kind", StructureKind.ConstructSignature); return structure as ConstructSignatureDeclarationStructure; } export function functionDeclaration(structure: OptionalKind<FunctionDeclarationStructure>): FunctionDeclarationStructure { functionBase(structure); if (structure.overloads) fill(structure.overloads, functionDeclarationOverload); setIfNull(structure, "kind", StructureKind.Function); return structure as FunctionDeclarationStructure; } export function functionDeclarationOverload(structure: OptionalKind<FunctionDeclarationOverloadStructure>): FunctionDeclarationOverloadStructure { functionBase(structure); setIfNull(structure, "kind", StructureKind.FunctionOverload); return structure as FunctionDeclarationOverloadStructure; } function functionBase(structure: OptionalKind<FunctionDeclarationStructure | FunctionDeclarationOverloadStructure>) { setIfNull(structure, "hasDeclareKeyword", false); setIfNull(structure, "isAsync", false); setIfNull(structure, "isDefaultExport", false); setIfNull(structure, "isExported", false); setIfNull(structure, "isGenerator", false); setIfNull(structure, "docs", []); setIfNull(structure, "parameters", []); setIfNull(structure, "returnType", undefined); setIfNull(structure, "typeParameters", []); fill(structure.docs!, jsDoc); fill(structure.parameters!, parameter); fill(structure.typeParameters!, typeParameter); } export function typeAlias(structure: OptionalKind<TypeAliasDeclarationStructure>): TypeAliasDeclarationStructure { setIfNull(structure, "hasDeclareKeyword", false); setIfNull(structure, "isDefaultExport", false); setIfNull(structure, "docs", []); setIfNull(structure, "typeParameters", []); fill(structure.docs!, jsDoc); fill(structure.typeParameters!, typeParameter); setIfNull(structure, "kind", StructureKind.TypeAlias); return structure as TypeAliasDeclarationStructure; } export function method(structure: OptionalKind<MethodDeclarationStructure>): MethodDeclarationStructure { methodBase(structure); setIfNull(structure, "decorators", []); setIfNull(structure, "statements", undefined); if (structure.overloads) fill(structure.overloads, methodOverload); fill(structure.decorators!, decorator); setIfNull(structure, "kind", StructureKind.Method); return structure as MethodDeclarationStructure; } export function methodOverload(structure: OptionalKind<MethodDeclarationOverloadStructure>): MethodDeclarationOverloadStructure { methodBase(structure); setIfNull(structure, "kind", StructureKind.MethodOverload); return structure as MethodDeclarationOverloadStructure; } function methodBase(structure: OptionalKind<MethodDeclarationStructure | MethodDeclarationOverloadStructure>) { setIfNull(structure, "isGenerator", false); setIfNull(structure, "isStatic", false); setIfNull(structure, "isAsync", false); setIfNull(structure, "isAbstract", false); setIfNull(structure, "hasQuestionToken", false); setIfNull(structure, "scope", undefined); setIfNull(structure, "returnType", undefined); setIfNull(structure, "docs", []); setIfNull(structure, "parameters", []); setIfNull(structure, "typeParameters", []); fill(structure.docs!, jsDoc); fill(structure.parameters!, parameter); fill(structure.typeParameters!, typeParameter); } export function methodSignature(structure: OptionalKind<MethodSignatureStructure>): MethodSignatureStructure { setIfNull(structure, "docs", []); setIfNull(structure, "parameters", []); setIfNull(structure, "typeParameters", []); setIfNull(structure, "hasQuestionToken", false); fill(structure.docs!, jsDoc); fill(structure.parameters!, parameter); fill(structure.typeParameters!, typeParameter); setIfNull(structure, "kind", StructureKind.MethodSignature); return structure as MethodSignatureStructure; } export function property(structure: OptionalKind<PropertyDeclarationStructure>): PropertyDeclarationStructure { setIfNull(structure, "decorators", []); setIfNull(structure, "docs", []); setIfNull(structure, "scope", undefined); setIfNull(structure, "isStatic", false); setIfNull(structure, "isReadonly", false); setIfNull(structure, "isAbstract", false); setIfNull(structure, "hasExclamationToken", false); setIfNull(structure, "hasQuestionToken", false); setIfNull(structure, "hasDeclareKeyword", false); setIfNull(structure, "initializer", undefined); setIfNull(structure, "scope", undefined); fill(structure.docs!, jsDoc); fill(structure.decorators!, decorator); setIfNull(structure, "kind", StructureKind.Property); return structure as PropertyDeclarationStructure; } export function propertySignature(structure: OptionalKind<PropertySignatureStructure>): PropertySignatureStructure { setIfNull(structure, "docs", []); setIfNull(structure, "isReadonly", false); setIfNull(structure, "hasQuestionToken", false); setIfNull(structure, "initializer", undefined); fill(structure.docs!, jsDoc); setIfNull(structure, "kind", StructureKind.PropertySignature); return structure as PropertySignatureStructure; } export function getAccessor(structure: OptionalKind<GetAccessorDeclarationStructure>): GetAccessorDeclarationStructure { setIfNull(structure, "decorators", []); setIfNull(structure, "docs", []); setIfNull(structure, "parameters", []); setIfNull(structure, "typeParameters", []); setIfNull(structure, "isAbstract", false); setIfNull(structure, "isStatic", false); setIfNull(structure, "returnType", undefined); setIfNull(structure, "statements", undefined); setIfNull(structure, "scope", undefined); fill(structure.decorators!, decorator); fill(structure.docs!, jsDoc); fill(structure.parameters!, parameter); fill(structure.typeParameters!, typeParameter); setIfNull(structure, "kind", StructureKind.GetAccessor); return structure as GetAccessorDeclarationStructure; } export function setAccessor(structure: OptionalKind<SetAccessorDeclarationStructure>): SetAccessorDeclarationStructure { setIfNull(structure, "decorators", []); setIfNull(structure, "docs", []); setIfNull(structure, "parameters", []); setIfNull(structure, "typeParameters", []); setIfNull(structure, "isAbstract", false); setIfNull(structure, "isStatic", false); setIfNull(structure, "returnType", undefined); setIfNull(structure, "statements", undefined); setIfNull(structure, "scope", undefined); fill(structure.decorators!, decorator); fill(structure.docs!, jsDoc); fill(structure.parameters!, parameter); fill(structure.typeParameters!, typeParameter); setIfNull(structure, "kind", StructureKind.SetAccessor); return structure as SetAccessorDeclarationStructure; } export function parameter(structure: OptionalKind<ParameterDeclarationStructure> | string): ParameterDeclarationStructure { if (typeof structure === "string") structure = { name: structure }; setIfNull(structure, "decorators", []); setIfNull(structure, "hasQuestionToken", false); setIfNull(structure, "initializer", undefined); setIfNull(structure, "isReadonly", false); setIfNull(structure, "isRestParameter", false); setIfNull(structure, "scope", undefined); setIfNull(structure, "type", undefined); setIfNull(structure, "kind", StructureKind.Parameter); return structure as ParameterDeclarationStructure; } export function decorator(structure: OptionalKind<DecoratorStructure>): DecoratorStructure { setIfNull(structure, "typeArguments", undefined); setIfNull(structure, "arguments", undefined); setIfNull(structure, "kind", StructureKind.Decorator); return structure as DecoratorStructure; } export function typeParameter(structure: OptionalKind<TypeParameterDeclarationStructure> | string): TypeParameterDeclarationStructure { if (typeof structure === "string") structure = { name: structure }; setIfNull(structure, "constraint", undefined); setIfNull(structure, "default", undefined); setIfNull(structure, "kind", StructureKind.TypeParameter); return structure as TypeParameterDeclarationStructure; } export function jsDoc(structure: OptionalKind<JSDocStructure>): JSDocStructure { setIfNull(structure, "kind", StructureKind.JSDoc); setIfNull(structure, "tags", []); fill(structure.tags!, jsDocTag); return structure as JSDocStructure; } export function jsDocTag(structure: OptionalKind<JSDocTagStructure>): JSDocTagStructure { setIfNull(structure, "kind", StructureKind.JSDocTag); return structure as JSDocTagStructure; } } function setIfNull<T, TKey extends keyof T>(structure: T, key: TKey, value: T[TKey]) { if (structure[key] == null) structure[key] = value; } function fill<T>(items: (OptionalKind<T> | string)[], fillItem: (item: OptionalKind<T>) => T) { if (items == null) throw new Error("Did not expect an undefined array."); for (let i = 0; i < items.length; i++) { const item = items[i]; if (typeof item !== "string") items[i] = fillItem(item); } }
{ "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.druid.math.expr; import com.google.common.collect.ImmutableMap; import org.apache.druid.common.config.NullHandling; import org.apache.druid.testing.InitializedNullHandlingTest; import org.junit.Assert; import org.junit.Test; /** */ public class EvalTest extends InitializedNullHandlingTest { private long evalLong(String x, Expr.ObjectBinding bindings) { ExprEval ret = eval(x, bindings); Assert.assertEquals(ExprType.LONG, ret.type()); return ret.asLong(); } private double evalDouble(String x, Expr.ObjectBinding bindings) { ExprEval ret = eval(x, bindings); Assert.assertEquals(ExprType.DOUBLE, ret.type()); return ret.asDouble(); } private ExprEval eval(String x, Expr.ObjectBinding bindings) { return Parser.parse(x, ExprMacroTable.nil()).eval(bindings); } @Test public void testDoubleEval() { Expr.ObjectBinding bindings = Parser.withMap(ImmutableMap.of("x", 2.0d)); Assert.assertEquals(2.0, evalDouble("x", bindings), 0.0001); Assert.assertEquals(2.0, evalDouble("\"x\"", bindings), 0.0001); Assert.assertEquals(304.0, evalDouble("300 + \"x\" * 2", bindings), 0.0001); Assert.assertFalse(evalDouble("1.0 && 0.0", bindings) > 0.0); Assert.assertTrue(evalDouble("1.0 && 2.0", bindings) > 0.0); Assert.assertTrue(evalDouble("1.0 || 0.0", bindings) > 0.0); Assert.assertFalse(evalDouble("0.0 || 0.0", bindings) > 0.0); Assert.assertTrue(evalDouble("2.0 > 1.0", bindings) > 0.0); Assert.assertTrue(evalDouble("2.0 >= 2.0", bindings) > 0.0); Assert.assertTrue(evalDouble("1.0 < 2.0", bindings) > 0.0); Assert.assertTrue(evalDouble("2.0 <= 2.0", bindings) > 0.0); Assert.assertTrue(evalDouble("2.0 == 2.0", bindings) > 0.0); Assert.assertTrue(evalDouble("2.0 != 1.0", bindings) > 0.0); Assert.assertEquals(3.5, evalDouble("2.0 + 1.5", bindings), 0.0001); Assert.assertEquals(0.5, evalDouble("2.0 - 1.5", bindings), 0.0001); Assert.assertEquals(3.0, evalDouble("2.0 * 1.5", bindings), 0.0001); Assert.assertEquals(4.0, evalDouble("2.0 / 0.5", bindings), 0.0001); Assert.assertEquals(0.2, evalDouble("2.0 % 0.3", bindings), 0.0001); Assert.assertEquals(8.0, evalDouble("2.0 ^ 3.0", bindings), 0.0001); Assert.assertEquals(-1.5, evalDouble("-1.5", bindings), 0.0001); Assert.assertTrue(evalDouble("!-1.0", bindings) > 0.0); Assert.assertTrue(evalDouble("!0.0", bindings) > 0.0); Assert.assertFalse(evalDouble("!2.0", bindings) > 0.0); Assert.assertEquals(2.0, evalDouble("sqrt(4.0)", bindings), 0.0001); Assert.assertEquals(2.0, evalDouble("if(1.0, 2.0, 3.0)", bindings), 0.0001); Assert.assertEquals(3.0, evalDouble("if(0.0, 2.0, 3.0)", bindings), 0.0001); } @Test public void testLongEval() { Expr.ObjectBinding bindings = Parser.withMap(ImmutableMap.of("x", 9223372036854775807L)); Assert.assertEquals(9223372036854775807L, evalLong("x", bindings)); Assert.assertEquals(9223372036854775807L, evalLong("\"x\"", bindings)); Assert.assertEquals(92233720368547759L, evalLong("\"x\" / 100 + 1", bindings)); Assert.assertFalse(evalLong("9223372036854775807 && 0", bindings) > 0); Assert.assertTrue(evalLong("9223372036854775807 && 9223372036854775806", bindings) > 0); Assert.assertTrue(evalLong("9223372036854775807 || 0", bindings) > 0); Assert.assertFalse(evalLong("-9223372036854775807 || -9223372036854775807", bindings) > 0); Assert.assertTrue(evalLong("-9223372036854775807 || 9223372036854775807", bindings) > 0); Assert.assertFalse(evalLong("0 || 0", bindings) > 0); Assert.assertTrue(evalLong("9223372036854775807 > 9223372036854775806", bindings) > 0); Assert.assertTrue(evalLong("9223372036854775807 >= 9223372036854775807", bindings) > 0); Assert.assertTrue(evalLong("9223372036854775806 < 9223372036854775807", bindings) > 0); Assert.assertTrue(evalLong("9223372036854775807 <= 9223372036854775807", bindings) > 0); Assert.assertTrue(evalLong("9223372036854775807 == 9223372036854775807", bindings) > 0); Assert.assertTrue(evalLong("9223372036854775807 != 9223372036854775806", bindings) > 0); Assert.assertEquals(9223372036854775807L, evalLong("9223372036854775806 + 1", bindings)); Assert.assertEquals(9223372036854775806L, evalLong("9223372036854775807 - 1", bindings)); Assert.assertEquals(9223372036854775806L, evalLong("4611686018427387903 * 2", bindings)); Assert.assertEquals(4611686018427387903L, evalLong("9223372036854775806 / 2", bindings)); Assert.assertEquals(7L, evalLong("9223372036854775807 % 9223372036854775800", bindings)); Assert.assertEquals(9223372030926249001L, evalLong("3037000499 ^ 2", bindings)); Assert.assertEquals(-9223372036854775807L, evalLong("-9223372036854775807", bindings)); Assert.assertTrue(evalLong("!-9223372036854775807", bindings) > 0); Assert.assertTrue(evalLong("!0", bindings) > 0); Assert.assertFalse(evalLong("!9223372036854775807", bindings) > 0); Assert.assertEquals(3037000499L, evalLong("cast(sqrt(9223372036854775807), 'long')", bindings)); Assert.assertEquals(1L, evalLong("if(x == 9223372036854775807, 1, 0)", bindings)); Assert.assertEquals(0L, evalLong("if(x - 1 == 9223372036854775807, 1, 0)", bindings)); Assert.assertEquals(1271030400000L, evalLong("timestamp('2010-04-12')", bindings)); Assert.assertEquals(1270998000000L, evalLong("timestamp('2010-04-12T+09:00')", bindings)); Assert.assertEquals(1271055781000L, evalLong("timestamp('2010-04-12T07:03:01')", bindings)); Assert.assertEquals(1271023381000L, evalLong("timestamp('2010-04-12T07:03:01+09:00')", bindings)); Assert.assertEquals(1271023381419L, evalLong("timestamp('2010-04-12T07:03:01.419+09:00')", bindings)); Assert.assertEquals(1271030400L, evalLong("unix_timestamp('2010-04-12')", bindings)); Assert.assertEquals(1270998000L, evalLong("unix_timestamp('2010-04-12T+09:00')", bindings)); Assert.assertEquals(1271055781L, evalLong("unix_timestamp('2010-04-12T07:03:01')", bindings)); Assert.assertEquals(1271023381L, evalLong("unix_timestamp('2010-04-12T07:03:01+09:00')", bindings)); Assert.assertEquals(1271023381L, evalLong("unix_timestamp('2010-04-12T07:03:01.419+09:00')", bindings)); Assert.assertEquals( NullHandling.replaceWithDefault() ? "NULL" : "", eval("nvl(if(x == 9223372036854775807, '', 'x'), 'NULL')", bindings).asString() ); Assert.assertEquals("x", eval("nvl(if(x == 9223372036854775806, '', 'x'), 'NULL')", bindings).asString()); } @Test public void testBooleanReturn() { Expr.ObjectBinding bindings = Parser.withMap( ImmutableMap.of("x", 100L, "y", 100L, "z", 100D, "w", 100D) ); ExprEval eval = Parser.parse("x==y", ExprMacroTable.nil()).eval(bindings); Assert.assertTrue(eval.asBoolean()); Assert.assertEquals(ExprType.LONG, eval.type()); eval = Parser.parse("x!=y", ExprMacroTable.nil()).eval(bindings); Assert.assertFalse(eval.asBoolean()); Assert.assertEquals(ExprType.LONG, eval.type()); eval = Parser.parse("x==z", ExprMacroTable.nil()).eval(bindings); Assert.assertTrue(eval.asBoolean()); Assert.assertEquals(ExprType.DOUBLE, eval.type()); eval = Parser.parse("x!=z", ExprMacroTable.nil()).eval(bindings); Assert.assertFalse(eval.asBoolean()); Assert.assertEquals(ExprType.DOUBLE, eval.type()); eval = Parser.parse("z==w", ExprMacroTable.nil()).eval(bindings); Assert.assertTrue(eval.asBoolean()); Assert.assertEquals(ExprType.DOUBLE, eval.type()); eval = Parser.parse("z!=w", ExprMacroTable.nil()).eval(bindings); Assert.assertFalse(eval.asBoolean()); Assert.assertEquals(ExprType.DOUBLE, eval.type()); } }
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Linq; using System.Management; using System.Text; using System.Xml; namespace CustomUpdateEngine { public class StopServiceAction : GenericAction { public StopServiceAction(string xmlFragment) { LogInitialization(xmlFragment); XmlReader reader = XmlReader.Create(new System.IO.StringReader(xmlFragment)); if (!reader.ReadToFollowing("ServiceName")) throw new ArgumentException("Unable to find token : ServiceName"); ServiceName = reader.ReadElementContentAsString(); LogCompletion(); } public string ServiceName { get; private set; } public override void Run(ref ReturnCodeAction returnCode) { Logger.Write("Running StopServiceAction. ServiceName = " + this.ServiceName); try { uint resultCode = 1; string filter = String.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", this.ServiceName); ManagementObjectSearcher query = new ManagementObjectSearcher(filter); if (query != null) { ManagementObjectCollection services = query.Get(); foreach (ManagementObject service in services) { ManagementBaseObject outParams = service.InvokeMethod("StopService", null, null); resultCode = Convert.ToUInt16(outParams.Properties["ReturnValue"].Value); if (resultCode == 0) Logger.Write("Successfully stop " + ServiceName); else Logger.Write("Failed to stop " + ServiceName + ". Result code = " + resultCode + " : " + this.GetResultCodeMeaning(resultCode)); } } else Logger.Write("The service " + ServiceName + " was not found."); } catch (Exception ex) { Logger.Write("Failed stop " + ServiceName + "\r\n" + ex.Message); } Logger.Write("End of StopServiceAction."); } private string GetResultCodeMeaning(uint resultCode) { string meaning = "Unknown result code."; switch (resultCode) { case 0: meaning = "The request was accepted"; break; case 1: meaning = "The request is not supported"; break; case 2: meaning = "The user did not have the necessary access"; break; case 3: meaning = "The service cannot be stopped because other services that are running are dependent on it"; break; case 4: meaning = "The requested control code is not valid, or it is unacceptable to the service"; break; case 5: meaning = "The requested control code cannot be sent to the service because the state of the service (Win32_BaseService.State property) is equal to 0, 1, or 2"; break; case 6: meaning = "The service has not been started"; break; case 7: meaning = "The service did not respond to the start request in a timely fashion"; break; case 8: meaning = "Unknown failure when starting the service"; break; case 9: meaning = "The directory path to the service executable file was not found"; break; case 10: meaning = "Service Already Running"; break; case 11: meaning = "The database to add a new service is locked"; break; case 12: meaning = "A dependency this service relies on has been removed from the system"; break; case 13: meaning = "The service failed to find the service needed from a dependent service"; break; case 14: meaning = "The service has been disabled from the system"; break; case 15: meaning = "The service does not have the correct authentication to run on the system"; break; case 16: meaning = "This service is being removed from the system"; break; case 17: meaning = "The service has no execution thread"; break; case 18: meaning = "The service has circular dependencies when it starts"; break; case 19: meaning = "A service is running under the same name"; break; case 20: meaning = "The service name has invalid characters"; break; case 21: meaning = "Invalid parameters have been passed to the service"; break; case 22: meaning = "The account under which this service runs is either invalid or lacks the permissions to run the service"; break; case 23: meaning = "The service exists in the database of services available from the system"; break; case 24: meaning = "The service is currently paused in the system"; break; } return meaning; } } }
{ "pile_set_name": "Github" }
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once /** * Common pin assignments for all RUMBA32 boards * */ #ifndef STM32F4 #error "Oops! Select an STM32F4 board in 'Tools > Board.'" #elif HOTENDS > 3 || E_STEPPERS > 3 #error "RUMBA32 boards support up to 3 hotends / E-steppers." #endif #define DEFAULT_MACHINE_NAME BOARD_INFO_NAME // Use soft PWM for fans - PWM is not working properly when paired with STM32 Arduino Core v1.7.0 // This can be removed when Core version is updated and PWM behaviour is fixed. #define FAN_SOFT_PWM // // Configure Timers // TIM6 is used for TONE // TIM7 is used for SERVO // TIMER_SERIAL defaults to TIM7 so we'll override it here // #define STEP_TIMER 10 #define TEMP_TIMER 14 #define TIMER_SERIAL TIM9 #define HAL_TIMER_RATE F_CPU // // Limit Switches // #define X_MIN_PIN PB12 #define X_MAX_PIN PB13 #define Y_MIN_PIN PB15 #define Y_MAX_PIN PD8 #define Z_MIN_PIN PD9 #define Z_MAX_PIN PD10 // // Steppers // #define X_STEP_PIN PA0 #define X_DIR_PIN PC15 #define X_ENABLE_PIN PC11 #define X_CS_PIN PC14 #define Y_STEP_PIN PE5 #define Y_DIR_PIN PE6 #define Y_ENABLE_PIN PE3 #define Y_CS_PIN PE4 #define Z_STEP_PIN PE1 #define Z_DIR_PIN PE2 #define Z_ENABLE_PIN PB7 #define Z_CS_PIN PE0 #define E0_STEP_PIN PB5 #define E0_DIR_PIN PB6 #define E0_ENABLE_PIN PC12 #define E0_CS_PIN PC13 #define E1_STEP_PIN PD6 #define E1_DIR_PIN PD7 #define E1_ENABLE_PIN PD4 #define E1_CS_PIN PD5 #define E2_STEP_PIN PD2 #define E2_DIR_PIN PD3 #define E2_ENABLE_PIN PD0 #define E2_CS_PIN PD1 #if ENABLED(TMC_USE_SW_SPI) #ifndef TMC_SW_MOSI #define TMC_SW_MOSI PA7 #endif #ifndef TMC_SW_MISO #define TMC_SW_MISO PA6 #endif #ifndef TMC_SW_SCK #define TMC_SW_SCK PA5 #endif #endif // // Temperature Sensors // #define TEMP_0_PIN PC4 #define TEMP_1_PIN PC3 #define TEMP_2_PIN PC2 #define TEMP_3_PIN PC1 #define TEMP_BED_PIN PC0 // // Heaters / Fans // #define HEATER_0_PIN PC6 #define HEATER_1_PIN PC7 #define HEATER_2_PIN PC8 #define HEATER_BED_PIN PA1 #define FAN_PIN PC9 #define FAN1_PIN PA8 // // SPI // #define SCK_PIN PA5 #define MISO_PIN PA6 #define MOSI_PIN PA7 // // Misc. Functions // #define LED_PIN PB14 #define BTN_PIN PC10 #define PS_ON_PIN PE11 #define KILL_PIN PC5 #define NEOPIXEL_PIN PB4 #define SDSS PA2 #define SD_DETECT_PIN PB0 #define BEEPER_PIN PE8 // // LCD / Controller // #if HAS_SPI_LCD #define BTN_EN1 PB2 #define BTN_EN2 PB1 #define BTN_ENC PE7 #define LCD_PINS_RS PE10 #define LCD_PINS_ENABLE PE9 #define LCD_PINS_D4 PE12 #if ENABLED(MKS_MINI_12864) #define DOGLCD_CS PE13 #define DOGLCD_A0 PE14 #endif #if ENABLED(ULTIPANEL) #define LCD_PINS_D5 PE13 #define LCD_PINS_D6 PE14 #define LCD_PINS_D7 PE15 #endif // Alter timing for graphical display #if HAS_GRAPHICAL_LCD #ifndef BOARD_ST7920_DELAY_1 #define BOARD_ST7920_DELAY_1 DELAY_NS(96) #endif #ifndef BOARD_ST7920_DELAY_2 #define BOARD_ST7920_DELAY_2 DELAY_NS(48) #endif #ifndef BOARD_ST7920_DELAY_3 #define BOARD_ST7920_DELAY_3 DELAY_NS(600) #endif #endif #endif
{ "pile_set_name": "Github" }
.cm-s-the-matrix.CodeMirror { background: #000000; color: #00FF00; } .cm-s-the-matrix div.CodeMirror-selected { background: #2D2D2D !important; } .cm-s-the-matrix.CodeMirror ::selection { background: rgba(45, 45, 45, 0.99); } .cm-s-the-matrix.CodeMirror ::-moz-selection { background: rgba(45, 45, 45, 0.99); } .cm-s-the-matrix .CodeMirror-gutters { background: #060; border-right: 2px solid #00FF00; } .cm-s-the-matrix .CodeMirror-guttermarker { color: #0f0; } .cm-s-the-matrix .CodeMirror-guttermarker-subtle { color: white; } .cm-s-the-matrix .CodeMirror-linenumber { color: #FFFFFF; } .cm-s-the-matrix .CodeMirror-cursor { border-left: 1px solid #00FF00 !important; } .cm-s-the-matrix span.cm-keyword {color: #008803; font-weight: bold;} .cm-s-the-matrix span.cm-atom {color: #3FF;} .cm-s-the-matrix span.cm-number {color: #FFB94F;} .cm-s-the-matrix span.cm-def {color: #99C;} .cm-s-the-matrix span.cm-variable {color: #F6C;} .cm-s-the-matrix span.cm-variable-2 {color: #C6F;} .cm-s-the-matrix span.cm-variable-3 {color: #96F;} .cm-s-the-matrix span.cm-property {color: #62FFA0;} .cm-s-the-matrix span.cm-operator {color: #999} .cm-s-the-matrix span.cm-comment {color: #CCCCCC;} .cm-s-the-matrix span.cm-string {color: #39C;} .cm-s-the-matrix span.cm-meta {color: #C9F;} .cm-s-the-matrix span.cm-qualifier {color: #FFF700;} .cm-s-the-matrix span.cm-builtin {color: #30a;} .cm-s-the-matrix span.cm-bracket {color: #cc7;} .cm-s-the-matrix span.cm-tag {color: #FFBD40;} .cm-s-the-matrix span.cm-attribute {color: #FFF700;} .cm-s-the-matrix span.cm-error {color: #FF0000;} .cm-s-the-matrix .CodeMirror-activeline-background {background: #040;}
{ "pile_set_name": "Github" }
// Copyright (C) 2019 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.google.gerrit.acceptance.rest.project; import static com.google.common.truth.Truth.assertThat; import com.google.gerrit.entities.LabelFunction; import com.google.gerrit.extensions.common.LabelDefinitionInfo; import com.google.gerrit.server.config.AllProjectsNameProvider; public class LabelAssert { public static void assertCodeReviewLabel(LabelDefinitionInfo codeReviewLabel) { assertThat(codeReviewLabel.name).isEqualTo("Code-Review"); assertThat(codeReviewLabel.projectName).isEqualTo(AllProjectsNameProvider.DEFAULT); assertThat(codeReviewLabel.function).isEqualTo(LabelFunction.MAX_WITH_BLOCK.getFunctionName()); assertThat(codeReviewLabel.values) .containsExactly( "+2", "Looks good to me, approved", "+1", "Looks good to me, but someone else must approve", " 0", "No score", "-1", "I would prefer this is not merged as is", "-2", "This shall not be merged"); assertThat(codeReviewLabel.defaultValue).isEqualTo(0); assertThat(codeReviewLabel.branches).isNull(); assertThat(codeReviewLabel.canOverride).isTrue(); assertThat(codeReviewLabel.copyAnyScore).isNull(); assertThat(codeReviewLabel.copyMinScore).isTrue(); assertThat(codeReviewLabel.copyMaxScore).isNull(); assertThat(codeReviewLabel.copyAllScoresIfNoChange).isTrue(); assertThat(codeReviewLabel.copyAllScoresIfNoCodeChange).isNull(); assertThat(codeReviewLabel.copyAllScoresOnTrivialRebase).isTrue(); assertThat(codeReviewLabel.copyAllScoresOnMergeFirstParentUpdate).isNull(); assertThat(codeReviewLabel.copyValues).isNull(); assertThat(codeReviewLabel.allowPostSubmit).isTrue(); assertThat(codeReviewLabel.ignoreSelfApproval).isNull(); } private LabelAssert() {} }
{ "pile_set_name": "Github" }
<?php /** * Kunena Component * * @package Kunena.Template.Crypsis * @subpackage Layout.Message * * @copyright Copyright (C) 2008 - 2020 Kunena Team. All rights reserved. * @license https://www.gnu.org/copyleft/gpl.html GNU/GPL * @link https://www.kunena.org **/ defined('_JEXEC') or die; use Joomla\CMS\Factory; use Joomla\CMS\HTML\HTMLHelper; use Joomla\CMS\Language\Text; use Joomla\CMS\Uri\Uri; $colspan = !empty($this->actions) ? 4 : 3; $cols = empty($this->checkbox) ? 4 : 5; $view = Factory::getApplication()->input->getWord('view'); ?> <div class="row"> <div class="col-md-12"> <div class="pull-left"> <h1> <?php echo $this->escape($this->headerText); ?> <small class="hidden-xs"> (<?php echo Text::sprintf($this->messagemore, $this->formatLargeNumber($this->pagination->total)); ?> ) </small> <?php // ToDo:: <span class="badge badge-success"> <?php echo $this->topics->count->unread; ?/></span> ?> </h1> </div> <?php if ($view != 'user') : ?> <h2 class="filter-time pull-right" id="filter-time"> <div class="filter-sel pull-right"> <form action="<?php echo $this->escape(Uri::getInstance()->toString()); ?>" id="timeselect" name="timeselect" method="post" target="_self" class="form-inline hidden-xs"> <?php $this->displayTimeFilter('sel'); ?> <?php echo HTMLHelper::_('form.token'); ?> </form> </div> </h2> <?php endif; ?> </div> </div> <div class="pull-right"> <?php echo $this->subLayout('Widget/Search') ->set('catid', 'all') ->setLayout('topic'); ?> </div> <div class="pull-left"> <?php echo $this->subLayout('Widget/Pagination/List') ->set('pagination', $this->pagination->setDisplayedPages(4)) ->set('display', true); ?> </div> <form action="<?php echo KunenaRoute::_('index.php?option=com_kunena&view=topics'); ?>" method="post" name="ktopicsform" id="ktopicsform"> <?php echo HTMLHelper::_('form.token'); ?> <table class="table<?php echo KunenaTemplate::getInstance()->borderless(); ?>"> <thead> <?php if (empty($this->messages)) : ?> <tr> <td colspan="<?php echo $colspan; ?>"> <?php echo Text::_('COM_KUNENA_NO_POSTS') ?> </td> </tr> <?php else : ?> <tr class="category"> <td class="col-md-1 center hidden-xs"> <a id="forumtop"> </a> <a href="#forumbottom" rel="nofollow"> <?php echo KunenaIcons::arrowdown(); ?> </a> </td> <td class="col-md-<?php echo $cols; ?>"> <?php echo Text::_('COM_KUNENA_GEN_MESSAGE'); ?> / <?php echo Text::_('COM_KUNENA_GEN_SUBJECT'); ?> </td> <td class="col-md-2 hidden-xs"> <?php echo Text::_('COM_KUNENA_GEN_REPLIES'); ?> / <?php echo Text::_('COM_KUNENA_GEN_HITS'); ?> </td> <td class="col-md-3"> <?php echo Text::_('COM_KUNENA_GEN_LAST_POST'); ?> </td> <?php if (!empty($this->actions)) : ?> <td class="col-md-1 center"> <label> <input class="kcheckall" type="checkbox" name="toggle" value=""/> </label> </td> <?php endif; ?> </tr> <?php endif; ?> </thead> <tfoot> <?php if (!empty($this->messages)) : ?> <tr> <td class="center hidden-xs"> <a id="forumbottom"> </a> <a href="#forumtop" rel="nofollow"> <?php echo KunenaIcons::arrowup(); ?> </a> </td> <td colspan="<?php echo $colspan; ?>"> <div class="form-group"> <div class="input-group" role="group"> <div class="input-group-btn"> <?php if (!empty($this->moreUri)) { echo HTMLHelper::_('kunenaforum.link', $this->moreUri, Text::_('COM_KUNENA_MORE'), null, 'btn btn-primary pull-left', 'nofollow'); } ?> <?php if (!empty($this->actions)) : ?> <?php echo HTMLHelper::_('select.genericlist', $this->actions, 'task', 'class="form-control kchecktask" ', 'value', 'text', 0, 'kchecktask'); ?> <?php if (isset($this->actions['move'])) : $options = array(HTMLHelper::_('select.option', '0', Text::_('COM_KUNENA_BULK_CHOOSE_DESTINATION'))); echo HTMLHelper::_('kunenaforum.categorylist', 'target', 0, $options, array(), 'class="form-control fbs" disabled="disabled"', 'value', 'text', 0, 'kchecktarget'); endif; ?> <input type="submit" name="kcheckgo" class="btn btn-default" value="<?php echo Text::_('COM_KUNENA_GO') ?>"/> <?php endif; ?> </div> </div> </div> </td> </tr> <?php endif; ?> </tfoot> <tbody class="message-list"> <?php foreach ($this->messages as $i => $message) { echo $this->subLayout('Message/Row') ->set('message', $message) ->set('position', $i) ->set('checkbox', !empty($this->actions)); } ?> </tbody> </table> </form> <div class="pull-left"> <?php echo $this->subLayout('Widget/Pagination/List') ->set('pagination', $this->pagination->setDisplayedPages(4)) ->set('display', true); ?> </div> <?php if ($view != 'user') : ?> <form action="<?php echo $this->escape(Uri::getInstance()->toString()); ?>" id="timeselect" name="timeselect" method="post" target="_self" class="timefilter pull-right"> <?php $this->displayTimeFilter('sel'); ?> </form> <?php endif; ?> <div class="clearfix"></div>
{ "pile_set_name": "Github" }
### Win32 build notes ### # Phil Ashby, Dec 2017 - Jan 2018 At present, MSYS2 on a Windows system is required to gather dependencies before building a Win32 version of gpredict using this build system. Install MSYS2, open a shell and install the Gtk3 and Goocanvas2 packages, following the instructions from GTK team: https://www.gtk.org/download/windows.php Once your MSYS2 output folder (/mingw32 or simlar) is accessible from this system, adjust the MINGW_ROOT parameter in config.mk to suit. You should now be able to cross-compile the Win32 version of GPredict using the 'make' command. Experimental Win32 build testing is being tracked in this ticket: https://github.com/csete/gpredict/issues/110 To build a deployable ZIP archive, use 'make dist', which packages all binary DLLs from dependant packages along with gpredict[-con].exe into a versioned ZIP. Good luck! Phlash.
{ "pile_set_name": "Github" }
using System.IO; using System.Text; using System.Xml.XPath; using ThoughtWorks.CruiseControl.Core.Util; namespace ThoughtWorks.CruiseControl.Core.Publishers { /// <summary> /// /// </summary> public class HtmlDetailsMessageBuilder : IMessageBuilder { private static readonly SystemPath HtmlCSSFile = new SystemPath(@"xsl\cruisecontrol.css"); private string htmlCss; private System.Collections.IList myXslFiles; /// <summary> /// Initializes a new instance of the <see cref="HtmlDetailsMessageBuilder" /> class. /// </summary> /// <remarks></remarks> public HtmlDetailsMessageBuilder() { } /// <summary> /// Gets or sets the XSL files. /// </summary> /// <value>The XSL files.</value> /// <remarks></remarks> public System.Collections.IList xslFiles { get { return myXslFiles; } set { myXslFiles = value; } } /// <summary> /// Builds the message. /// </summary> /// <param name="result">The result.</param> /// <returns></returns> /// <remarks></remarks> public string BuildMessage(IIntegrationResult result) { StringBuilder message = new StringBuilder(10000); AppendHtmlHeader(message); AppendLinkToWebPage(message, result); AppendHorizontalRule(message); AppendHtmlMessageDetails(message, result); AppendHtmlFooter(message); return message.ToString(); } private void AppendHtmlHeader(StringBuilder message) { message.Append("<html><head>"); message.Append("<style>"); message.Append(HtmlEmailCss); message.Append("</style>"); message.Append("</head><body>"); } private void AppendLinkToWebPage(StringBuilder message, IIntegrationResult result) { message.Append(new HtmlLinkMessageBuilder(true).BuildMessage(result)); } private void AppendHorizontalRule(StringBuilder message) { message.Append(@"<p></p><hr size=""1"" width=""98%"" align=""left"" color=""#888888""/>"); } private void AppendHtmlMessageDetails(StringBuilder message, IIntegrationResult result) { StringWriter buffer = new StringWriter(); using (XmlIntegrationResultWriter integrationWriter = new XmlIntegrationResultWriter(buffer)) { integrationWriter.Write(result); } XPathDocument xml = new XPathDocument(new StringReader(buffer.ToString())); if (xslFiles == null) { message.Append(new BuildLogTransformer().TransformResultsWithAllStyleSheets(xml)); } else { message.Append(new BuildLogTransformer().TransformResults(xslFiles,xml )); } } private void AppendHtmlFooter(StringBuilder message) { message.Append("</body></html>"); } private string HtmlEmailCss { get { if (htmlCss == null) { htmlCss = HtmlCSSFile.ReadTextFile(); } return htmlCss; } } } }
{ "pile_set_name": "Github" }
const babelConfig = { presets: ["@babel/preset-env"], plugins: ["istanbul"], }; module.exports = (babel) => { babel.cache.never(); return babelConfig; };
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <grit-part> <include name="IDR_WEBUI_JS_CR_UI_FOCUS_ROW_BEHAVIOR_M_JS" file="${root_gen_dir}/ui/webui/resources/js/cr/ui/focus_row_behavior.m.js" use_base_dir="false" type="BINDATA" /> <include name="IDR_WEBUI_JS_FIND_SHORTCUT_BEHAVIOR_M_JS" file="${root_gen_dir}/ui/webui/resources/js/find_shortcut_behavior.m.js" use_base_dir="false" type="BINDATA" /> <include name="IDR_WEBUI_JS_I18N_BEHAVIOR_M_JS" file="${root_gen_dir}/ui/webui/resources/js/i18n_behavior.m.js" use_base_dir="false" type="BINDATA" preprocess="true" /> <include name="IDR_WEBUI_JS_LIST_PROPERTY_UPDATE_BEHAVIOR_M_JS" file="${root_gen_dir}/ui/webui/resources/js/list_property_update_behavior.m.js" use_base_dir="false" type="BINDATA" /> <include name="IDR_WEBUI_JS_SEARCH_HIGHLIGHT_UTILS_M_JS" file="${root_gen_dir}/ui/webui/resources/js/search_highlight_utils.m.js" use_base_dir="false" type="BINDATA" /> <include name="IDR_WEBUI_JS_WEBUI_LISTENER_BEHAVIOR_M_JS" file="${root_gen_dir}/ui/webui/resources/js/web_ui_listener_behavior.m.js" use_base_dir="false" type="BINDATA" /> </grit-part>
{ "pile_set_name": "Github" }
# Generated by h2py from /usr/include/dlfcn.h from TYPES import * RTLD_LAZY = 0x00001 RTLD_NOW = 0x00002 RTLD_NOLOAD = 0x00004 RTLD_GLOBAL = 0x00100 RTLD_LOCAL = 0x00000 RTLD_PARENT = 0x00200 RTLD_GROUP = 0x00400 RTLD_WORLD = 0x00800 RTLD_NODELETE = 0x01000 RTLD_CONFGEN = 0x10000 RTLD_REL_RELATIVE = 0x00001 RTLD_REL_EXEC = 0x00002 RTLD_REL_DEPENDS = 0x00004 RTLD_REL_PRELOAD = 0x00008 RTLD_REL_SELF = 0x00010 RTLD_REL_WEAK = 0x00020 RTLD_REL_ALL = 0x00fff RTLD_MEMORY = 0x01000 RTLD_STRIP = 0x02000 RTLD_NOHEAP = 0x04000 RTLD_CONFSET = 0x10000 RTLD_DI_LMID = 1 RTLD_DI_LINKMAP = 2 RTLD_DI_CONFIGADDR = 3 RTLD_DI_MAX = 3
{ "pile_set_name": "Github" }
/* Copyright 2016 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 rest import ( autoscalingapiv1 "k8s.io/api/autoscaling/v1" autoscalingapiv2beta1 "k8s.io/api/autoscaling/v2beta1" "k8s.io/apiserver/pkg/registry/generic" "k8s.io/apiserver/pkg/registry/rest" genericapiserver "k8s.io/apiserver/pkg/server" serverstorage "k8s.io/apiserver/pkg/server/storage" "k8s.io/kubernetes/pkg/api/legacyscheme" "k8s.io/kubernetes/pkg/apis/autoscaling" horizontalpodautoscalerstore "k8s.io/kubernetes/pkg/registry/autoscaling/horizontalpodautoscaler/storage" ) type RESTStorageProvider struct{} func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) { apiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(autoscaling.GroupName, legacyscheme.Registry, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs) // If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities. // TODO refactor the plumbing to provide the information in the APIGroupInfo if apiResourceConfigSource.VersionEnabled(autoscalingapiv2beta1.SchemeGroupVersion) { apiGroupInfo.VersionedResourcesStorageMap[autoscalingapiv2beta1.SchemeGroupVersion.Version] = p.v2beta1Storage(apiResourceConfigSource, restOptionsGetter) apiGroupInfo.GroupMeta.GroupVersion = autoscalingapiv2beta1.SchemeGroupVersion } if apiResourceConfigSource.VersionEnabled(autoscalingapiv1.SchemeGroupVersion) { apiGroupInfo.VersionedResourcesStorageMap[autoscalingapiv1.SchemeGroupVersion.Version] = p.v1Storage(apiResourceConfigSource, restOptionsGetter) apiGroupInfo.GroupMeta.GroupVersion = autoscalingapiv1.SchemeGroupVersion } return apiGroupInfo, true } func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage { storage := map[string]rest.Storage{} // horizontalpodautoscalers hpaStorage, hpaStatusStorage := horizontalpodautoscalerstore.NewREST(restOptionsGetter) storage["horizontalpodautoscalers"] = hpaStorage storage["horizontalpodautoscalers/status"] = hpaStatusStorage return storage } func (p RESTStorageProvider) v2beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage { storage := map[string]rest.Storage{} // horizontalpodautoscalers hpaStorage, hpaStatusStorage := horizontalpodautoscalerstore.NewREST(restOptionsGetter) storage["horizontalpodautoscalers"] = hpaStorage storage["horizontalpodautoscalers/status"] = hpaStatusStorage return storage } func (p RESTStorageProvider) GroupName() string { return autoscaling.GroupName }
{ "pile_set_name": "Github" }
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /************************************************************* * * MathJax/extensions/MatchWebFonts.js * * Adds code to the output jax so that if web fonts are used on the page, * MathJax will be able to detect their arrival and update the math to * accommodate the change in font. For the NativeMML output, this works * both for web fonts in main text, and for web fonts in the math as well. * * --------------------------------------------------------------------- * * Copyright (c) 2013-2018 The MathJax Consortium * * 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. */ (function (HUB,AJAX) { var VERSION = "2.7.5"; var CONFIG = MathJax.Hub.CombineConfig("MatchWebFonts",{ matchFor: { "HTML-CSS": true, NativeMML: true, SVG: true }, fontCheckDelay: 500, // initial delay for the first check for web fonts fontCheckTimeout: 15 * 1000, // how long to keep looking for fonts (15 seconds) }); MathJax.Extension.MatchWebFonts = { version: VERSION, config: CONFIG }; HUB.Register.StartupHook("HTML-CSS Jax Ready",function () { var HTMLCSS = MathJax.OutputJax["HTML-CSS"]; var POSTTRANSLATE = HTMLCSS.postTranslate; HTMLCSS.Augment({ postTranslate: function (state,partial) { if (!partial && CONFIG.matchFor["HTML-CSS"] && this.config.matchFontHeight) { // // Check for changes in the web fonts that might affect the font // size for math elements. This is a periodic check that goes on // until a timeout is reached. // AJAX.timer.start(AJAX,["checkFonts",this,state.jax[this.id]], CONFIG.fontCheckDelay,CONFIG.fontCheckTimeout); } return POSTTRANSLATE.apply(this,arguments); // do the original function }, checkFonts: function (check,scripts) { if (check.time(function () {})) return; var size = [], i, m, retry = false; // // Add the elements used for testing ex and em sizes // for (i = 0, m = scripts.length; i < m; i++) { script = scripts[i]; if (script.parentNode && script.MathJax.elementJax) { script.parentNode.insertBefore(this.EmExSpan.cloneNode(true),script); } } // // Check to see if anything has changed // for (i = 0, m = scripts.length; i < m; i++) { script = scripts[i]; if (!script.parentNode) continue; retry = true; var jax = script.MathJax.elementJax; if (!jax) continue; // // Check if ex or mex has changed // var test = script.previousSibling; var ex = test.firstChild.offsetHeight/60; var em = test.lastChild.lastChild.offsetHeight/60; if (ex === 0 || ex === "NaN") {ex = this.defaultEx; em = this.defaultEm} if (ex !== jax.HTMLCSS.ex || em !== jax.HTMLCSS.em) { var scale = ex/this.TeX.x_height/em; scale = Math.floor(Math.max(this.config.minScaleAdjust/100,scale)*this.config.scale); if (scale/100 !== jax.scale) {size.push(script); scripts[i] = {}} } } // // Remove markers // scripts = scripts.concat(size); // some scripts have been moved to the size array for (i = 0, m = scripts.length; i < m; i++) { script = scripts[i]; if (script && script.parentNode && script.MathJax.elementJax) { script.parentNode.removeChild(script.previousSibling); } } // // Rerender the changed items // if (size.length) {HUB.Queue(["Rerender",HUB,[size],{}])} // // Try again later // if (retry) {setTimeout(check,check.delay)} } }); }); HUB.Register.StartupHook("SVG Jax Ready",function () { var SVG = MathJax.OutputJax.SVG; var POSTTRANSLATE = SVG.postTranslate; SVG.Augment({ postTranslate: function (state,partial) { if (!partial && CONFIG.matchFor.SVG) { // // Check for changes in the web fonts that might affect the font // size for math elements. This is a periodic check that goes on // until a timeout is reached. // AJAX.timer.start(AJAX,["checkFonts",this,state.jax[this.id]], CONFIG.fontCheckDelay,CONFIG.fontCheckTimeout); } return POSTTRANSLATE.apply(this,arguments); // do the original function }, checkFonts: function (check,scripts) { if (check.time(function () {})) return; var size = [], i, m, retry = false; // // Add the elements used for testing ex and em sizes // for (i = 0, m = scripts.length; i < m; i++) { script = scripts[i]; if (script.parentNode && script.MathJax.elementJax) { script.parentNode.insertBefore(this.ExSpan.cloneNode(true),script); } } // // Check to see if anything has changed // for (i = 0, m = scripts.length; i < m; i++) { script = scripts[i]; if (!script.parentNode) continue; retry = true; var jax = script.MathJax.elementJax; if (!jax) continue; // // Check if ex or mex has changed // var test = script.previousSibling; var ex = test.firstChild.offsetHeight/60; if (ex === 0 || ex === "NaN") {ex = this.defaultEx} if (ex !== jax.SVG.ex) {size.push(script); scripts[i] = {}} } // // Remove markers // scripts = scripts.concat(size); // some scripts have been moved to the size array for (i = 0, m = scripts.length; i < m; i++) { script = scripts[i]; if (script.parentNode && script.MathJax.elementJax) { script.parentNode.removeChild(script.previousSibling); } } // // Rerender the changed items // if (size.length) {HUB.Queue(["Rerender",HUB,[size],{}])} // // Try again later (if not all the scripts are null) // if (retry) setTimeout(check,check.delay); } }); }); HUB.Register.StartupHook("NativeMML Jax Ready",function () { var nMML = MathJax.OutputJax.NativeMML; var POSTTRANSLATE = nMML.postTranslate; nMML.Augment({ postTranslate: function (state) { if (!HUB.Browser.isMSIE && CONFIG.matchFor.NativeMML) { // // Check for changes in the web fonts that might affect the sizes // of math elements. This is a periodic check that goes on until // a timeout is reached. // AJAX.timer.start(AJAX,["checkFonts",this,state.jax[this.id]], CONFIG.fontCheckDelay,CONFIG.fontCheckTimeout); } POSTTRANSLATE.apply(this,arguments); // do the original routine }, // // Check to see if web fonts have been loaded that change the ex size // of the surrounding font, the ex size within the math, or the widths // of math elements. We do this by rechecking the ex and mex sizes // (to see if the font scaling needs adjusting) and by checking the // size of the inner mrow of math elements and mtd elements. The // sizes of these have been stored in the NativeMML object of the // element jax so that we can check for them here. // checkFonts: function (check,scripts) { if (check.time(function () {})) return; var adjust = [], mtd = [], size = [], i, m, script; // // Add the elements used for testing ex and em sizes // for (i = 0, m = scripts.length; i < m; i++) { script = scripts[i]; if (script.parentNode && script.MathJax.elementJax) { script.parentNode.insertBefore(this.EmExSpan.cloneNode(true),script); } } // // Check to see if anything has changed // for (i = 0, m = scripts.length; i < m; i++) { script = scripts[i]; if (!script.parentNode) continue; var jax = script.MathJax.elementJax; if (!jax) continue; var span = document.getElementById(jax.inputID+"-Frame"); var math = span.getElementsByTagName("math")[0]; if (!math) continue; jax = jax.NativeMML; // // Check if ex or mex has changed // var test = script.previousSibling; var ex = test.firstChild.offsetWidth/60; var mex = test.lastChild.offsetWidth/60; if (ex === 0 || ex === "NaN") {ex = this.defaultEx; mex = this.defaultMEx} var newEx = (ex !== jax.ex); if (newEx || mex != jax.mex) { var scale = (this.config.matchFontHeight && mex > 1 ? ex/mex : 1); scale = Math.floor(Math.max(this.config.minScaleAdjust/100,scale) * this.config.scale); if (scale/100 !== jax.scale) {size.push([span.style,scale])} jax.scale = scale/100; jax.fontScale = scale+"%"; jax.ex = ex; jax.mex = mex; } // // Check width of math elements // if ("scrollWidth" in jax && (newEx || jax.scrollWidth !== math.firstChild.scrollWidth)) { jax.scrollWidth = math.firstChild.scrollWidth; adjust.push([math.parentNode.style,jax.scrollWidth/jax.ex/jax.scale]); } // // Check widths of mtd elements // if (math.MathJaxMtds) { for (var j = 0, n = math.MathJaxMtds.length; j < n; j++) { if (!math.MathJaxMtds[j].parentNode) continue; if (newEx || math.MathJaxMtds[j].firstChild.scrollWidth !== jax.mtds[j]) { jax.mtds[j] = math.MathJaxMtds[j].firstChild.scrollWidth; mtd.push([math.MathJaxMtds[j],jax.mtds[j]/jax.ex]); } } } } // // Remove markers // for (i = 0, m = scripts.length; i < m; i++) { script = scripts[i]; if (script.parentNode && script.MathJax.elementJax) { script.parentNode.removeChild(script.previousSibling); } } // // Adjust scaling factor // for (i = 0, m = size.length; i < m; i++) { size[i][0].fontSize = size[i][1] + "%"; } // // Adjust width of spans containing math elements that have changed // for (i = 0, m = adjust.length; i < m; i++) { adjust[i][0].width = adjust[i][1].toFixed(3)+"ex"; } // // Adjust widths of mtd elements that have changed // for (i = 0, m = mtd.length; i < m; i++) { var style = mtd[i][0].getAttribute("style"); style = style.replace(/(($|;)\s*min-width:).*?ex/,"$1 "+mtd[i][1].toFixed(3)+"ex"); mtd[i][0].setAttribute("style",style); } // // Try again later // setTimeout(check,check.delay); } }); }); HUB.Startup.signal.Post("MatchWebFonts Extension Ready"); AJAX.loadComplete("[MathJax]/extensions/MatchWebFonts.js"); })(MathJax.Hub,MathJax.Ajax);
{ "pile_set_name": "Github" }
/* * jpeglib.h * * Copyright (C) 1991-1998, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file defines the application interface for the JPEG library. * Most applications using the library need only include this file, * and perhaps jerror.h if they want to know the exact error codes. */ #ifndef JPEGLIB_H #define JPEGLIB_H /* * First we include the configuration files that record how this * installation of the JPEG library is set up. jconfig.h can be * generated automatically for many systems. jmorecfg.h contains * manual configuration options that most people need not worry about. */ #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */ #include "jconfig.h" /* widely used configuration options */ #endif #include "jmorecfg.h" /* seldom changed options */ /* Version ID for the JPEG library. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60". */ #define JPEG_LIB_VERSION 62 /* Version 6b */ /* Various constants determining the sizes of things. * All of these are specified by the JPEG standard, so don't change them * if you want to be compatible. */ #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */ #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */ #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */ #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */ #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */ #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */ #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */ /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard; * the PostScript DCT filter can emit files with many more than 10 blocks/MCU. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU * to handle it. We even let you do this from the jconfig.h file. However, * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe * sometimes emits noncompliant files doesn't mean you should too. */ #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */ #ifndef D_MAX_BLOCKS_IN_MCU #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */ #endif /* Data structures for images (arrays of samples and of DCT coefficients). * On 80x86 machines, the image arrays are too big for near pointers, * but the pointer arrays can fit in near memory. */ typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */ typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */ typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */ typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */ typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */ typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */ typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */ typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */ /* Types for JPEG compression parameters and working tables. */ /* DCT coefficient quantization tables. */ typedef struct { /* This array gives the coefficient quantizers in natural array order * (not the zigzag order in which they are stored in a JPEG DQT marker). * CAUTION: IJG versions prior to v6a kept this array in zigzag order. */ UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */ /* This field is used only during compression. It's initialized FALSE when * the table is created, and set TRUE when it's been output to the file. * You could suppress output of a table by setting this to TRUE. * (See jpeg_suppress_tables for an example.) */ boolean sent_table; /* TRUE when table has been output */ } JQUANT_TBL; /* Huffman coding tables. */ typedef struct { /* These two fields directly represent the contents of a JPEG DHT marker */ UINT8 bits[17]; /* bits[k] = # of symbols with codes of */ /* length k bits; bits[0] is unused */ UINT8 huffval[256]; /* The symbols, in order of incr code length */ /* This field is used only during compression. It's initialized FALSE when * the table is created, and set TRUE when it's been output to the file. * You could suppress output of a table by setting this to TRUE. * (See jpeg_suppress_tables for an example.) */ boolean sent_table; /* TRUE when table has been output */ } JHUFF_TBL; /* Basic info about one component (color channel). */ typedef struct { /* These values are fixed over the whole image. */ /* For compression, they must be supplied by parameter setup; */ /* for decompression, they are read from the SOF marker. */ int component_id; /* identifier for this component (0..255) */ int component_index; /* its index in SOF or cinfo->comp_info[] */ int h_samp_factor; /* horizontal sampling factor (1..4) */ int v_samp_factor; /* vertical sampling factor (1..4) */ int quant_tbl_no; /* quantization table selector (0..3) */ /* These values may vary between scans. */ /* For compression, they must be supplied by parameter setup; */ /* for decompression, they are read from the SOS marker. */ /* The decompressor output side may not use these variables. */ int dc_tbl_no; /* DC entropy table selector (0..3) */ int ac_tbl_no; /* AC entropy table selector (0..3) */ /* Remaining fields should be treated as private by applications. */ /* These values are computed during compression or decompression startup: */ /* Component's size in DCT blocks. * Any dummy blocks added to complete an MCU are not counted; therefore * these values do not depend on whether a scan is interleaved or not. */ JDIMENSION width_in_blocks; JDIMENSION height_in_blocks; /* Size of a DCT block in samples. Always DCTSIZE for compression. * For decompression this is the size of the output from one DCT block, * reflecting any scaling we choose to apply during the IDCT step. * Values of 1,2,4,8 are likely to be supported. Note that different * components may receive different IDCT scalings. */ int DCT_scaled_size; /* The downsampled dimensions are the component's actual, unpadded number * of samples at the main buffer (preprocessing/compression interface), thus * downsampled_width = ceil(image_width * Hi/Hmax) * and similarly for height. For decompression, IDCT scaling is included, so * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE) */ JDIMENSION downsampled_width; /* actual width in samples */ JDIMENSION downsampled_height; /* actual height in samples */ /* This flag is used only for decompression. In cases where some of the * components will be ignored (eg grayscale output from YCbCr image), * we can skip most computations for the unused components. */ boolean component_needed; /* do we need the value of this component? */ /* These values are computed before starting a scan of the component. */ /* The decompressor output side may not use these variables. */ int MCU_width; /* number of blocks per MCU, horizontally */ int MCU_height; /* number of blocks per MCU, vertically */ int MCU_blocks; /* MCU_width * MCU_height */ int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */ int last_col_width; /* # of non-dummy blocks across in last MCU */ int last_row_height; /* # of non-dummy blocks down in last MCU */ /* Saved quantization table for component; NULL if none yet saved. * See jdinput.c comments about the need for this information. * This field is currently used only for decompression. */ JQUANT_TBL * quant_table; /* Private per-component storage for DCT or IDCT subsystem. */ void * dct_table; } jpeg_component_info; /* The script for encoding a multiple-scan file is an array of these: */ typedef struct { int comps_in_scan; /* number of components encoded in this scan */ int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */ int Ss, Se; /* progressive JPEG spectral selection parms */ int Ah, Al; /* progressive JPEG successive approx. parms */ } jpeg_scan_info; /* The decompressor can save APPn and COM markers in a list of these: */ typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr; struct jpeg_marker_struct { jpeg_saved_marker_ptr next; /* next in list, or NULL */ UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */ unsigned int original_length; /* # bytes of data in the file */ unsigned int data_length; /* # bytes of data saved at data[] */ JOCTET FAR * data; /* the data contained in the marker */ /* the marker length word is not counted in data_length or original_length */ }; /* Known color spaces. */ typedef enum { JCS_UNKNOWN, /* error/unspecified */ JCS_GRAYSCALE, /* monochrome */ JCS_RGB, /* red/green/blue */ JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */ JCS_CMYK, /* C/M/Y/K */ JCS_YCCK /* Y/Cb/Cr/K */ } J_COLOR_SPACE; /* DCT/IDCT algorithm options. */ typedef enum { JDCT_ISLOW, /* slow but accurate integer algorithm */ JDCT_IFAST, /* faster, less accurate integer method */ JDCT_FLOAT /* floating-point: accurate, fast on fast HW */ } J_DCT_METHOD; #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */ #define JDCT_DEFAULT JDCT_ISLOW #endif #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */ #define JDCT_FASTEST JDCT_IFAST #endif /* Dithering options for decompression. */ typedef enum { JDITHER_NONE, /* no dithering */ JDITHER_ORDERED, /* simple ordered dither */ JDITHER_FS /* Floyd-Steinberg error diffusion dither */ } J_DITHER_MODE; /* Common fields between JPEG compression and decompression master structs. */ #define jpeg_common_fields \ struct jpeg_error_mgr * err; /* Error handler module */\ struct jpeg_memory_mgr * mem; /* Memory manager module */\ struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\ void * client_data; /* Available for use by application */\ boolean is_decompressor; /* So common code can tell which is which */\ int global_state /* For checking call sequence validity */ /* Routines that are to be used by both halves of the library are declared * to receive a pointer to this structure. There are no actual instances of * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct. */ struct jpeg_common_struct { jpeg_common_fields; /* Fields common to both master struct types */ /* Additional fields follow in an actual jpeg_compress_struct or * jpeg_decompress_struct. All three structs must agree on these * initial fields! (This would be a lot cleaner in C++.) */ }; typedef struct jpeg_common_struct * j_common_ptr; typedef struct jpeg_compress_struct * j_compress_ptr; typedef struct jpeg_decompress_struct * j_decompress_ptr; /* Master record for a compression instance */ struct jpeg_compress_struct { jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */ /* Destination for compressed data */ struct jpeg_destination_mgr * dest; /* Description of source image --- these fields must be filled in by * outer application before starting compression. in_color_space must * be correct before you can even call jpeg_set_defaults(). */ JDIMENSION image_width; /* input image width */ JDIMENSION image_height; /* input image height */ int input_components; /* # of color components in input image */ J_COLOR_SPACE in_color_space; /* colorspace of input image */ double input_gamma; /* image gamma of input image */ /* Compression parameters --- these fields must be set before calling * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to * initialize everything to reasonable defaults, then changing anything * the application specifically wants to change. That way you won't get * burnt when new parameters are added. Also note that there are several * helper routines to simplify changing parameters. */ int data_precision; /* bits of precision in image data */ int num_components; /* # of color components in JPEG image */ J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ jpeg_component_info * comp_info; /* comp_info[i] describes component that appears i'th in SOF */ JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]; /* ptrs to coefficient quantization tables, or NULL if not defined */ JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; /* ptrs to Huffman coding tables, or NULL if not defined */ UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ int num_scans; /* # of entries in scan_info array */ const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */ /* The default value of scan_info is NULL, which causes a single-scan * sequential JPEG file to be emitted. To create a multi-scan file, * set num_scans and scan_info to point to an array of scan definitions. */ boolean raw_data_in; /* TRUE=caller supplies downsampled data */ boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ boolean optimize_coding; /* TRUE=optimize entropy encoding parms */ boolean CCIR601_sampling; /* TRUE=first samples are cosited */ int smoothing_factor; /* 1..100, or 0 for no input smoothing */ J_DCT_METHOD dct_method; /* DCT algorithm selector */ /* The restart interval can be specified in absolute MCUs by setting * restart_interval, or in MCU rows by setting restart_in_rows * (in which case the correct restart_interval will be figured * for each scan). */ unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */ int restart_in_rows; /* if > 0, MCU rows per restart interval */ /* Parameters controlling emission of special markers. */ boolean write_JFIF_header; /* should a JFIF marker be written? */ UINT8 JFIF_major_version; /* What to write for the JFIF version number */ UINT8 JFIF_minor_version; /* These three values are not used by the JPEG code, merely copied */ /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */ /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */ /* ratio is defined by X_density/Y_density even when density_unit=0. */ UINT8 density_unit; /* JFIF code for pixel size units */ UINT16 X_density; /* Horizontal pixel density */ UINT16 Y_density; /* Vertical pixel density */ boolean write_Adobe_marker; /* should an Adobe marker be written? */ /* State variable: index of next scanline to be written to * jpeg_write_scanlines(). Application may use this to control its * processing loop, e.g., "while (next_scanline < image_height)". */ JDIMENSION next_scanline; /* 0 .. image_height-1 */ /* Remaining fields are known throughout compressor, but generally * should not be touched by a surrounding application. */ /* * These fields are computed during compression startup */ boolean progressive_mode; /* TRUE if scan script uses progressive mode */ int max_h_samp_factor; /* largest h_samp_factor */ int max_v_samp_factor; /* largest v_samp_factor */ JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */ /* The coefficient controller receives data in units of MCU rows as defined * for fully interleaved scans (whether the JPEG file is interleaved or not). * There are v_samp_factor * DCTSIZE sample rows of each component in an * "iMCU" (interleaved MCU) row. */ /* * These fields are valid during any one scan. * They describe the components and MCUs actually appearing in the scan. */ int comps_in_scan; /* # of JPEG components in this scan */ jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN]; /* *cur_comp_info[i] describes component that appears i'th in SOS */ JDIMENSION MCUs_per_row; /* # of MCUs across the image */ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ int blocks_in_MCU; /* # of DCT blocks per MCU */ int MCU_membership[C_MAX_BLOCKS_IN_MCU]; /* MCU_membership[i] is index in cur_comp_info of component owning */ /* i'th block in an MCU */ int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ /* * Links to compression subobjects (methods and private variables of modules) */ struct jpeg_comp_master * master; struct jpeg_c_main_controller * main; struct jpeg_c_prep_controller * prep; struct jpeg_c_coef_controller * coef; struct jpeg_marker_writer * marker; struct jpeg_color_converter * cconvert; struct jpeg_downsampler * downsample; struct jpeg_forward_dct * fdct; struct jpeg_entropy_encoder * entropy; jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */ int script_space_size; }; /* Master record for a decompression instance */ struct jpeg_decompress_struct { jpeg_common_fields; /* Fields shared with jpeg_compress_struct */ /* Source of compressed data */ struct jpeg_source_mgr * src; /* Basic description of image --- filled in by jpeg_read_header(). */ /* Application may inspect these values to decide how to process image. */ JDIMENSION image_width; /* nominal image width (from SOF marker) */ JDIMENSION image_height; /* nominal image height */ int num_components; /* # of color components in JPEG image */ J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ /* Decompression processing parameters --- these fields must be set before * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes * them to default values. */ J_COLOR_SPACE out_color_space; /* colorspace for output */ unsigned int scale_num, scale_denom; /* fraction by which to scale image */ double output_gamma; /* image gamma wanted in output */ boolean buffered_image; /* TRUE=multiple output passes */ boolean raw_data_out; /* TRUE=downsampled data wanted */ J_DCT_METHOD dct_method; /* IDCT algorithm selector */ boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */ boolean do_block_smoothing; /* TRUE=apply interblock smoothing */ boolean quantize_colors; /* TRUE=colormapped output wanted */ /* the following are ignored if not quantize_colors: */ J_DITHER_MODE dither_mode; /* type of color dithering to use */ boolean two_pass_quantize; /* TRUE=use two-pass color quantization */ int desired_number_of_colors; /* max # colors to use in created colormap */ /* these are significant only in buffered-image mode: */ boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */ boolean enable_external_quant;/* enable future use of external colormap */ boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */ /* Description of actual output image that will be returned to application. * These fields are computed by jpeg_start_decompress(). * You can also use jpeg_calc_output_dimensions() to determine these values * in advance of calling jpeg_start_decompress(). */ JDIMENSION output_width; /* scaled image width */ JDIMENSION output_height; /* scaled image height */ int out_color_components; /* # of color components in out_color_space */ int output_components; /* # of color components returned */ /* output_components is 1 (a colormap index) when quantizing colors; * otherwise it equals out_color_components. */ int rec_outbuf_height; /* min recommended height of scanline buffer */ /* If the buffer passed to jpeg_read_scanlines() is less than this many rows * high, space and time will be wasted due to unnecessary data copying. * Usually rec_outbuf_height will be 1 or 2, at most 4. */ /* When quantizing colors, the output colormap is described by these fields. * The application can supply a colormap by setting colormap non-NULL before * calling jpeg_start_decompress; otherwise a colormap is created during * jpeg_start_decompress or jpeg_start_output. * The map has out_color_components rows and actual_number_of_colors columns. */ int actual_number_of_colors; /* number of entries in use */ JSAMPARRAY colormap; /* The color map as a 2-D pixel array */ /* State variables: these variables indicate the progress of decompression. * The application may examine these but must not modify them. */ /* Row index of next scanline to be read from jpeg_read_scanlines(). * Application may use this to control its processing loop, e.g., * "while (output_scanline < output_height)". */ JDIMENSION output_scanline; /* 0 .. output_height-1 */ /* Current input scan number and number of iMCU rows completed in scan. * These indicate the progress of the decompressor input side. */ int input_scan_number; /* Number of SOS markers seen so far */ JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */ /* The "output scan number" is the notional scan being displayed by the * output side. The decompressor will not allow output scan/row number * to get ahead of input scan/row, but it can fall arbitrarily far behind. */ int output_scan_number; /* Nominal scan number being displayed */ JDIMENSION output_iMCU_row; /* Number of iMCU rows read */ /* Current progression status. coef_bits[c][i] indicates the precision * with which component c's DCT coefficient i (in zigzag order) is known. * It is -1 when no data has yet been received, otherwise it is the point * transform (shift) value for the most recent scan of the coefficient * (thus, 0 at completion of the progression). * This pointer is NULL when reading a non-progressive file. */ int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */ /* Internal JPEG parameters --- the application usually need not look at * these fields. Note that the decompressor output side may not use * any parameters that can change between scans. */ /* Quantization and Huffman tables are carried forward across input * datastreams when processing abbreviated JPEG datastreams. */ JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]; /* ptrs to coefficient quantization tables, or NULL if not defined */ JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; /* ptrs to Huffman coding tables, or NULL if not defined */ /* These parameters are never carried across datastreams, since they * are given in SOF/SOS markers or defined to be reset by SOI. */ int data_precision; /* bits of precision in image data */ jpeg_component_info * comp_info; /* comp_info[i] describes component that appears i'th in SOF */ boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */ boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */ /* These fields record data obtained from optional markers recognized by * the JPEG library. */ boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */ /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */ UINT8 JFIF_major_version; /* JFIF version number */ UINT8 JFIF_minor_version; UINT8 density_unit; /* JFIF code for pixel size units */ UINT16 X_density; /* Horizontal pixel density */ UINT16 Y_density; /* Vertical pixel density */ boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */ UINT8 Adobe_transform; /* Color transform code from Adobe marker */ boolean CCIR601_sampling; /* TRUE=first samples are cosited */ /* Aside from the specific data retained from APPn markers known to the * library, the uninterpreted contents of any or all APPn and COM markers * can be saved in a list for examination by the application. */ jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */ /* Remaining fields are known throughout decompressor, but generally * should not be touched by a surrounding application. */ /* * These fields are computed during decompression startup */ int max_h_samp_factor; /* largest h_samp_factor */ int max_v_samp_factor; /* largest v_samp_factor */ int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */ JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */ /* The coefficient controller's input and output progress is measured in * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows * in fully interleaved JPEG scans, but are used whether the scan is * interleaved or not. We define an iMCU row as v_samp_factor DCT block * rows of each component. Therefore, the IDCT output contains * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row. */ JSAMPLE * sample_range_limit; /* table for fast range-limiting */ /* * These fields are valid during any one scan. * They describe the components and MCUs actually appearing in the scan. * Note that the decompressor output side must not use these fields. */ int comps_in_scan; /* # of JPEG components in this scan */ jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN]; /* *cur_comp_info[i] describes component that appears i'th in SOS */ JDIMENSION MCUs_per_row; /* # of MCUs across the image */ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ int blocks_in_MCU; /* # of DCT blocks per MCU */ int MCU_membership[D_MAX_BLOCKS_IN_MCU]; /* MCU_membership[i] is index in cur_comp_info of component owning */ /* i'th block in an MCU */ int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ /* This field is shared between entropy decoder and marker parser. * It is either zero or the code of a JPEG marker that has been * read from the data source, but has not yet been processed. */ int unread_marker; /* * Links to decompression subobjects (methods, private variables of modules) */ struct jpeg_decomp_master * master; struct jpeg_d_main_controller * main; struct jpeg_d_coef_controller * coef; struct jpeg_d_post_controller * post; struct jpeg_input_controller * inputctl; struct jpeg_marker_reader * marker; struct jpeg_entropy_decoder * entropy; struct jpeg_inverse_dct * idct; struct jpeg_upsampler * upsample; struct jpeg_color_deconverter * cconvert; struct jpeg_color_quantizer * cquantize; }; /* "Object" declarations for JPEG modules that may be supplied or called * directly by the surrounding application. * As with all objects in the JPEG library, these structs only define the * publicly visible methods and state variables of a module. Additional * private fields may exist after the public ones. */ /* Error handler object */ #if defined(__GNUC__) && __GNUC__ >= 3 && defined(ENABLE_LIBJPEG_NO_RETURN) #define LIBJPEG_NO_RETURN __attribute__((noreturn)) #else #define LIBJPEG_NO_RETURN #endif struct jpeg_error_mgr { /* Error exit handler: does not return to caller */ JMETHOD(void, error_exit, (j_common_ptr cinfo)) LIBJPEG_NO_RETURN; /* Conditionally emit a trace or warning message */ JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level)); /* Routine that actually outputs a trace or error message */ JMETHOD(void, output_message, (j_common_ptr cinfo)); /* Format a message string for the most recent JPEG error or message */ JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer)); #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */ /* Reset error state variables at start of a new image */ JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo)); /* The message ID code and any parameters are saved here. * A message can have one string parameter or up to 8 int parameters. */ int msg_code; #define JMSG_STR_PARM_MAX 80 union { int i[8]; char s[JMSG_STR_PARM_MAX]; } msg_parm; /* Standard state variables for error facility */ int trace_level; /* max msg_level that will be displayed */ /* For recoverable corrupt-data errors, we emit a warning message, * but keep going unless emit_message chooses to abort. emit_message * should count warnings in num_warnings. The surrounding application * can check for bad data by seeing if num_warnings is nonzero at the * end of processing. */ long num_warnings; /* number of corrupt-data warnings */ /* These fields point to the table(s) of error message strings. * An application can change the table pointer to switch to a different * message list (typically, to change the language in which errors are * reported). Some applications may wish to add additional error codes * that will be handled by the JPEG library error mechanism; the second * table pointer is used for this purpose. * * First table includes all errors generated by JPEG library itself. * Error code 0 is reserved for a "no such error string" message. */ const char * const * jpeg_message_table; /* Library errors */ int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */ /* Second table can be added by application (see cjpeg/djpeg for example). * It contains strings numbered first_addon_message..last_addon_message. */ const char * const * addon_message_table; /* Non-library errors */ int first_addon_message; /* code for first string in addon table */ int last_addon_message; /* code for last string in addon table */ }; /* Progress monitor object */ struct jpeg_progress_mgr { JMETHOD(void, progress_monitor, (j_common_ptr cinfo)); long pass_counter; /* work units completed in this pass */ long pass_limit; /* total number of work units in this pass */ int completed_passes; /* passes completed so far */ int total_passes; /* total number of passes expected */ }; /* Data destination object for compression */ struct jpeg_destination_mgr { JOCTET * next_output_byte; /* => next byte to write in buffer */ size_t free_in_buffer; /* # of byte spaces remaining in buffer */ JMETHOD(void, init_destination, (j_compress_ptr cinfo)); JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo)); JMETHOD(void, term_destination, (j_compress_ptr cinfo)); }; /* Data source object for decompression */ struct jpeg_source_mgr { const JOCTET * next_input_byte; /* => next byte to read from buffer */ size_t bytes_in_buffer; /* # of bytes remaining in buffer */ JMETHOD(void, init_source, (j_decompress_ptr cinfo)); JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo)); JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes)); JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired)); JMETHOD(void, term_source, (j_decompress_ptr cinfo)); }; /* Memory manager object. * Allocates "small" objects (a few K total), "large" objects (tens of K), * and "really big" objects (virtual arrays with backing store if needed). * The memory manager does not allow individual objects to be freed; rather, * each created object is assigned to a pool, and whole pools can be freed * at once. This is faster and more convenient than remembering exactly what * to free, especially where malloc()/free() are not too speedy. * NB: alloc routines never return NULL. They exit to error_exit if not * successful. */ #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */ #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */ #define JPOOL_NUMPOOLS 2 typedef struct jvirt_sarray_control * jvirt_sarray_ptr; typedef struct jvirt_barray_control * jvirt_barray_ptr; struct jpeg_memory_mgr { /* Method pointers */ JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id, size_t sizeofobject)); JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id, size_t sizeofobject)); JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id, JDIMENSION samplesperrow, JDIMENSION numrows)); JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id, JDIMENSION blocksperrow, JDIMENSION numrows)); JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo, int pool_id, boolean pre_zero, JDIMENSION samplesperrow, JDIMENSION numrows, JDIMENSION maxaccess)); JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo, int pool_id, boolean pre_zero, JDIMENSION blocksperrow, JDIMENSION numrows, JDIMENSION maxaccess)); JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo)); JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo, jvirt_sarray_ptr ptr, JDIMENSION start_row, JDIMENSION num_rows, boolean writable)); JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo, jvirt_barray_ptr ptr, JDIMENSION start_row, JDIMENSION num_rows, boolean writable)); JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id)); JMETHOD(void, self_destruct, (j_common_ptr cinfo)); /* Limit on memory allocation for this JPEG object. (Note that this is * merely advisory, not a guaranteed maximum; it only affects the space * used for virtual-array buffers.) May be changed by outer application * after creating the JPEG object. */ long max_memory_to_use; /* Maximum allocation request accepted by alloc_large. */ long max_alloc_chunk; }; /* Routine signature for application-supplied marker processing methods. * Need not pass marker code since it is stored in cinfo->unread_marker. */ typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo)); /* Declarations for routines called by application. * The JPP macro hides prototype parameters from compilers that can't cope. * Note JPP requires double parentheses. */ #ifdef HAVE_PROTOTYPES #define JPP(arglist) arglist #else #define JPP(arglist) () #endif /* Short forms of external names for systems with brain-damaged linkers. * We shorten external names to be unique in the first six letters, which * is good enough for all known systems. * (If your compiler itself needs names to be unique in less than 15 * characters, you are out of luck. Get a better compiler.) */ #ifdef NEED_SHORT_EXTERNAL_NAMES #define jpeg_std_error jStdError #define jpeg_CreateCompress jCreaCompress #define jpeg_CreateDecompress jCreaDecompress #define jpeg_destroy_compress jDestCompress #define jpeg_destroy_decompress jDestDecompress #define jpeg_stdio_dest jStdDest #define jpeg_stdio_src jStdSrc #define jpeg_set_defaults jSetDefaults #define jpeg_set_colorspace jSetColorspace #define jpeg_default_colorspace jDefColorspace #define jpeg_set_quality jSetQuality #define jpeg_set_linear_quality jSetLQuality #define jpeg_add_quant_table jAddQuantTable #define jpeg_quality_scaling jQualityScaling #define jpeg_simple_progression jSimProgress #define jpeg_suppress_tables jSuppressTables #define jpeg_alloc_quant_table jAlcQTable #define jpeg_alloc_huff_table jAlcHTable #define jpeg_start_compress jStrtCompress #define jpeg_write_scanlines jWrtScanlines #define jpeg_finish_compress jFinCompress #define jpeg_write_raw_data jWrtRawData #define jpeg_write_marker jWrtMarker #define jpeg_write_m_header jWrtMHeader #define jpeg_write_m_byte jWrtMByte #define jpeg_write_tables jWrtTables #define jpeg_read_header jReadHeader #define jpeg_start_decompress jStrtDecompress #define jpeg_read_scanlines jReadScanlines #define jpeg_finish_decompress jFinDecompress #define jpeg_read_raw_data jReadRawData #define jpeg_has_multiple_scans jHasMultScn #define jpeg_start_output jStrtOutput #define jpeg_finish_output jFinOutput #define jpeg_input_complete jInComplete #define jpeg_new_colormap jNewCMap #define jpeg_consume_input jConsumeInput #define jpeg_calc_output_dimensions jCalcDimensions #define jpeg_save_markers jSaveMarkers #define jpeg_set_marker_processor jSetMarker #define jpeg_read_coefficients jReadCoefs #define jpeg_write_coefficients jWrtCoefs #define jpeg_copy_critical_parameters jCopyCrit #define jpeg_abort_compress jAbrtCompress #define jpeg_abort_decompress jAbrtDecompress #define jpeg_abort jAbort #define jpeg_destroy jDestroy #define jpeg_resync_to_restart jResyncRestart #endif /* NEED_SHORT_EXTERNAL_NAMES */ /* Sometimes it is desirable to build with special external names for 12bit, so that 8bit and 12bit jpeg DLLs can be used in the same applications. */ #ifdef NEED_12_BIT_NAMES #define jpeg_std_error jpeg_std_error_12 #define jpeg_CreateCompress jpeg_CreateCompress_12 #define jpeg_CreateDecompress jpeg_CreateDecompress_12 #define jpeg_destroy_compress jpeg_destroy_compress_12 #define jpeg_destroy_decompress jpeg_destroy_decompress_12 #define jpeg_stdio_dest jpeg_stdio_dest_12 #define jpeg_stdio_src jpeg_stdio_src_12 #define jpeg_set_defaults jpeg_set_defaults_12 #define jpeg_set_colorspace jpeg_set_colorspace_12 #define jpeg_default_colorspace jpeg_default_colorspace_12 #define jpeg_set_quality jpeg_set_quality_12 #define jpeg_set_linear_quality jpeg_set_linear_quality_12 #define jpeg_add_quant_table jpeg_add_quant_table_12 #define jpeg_quality_scaling jpeg_quality_scaling_12 #define jpeg_simple_progression jpeg_simple_progression_12 #define jpeg_suppress_tables jpeg_suppress_tables_12 #define jpeg_alloc_quant_table jpeg_alloc_quant_table_12 #define jpeg_alloc_huff_table jpeg_alloc_huff_table_12 #define jpeg_start_compress jpeg_start_compress_12 #define jpeg_write_scanlines jpeg_write_scanlines_12 #define jpeg_finish_compress jpeg_finish_compress_12 #define jpeg_write_raw_data jpeg_write_raw_data_12 #define jpeg_write_marker jpeg_write_marker_12 #define jpeg_write_m_header jpeg_write_m_header_12 #define jpeg_write_m_byte jpeg_write_m_byte_12 #define jpeg_write_tables jpeg_write_tables_12 #define jpeg_read_header jpeg_read_header_12 #define jpeg_start_decompress jpeg_start_decompress_12 #define jpeg_read_scanlines jpeg_read_scanlines_12 #define jpeg_finish_decompress jpeg_finish_decompress_12 #define jpeg_read_raw_data jpeg_read_raw_data_12 #define jpeg_has_multiple_scans jpeg_has_multiple_scans_12 #define jpeg_start_output jpeg_start_output_12 #define jpeg_finish_output jpeg_finish_output_12 #define jpeg_input_complete jpeg_input_complete_12 #define jpeg_new_colormap jpeg_new_colormap_12 #define jpeg_consume_input jpeg_consume_input_12 #define jpeg_calc_output_dimensions jpeg_calc_output_dimensions_12 #define jpeg_save_markers jpeg_save_markers_12 #define jpeg_set_marker_processor jpeg_set_marker_processor_12 #define jpeg_read_coefficients jpeg_read_coefficients_12 #define jpeg_write_coefficients jpeg_write_coefficients_12 #define jpeg_copy_critical_parameters jpeg_copy_critical_parameters_12 #define jpeg_abort_compress jpeg_abort_compress_12 #define jpeg_abort_decompress jpeg_abort_decompress_12 #define jpeg_abort jpeg_abort_12 #define jpeg_destroy jpeg_destroy_12 #define jpeg_resync_to_restart jpeg_resync_to_restart_12 #endif /* NEED_SHORT_EXTERNAL_NAMES */ /* Default error-management setup */ EXTERN(struct jpeg_error_mgr *) jpeg_std_error JPP((struct jpeg_error_mgr * err)); /* Initialization of JPEG compression objects. * jpeg_create_compress() and jpeg_create_decompress() are the exported * names that applications should call. These expand to calls on * jpeg_CreateCompress and jpeg_CreateDecompress with additional information * passed for version mismatch checking. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx. */ #define jpeg_create_compress(cinfo) \ jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \ (size_t) sizeof(struct jpeg_compress_struct)) #define jpeg_create_decompress(cinfo) \ jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \ (size_t) sizeof(struct jpeg_decompress_struct)) EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo, int version, size_t structsize)); EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo, int version, size_t structsize)); /* Destruction of JPEG compression objects */ EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo)); EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo)); /* Standard data source and destination managers: stdio streams. */ /* Caller is responsible for opening the file before and closing after. */ EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile)); EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile)); /* Default parameter setup for compression */ EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo)); /* Compression parameter setup aids */ EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo, J_COLOR_SPACE colorspace)); EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo)); EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality, boolean force_baseline)); EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo, int scale_factor, boolean force_baseline)); EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl, const unsigned int *basic_table, int scale_factor, boolean force_baseline)); EXTERN(int) jpeg_quality_scaling JPP((int quality)); EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo)); EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo, boolean suppress)); EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo)); EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo)); /* Main entry points for compression */ EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo, boolean write_all_tables)); EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION num_lines)); EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo)); /* Replaces jpeg_write_scanlines when writing raw downsampled data. */ EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo, JSAMPIMAGE data, JDIMENSION num_lines)); /* Write a special marker. See libjpeg.doc concerning safe usage. */ EXTERN(void) jpeg_write_marker JPP((j_compress_ptr cinfo, int marker, const JOCTET * dataptr, unsigned int datalen)); /* Same, but piecemeal. */ EXTERN(void) jpeg_write_m_header JPP((j_compress_ptr cinfo, int marker, unsigned int datalen)); EXTERN(void) jpeg_write_m_byte JPP((j_compress_ptr cinfo, int val)); /* Alternate compression function: just write an abbreviated table file */ EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo)); /* Decompression startup: read start of JPEG datastream to see what's there */ EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo, boolean require_image)); /* Return value is one of: */ #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */ #define JPEG_HEADER_OK 1 /* Found valid image datastream */ #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */ /* If you pass require_image = TRUE (normal case), you need not check for * a TABLES_ONLY return code; an abbreviated file will cause an error exit. * JPEG_SUSPENDED is only possible if you use a data source module that can * give a suspension return (the stdio source module doesn't). */ /* Main entry points for decompression */ EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo)); EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION max_lines)); EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo)); /* Replaces jpeg_read_scanlines when reading raw downsampled data. */ EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo, JSAMPIMAGE data, JDIMENSION max_lines)); /* Additional entry points for buffered-image mode. */ EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo)); EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo, int scan_number)); EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo)); EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo)); EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo)); EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo)); /* Return value is one of: */ /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */ #define JPEG_REACHED_SOS 1 /* Reached start of new scan */ #define JPEG_REACHED_EOI 2 /* Reached end of image */ #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */ #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */ /* Precalculate output dimensions for current decompression parameters. */ EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo)); /* Control saving of COM and APPn markers into marker_list. */ EXTERN(void) jpeg_save_markers JPP((j_decompress_ptr cinfo, int marker_code, unsigned int length_limit)); /* Install a special processing method for COM or APPn markers. */ EXTERN(void) jpeg_set_marker_processor JPP((j_decompress_ptr cinfo, int marker_code, jpeg_marker_parser_method routine)); /* Read or write raw DCT coefficients --- useful for lossless transcoding. */ EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo)); EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)); EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo)); /* If you choose to abort compression or decompression before completing * jpeg_finish_(de)compress, then you need to clean up to release memory, * temporary files, etc. You can just call jpeg_destroy_(de)compress * if you're done with the JPEG object, but if you want to clean it up and * reuse it, call this: */ EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo)); EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo)); /* Generic versions of jpeg_abort and jpeg_destroy that work on either * flavor of JPEG object. These may be more convenient in some places. */ EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo)); EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo)); /* Default restart-marker-resync procedure for use by data source modules */ EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo, int desired)); /* These marker codes are exported since applications and data source modules * are likely to want to use them. */ #define JPEG_RST0 0xD0 /* RST0 marker code */ #define JPEG_EOI 0xD9 /* EOI marker code */ #define JPEG_APP0 0xE0 /* APP0 marker code */ #define JPEG_COM 0xFE /* COM marker code */ /* If we have a brain-damaged compiler that emits warnings (or worse, errors) * for structure definitions that are never filled in, keep it quiet by * supplying dummy definitions for the various substructures. */ #ifdef INCOMPLETE_TYPES_BROKEN #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */ struct jvirt_sarray_control { long dummy; }; struct jvirt_barray_control { long dummy; }; struct jpeg_comp_master { long dummy; }; struct jpeg_c_main_controller { long dummy; }; struct jpeg_c_prep_controller { long dummy; }; struct jpeg_c_coef_controller { long dummy; }; struct jpeg_marker_writer { long dummy; }; struct jpeg_color_converter { long dummy; }; struct jpeg_downsampler { long dummy; }; struct jpeg_forward_dct { long dummy; }; struct jpeg_entropy_encoder { long dummy; }; struct jpeg_decomp_master { long dummy; }; struct jpeg_d_main_controller { long dummy; }; struct jpeg_d_coef_controller { long dummy; }; struct jpeg_d_post_controller { long dummy; }; struct jpeg_input_controller { long dummy; }; struct jpeg_marker_reader { long dummy; }; struct jpeg_entropy_decoder { long dummy; }; struct jpeg_inverse_dct { long dummy; }; struct jpeg_upsampler { long dummy; }; struct jpeg_color_deconverter { long dummy; }; struct jpeg_color_quantizer { long dummy; }; #endif /* JPEG_INTERNALS */ #endif /* INCOMPLETE_TYPES_BROKEN */ /* * The JPEG library modules define JPEG_INTERNALS before including this file. * The internal structure declarations are read only when that is true. * Applications using the library should not include jpegint.h, but may wish * to include jerror.h. */ #ifdef JPEG_INTERNALS #include "jpegint.h" /* fetch private declarations */ #include "jerror.h" /* fetch error codes too */ #endif #endif /* JPEGLIB_H */
{ "pile_set_name": "Github" }
#!/usr/bin/env node var width = 960, height = 500, projectionName = process.argv[2], projectionSymbol = "geo" + projectionName[0].toUpperCase() + projectionName.slice(1); if (!/^[a-z0-9]+$/i.test(projectionName)) throw new Error; var fs = require("fs"), topojson = require("topojson-client"), Canvas = require("canvas"), d3_geo = require("../"); // canvas@2 compatibility check if (Canvas.Canvas) Canvas = Canvas.Canvas; var canvas = new Canvas(width, height), context = canvas.getContext("2d"); var world = require("world-atlas/world/50m.json"), graticule = d3_geo.geoGraticule(), outline = {type: "Sphere"}; // switch (projectionName) { // case "littrow": outline = graticule.extent([[-90, -60], [90, 60]]).outline(); break; // } var projection; if (projectionSymbol == 'geoAngleorient30') projection = d3_geo.geoEquirectangular().clipAngle(90).angle(-30).precision(0.1).fitExtent([[0,0],[width,height]], {type:"Sphere"}); else projection = d3_geo[projectionSymbol]().precision(0.1); var path = d3_geo.geoPath() .projection(projection) .context(context); context.fillStyle = "#fff"; context.fillRect(0, 0, width, height); context.save(); // switch (projectionName) { // case "armadillo": { // context.beginPath(); // path(outline); // context.clip(); // break; // } // } context.beginPath(); path(topojson.feature(world, world.objects.land)); context.fillStyle = "#000"; context.fill(); context.beginPath(); path(graticule()); context.strokeStyle = "rgba(119,119,119,0.5)"; context.stroke(); context.restore(); context.beginPath(); path(outline); context.strokeStyle = "#000"; context.stroke(); canvas.pngStream().pipe(process.stdout);
{ "pile_set_name": "Github" }
@startuml sprite $bitbucket [48x48/16] { 000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000124556655421000000000000000000 0000000000000269CFFFFFFFFFFFFFFC9620000000000000 000000000017DFFFFFFFFFFFFFFFFFFFFFFD710000000000 0000000008FFFFFFFCA8765556678ADFFFFFFF8000000000 00000000CFFFFF94000000000000000049FFFFFC00000000 00000008FFFFF6000000000000000000007FFFFF80000000 0000000AFFFFFE71000000000000000016EFFFFFA0000000 00000007FFFFFFFFDA864432234458ACFFFFFFFF70000000 00000005FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF50000000 00000002FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF20000000 00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000 00000000DFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD00000000 00000000BFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB00000000 000000008FFFFFFFFFFFFFFEEFFFFFFFFFFFFFF800000000 000000006FFFFFFFFFFFF810018FFFFFFFFFFFF500000000 000000003FFFFFFFFFFF40000004FFFFFFFFFFF300000000 000000000FFFFFFFFFF7002894007FFFFFFFFFF000000000 000000000DFFFFFFFFF002FFFF600FFFFFFFFFD000000000 000000000BFFFFFFFFC009FFFFE00CFFFFFFFFB000000000 0000000008FFFFFFFFB00AFFFFF00BFFFFFFFF8000000000 0000000005FFFFFFFFE006FFFFA00EFFFFFFFF5000000000 0000000002FFFFFFFFF4008FFB104FFFFFFFFF2000000000 0000000000FFFFFFFFFD00000000DFFFFFFFFF0000000000 0000000000BFFFFFFFFFC200002DFFFFFFFFFB0000000000 00000000001DFFFFFFFFFFC99CFFFFFFFFFFD10000000000 0000000000019FFFFFFFFFFFFFFFFFFFFFF9000000000000 000000000000029EFFFFFFFFFFFFFFFFE920000000000000 000000000008E50037BDFFFFFFFFDB73005E800000000000 000000000006FFD500000123321000005DFF600000000000 000000000003FFFFFA620000000026AFFFFF300000000000 000000000000FFFFFFFFFECBBCEFFFFFFFFF000000000000 000000000000DFFFFFFFFFFFFFFFFFFFFFFD000000000000 000000000000AFFFFFFFFFFFFFFFFFFFFFFA000000000000 0000000000007FFFFFFFFFFFFFFFFFFFFFF7000000000000 0000000000001FFFFFFFFFFFFFFFFFFFFFF1000000000000 00000000000004FFFFFFFFFFFFFFFFFFFF40000000000000 0000000000000019FFFFFFFFFFFFFFFF9100000000000000 000000000000000016ADFFFFFFFFDA510000000000000000 000000000000000000000133331000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000 } !define DEV_BITBUCKET(_alias) ENTITY(rectangle,black,bitbucket,_alias,DEV BITBUCKET) !define DEV_BITBUCKET(_alias, _label) ENTITY(rectangle,black,bitbucket,_label, _alias,DEV BITBUCKET) !define DEV_BITBUCKET(_alias, _label, _shape) ENTITY(_shape,black,bitbucket,_label, _alias,DEV BITBUCKET) !define DEV_BITBUCKET(_alias, _label, _shape, _color) ENTITY(_shape,_color,bitbucket,_label, _alias,DEV BITBUCKET) skinparam folderBackgroundColor<<DEV BITBUCKET>> White @enduml
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html class="client-nojs" lang="en" dir="ltr"> <head> <meta charset="UTF-8"/> <title>Jonathan G. Ornstein - Wikipedia</title> <script>document.documentElement.className="client-js";RLCONF={"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":!1,"wgNamespaceNumber":0,"wgPageName":"Jonathan_G._Ornstein","wgTitle":"Jonathan G. Ornstein","wgCurRevisionId":890705399,"wgRevisionId":890705399,"wgArticleId":3810310,"wgIsArticle":!0,"wgIsRedirect":!1,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":["Articles with hCards","Year of birth missing (living people)","All stub articles","Living people","American airline chief executives","American chief executive stubs"],"wgBreakFrames":!1,"wgPageContentLanguage":"en","wgPageContentModel":"wikitext","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"dmy","wgMonthNames":["","January","February","March","April","May","June","July","August","September","October","November","December"],"wgMonthNamesShort":["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"wgRelevantPageName": "Jonathan_G._Ornstein","wgRelevantArticleId":3810310,"wgRequestId":"XbGdkApAMF0AAFSGcgoAAADY","wgCSPNonce":!1,"wgIsProbablyEditable":!0,"wgRelevantPageIsProbablyEditable":!0,"wgRestrictionEdit":[],"wgRestrictionMove":[],"wgRedirectedFrom":"Jonathan_Ornstein","wgMediaViewerOnClick":!0,"wgMediaViewerEnabledByDefault":!0,"wgPopupsReferencePreviews":!1,"wgPopupsConflictsWithNavPopupGadget":!1,"wgVisualEditor":{"pageLanguageCode":"en","pageLanguageDir":"ltr","pageVariantFallbacks":"en"},"wgMFDisplayWikibaseDescriptions":{"search":!0,"nearby":!0,"watchlist":!0,"tagline":!1},"wgWMESchemaEditAttemptStepOversample":!1,"wgULSCurrentAutonym":"English","wgNoticeProject":"wikipedia","wgInternalRedirectTargetUrl":"/wiki/Jonathan_G._Ornstein","wgWikibaseItemId":"Q6273164","wgCentralAuthMobileDomain":!1,"wgEditSubmitButtonLabelPublish":!0};RLSTATE={"ext.globalCssJs.user.styles":"ready","site.styles":"ready","noscript":"ready","user.styles":"ready", "ext.globalCssJs.user":"ready","user":"ready","user.options":"ready","user.tokens":"loading","ext.cite.styles":"ready","mediawiki.legacy.shared":"ready","mediawiki.legacy.commonPrint":"ready","wikibase.client.init":"ready","ext.visualEditor.desktopArticleTarget.noscript":"ready","ext.uls.interlanguage":"ready","ext.wikimediaBadges":"ready","ext.3d.styles":"ready","mediawiki.skinning.interface":"ready","skins.vector.styles":"ready"};RLPAGEMODULES=["mediawiki.action.view.redirect","ext.cite.ux-enhancements","ext.cite.tracking","site","mediawiki.page.startup","mediawiki.page.ready","mediawiki.searchSuggest","ext.gadget.teahouse","ext.gadget.ReferenceTooltips","ext.gadget.watchlist-notice","ext.gadget.DRN-wizard","ext.gadget.charinsert","ext.gadget.refToolbar","ext.gadget.extra-toolbar-buttons","ext.gadget.switcher","ext.centralauth.centralautologin","mmv.head","mmv.bootstrap.autostart","ext.popups","ext.visualEditor.desktopArticleTarget.init","ext.visualEditor.targetLoader", "ext.eventLogging","ext.wikimediaEvents","ext.navigationTiming","ext.uls.compactlinks","ext.uls.interface","ext.cx.eventlogging.campaigns","ext.quicksurveys.init","ext.centralNotice.geoIP","ext.centralNotice.startUp","skins.vector.js"];</script> <script>(RLQ=window.RLQ||[]).push(function(){mw.loader.implement("user.tokens@tffin",function($,jQuery,require,module){/*@nomin*/mw.user.tokens.set({"patrolToken":"+\\","watchToken":"+\\","csrfToken":"+\\"}); });});</script> <link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=ext.3d.styles%7Cext.cite.styles%7Cext.uls.interlanguage%7Cext.visualEditor.desktopArticleTarget.noscript%7Cext.wikimediaBadges%7Cmediawiki.legacy.commonPrint%2Cshared%7Cmediawiki.skinning.interface%7Cskins.vector.styles%7Cwikibase.client.init&amp;only=styles&amp;skin=vector"/> <script async="" src="/w/load.php?lang=en&amp;modules=startup&amp;only=scripts&amp;raw=1&amp;skin=vector"></script> <meta name="ResourceLoaderDynamicStyles" content=""/> <link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=vector"/> <meta name="generator" content="MediaWiki 1.35.0-wmf.2"/> <meta name="referrer" content="origin"/> <meta name="referrer" content="origin-when-crossorigin"/> <meta name="referrer" content="origin-when-cross-origin"/> <link rel="alternate" href="android-app://org.wikipedia/http/en.m.wikipedia.org/wiki/Jonathan_G._Ornstein"/> <link rel="alternate" type="application/x-wiki" title="Edit this page" href="/w/index.php?title=Jonathan_G._Ornstein&amp;action=edit"/> <link rel="edit" title="Edit this page" href="/w/index.php?title=Jonathan_G._Ornstein&amp;action=edit"/> <link rel="apple-touch-icon" href="/static/apple-touch/wikipedia.png"/> <link rel="shortcut icon" href="/static/favicon/wikipedia.ico"/> <link rel="search" type="application/opensearchdescription+xml" href="/w/opensearch_desc.php" title="Wikipedia (en)"/> <link rel="EditURI" type="application/rsd+xml" href="//en.wikipedia.org/w/api.php?action=rsd"/> <link rel="license" href="//creativecommons.org/licenses/by-sa/3.0/"/> <link rel="canonical" href="https://en.wikipedia.org/wiki/Jonathan_G._Ornstein"/> <link rel="dns-prefetch" href="//login.wikimedia.org"/> <link rel="dns-prefetch" href="//meta.wikimedia.org" /> <!--[if lt IE 9]><script src="/w/resources/lib/html5shiv/html5shiv.js"></script><![endif]--> </head> <body class="mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject mw-editable page-Jonathan_G_Ornstein rootpage-Jonathan_G_Ornstein skin-vector action-view"> <div id="mw-page-base" class="noprint"></div> <div id="mw-head-base" class="noprint"></div> <div id="content" class="mw-body" role="main"> <a id="top"></a> <div id="siteNotice" class="mw-body-content"><!-- CentralNotice --></div> <div class="mw-indicators mw-body-content"> </div> <h1 id="firstHeading" class="firstHeading" lang="en">Jonathan G. Ornstein</h1> <div id="bodyContent" class="mw-body-content"> <div id="siteSub" class="noprint">From Wikipedia, the free encyclopedia</div> <div id="contentSub"><span class="mw-redirectedfrom">&#160;&#160;(Redirected from <a href="/w/index.php?title=Jonathan_Ornstein&amp;redirect=no" class="mw-redirect" title="Jonathan Ornstein">Jonathan Ornstein</a>)</span></div> <div id="jump-to-nav"></div> <a class="mw-jump-link" href="#mw-head">Jump to navigation</a> <a class="mw-jump-link" href="#p-search">Jump to search</a> <div id="mw-content-text" lang="en" dir="ltr" class="mw-content-ltr"><div class="mw-parser-output"><table class="infobox biography vcard" style="width:22em"><tbody><tr><th colspan="2" style="text-align:center;font-size:125%;font-weight:bold"><div class="fn" style="display:inline">Jonathan G. Ornstein</div></th></tr><tr><th scope="row">Residence</th><td class="label"><a href="/wiki/Los_Angeles,_California" class="mw-redirect" title="Los Angeles, California">Los Angeles, California</a></td></tr><tr><th scope="row">Occupation</th><td class="role">Chairman/CEO, <a href="/wiki/Mesa_Air_Group" title="Mesa Air Group">Mesa Air Group</a></td></tr></tbody></table> <p><b>Jonathan Ornstein</b> is <a href="/wiki/Chairman" class="mw-redirect" title="Chairman">Chairman</a> and <a href="/wiki/Chief_Executive_Officer" class="mw-redirect" title="Chief Executive Officer">Chief Executive Officer</a> of <a href="/wiki/Mesa_Air_Group" title="Mesa Air Group">Mesa Air Group</a>, Inc., and was appointed effective May 1, 1998. From April 1996 to his joining the company as Chief Executive Officer, Ornstein served as President and Chief Executive Officer and Chairman of <a href="/wiki/Virgin_Express" title="Virgin Express">Virgin Express</a>, a European airline. From 1995 to April 1996, Ornstein served as Chief Executive Officer of Virgin Express Holdings, Inc. Ornstein joined <a href="/wiki/Continental_Express" title="Continental Express">Continental Express</a> as President and Chief Executive Officer in July 1994 and, in November 1994, was named Senior Vice President, Airport Services at <a href="/wiki/Continental_Airlines" title="Continental Airlines">Continental Airlines</a>. Ornstein was previously employed by the company from 1988 to 1994, as Executive Vice President and as President of the company's WestAir Holding, Inc., subsidiary. </p> <h2><span class="mw-headline" id="Controversies">Controversies</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Jonathan_G._Ornstein&amp;action=edit&amp;section=1" title="Edit section: Controversies">edit</a><span class="mw-editsection-bracket">]</span></span></h2> <p>In 1978 Ornstein dropped out of the University of Pennsylvania after his junior year and relocated to the Los Angeles area when he was 21 years old. He became a well recognized broker for the firm E.F. Hutton as the youngest ever to hold a position there. Through the years following he left and accepted offers at other firms, however being terminated from some in the process due to breaching ethical standards such as unauthorized trading, misrepresentation, document alteration and churning. At a later time he was fined $20,000 and unable to be a broker due to suspension for a period of three years.<sup id="cite_ref-1" class="reference"><a href="#cite_note-1">&#91;1&#93;</a></sup> </p> <h2><span class="mw-headline" id="References">References</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Jonathan_G._Ornstein&amp;action=edit&amp;section=2" title="Edit section: References">edit</a><span class="mw-editsection-bracket">]</span></span></h2> <div class="reflist" style="list-style-type: decimal;"> <div class="mw-references-wrap"><ol class="references"> <li id="cite_note-1"><span class="mw-cite-backlink"><b><a href="#cite_ref-1">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external free" href="https://www.forbes.com/global/1999/0809/215065a.html">https://www.forbes.com/global/1999/0809/215065a.html</a></span> </li> </ol></div></div> <h2><span class="mw-headline" id="External_links">External links</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Jonathan_G._Ornstein&amp;action=edit&amp;section=3" title="Edit section: External links">edit</a><span class="mw-editsection-bracket">]</span></span></h2> <ul><li><a rel="nofollow" class="external text" href="http://phx.corporate-ir.net/phoenix.zhtml?c=78947&amp;p=irol-govBio&amp;ID=136195">Official biography</a></li></ul> <p><br /> </p> <table class="metadata plainlinks stub" role="presentation" style="background:transparent"><tbody><tr><td><a href="/wiki/File:Crystal_personal.svg" class="image"><img alt="Stub icon" src="//upload.wikimedia.org/wikipedia/en/thumb/2/24/Crystal_personal.svg/20px-Crystal_personal.svg.png" decoding="async" width="20" height="20" srcset="//upload.wikimedia.org/wikipedia/en/thumb/2/24/Crystal_personal.svg/30px-Crystal_personal.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/2/24/Crystal_personal.svg/40px-Crystal_personal.svg.png 2x" data-file-width="70" data-file-height="70" /></a></td><td><i>This article about a chief executive from the United States is a <a href="/wiki/Wikipedia:Stub" title="Wikipedia:Stub">stub</a>. You can help Wikipedia by <a class="external text" href="https://en.wikipedia.org/w/index.php?title=Jonathan_G._Ornstein&amp;action=edit">expanding it</a>.</i><div class="plainlinks hlist navbar mini" style="position: absolute; right: 15px; display: none;"><ul><li class="nv-view"><a href="/wiki/Template:US-CEO-stub" title="Template:US-CEO-stub"><abbr title="View this template">v</abbr></a></li><li class="nv-talk"><a href="/wiki/Template_talk:US-CEO-stub" title="Template talk:US-CEO-stub"><abbr title="Discuss this template">t</abbr></a></li><li class="nv-edit"><a class="external text" href="https://en.wikipedia.org/w/index.php?title=Template:US-CEO-stub&amp;action=edit"><abbr title="Edit this template">e</abbr></a></li></ul></div></td></tr></tbody></table> <!-- NewPP limit report Parsed by mw1323 Cached time: 20191016184058 Cache expiry: 2592000 Dynamic content: false Complications: [] CPU time usage: 0.132 seconds Real time usage: 0.186 seconds Preprocessor visited node count: 900/1000000 Preprocessor generated node count: 0/1500000 Post‐expand include size: 4725/2097152 bytes Template argument size: 309/2097152 bytes Highest expansion depth: 9/40 Expensive parser function count: 0/500 Unstrip recursion depth: 0/20 Unstrip post‐expand size: 443/5000000 bytes Number of Wikibase entities loaded: 1/400 Lua time usage: 0.046/10.000 seconds Lua memory usage: 1.65 MB/50 MB --> <!-- Transclusion expansion time report (%,ms,calls,template) 100.00% 166.590 1 -total 68.16% 113.546 1 Template:Infobox_person 51.86% 86.388 1 Template:Infobox 15.42% 25.684 1 Template:Authority_control 12.46% 20.761 5 Template:Br_separated_entries 10.29% 17.145 1 Template:US-CEO-stub 8.17% 13.605 1 Template:Asbox 6.32% 10.524 1 Template:Wikidata_image 4.75% 7.913 1 Template:Reflist 4.55% 7.585 1 Template:Unbulleted_list --> <!-- Saved in parser cache with key enwiki:pcache:idhash:3810310-0!canonical and timestamp 20191016184058 and revision id 890705399 --> </div><noscript><img src="//en.wikipedia.org/wiki/Special:CentralAutoLogin/start?type=1x1" alt="" title="" width="1" height="1" style="border: none; position: absolute;" /></noscript></div> <div class="printfooter">Retrieved from "<a dir="ltr" href="https://en.wikipedia.org/w/index.php?title=Jonathan_G._Ornstein&amp;oldid=890705399">https://en.wikipedia.org/w/index.php?title=Jonathan_G._Ornstein&amp;oldid=890705399</a>"</div> <div id="catlinks" class="catlinks" data-mw="interface"><div id="mw-normal-catlinks" class="mw-normal-catlinks"><a href="/wiki/Help:Category" title="Help:Category">Categories</a>: <ul><li><a href="/wiki/Category:Living_people" title="Category:Living people">Living people</a></li><li><a href="/wiki/Category:American_airline_chief_executives" title="Category:American airline chief executives">American airline chief executives</a></li><li><a href="/wiki/Category:American_chief_executive_stubs" title="Category:American chief executive stubs">American chief executive stubs</a></li></ul></div><div id="mw-hidden-catlinks" class="mw-hidden-catlinks mw-hidden-cats-hidden">Hidden categories: <ul><li><a href="/wiki/Category:Articles_with_hCards" title="Category:Articles with hCards">Articles with hCards</a></li><li><a href="/wiki/Category:Year_of_birth_missing_(living_people)" title="Category:Year of birth missing (living people)">Year of birth missing (living people)</a></li><li><a href="/wiki/Category:All_stub_articles" title="Category:All stub articles">All stub articles</a></li></ul></div></div> <div class="visualClear"></div> </div> </div> <div id='mw-data-after-content'> <div class="read-more-container"></div> </div> <div id="mw-navigation"> <h2>Navigation menu</h2> <div id="mw-head"> <div id="p-personal" role="navigation" aria-labelledby="p-personal-label"> <h3 id="p-personal-label">Personal tools</h3> <ul> <li id="pt-anonuserpage">Not logged in</li><li id="pt-anontalk"><a href="/wiki/Special:MyTalk" title="Discussion about edits from this IP address [n]" accesskey="n">Talk</a></li><li id="pt-anoncontribs"><a href="/wiki/Special:MyContributions" title="A list of edits made from this IP address [y]" accesskey="y">Contributions</a></li><li id="pt-createaccount"><a href="/w/index.php?title=Special:CreateAccount&amp;returnto=Jonathan+G.+Ornstein" title="You are encouraged to create an account and log in; however, it is not mandatory">Create account</a></li><li id="pt-login"><a href="/w/index.php?title=Special:UserLogin&amp;returnto=Jonathan+G.+Ornstein" title="You&#039;re encouraged to log in; however, it&#039;s not mandatory. [o]" accesskey="o">Log in</a></li> </ul> </div> <div id="left-navigation"> <div id="p-namespaces" role="navigation" class="vectorTabs" aria-labelledby="p-namespaces-label"> <h3 id="p-namespaces-label">Namespaces</h3> <ul> <li id="ca-nstab-main" class="selected"><span><a href="/wiki/Jonathan_G._Ornstein" title="View the content page [c]" accesskey="c">Article</a></span></li><li id="ca-talk"><span><a href="/wiki/Talk:Jonathan_G._Ornstein" rel="discussion" title="Discussion about the content page [t]" accesskey="t">Talk</a></span></li> </ul> </div> <div id="p-variants" role="navigation" class="vectorMenu emptyPortlet" aria-labelledby="p-variants-label"> <input type="checkbox" class="vectorMenuCheckbox" aria-labelledby="p-variants-label" /> <h3 id="p-variants-label"> <span>Variants</span> </h3> <ul class="menu"> </ul> </div> </div> <div id="right-navigation"> <div id="p-views" role="navigation" class="vectorTabs" aria-labelledby="p-views-label"> <h3 id="p-views-label">Views</h3> <ul> <li id="ca-view" class="collapsible selected"><span><a href="/wiki/Jonathan_G._Ornstein">Read</a></span></li><li id="ca-edit" class="collapsible"><span><a href="/w/index.php?title=Jonathan_G._Ornstein&amp;action=edit" title="Edit this page [e]" accesskey="e">Edit</a></span></li><li id="ca-history" class="collapsible"><span><a href="/w/index.php?title=Jonathan_G._Ornstein&amp;action=history" title="Past revisions of this page [h]" accesskey="h">View history</a></span></li> </ul> </div> <div id="p-cactions" role="navigation" class="vectorMenu emptyPortlet" aria-labelledby="p-cactions-label"> <input type="checkbox" class="vectorMenuCheckbox" aria-labelledby="p-cactions-label" /> <h3 id="p-cactions-label"><span>More</span></h3> <ul class="menu"> </ul> </div> <div id="p-search" role="search"> <h3> <label for="searchInput">Search</label> </h3> <form action="/w/index.php" id="searchform"> <div id="simpleSearch"> <input type="search" name="search" placeholder="Search Wikipedia" title="Search Wikipedia [f]" accesskey="f" id="searchInput"/><input type="hidden" value="Special:Search" name="title"/><input type="submit" name="fulltext" value="Search" title="Search Wikipedia for this text" id="mw-searchButton" class="searchButton mw-fallbackSearchButton"/><input type="submit" name="go" value="Go" title="Go to a page with this exact name if it exists" id="searchButton" class="searchButton"/> </div> </form> </div> </div> </div> <div id="mw-panel"> <div id="p-logo" role="banner"><a class="mw-wiki-logo" href="/wiki/Main_Page" title="Visit the main page"></a></div> <div class="portal" role="navigation" id="p-navigation" aria-labelledby="p-navigation-label"> <h3 id="p-navigation-label">Navigation</h3> <div class="body"> <ul> <li id="n-mainpage-description"><a href="/wiki/Main_Page" title="Visit the main page [z]" accesskey="z">Main page</a></li><li id="n-contents"><a href="/wiki/Portal:Contents" title="Guides to browsing Wikipedia">Contents</a></li><li id="n-featuredcontent"><a href="/wiki/Portal:Featured_content" title="Featured content – the best of Wikipedia">Featured content</a></li><li id="n-currentevents"><a href="/wiki/Portal:Current_events" title="Find background information on current events">Current events</a></li><li id="n-randompage"><a href="/wiki/Special:Random" title="Load a random article [x]" accesskey="x">Random article</a></li><li id="n-sitesupport"><a href="https://donate.wikimedia.org/wiki/Special:FundraiserRedirector?utm_source=donate&amp;utm_medium=sidebar&amp;utm_campaign=C13_en.wikipedia.org&amp;uselang=en" title="Support us">Donate to Wikipedia</a></li><li id="n-shoplink"><a href="//shop.wikimedia.org" title="Visit the Wikipedia store">Wikipedia store</a></li> </ul> </div> </div> <div class="portal" role="navigation" id="p-interaction" aria-labelledby="p-interaction-label"> <h3 id="p-interaction-label">Interaction</h3> <div class="body"> <ul> <li id="n-help"><a href="/wiki/Help:Contents" title="Guidance on how to use and edit Wikipedia">Help</a></li><li id="n-aboutsite"><a href="/wiki/Wikipedia:About" title="Find out about Wikipedia">About Wikipedia</a></li><li id="n-portal"><a href="/wiki/Wikipedia:Community_portal" title="About the project, what you can do, where to find things">Community portal</a></li><li id="n-recentchanges"><a href="/wiki/Special:RecentChanges" title="A list of recent changes in the wiki [r]" accesskey="r">Recent changes</a></li><li id="n-contactpage"><a href="//en.wikipedia.org/wiki/Wikipedia:Contact_us" title="How to contact Wikipedia">Contact page</a></li> </ul> </div> </div> <div class="portal" role="navigation" id="p-tb" aria-labelledby="p-tb-label"> <h3 id="p-tb-label">Tools</h3> <div class="body"> <ul> <li id="t-whatlinkshere"><a href="/wiki/Special:WhatLinksHere/Jonathan_G._Ornstein" title="List of all English Wikipedia pages containing links to this page [j]" accesskey="j">What links here</a></li><li id="t-recentchangeslinked"><a href="/wiki/Special:RecentChangesLinked/Jonathan_G._Ornstein" rel="nofollow" title="Recent changes in pages linked from this page [k]" accesskey="k">Related changes</a></li><li id="t-upload"><a href="/wiki/Wikipedia:File_Upload_Wizard" title="Upload files [u]" accesskey="u">Upload file</a></li><li id="t-specialpages"><a href="/wiki/Special:SpecialPages" title="A list of all special pages [q]" accesskey="q">Special pages</a></li><li id="t-permalink"><a href="/w/index.php?title=Jonathan_G._Ornstein&amp;oldid=890705399" title="Permanent link to this revision of the page">Permanent link</a></li><li id="t-info"><a href="/w/index.php?title=Jonathan_G._Ornstein&amp;action=info" title="More information about this page">Page information</a></li><li id="t-wikibase"><a href="https://www.wikidata.org/wiki/Special:EntityPage/Q6273164" title="Link to connected data repository item [g]" accesskey="g">Wikidata item</a></li><li id="t-cite"><a href="/w/index.php?title=Special:CiteThisPage&amp;page=Jonathan_G._Ornstein&amp;id=890705399" title="Information on how to cite this page">Cite this page</a></li> </ul> </div> </div> <div class="portal" role="navigation" id="p-coll-print_export" aria-labelledby="p-coll-print_export-label"> <h3 id="p-coll-print_export-label">Print/export</h3> <div class="body"> <ul> <li id="coll-create_a_book"><a href="/w/index.php?title=Special:Book&amp;bookcmd=book_creator&amp;referer=Jonathan+G.+Ornstein">Create a book</a></li><li id="coll-download-as-rl"><a href="/w/index.php?title=Special:ElectronPdf&amp;page=Jonathan+G.+Ornstein&amp;action=show-download-screen">Download as PDF</a></li><li id="t-print"><a href="/w/index.php?title=Jonathan_G._Ornstein&amp;printable=yes" title="Printable version of this page [p]" accesskey="p">Printable version</a></li> </ul> </div> </div> <div class="portal" role="navigation" id="p-lang" aria-labelledby="p-lang-label"> <h3 id="p-lang-label">Languages</h3> <div class="body"> <ul> </ul> <div class="after-portlet after-portlet-lang"><span class="wb-langlinks-add wb-langlinks-link"><a href="https://www.wikidata.org/wiki/Special:EntityPage/Q6273164#sitelinks-wikipedia" title="Add interlanguage links" class="wbc-editpage">Add links</a></span></div> </div> </div> </div> </div> <div id="footer" role="contentinfo"> <ul id="footer-info"> <li id="footer-info-lastmod"> This page was last edited on 3 April 2019, at 00:58<span class="anonymous-show">&#160;(UTC)</span>.</li> <li id="footer-info-copyright">Text is available under the <a rel="license" href="//en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License">Creative Commons Attribution-ShareAlike License</a><a rel="license" href="//creativecommons.org/licenses/by-sa/3.0/" style="display:none;"></a>; additional terms may apply. By using this site, you agree to the <a href="//foundation.wikimedia.org/wiki/Terms_of_Use">Terms of Use</a> and <a href="//foundation.wikimedia.org/wiki/Privacy_policy">Privacy Policy</a>. Wikipedia® is a registered trademark of the <a href="//www.wikimediafoundation.org/">Wikimedia Foundation, Inc.</a>, a non-profit organization.</li> </ul> <ul id="footer-places"> <li id="footer-places-privacy"><a href="https://foundation.wikimedia.org/wiki/Privacy_policy" class="extiw" title="wmf:Privacy policy">Privacy policy</a></li> <li id="footer-places-about"><a href="/wiki/Wikipedia:About" title="Wikipedia:About">About Wikipedia</a></li> <li id="footer-places-disclaimer"><a href="/wiki/Wikipedia:General_disclaimer" title="Wikipedia:General disclaimer">Disclaimers</a></li> <li id="footer-places-contact"><a href="//en.wikipedia.org/wiki/Wikipedia:Contact_us">Contact Wikipedia</a></li> <li id="footer-places-developers"><a href="https://www.mediawiki.org/wiki/Special:MyLanguage/How_to_contribute">Developers</a></li> <li id="footer-places-cookiestatement"><a href="https://foundation.wikimedia.org/wiki/Cookie_statement">Cookie statement</a></li> <li id="footer-places-mobileview"><a href="//en.m.wikipedia.org/w/index.php?title=Jonathan_G._Ornstein&amp;mobileaction=toggle_view_mobile" class="noprint stopMobileRedirectToggle">Mobile view</a></li> </ul> <ul id="footer-icons" class="noprint"> <li id="footer-copyrightico"> <a href="https://wikimediafoundation.org/"><img src="/static/images/wikimedia-button.png" srcset="/static/images/wikimedia-button-1.5x.png 1.5x, /static/images/wikimedia-button-2x.png 2x" width="88" height="31" alt="Wikimedia Foundation"/></a> </li> <li id="footer-poweredbyico"> <a href="https://www.mediawiki.org/"><img src="/static/images/poweredby_mediawiki_88x31.png" alt="Powered by MediaWiki" srcset="/static/images/poweredby_mediawiki_132x47.png 1.5x, /static/images/poweredby_mediawiki_176x62.png 2x" width="88" height="31"/></a> </li> </ul> <div style="clear: both;"></div> </div> <script>(RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgPageParseReport":{"limitreport":{"cputime":"0.132","walltime":"0.186","ppvisitednodes":{"value":900,"limit":1000000},"ppgeneratednodes":{"value":0,"limit":1500000},"postexpandincludesize":{"value":4725,"limit":2097152},"templateargumentsize":{"value":309,"limit":2097152},"expansiondepth":{"value":9,"limit":40},"expensivefunctioncount":{"value":0,"limit":500},"unstrip-depth":{"value":0,"limit":20},"unstrip-size":{"value":443,"limit":5000000},"entityaccesscount":{"value":1,"limit":400},"timingprofile":["100.00% 166.590 1 -total"," 68.16% 113.546 1 Template:Infobox_person"," 51.86% 86.388 1 Template:Infobox"," 15.42% 25.684 1 Template:Authority_control"," 12.46% 20.761 5 Template:Br_separated_entries"," 10.29% 17.145 1 Template:US-CEO-stub"," 8.17% 13.605 1 Template:Asbox"," 6.32% 10.524 1 Template:Wikidata_image"," 4.75% 7.913 1 Template:Reflist"," 4.55% 7.585 1 Template:Unbulleted_list"]},"scribunto":{"limitreport-timeusage":{"value":"0.046","limit":"10.000"},"limitreport-memusage":{"value":1734529,"limit":52428800}},"cachereport":{"origin":"mw1323","timestamp":"20191016184058","ttl":2592000,"transientcontent":false}}});});</script> <script type="application/ld+json">{"@context":"https:\/\/schema.org","@type":"Article","name":"Jonathan G. Ornstein","url":"https:\/\/en.wikipedia.org\/wiki\/Jonathan_G._Ornstein","sameAs":"http:\/\/www.wikidata.org\/entity\/Q6273164","mainEntity":"http:\/\/www.wikidata.org\/entity\/Q6273164","author":{"@type":"Organization","name":"Contributors to Wikimedia projects"},"publisher":{"@type":"Organization","name":"Wikimedia Foundation, Inc.","logo":{"@type":"ImageObject","url":"https:\/\/www.wikimedia.org\/static\/images\/wmf-hor-googpub.png"}},"datePublished":"2006-01-22T18:14:13Z","dateModified":"2019-04-03T00:58:56Z","headline":"businessman from the United States"}</script> <script>(RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgBackendResponseTime":115,"wgHostname":"mw1258"});});</script> </body> </html>
{ "pile_set_name": "Github" }
ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[a-zA-Z][-_a-zA-Z0-9]*"; this.$rules = { start : [ {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, { token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true }, { token : ["punctuation.instruction.xml", "keyword.instruction.xml"], regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction", }, {token : "comment.xml", regex : "<\\!--", next : "comment"}, { token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true }, {include : "tag"}, {token : "text.end-tag-open.xml", regex: "</"}, {token : "text.tag-open.xml", regex: "<"}, {include : "reference"}, {defaultToken : "text.xml"} ], xml_decl : [{ token : "entity.other.attribute-name.decl-attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.decl-attribute-equals.xml", regex : "=" }, { include: "whitespace" }, { include: "string" }, { token : "punctuation.xml-decl.xml", regex : "\\?>", next : "start" }], processing_instruction : [ {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, {defaultToken : "instruction.xml"} ], doctype : [ {include : "whitespace"}, {include : "string"}, {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} ], int_subset : [{ token : "text.xml", regex : "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex : "(<\\!)(" + tagRegex + ")", push : [{ token : "text", regex : "\\s+" }, { token : "punctuation.markup-decl.xml", regex : ">", next : "pop" }, {include : "string"}] }], cdata : [ {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, {token : "text.xml", regex : "\\s+"}, {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} ], comment : [ {token : "comment.xml", regex : "-->", next : "start"}, {defaultToken : "comment.xml"} ], reference : [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference : [{ token : "constant.language.escape.reference.attribute-value.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag : [{ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }], tag_whitespace : [ {token : "text.tag-whitespace.xml", regex : "\\s+"} ], whitespace : [ {token : "text.whitespace.xml", regex : "\\s+"} ], string: [{ token : "string.xml", regex : "'", push : [ {token : "string.xml", regex: "'", next: "pop"}, {defaultToken : "string.xml"} ] }, { token : "string.xml", regex : '"', push : [ {token : "string.xml", regex: '"', next: "pop"}, {defaultToken : "string.xml"} ] }], attributes: [{ token : "entity.other.attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token : "string.attribute-value.xml", regex : "'", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag){ this.$rules.tag.unshift({ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(<)(" + tag + "(?=\\s|>|$))", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} ] }); this.$rules[tag + "-end"] = [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", onMatch : function(value, currentState, stack) { stack.splice(0); return this.token; }} ] this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex : "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex : "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function () { this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getCursorPosition(); var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var firstChar = token.value.charAt(0); if (firstChar == '"' || firstChar == "'") { var lastChar = token.value.charAt(token.value.length - 1); var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) return; } } while (!is(token, "tag-name")) { token = iterator.stepBackward(); } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column+1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; this.optionalEndTags = oop.mixin({}, this.voidElements); if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags); }; oop.inherits(FoldMode, BaseFoldMode); var Tag = function() { this.tagName = ""; this.closing = false; this.selfClosing = false; this.start = {row: 0, column: 0}; this.end = {row: 0, column: 0}; }; function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (!tag) return ""; if (tag.closing || (!tag.tagName && tag.selfClosing)) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) return ""; if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var tag = new Tag(); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (is(token, "tag-open")) { tag.end.column = tag.start.column + token.value.length; tag.closing = is(token, "end-tag-open"); token = tokens[++i]; if (!token) return null; tag.tagName = token.value; tag.end.column += token.value.length; for (i++; i < tokens.length; i++) { token = tokens[i]; tag.end.column += token.value.length; if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; break; } } return tag; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; return tag; } tag.start.column += token.value.length; } return null; }; this._findEndTagInLine = function(session, row, tagName, startColumn) { var tokens = session.getTokens(row); var column = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; column += token.value.length; if (column < startColumn) continue; if (is(token, "end-tag-open")) { token = tokens[i + 1]; if (token && token.value == tagName) return true; } } return false; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; iterator.stepForward(); return tag; } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); iterator.stepBackward(); return tag; } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.start.column); var start = { row: row, column: firstTag.start.column + firstTag.tagName.length + 2 }; if (firstTag.start.row == firstTag.end.row) start.column = firstTag.end.column; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag); } } } else { var iterator = new TokenIterator(session, row, firstTag.end.column); var end = { row: row, column: firstTag.start.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) tag.start.column = tag.end.column; return Range.fromPoints(tag.start, end); } } else { stack.push(tag); } } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var XmlFoldMode = require("./folding/xml").FoldMode; var WorkerClient = require("../worker/worker_client").WorkerClient; var Mode = function() { this.HighlightRules = XmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.foldingRules = new XmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.voidElements = lang.arrayToMap([]); this.blockComment = {start: "<!--", end: "-->"}; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/xml_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/xml"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, DocCommentHighlightRules.getTagRule(), { defaultToken : "comment.doc", caseInsensitive: true }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getTagRule = function(start) { return { token : "comment.doc.tag.storage.type", regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" }; } DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function(options) { var keywordMapper = this.createKeywordMapper({ "variable.language": "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors "Namespace|QName|XML|XMLList|" + // E4X "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors "SyntaxError|TypeError|URIError|" + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions "isNaN|parseFloat|parseInt|" + "JSON|Math|" + // Other "this|arguments|prototype|window|document" , // Pseudo "keyword": "const|yield|import|get|set|" + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + "__parent__|__count__|escape|unescape|with|__proto__|" + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", "storage.type": "const|let|var|function", "constant.language": "null|Infinity|NaN|undefined", "support.function": "alert", "constant.language.boolean": "true|false" }, "identifier"); var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; this.$rules = { "no_regex" : [ { token : "comment", regex : "\\/\\/", next : "line_comment" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text","keyword.operator" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "start" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["support.constant"], regex : /that\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ }, { token : keywordMapper, regex : identifierRe }, { token : "keyword.operator", regex : /--|\+\+|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|[!$%&*+\-~\/^]=?/, next : "start" }, { token : "punctuation.operator", regex : /[?:,;.]/, next : "start" }, { token : "paren.lparen", regex : /[\[({]/, next : "start" }, { token : "paren.rparen", regex : /[\])}]/ }, { token: "comment", regex: /^#!.*$/ } ], "start": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/", next : "line_comment_regex_allowed" }, { token: "string.regexp", regex: "\\/", next: "regex" }, { token : "text", regex : "\\s+|^$", next : "start" }, { token: "empty", regex: "", next: "no_regex" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp", regex: "/[sxngimy]*", next: "no_regex" }, { token : "invalid", regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ }, { token : "constant.language.escape", regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ }, { token : "constant.language.delimiter", regex: /\|/ }, { token: "constant.language.escape", regex: /\[\^?/, next: "regex_character_class" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp" } ], "regex_character_class": [ { token: "regexp.charclass.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "constant.language.escape", regex: "]", next: "regex" }, { token: "constant.language.escape", regex: "-" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp.charachterclass" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe }, { token: "punctuation.operator", regex: "[, ]+" }, { token: "punctuation.operator", regex: "$" }, { token: "empty", regex: "", next: "no_regex" } ], "comment_regex_allowed" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : "start"}, {defaultToken : "comment", caseInsensitive: true} ], "comment" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : "no_regex"}, {defaultToken : "comment", caseInsensitive: true} ], "line_comment_regex_allowed" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : "start"}, {defaultToken : "comment", caseInsensitive: true} ], "line_comment" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : "no_regex"}, {defaultToken : "comment", caseInsensitive: true} ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qqstring" }, { token : "string", regex : '"|$', next : "no_regex" }, { defaultToken: "string" } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qstring" }, { token : "string", regex : "'|$", next : "no_regex" }, { defaultToken: "string" } ] }; if (!options || !options.noES6) { this.$rules.no_regex.unshift({ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); return "paren"; } if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1) return "paren.quasi.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.quasi.start", regex : /`/, push : [{ token : "constant.language.escape", regex : escapedRe }, { token : "paren.quasi.start", regex : /\${/, push : "start" }, { token : "string.quasi.end", regex : /`/, next : "pop" }, { defaultToken: "string.quasi" }] }); } this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("no_regex") ]); this.normalizeRules(); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); var SAFE_INSERT_IN_TOKENS = ["text", "paren.rparen", "punctuation.operator"]; var SAFE_INSERT_BEFORE_TOKENS = ["text", "paren.rparen", "punctuation.operator", "comment"]; var context; var contextCache = {}; var initContext = function(editor) { var id = -1; if (editor.multiSelect) { id = editor.selection.index; if (contextCache.rangeCount != editor.multiSelect.rangeCount) contextCache = {rangeCount: editor.multiSelect.rangeCount}; } if (contextCache[id]) return context = contextCache[id]; context = contextCache[id] = { autoInsertedBrackets: 0, autoInsertedRow: -1, autoInsertedLineEnd: "", maybeInsertedBrackets: 0, maybeInsertedRow: -1, maybeInsertedLineStart: "", maybeInsertedLineEnd: "" }; }; var getWrapped = function(selection, selected, opening, closing) { var rowDiff = selection.end.row - selection.start.row; return { text: opening + selected + closing, selection: [ 0, selection.start.column + 1, rowDiff, selection.end.column + (rowDiff ? 0 : 1) ] }; }; var CstyleBehaviour = function() { this.add("braces", "insertion", function(state, action, editor, session, text) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (text == '{') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '{', '}'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) { CstyleBehaviour.recordAutoInsert(editor, session, "}"); return { text: '{}', selection: [1, 1] }; } else { CstyleBehaviour.recordMaybeInsert(editor, session, "{"); return { text: '{', selection: [1, 1] }; } } } else if (text == '}') { initContext(editor); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } else if (text == "\n" || text == "\r\n") { initContext(editor); var closing = ""; if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { closing = lang.stringRepeat("}", context.maybeInsertedBrackets); CstyleBehaviour.clearMaybeInsertedClosing(); } var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}'); if (!openBracePos) return null; var next_indent = this.$getIndent(session.getLine(openBracePos.row)); } else if (closing) { var next_indent = this.$getIndent(line); } else { CstyleBehaviour.clearMaybeInsertedClosing(); return; } var indent = next_indent + session.getTabString(); return { text: '\n' + indent + '\n' + next_indent + closing, selection: [1, indent.length, 1, indent.length] }; } else { CstyleBehaviour.clearMaybeInsertedClosing(); } }); this.add("braces", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } else { context.maybeInsertedBrackets--; } } }); this.add("parens", "insertion", function(state, action, editor, session, text) { if (text == '(') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '(', ')'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, ")"); return { text: '()', selection: [1, 1] }; } } else if (text == ')') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("brackets", "insertion", function(state, action, editor, session, text) { if (text == '[') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '[', ']'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, "]"); return { text: '[]', selection: [1, 1] }; } } else if (text == ']') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ']') { var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("brackets", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '[') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ']') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function(state, action, editor, session, text) { if (text == '"' || text == "'") { initContext(editor); var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, quote, quote); } else if (!selected) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); var rightChar = line.substring(cursor.column, cursor.column + 1); var token = session.getTokenAt(cursor.row, cursor.column); var rightToken = session.getTokenAt(cursor.row, cursor.column + 1); if (leftChar == "\\" && token && /escape/.test(token.type)) return null; var stringBefore = token && /string/.test(token.type); var stringAfter = !rightToken || /string/.test(rightToken.type); var pair; if (rightChar == quote) { pair = stringBefore !== stringAfter; } else { if (stringBefore && !stringAfter) return null; // wrap string with different quote if (stringBefore && stringAfter) return null; // do not pair quotes inside strings var wordRe = session.$mode.tokenRe; wordRe.lastIndex = 0; var isWordBefore = wordRe.test(leftChar); wordRe.lastIndex = 0; var isWordAfter = wordRe.test(leftChar); if (isWordBefore || isWordAfter) return null; // before or after alphanumeric if (rightChar && !/[\s;,.})\]\\]/.test(rightChar)) return null; // there is rightChar and it isn't closing pair = true; } return { text: pair ? quote + quote : "", selection: [1,1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); }; CstyleBehaviour.isSaneInsertion = function(editor, session) { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) return false; } iterator.stepForward(); return iterator.getCurrentTokenRow() !== cursor.row || this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); }; CstyleBehaviour.$matchTokenType = function(token, types) { return types.indexOf(token.type || token) > -1; }; CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) context.autoInsertedBrackets = 0; context.autoInsertedRow = cursor.row; context.autoInsertedLineEnd = bracket + line.substr(cursor.column); context.autoInsertedBrackets++; }; CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isMaybeInsertedClosing(cursor, line)) context.maybeInsertedBrackets = 0; context.maybeInsertedRow = cursor.row; context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; context.maybeInsertedLineEnd = line.substr(cursor.column); context.maybeInsertedBrackets++; }; CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { return context.autoInsertedBrackets > 0 && cursor.row === context.autoInsertedRow && bracket === context.autoInsertedLineEnd[0] && line.substr(cursor.column) === context.autoInsertedLineEnd; }; CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { return context.maybeInsertedBrackets > 0 && cursor.row === context.maybeInsertedRow && line.substr(cursor.column) === context.maybeInsertedLineEnd && line.substr(0, cursor.column) == context.maybeInsertedLineStart; }; CstyleBehaviour.popAutoInsertedClosing = function() { context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); context.autoInsertedBrackets--; }; CstyleBehaviour.clearMaybeInsertedClosing = function() { if (context) { context.maybeInsertedBrackets = 0; context.maybeInsertedRow = -1; } }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/)#(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = JavaScriptHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "no_regex") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || endState == "no_regex") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(results) { session.setAnnotations(results.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/javascript"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/svg_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var SvgHighlightRules = function() { XmlHighlightRules.call(this); this.embedTagRules(JavaScriptHighlightRules, "js-", "script"); this.normalizeRules(); }; oop.inherits(SvgHighlightRules, XmlHighlightRules); exports.SvgHighlightRules = SvgHighlightRules; }); ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { if (typeof state != "string") state = state[0]; for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); ace.define("ace/mode/svg",["require","exports","module","ace/lib/oop","ace/mode/xml","ace/mode/javascript","ace/mode/svg_highlight_rules","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var XmlMode = require("./xml").Mode; var JavaScriptMode = require("./javascript").Mode; var SvgHighlightRules = require("./svg_highlight_rules").SvgHighlightRules; var MixedFoldMode = require("./folding/mixed").FoldMode; var XmlFoldMode = require("./folding/xml").FoldMode; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { XmlMode.call(this); this.HighlightRules = SvgHighlightRules; this.createModeDelegates({ "js-": JavaScriptMode }); this.foldingRules = new MixedFoldMode(new XmlFoldMode(), { "js-": new CStyleFoldMode() }); }; oop.inherits(Mode, XmlMode); (function() { this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.$id = "ace/mode/svg"; }).call(Mode.prototype); exports.Mode = Mode; });
{ "pile_set_name": "Github" }
org.jupiter.rpc.executor.CallerRunsExecutorFactory org.jupiter.rpc.executor.ThreadPoolExecutorFactory org.jupiter.rpc.executor.DisruptorExecutorFactory
{ "pile_set_name": "Github" }
Essential Studio includes seven component libraries in one great package.Essential Studio is available with full source code. It incorporates a unique debugging support system that allows switching between 'Debug' and 'Release' versions of our library with a single click from inside the Visual Studio.NET IDE. To ensure the highest quality of support possible, we use a state of the art Customer Relationship Management software (CRM) based Developer Support System called Direct-Trac. Syncfusion Direc-Trac is a support system that is uniquely tailored for developer needs. Support incidents can be created and tracked to completion 24 hours a day, 7 days a week. We have a simple, royalty-free licensing model. Components are licensed to a single user. We recognize that you often work at home or on your laptop in addition to your work machine. Therefore, our license permits our products to be installed in more than one location.At Syncfusion, we stand behind our products 100%. We have top notch management, architects, product managers, sales people, support personnel, and developers all working with you, the customer, as their focal point. Backoffice products: These products helps in creating reports of different files formats. Following are some backoffice products and short description of its use. 1) Essential PDF 2) Essential XlsIO 3) Essential DocIO.
{ "pile_set_name": "Github" }
package server import ( "bytes" "fmt" "net" "sync/atomic" "time" bnet "github.com/bio-routing/bio-rd/net" "github.com/bio-routing/bio-rd/protocols/bgp/packet" "github.com/bio-routing/bio-rd/route" "github.com/bio-routing/bio-rd/routingtable" "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) type establishedState struct { fsm *FSM } func newEstablishedState(fsm *FSM) *establishedState { return &establishedState{ fsm: fsm, } } func (s establishedState) run() (state, string) { if !s.fsm.ribsInitialized { err := s.init() if err != nil { return newCeaseState(), fmt.Sprintf("Init failed: %v", err) } } opt := s.fsm.decodeOptions() for { select { case e := <-s.fsm.eventCh: switch e { case ManualStop: return s.manualStop() case AutomaticStop: return s.automaticStop() case Cease: return s.cease() default: continue } case <-s.fsm.keepaliveTimer.C: return s.keepaliveTimerExpired() case <-time.After(time.Second): return s.checkHoldtimer() case recvMsg := <-s.fsm.msgRecvCh: return s.msgReceived(recvMsg, opt) } } } func (s *establishedState) checkHoldtimer() (state, string) { if time.Since(s.fsm.lastUpdateOrKeepalive) > s.fsm.holdTime { return s.holdTimerExpired() } return newEstablishedState(s.fsm), s.fsm.reason } func (s *establishedState) init() error { host, _, err := net.SplitHostPort(s.fsm.con.LocalAddr().String()) if err != nil { return errors.Wrap(err, "Unable to get local address") } localAddr, err := bnet.IPFromString(host) if err != nil { return errors.Wrap(err, "Unable to parse address") } n := &routingtable.Neighbor{ Type: route.BGPPathType, Address: s.fsm.peer.addr, IBGP: s.fsm.peer.localASN == s.fsm.peer.peerASN, LocalASN: s.fsm.peer.localASN, RouteServerClient: s.fsm.peer.routeServerClient, LocalAddress: localAddr.Dedup(), RouteReflectorClient: s.fsm.peer.routeReflectorClient, ClusterID: s.fsm.peer.clusterID, } if s.fsm.ipv4Unicast != nil { s.fsm.ipv4Unicast.init(n) } if s.fsm.ipv6Unicast != nil { s.fsm.ipv6Unicast.init(n) } s.fsm.ribsInitialized = true return nil } func (s *establishedState) uninit() { if s.fsm.ipv4Unicast != nil { s.fsm.ipv4Unicast.dispose() } if s.fsm.ipv6Unicast != nil { s.fsm.ipv6Unicast.dispose() } s.fsm.counters.reset() s.fsm.ribsInitialized = false } func (s *establishedState) manualStop() (state, string) { s.fsm.sendNotification(packet.Cease, 0) s.uninit() stopTimer(s.fsm.connectRetryTimer) s.fsm.con.Close() s.fsm.connectRetryCounter = 0 return newIdleState(s.fsm), "Manual stop event" } func (s *establishedState) automaticStop() (state, string) { s.fsm.sendNotification(packet.Cease, 0) s.uninit() stopTimer(s.fsm.connectRetryTimer) s.fsm.con.Close() s.fsm.connectRetryCounter++ return newIdleState(s.fsm), "Automatic stop event" } func (s *establishedState) cease() (state, string) { s.fsm.sendNotification(packet.Cease, 0) s.uninit() s.fsm.con.Close() return newCeaseState(), "Cease" } func (s *establishedState) holdTimerExpired() (state, string) { s.fsm.sendNotification(packet.HoldTimeExpired, 0) s.uninit() stopTimer(s.fsm.connectRetryTimer) s.fsm.con.Close() s.fsm.connectRetryCounter++ return newIdleState(s.fsm), "Holdtimer expired" } func (s *establishedState) keepaliveTimerExpired() (state, string) { err := s.fsm.sendKeepalive() if err != nil { s.uninit() stopTimer(s.fsm.connectRetryTimer) s.fsm.con.Close() s.fsm.connectRetryCounter++ return newIdleState(s.fsm), fmt.Sprintf("Failed to send keepalive: %v", err) } s.fsm.keepaliveTimer.Reset(s.fsm.keepaliveTime) return newEstablishedState(s.fsm), s.fsm.reason } func (s *establishedState) msgReceived(data []byte, opt *packet.DecodeOptions) (state, string) { msg, err := packet.Decode(bytes.NewBuffer(data), opt) if err != nil { switch bgperr := err.(type) { case packet.BGPError: s.fsm.sendNotification(bgperr.ErrorCode, bgperr.ErrorSubCode) } stopTimer(s.fsm.connectRetryTimer) if s.fsm.con != nil { s.fsm.con.Close() } s.fsm.connectRetryCounter++ return newIdleState(s.fsm), fmt.Sprintf("Failed to decode BGP message: %v", err) } switch msg.Header.Type { case packet.NotificationMsg: fmt.Println(data) return s.notification() case packet.UpdateMsg: return s.update(msg.Body.(*packet.BGPUpdate)) case packet.KeepaliveMsg: return s.keepaliveReceived() default: return s.unexpectedMessage() } } func (s *establishedState) notification() (state, string) { stopTimer(s.fsm.connectRetryTimer) s.uninit() s.fsm.con.Close() s.fsm.connectRetryCounter++ return newIdleState(s.fsm), "Received NOTIFICATION" } func (s *establishedState) update(u *packet.BGPUpdate) (state, string) { atomic.AddUint64(&s.fsm.counters.updatesReceived, 1) if s.fsm.holdTime != 0 { s.fsm.updateLastUpdateOrKeepalive() } if s.fsm.ipv4Unicast != nil { s.fsm.ipv4Unicast.processUpdate(u) } if s.fsm.ipv6Unicast != nil { s.fsm.ipv6Unicast.processUpdate(u) } afi, safi := s.updateAddressFamily(u) if safi != packet.UnicastSAFI { // only unicast support, so other SAFIs are ignored return newEstablishedState(s.fsm), s.fsm.reason } switch afi { case packet.IPv4AFI: if s.fsm.ipv4Unicast == nil { log.Warnf("Received update for family IPv4 unicast, but this family is not configured.") } case packet.IPv6AFI: if s.fsm.ipv6Unicast == nil { log.Warnf("Received update for family IPv6 unicast, but this family is not configured.") } } return newEstablishedState(s.fsm), s.fsm.reason } func (s *establishedState) updateAddressFamily(u *packet.BGPUpdate) (afi uint16, safi uint8) { if u.WithdrawnRoutes != nil || u.NLRI != nil { return packet.IPv4AFI, packet.UnicastSAFI } for cur := u.PathAttributes; cur != nil; cur = cur.Next { if cur.TypeCode == packet.MultiProtocolReachNLRICode { a := cur.Value.(packet.MultiProtocolReachNLRI) return a.AFI, a.SAFI } if cur.TypeCode == packet.MultiProtocolUnreachNLRICode { a := cur.Value.(packet.MultiProtocolUnreachNLRI) return a.AFI, a.SAFI } } return } func (s *establishedState) keepaliveReceived() (state, string) { if s.fsm.holdTime != 0 { s.fsm.updateLastUpdateOrKeepalive() } return newEstablishedState(s.fsm), s.fsm.reason } func (s *establishedState) unexpectedMessage() (state, string) { s.fsm.sendNotification(packet.FiniteStateMachineError, 0) s.uninit() stopTimer(s.fsm.connectRetryTimer) s.fsm.con.Close() s.fsm.connectRetryCounter++ return newIdleState(s.fsm), "FSM Error" }
{ "pile_set_name": "Github" }
<resources> <string name="app_name">example</string> </resources>
{ "pile_set_name": "Github" }
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。 示例 1: 输入: [1,2,3,1] 输出: 4 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。 偷窃到的最高金额 = 1 + 3 = 4 。 示例 2: 输入: [2,7,9,3,1] 输出: 12 解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。 偷窃到的最高金额 = 2 + 9 + 1 = 12 。
{ "pile_set_name": "Github" }
/* * 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 io.prestosql.type; import com.google.common.collect.ImmutableList; import io.airlift.slice.Slice; import io.airlift.slice.XxHash64; import io.prestosql.annotation.UsedByGeneratedCode; import io.prestosql.metadata.PolymorphicScalarFunctionBuilder; import io.prestosql.metadata.PolymorphicScalarFunctionBuilder.SpecializeContext; import io.prestosql.metadata.Signature; import io.prestosql.metadata.SignatureBuilder; import io.prestosql.metadata.SqlScalarFunction; import io.prestosql.spi.PrestoException; import io.prestosql.spi.function.IsNull; import io.prestosql.spi.function.LiteralParameters; import io.prestosql.spi.function.ScalarOperator; import io.prestosql.spi.function.SqlType; import io.prestosql.spi.type.DecimalType; import io.prestosql.spi.type.Decimals; import io.prestosql.spi.type.StandardTypes; import io.prestosql.spi.type.TypeSignature; import io.prestosql.spi.type.UnscaledDecimal128Arithmetic; import java.math.BigInteger; import java.util.List; import static io.prestosql.metadata.Signature.longVariableExpression; import static io.prestosql.spi.StandardErrorCode.DIVISION_BY_ZERO; import static io.prestosql.spi.StandardErrorCode.NUMERIC_VALUE_OUT_OF_RANGE; import static io.prestosql.spi.function.OperatorType.ADD; import static io.prestosql.spi.function.OperatorType.DIVIDE; import static io.prestosql.spi.function.OperatorType.HASH_CODE; import static io.prestosql.spi.function.OperatorType.INDETERMINATE; import static io.prestosql.spi.function.OperatorType.MODULUS; import static io.prestosql.spi.function.OperatorType.MULTIPLY; import static io.prestosql.spi.function.OperatorType.NEGATION; import static io.prestosql.spi.function.OperatorType.SUBTRACT; import static io.prestosql.spi.function.OperatorType.XX_HASH_64; import static io.prestosql.spi.type.Decimals.encodeUnscaledValue; import static io.prestosql.spi.type.Decimals.longTenToNth; import static io.prestosql.spi.type.TypeSignatureParameter.typeVariable; import static io.prestosql.spi.type.UnscaledDecimal128Arithmetic.divideRoundUp; import static io.prestosql.spi.type.UnscaledDecimal128Arithmetic.isZero; import static io.prestosql.spi.type.UnscaledDecimal128Arithmetic.remainder; import static io.prestosql.spi.type.UnscaledDecimal128Arithmetic.rescale; import static io.prestosql.spi.type.UnscaledDecimal128Arithmetic.throwIfOverflows; import static io.prestosql.spi.type.UnscaledDecimal128Arithmetic.unscaledDecimal; import static io.prestosql.spi.type.UnscaledDecimal128Arithmetic.unscaledDecimalToUnscaledLong; import static java.lang.Integer.max; import static java.lang.Long.signum; import static java.lang.Math.abs; import static java.lang.Math.toIntExact; import static java.util.Objects.requireNonNull; public final class DecimalOperators { public static final SqlScalarFunction DECIMAL_ADD_OPERATOR = decimalAddOperator(); public static final SqlScalarFunction DECIMAL_SUBTRACT_OPERATOR = decimalSubtractOperator(); public static final SqlScalarFunction DECIMAL_MULTIPLY_OPERATOR = decimalMultiplyOperator(); public static final SqlScalarFunction DECIMAL_DIVIDE_OPERATOR = decimalDivideOperator(); public static final SqlScalarFunction DECIMAL_MODULUS_OPERATOR = decimalModulusOperator(); private DecimalOperators() { } private static SqlScalarFunction decimalAddOperator() { TypeSignature decimalLeftSignature = new TypeSignature("decimal", typeVariable("a_precision"), typeVariable("a_scale")); TypeSignature decimalRightSignature = new TypeSignature("decimal", typeVariable("b_precision"), typeVariable("b_scale")); TypeSignature decimalResultSignature = new TypeSignature("decimal", typeVariable("r_precision"), typeVariable("r_scale")); Signature signature = Signature.builder() .operatorType(ADD) .longVariableConstraints( longVariableExpression("r_precision", "min(38, max(a_precision - a_scale, b_precision - b_scale) + max(a_scale, b_scale) + 1)"), longVariableExpression("r_scale", "max(a_scale, b_scale)")) .argumentTypes(decimalLeftSignature, decimalRightSignature) .returnType(decimalResultSignature) .build(); return new PolymorphicScalarFunctionBuilder(DecimalOperators.class) .signature(signature) .deterministic(true) .choice(choice -> choice .implementation(methodsGroup -> methodsGroup .methods("addShortShortShort") .withExtraParameters(DecimalOperators::calculateShortRescaleParameters)) .implementation(methodsGroup -> methodsGroup .methods("addShortShortLong", "addLongLongLong", "addShortLongLong", "addLongShortLong") .withExtraParameters(DecimalOperators::calculateLongRescaleParameters))) .build(); } @UsedByGeneratedCode public static long addShortShortShort(long a, long b, long aRescale, long bRescale) { return a * aRescale + b * bRescale; } @UsedByGeneratedCode public static Slice addShortShortLong(long a, long b, int rescale, boolean left) { return internalAddLongLongLong(unscaledDecimal(a), unscaledDecimal(b), rescale, left); } @UsedByGeneratedCode public static Slice addLongLongLong(Slice a, Slice b, int rescale, boolean left) { return internalAddLongLongLong(a, b, rescale, left); } @UsedByGeneratedCode public static Slice addShortLongLong(long a, Slice b, int rescale, boolean left) { return internalAddLongLongLong(unscaledDecimal(a), b, rescale, left); } @UsedByGeneratedCode public static Slice addLongShortLong(Slice a, long b, int rescale, boolean left) { return internalAddLongLongLong(a, unscaledDecimal(b), rescale, left); } private static Slice internalAddLongLongLong(Slice a, Slice b, int rescale, boolean rescaleLeft) { try { Slice left = unscaledDecimal(); Slice right; if (rescaleLeft) { rescale(a, rescale, left); right = b; } else { rescale(b, rescale, left); right = a; } UnscaledDecimal128Arithmetic.add(left, right, left); throwIfOverflows(left); return left; } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } private static SqlScalarFunction decimalSubtractOperator() { TypeSignature decimalLeftSignature = new TypeSignature("decimal", typeVariable("a_precision"), typeVariable("a_scale")); TypeSignature decimalRightSignature = new TypeSignature("decimal", typeVariable("b_precision"), typeVariable("b_scale")); TypeSignature decimalResultSignature = new TypeSignature("decimal", typeVariable("r_precision"), typeVariable("r_scale")); Signature signature = Signature.builder() .operatorType(SUBTRACT) .longVariableConstraints( longVariableExpression("r_precision", "min(38, max(a_precision - a_scale, b_precision - b_scale) + max(a_scale, b_scale) + 1)"), longVariableExpression("r_scale", "max(a_scale, b_scale)")) .argumentTypes(decimalLeftSignature, decimalRightSignature) .returnType(decimalResultSignature) .build(); return new PolymorphicScalarFunctionBuilder(DecimalOperators.class) .signature(signature) .deterministic(true) .choice(choice -> choice .implementation(methodsGroup -> methodsGroup .methods("subtractShortShortShort") .withExtraParameters(DecimalOperators::calculateShortRescaleParameters)) .implementation(methodsGroup -> methodsGroup .methods("subtractShortShortLong", "subtractLongLongLong", "subtractShortLongLong", "subtractLongShortLong") .withExtraParameters(DecimalOperators::calculateLongRescaleParameters))) .build(); } @UsedByGeneratedCode public static long subtractShortShortShort(long a, long b, long aRescale, long bRescale) { return a * aRescale - b * bRescale; } @UsedByGeneratedCode public static Slice subtractShortShortLong(long a, long b, int rescale, boolean left) { return internalSubtractLongLongLong(unscaledDecimal(a), unscaledDecimal(b), rescale, left); } @UsedByGeneratedCode public static Slice subtractLongLongLong(Slice a, Slice b, int rescale, boolean left) { return internalSubtractLongLongLong(a, b, rescale, left); } @UsedByGeneratedCode public static Slice subtractShortLongLong(long a, Slice b, int rescale, boolean left) { return internalSubtractLongLongLong(unscaledDecimal(a), b, rescale, left); } @UsedByGeneratedCode public static Slice subtractLongShortLong(Slice a, long b, int rescale, boolean left) { return internalSubtractLongLongLong(a, unscaledDecimal(b), rescale, left); } private static Slice internalSubtractLongLongLong(Slice a, Slice b, int rescale, boolean rescaleLeft) { try { Slice tmp = unscaledDecimal(); if (rescaleLeft) { rescale(a, rescale, tmp); UnscaledDecimal128Arithmetic.subtract(tmp, b, tmp); } else { rescale(b, rescale, tmp); UnscaledDecimal128Arithmetic.subtract(a, tmp, tmp); } throwIfOverflows(tmp); return tmp; } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } private static SqlScalarFunction decimalMultiplyOperator() { TypeSignature decimalLeftSignature = new TypeSignature("decimal", typeVariable("a_precision"), typeVariable("a_scale")); TypeSignature decimalRightSignature = new TypeSignature("decimal", typeVariable("b_precision"), typeVariable("b_scale")); TypeSignature decimalResultSignature = new TypeSignature("decimal", typeVariable("r_precision"), typeVariable("r_scale")); Signature signature = Signature.builder() .operatorType(MULTIPLY) .longVariableConstraints( longVariableExpression("r_precision", "min(38, a_precision + b_precision)"), longVariableExpression("r_scale", "a_scale + b_scale")) .argumentTypes(decimalLeftSignature, decimalRightSignature) .returnType(decimalResultSignature) .build(); return new PolymorphicScalarFunctionBuilder(DecimalOperators.class) .signature(signature) .deterministic(true) .choice(choice -> choice .implementation(methodsGroup -> methodsGroup .methods("multiplyShortShortShort", "multiplyShortShortLong", "multiplyLongLongLong", "multiplyShortLongLong", "multiplyLongShortLong"))) .build(); } @UsedByGeneratedCode public static long multiplyShortShortShort(long a, long b) { return a * b; } @UsedByGeneratedCode public static Slice multiplyShortShortLong(long a, long b) { return multiplyLongLongLong(encodeUnscaledValue(a), encodeUnscaledValue(b)); } @UsedByGeneratedCode public static Slice multiplyLongLongLong(Slice a, Slice b) { try { Slice result = UnscaledDecimal128Arithmetic.multiply(a, b); throwIfOverflows(result); return result; } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } @UsedByGeneratedCode public static Slice multiplyShortLongLong(long a, Slice b) { return multiplyLongLongLong(encodeUnscaledValue(a), b); } @UsedByGeneratedCode public static Slice multiplyLongShortLong(Slice a, long b) { return multiplyLongLongLong(a, encodeUnscaledValue(b)); } private static SqlScalarFunction decimalDivideOperator() { TypeSignature decimalLeftSignature = new TypeSignature("decimal", typeVariable("a_precision"), typeVariable("a_scale")); TypeSignature decimalRightSignature = new TypeSignature("decimal", typeVariable("b_precision"), typeVariable("b_scale")); TypeSignature decimalResultSignature = new TypeSignature("decimal", typeVariable("r_precision"), typeVariable("r_scale")); // we extend target precision by b_scale. This is upper bound on how much division result will grow. // pessimistic case is a / 0.0000001 // if scale of divisor is greater than scale of dividend we extend scale further as we // want result scale to be maximum of scales of divisor and dividend. Signature signature = Signature.builder() .operatorType(DIVIDE) .longVariableConstraints( longVariableExpression("r_precision", "min(38, a_precision + b_scale + max(b_scale - a_scale, 0))"), longVariableExpression("r_scale", "max(a_scale, b_scale)")) .argumentTypes(decimalLeftSignature, decimalRightSignature) .returnType(decimalResultSignature) .build(); return new PolymorphicScalarFunctionBuilder(DecimalOperators.class) .signature(signature) .deterministic(true) .choice(choice -> choice .implementation(methodsGroup -> methodsGroup .methods("divideShortShortShort", "divideShortLongShort", "divideLongShortShort", "divideShortShortLong", "divideLongLongLong", "divideShortLongLong", "divideLongShortLong") .withExtraParameters(DecimalOperators::divideRescaleFactor))) .build(); } private static List<Object> divideRescaleFactor(PolymorphicScalarFunctionBuilder.SpecializeContext context) { DecimalType returnType = (DecimalType) context.getReturnType(); int dividendScale = toIntExact(requireNonNull(context.getLiteral("a_scale"), "a_scale is null")); int divisorScale = toIntExact(requireNonNull(context.getLiteral("b_scale"), "b_scale is null")); int resultScale = returnType.getScale(); int rescaleFactor = resultScale - dividendScale + divisorScale; return ImmutableList.of(rescaleFactor); } @UsedByGeneratedCode public static long divideShortShortShort(long dividend, long divisor, int rescaleFactor) { if (divisor == 0) { throw new PrestoException(DIVISION_BY_ZERO, "Division by zero"); } if (dividend == 0) { return 0; } int resultSignum = signum(dividend) * signum(divisor); long unsignedDividend = abs(dividend); long unsignedDivisor = abs(divisor); long rescaledUnsignedDividend = unsignedDividend * longTenToNth(rescaleFactor); long quotient = rescaledUnsignedDividend / unsignedDivisor; long remainder = rescaledUnsignedDividend - (quotient * unsignedDivisor); if (Long.compareUnsigned(remainder * 2, unsignedDivisor) >= 0) { quotient++; } return resultSignum * quotient; } @UsedByGeneratedCode public static long divideShortLongShort(long dividend, Slice divisor, int rescaleFactor) { if (isZero(divisor)) { throw new PrestoException(DIVISION_BY_ZERO, "Division by zero"); } try { return unscaledDecimalToUnscaledLong(divideRoundUp(dividend, rescaleFactor, divisor)); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } @UsedByGeneratedCode public static long divideLongShortShort(Slice dividend, long divisor, int rescaleFactor) { if (divisor == 0) { throw new PrestoException(DIVISION_BY_ZERO, "Division by zero"); } try { return unscaledDecimalToUnscaledLong(divideRoundUp(dividend, rescaleFactor, divisor)); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } @UsedByGeneratedCode public static Slice divideShortShortLong(long dividend, long divisor, int rescaleFactor) { if (divisor == 0) { throw new PrestoException(DIVISION_BY_ZERO, "Division by zero"); } try { return divideRoundUp(dividend, rescaleFactor, divisor); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } @UsedByGeneratedCode public static Slice divideLongLongLong(Slice dividend, Slice divisor, int rescaleFactor) { if (isZero(divisor)) { throw new PrestoException(DIVISION_BY_ZERO, "Division by zero"); } try { return divideRoundUp(dividend, rescaleFactor, divisor); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } @UsedByGeneratedCode public static Slice divideShortLongLong(long dividend, Slice divisor, int rescaleFactor) { if (isZero(divisor)) { throw new PrestoException(DIVISION_BY_ZERO, "Division by zero"); } try { return divideRoundUp(dividend, rescaleFactor, divisor); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } @UsedByGeneratedCode public static Slice divideLongShortLong(Slice dividend, long divisor, int rescaleFactor) { if (divisor == 0) { throw new PrestoException(DIVISION_BY_ZERO, "Division by zero"); } try { return divideRoundUp(dividend, rescaleFactor, divisor); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } private static SqlScalarFunction decimalModulusOperator() { Signature signature = modulusSignatureBuilder() .operatorType(MODULUS) .build(); return modulusScalarFunction(signature); } public static SqlScalarFunction modulusScalarFunction(Signature signature) { return new PolymorphicScalarFunctionBuilder(DecimalOperators.class) .signature(signature) .deterministic(true) .choice(choice -> choice .implementation(methodsGroup -> methodsGroup .methods("modulusShortShortShort", "modulusLongLongLong", "modulusShortLongLong", "modulusShortLongShort", "modulusLongShortShort", "modulusLongShortLong") .withExtraParameters(DecimalOperators::modulusRescaleParameters))) .build(); } public static SignatureBuilder modulusSignatureBuilder() { TypeSignature decimalLeftSignature = new TypeSignature("decimal", typeVariable("a_precision"), typeVariable("a_scale")); TypeSignature decimalRightSignature = new TypeSignature("decimal", typeVariable("b_precision"), typeVariable("b_scale")); TypeSignature decimalResultSignature = new TypeSignature("decimal", typeVariable("r_precision"), typeVariable("r_scale")); return Signature.builder() .longVariableConstraints( longVariableExpression("r_precision", "min(b_precision - b_scale, a_precision - a_scale) + max(a_scale, b_scale)"), longVariableExpression("r_scale", "max(a_scale, b_scale)")) .argumentTypes(decimalLeftSignature, decimalRightSignature) .returnType(decimalResultSignature); } private static List<Object> calculateShortRescaleParameters(SpecializeContext context) { long aRescale = longTenToNth(rescaleFactor(context.getLiteral("a_scale"), context.getLiteral("b_scale"))); long bRescale = longTenToNth(rescaleFactor(context.getLiteral("b_scale"), context.getLiteral("a_scale"))); return ImmutableList.of(aRescale, bRescale); } private static List<Object> calculateLongRescaleParameters(SpecializeContext context) { long aScale = context.getLiteral("a_scale"); long bScale = context.getLiteral("b_scale"); int aRescale = rescaleFactor(aScale, bScale); int bRescale = rescaleFactor(bScale, aScale); int rescale; boolean left; if (aRescale == 0) { rescale = bRescale; left = false; } else if (bRescale == 0) { rescale = aRescale; left = true; } else { throw new IllegalStateException(); } return ImmutableList.of(rescale, left); } private static List<Object> modulusRescaleParameters(PolymorphicScalarFunctionBuilder.SpecializeContext context) { int dividendScale = toIntExact(requireNonNull(context.getLiteral("a_scale"), "a_scale is null")); int divisorScale = toIntExact(requireNonNull(context.getLiteral("b_scale"), "b_scale is null")); int dividendRescaleFactor = rescaleFactor(dividendScale, divisorScale); int divisorRescaleFactor = rescaleFactor(divisorScale, dividendScale); return ImmutableList.of(dividendRescaleFactor, divisorRescaleFactor); } private static int rescaleFactor(long fromScale, long toScale) { return max(0, (int) toScale - (int) fromScale); } @UsedByGeneratedCode public static long modulusShortShortShort(long dividend, long divisor, int dividendRescaleFactor, int divisorRescaleFactor) { if (divisor == 0) { throw new PrestoException(DIVISION_BY_ZERO, "Division by zero"); } try { return unscaledDecimalToUnscaledLong(remainder(dividend, dividendRescaleFactor, divisor, divisorRescaleFactor)); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } @UsedByGeneratedCode public static long modulusShortLongShort(long dividend, Slice divisor, int dividendRescaleFactor, int divisorRescaleFactor) { if (isZero(divisor)) { throw new PrestoException(DIVISION_BY_ZERO, "Division by zero"); } try { return unscaledDecimalToUnscaledLong(remainder(dividend, dividendRescaleFactor, divisor, divisorRescaleFactor)); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } @UsedByGeneratedCode public static long modulusLongShortShort(Slice dividend, long divisor, int dividendRescaleFactor, int divisorRescaleFactor) { if (divisor == 0) { throw new PrestoException(DIVISION_BY_ZERO, "Division by zero"); } try { return unscaledDecimalToUnscaledLong(remainder(dividend, dividendRescaleFactor, divisor, divisorRescaleFactor)); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } @UsedByGeneratedCode public static Slice modulusShortLongLong(long dividend, Slice divisor, int dividendRescaleFactor, int divisorRescaleFactor) { if (isZero(divisor)) { throw new PrestoException(DIVISION_BY_ZERO, "Division by zero"); } try { return remainder(dividend, dividendRescaleFactor, divisor, divisorRescaleFactor); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } @UsedByGeneratedCode public static Slice modulusLongShortLong(Slice dividend, long divisor, int dividendRescaleFactor, int divisorRescaleFactor) { if (divisor == 0) { throw new PrestoException(DIVISION_BY_ZERO, "Division by zero"); } try { return remainder(dividend, dividendRescaleFactor, divisor, divisorRescaleFactor); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } @UsedByGeneratedCode public static Slice modulusLongLongLong(Slice dividend, Slice divisor, int dividendRescaleFactor, int divisorRescaleFactor) { if (isZero(divisor)) { throw new PrestoException(DIVISION_BY_ZERO, "Division by zero"); } try { return remainder(dividend, dividendRescaleFactor, divisor, divisorRescaleFactor); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "Decimal overflow", e); } } @ScalarOperator(NEGATION) public static final class Negation { @LiteralParameters({"p", "s"}) @SqlType("decimal(p, s)") public static long negate(@SqlType("decimal(p, s)") long arg) { return -arg; } @LiteralParameters({"p", "s"}) @SqlType("decimal(p, s)") public static Slice negate(@SqlType("decimal(p, s)") Slice arg) { BigInteger argBigInteger = Decimals.decodeUnscaledValue(arg); return encodeUnscaledValue(argBigInteger.negate()); } } @ScalarOperator(HASH_CODE) public static final class HashCode { @LiteralParameters({"p", "s"}) @SqlType(StandardTypes.BIGINT) public static long hashCode(@SqlType("decimal(p, s)") long value) { return value; } @LiteralParameters({"p", "s"}) @SqlType(StandardTypes.BIGINT) public static long hashCode(@SqlType("decimal(p, s)") Slice value) { return UnscaledDecimal128Arithmetic.hash(value); } } @ScalarOperator(INDETERMINATE) public static final class Indeterminate { @LiteralParameters({"p", "s"}) @SqlType(StandardTypes.BOOLEAN) public static boolean indeterminate(@SqlType("decimal(p, s)") long value, @IsNull boolean isNull) { return isNull; } @LiteralParameters({"p", "s"}) @SqlType(StandardTypes.BOOLEAN) public static boolean indeterminate(@SqlType("decimal(p, s)") Slice value, @IsNull boolean isNull) { return isNull; } } @ScalarOperator(XX_HASH_64) public static final class XxHash64Operator { @LiteralParameters({"p", "s"}) @SqlType(StandardTypes.BIGINT) public static long xxHash64(@SqlType("decimal(p, s)") long value) { return XxHash64.hash(value); } @LiteralParameters({"p", "s"}) @SqlType(StandardTypes.BIGINT) public static long xxHash64(@SqlType("decimal(p, s)") Slice value) { return XxHash64.hash(value); } } }
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Windows; namespace LinqExample { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: e227d0e11c8e0498a88231ab7e5f9da8 timeCreated: 1510610474 licenseType: Free MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
var convert = require('./convert'), func = convert('every', require('../every')); func.placeholder = require('./placeholder'); module.exports = func;
{ "pile_set_name": "Github" }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Threading; using Microsoft.VisualStudio.Workspace.VSIntegration.UI; namespace NuGet.VisualStudio.OnlineEnvironment.Client { /// <summary> /// Extends the Solution Explorer in online environment scenarios. /// </summary> internal class NuGetWorkspaceCommandHandler : IWorkspaceCommandHandler { private readonly RestoreCommandHandler _restoreCommandHandler; private readonly PackageManagerUICommandHandler _packageManagerUICommandHandler; internal NuGetWorkspaceCommandHandler(JoinableTaskContext taskContext, IAsyncServiceProvider asyncServiceProvider) { if (taskContext == null) { throw new ArgumentNullException(nameof(taskContext)); } _restoreCommandHandler = new RestoreCommandHandler(taskContext.Factory, asyncServiceProvider); _packageManagerUICommandHandler = new PackageManagerUICommandHandler(taskContext.Factory, asyncServiceProvider); } /// <summary> /// The command handlers priority. If there are multiple handlers for a given node /// then they are called in order of decreasing priority. /// </summary> public int Priority => 2000; /// <summary> /// Whether or not this handler should be ignored when multiple nodes are selected. /// </summary> public bool IgnoreOnMultiselect => true; public int Exec(List<WorkspaceVisualNodeBase> selection, Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (pguidCmdGroup == CommandGroup.NuGetOnlineEnvironmentsClientProjectCommandSetGuid) { var nCmdIDInt = (int)nCmdID; switch (nCmdIDInt) { case PkgCmdIDList.CmdidRestorePackages: if (IsSolutionOnlySelection(selection)) { _restoreCommandHandler.RunSolutionRestore(); return VSConstants.S_OK; } break; case PkgCmdIDList.CmdIdManageProjectUI: if (IsSupportedProjectSelection(selection)) { _packageManagerUICommandHandler.OpenPackageManagerUI(selection.Single()); return VSConstants.S_OK; } break; default: break; } } return (int)Constants.OLECMDERR_E_NOTSUPPORTED; } public bool QueryStatus(List<WorkspaceVisualNodeBase> selection, Guid pguidCmdGroup, uint nCmdID, ref uint cmdf, ref string customTitle) { bool handled = false; if (pguidCmdGroup == CommandGroup.NuGetOnlineEnvironmentsClientProjectCommandSetGuid) { var nCmdIDInt = (int)nCmdID; { switch (nCmdIDInt) { case PkgCmdIDList.CmdidRestorePackages: if (IsSolutionOnlySelection(selection)) { var isRestoreActionInProgress = _restoreCommandHandler.IsRestoreActionInProgress(); cmdf = (uint)((isRestoreActionInProgress ? 0 : OLECMDF.OLECMDF_ENABLED) | OLECMDF.OLECMDF_SUPPORTED); handled = true; } break; case PkgCmdIDList.CmdIdManageProjectUI: if (IsSupportedProjectSelection(selection)) { var isPackageManagerUISupported = _packageManagerUICommandHandler.IsPackageManagerUISupported(selection.Single()); cmdf = (uint)(isPackageManagerUISupported ? (OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED) : OLECMDF.OLECMDF_INVISIBLE); handled = true; } break; default: break; } } } return handled; } private static bool IsSupportedProjectSelection(List<WorkspaceVisualNodeBase> selection) { if (selection != null && selection.Count.Equals(1)) { // We support every item representing a project // - we don't have the ability to do a capabilities check, because we don't have enough information. string fileExtension; try { fileExtension = Path.GetExtension(selection.Single().NodeMoniker); } catch (ArgumentException) { return false; } if (fileExtension == null) { return false; } // We do not know if the project is supported return fileExtension.EndsWith("proj", StringComparison.OrdinalIgnoreCase); } return false; } private static bool IsSolutionOnlySelection(List<WorkspaceVisualNodeBase> selection) { return selection != null && selection.Count.Equals(1) && selection.First().NodeMoniker.Equals(string.Empty); } } }
{ "pile_set_name": "Github" }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.sync; import android.support.annotation.Nullable; import org.json.JSONArray; import org.json.JSONException; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.components.sync.ModelType; import org.chromium.components.sync.PassphraseType; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; /** * JNI wrapper for the native ProfileSyncService. * * This class purely makes calls to native and contains absolutely no business logic. It is only * usable from the UI thread as the native ProfileSyncService requires its access to be on the * UI thread. See chrome/browser/sync/profile_sync_service.h for more details. */ public class ProfileSyncService { /** * Listener for the underlying sync status. */ public interface SyncStateChangedListener { // Invoked when the status has changed. public void syncStateChanged(); } /** * Callback for getAllNodes. */ public static class GetAllNodesCallback { private String mNodesString; // Invoked when getAllNodes completes. public void onResult(String nodesString) { mNodesString = nodesString; } // Returns the result of GetAllNodes as a JSONArray. @VisibleForTesting public JSONArray getNodesAsJsonArray() throws JSONException { return new JSONArray(mNodesString); } } /** * Provider for the Android master sync flag. */ interface MasterSyncEnabledProvider { // Returns whether master sync is enabled. public boolean isMasterSyncEnabled(); } private static final String TAG = "ProfileSyncService"; private static final int[] ALL_SELECTABLE_TYPES = new int[] { ModelType.AUTOFILL, ModelType.BOOKMARKS, ModelType.PASSWORDS, ModelType.PREFERENCES, ModelType.PROXY_TABS, ModelType.TYPED_URLS }; private static ProfileSyncService sProfileSyncService; private static boolean sInitialized; // Sync state changes more often than listeners are added/removed, so using CopyOnWrite. private final List<SyncStateChangedListener> mListeners = new CopyOnWriteArrayList<SyncStateChangedListener>(); /** * Native ProfileSyncServiceAndroid object. Cannot be final because it is initialized in * {@link init()}. */ private long mNativeProfileSyncServiceAndroid; /** * An object that knows whether Android's master sync setting is enabled. */ private MasterSyncEnabledProvider mMasterSyncEnabledProvider; private int mSetupInProgressCounter; /** * Retrieves or creates the ProfileSyncService singleton instance. Returns null if sync is * disabled (via flag or variation). * * Can only be accessed on the main thread. */ @Nullable public static ProfileSyncService get() { ThreadUtils.assertOnUiThread(); if (!sInitialized) { sProfileSyncService = new ProfileSyncService(); if (sProfileSyncService.mNativeProfileSyncServiceAndroid == 0) { sProfileSyncService = null; } sInitialized = true; } return sProfileSyncService; } /** * Overrides the initialization for tests. The tests should call resetForTests() at shutdown. */ @VisibleForTesting public static void overrideForTests(ProfileSyncService profileSyncService) { sProfileSyncService = profileSyncService; sInitialized = true; } /** * Resets the ProfileSyncService instance. Calling get() next time will initialize with a new * instance. */ @VisibleForTesting public static void resetForTests() { sInitialized = false; sProfileSyncService = null; } protected ProfileSyncService() { init(); } /** * This is called pretty early in our application. Avoid any blocking operations here. init() * is a separate function to enable a test subclass of ProfileSyncService to completely stub out * ProfileSyncService. */ protected void init() { ThreadUtils.assertOnUiThread(); // This may cause us to create ProfileSyncService even if sync has not // been set up, but ProfileSyncService::Startup() won't be called until // credentials are available. mNativeProfileSyncServiceAndroid = nativeInit(); } @CalledByNative private static long getProfileSyncServiceAndroid() { return get().mNativeProfileSyncServiceAndroid; } /** * Sets the the machine tag used by session sync. */ public void setSessionsId(String sessionTag) { ThreadUtils.assertOnUiThread(); nativeSetSyncSessionsId(mNativeProfileSyncServiceAndroid, sessionTag); } /** * Returns the actual passphrase type being used for encryption. The sync engine must be * running (isEngineInitialized() returns true) before calling this function. * <p/> * This method should only be used if you want to know the raw value. For checking whether * we should ask the user for a passphrase, use isPassphraseRequiredForDecryption(). */ public PassphraseType getPassphraseType() { assert isEngineInitialized(); int passphraseType = nativeGetPassphraseType(mNativeProfileSyncServiceAndroid); return PassphraseType.fromInternalValue(passphraseType); } /** * Returns true if the current explicit passphrase time is defined. */ public boolean hasExplicitPassphraseTime() { assert isEngineInitialized(); return nativeHasExplicitPassphraseTime(mNativeProfileSyncServiceAndroid); } /** * Returns the current explicit passphrase time in milliseconds since epoch. */ public long getExplicitPassphraseTime() { assert isEngineInitialized(); return nativeGetExplicitPassphraseTime(mNativeProfileSyncServiceAndroid); } public String getSyncEnterGooglePassphraseBodyWithDateText() { assert isEngineInitialized(); return nativeGetSyncEnterGooglePassphraseBodyWithDateText(mNativeProfileSyncServiceAndroid); } public String getSyncEnterCustomPassphraseBodyWithDateText() { assert isEngineInitialized(); return nativeGetSyncEnterCustomPassphraseBodyWithDateText(mNativeProfileSyncServiceAndroid); } public String getCurrentSignedInAccountText() { assert isEngineInitialized(); return nativeGetCurrentSignedInAccountText(mNativeProfileSyncServiceAndroid); } public String getSyncEnterCustomPassphraseBodyText() { return nativeGetSyncEnterCustomPassphraseBodyText(mNativeProfileSyncServiceAndroid); } /** * Checks if sync is currently set to use a custom passphrase. The sync engine must be running * (isEngineInitialized() returns true) before calling this function. * * @return true if sync is using a custom passphrase. */ public boolean isUsingSecondaryPassphrase() { assert isEngineInitialized(); return nativeIsUsingSecondaryPassphrase(mNativeProfileSyncServiceAndroid); } /** * Checks if we need a passphrase to decrypt a currently-enabled data type. This returns false * if a passphrase is needed for a type that is not currently enabled. * * @return true if we need a passphrase. */ public boolean isPassphraseRequiredForDecryption() { assert isEngineInitialized(); return nativeIsPassphraseRequiredForDecryption(mNativeProfileSyncServiceAndroid); } /** * Checks if the sync engine is running. * * @return true if sync is initialized/running. */ public boolean isEngineInitialized() { return nativeIsEngineInitialized(mNativeProfileSyncServiceAndroid); } /** * Checks if encrypting all the data types is allowed. * * @return true if encrypting all data types is allowed, false if only passwords are allowed to * be encrypted. */ public boolean isEncryptEverythingAllowed() { assert isEngineInitialized(); return nativeIsEncryptEverythingAllowed(mNativeProfileSyncServiceAndroid); } /** * Checks if the user has chosen to encrypt all data types. Note that some data types (e.g. * DEVICE_INFO) are never encrypted. * * @return true if all data types are encrypted, false if only passwords are encrypted. */ public boolean isEncryptEverythingEnabled() { assert isEngineInitialized(); return nativeIsEncryptEverythingEnabled(mNativeProfileSyncServiceAndroid); } /** * Turns on encryption of all data types. This only takes effect after sync configuration is * completed and setChosenDataTypes() is invoked. */ public void enableEncryptEverything() { assert isEngineInitialized(); nativeEnableEncryptEverything(mNativeProfileSyncServiceAndroid); } public void setEncryptionPassphrase(String passphrase) { assert isEngineInitialized(); nativeSetEncryptionPassphrase(mNativeProfileSyncServiceAndroid, passphrase); } public boolean setDecryptionPassphrase(String passphrase) { assert isEngineInitialized(); return nativeSetDecryptionPassphrase(mNativeProfileSyncServiceAndroid, passphrase); } public @GoogleServiceAuthError.State int getAuthError() { int authErrorCode = nativeGetAuthError(mNativeProfileSyncServiceAndroid); if (authErrorCode < 0 || authErrorCode >= GoogleServiceAuthError.State.NUM_ENTRIES) { throw new IllegalArgumentException("No state for code: " + authErrorCode); } return authErrorCode; } /** * Gets client action for sync protocol error. * * @return {@link ProtocolErrorClientAction}. */ public int getProtocolErrorClientAction() { return nativeGetProtocolErrorClientAction(mNativeProfileSyncServiceAndroid); } /** * Gets the set of data types that are currently syncing. * * This is affected by whether sync is on. * * @return Set of active data types. */ public Set<Integer> getActiveDataTypes() { int[] activeDataTypes = nativeGetActiveDataTypes(mNativeProfileSyncServiceAndroid); return modelTypeArrayToSet(activeDataTypes); } /** * Gets the set of data types that are enabled in sync. This will always * return a subset of syncer::UserSelectableTypes(). * * This is unaffected by whether sync is on. * * @return Set of chosen types. */ public Set<Integer> getChosenDataTypes() { int[] modelTypeArray = nativeGetChosenDataTypes(mNativeProfileSyncServiceAndroid); return modelTypeArrayToSet(modelTypeArray); } /** * Gets the set of data types that are "preferred" in sync. Those are the * "chosen" ones (see above), plus any that are implied by them. * * This is unaffected by whether sync is on. * * @return Set of preferred types. */ public Set<Integer> getPreferredDataTypes() { int[] modelTypeArray = nativeGetPreferredDataTypes(mNativeProfileSyncServiceAndroid); return modelTypeArrayToSet(modelTypeArray); } private static Set<Integer> modelTypeArrayToSet(int[] modelTypeArray) { Set<Integer> modelTypeSet = new HashSet<Integer>(); for (int i = 0; i < modelTypeArray.length; i++) { modelTypeSet.add(modelTypeArray[i]); } return modelTypeSet; } private static int[] modelTypeSetToArray(Set<Integer> modelTypeSet) { int[] modelTypeArray = new int[modelTypeSet.size()]; int i = 0; for (int modelType : modelTypeSet) { modelTypeArray[i++] = modelType; } return modelTypeArray; } public boolean hasKeepEverythingSynced() { return nativeHasKeepEverythingSynced(mNativeProfileSyncServiceAndroid); } /** * Enables syncing for the passed data types. * * @param syncEverything Set to true if the user wants to sync all data types * (including new data types we add in the future). * @param enabledTypes The set of types to enable. Ignored (can be null) if * syncEverything is true. */ public void setChosenDataTypes(boolean syncEverything, Set<Integer> enabledTypes) { nativeSetChosenDataTypes(mNativeProfileSyncServiceAndroid, syncEverything, syncEverything ? ALL_SELECTABLE_TYPES : modelTypeSetToArray(enabledTypes)); } public void setFirstSetupComplete() { nativeSetFirstSetupComplete(mNativeProfileSyncServiceAndroid); } public boolean isFirstSetupComplete() { return nativeIsFirstSetupComplete(mNativeProfileSyncServiceAndroid); } /** * Checks whether syncing is "requested" by the user, i.e. the user has not disabled syncing * in settings. Note that even if this is true, other reasons might prevent Sync from actually * starting up. * * @return true if the user wants to sync, false otherwise. */ public boolean isSyncRequested() { return nativeIsSyncRequested(mNativeProfileSyncServiceAndroid); } /** * Checks whether Sync-the-feature can (attempt to) start. This means that there is a primary * account and no disable reasons. Note that the Sync machinery may start up in transport-only * mode even if this is false. * * @return true if Sync can start, false otherwise. */ public boolean canSyncFeatureStart() { return nativeCanSyncFeatureStart(mNativeProfileSyncServiceAndroid); } /** * Checks whether Sync-the-feature is currently active. Note that Sync-the-transport may be * active even if this is false. * * @return true if Sync is active, false otherwise. */ public boolean isSyncActive() { return nativeIsSyncActive(mNativeProfileSyncServiceAndroid); } /** * Instances of this class keep sync paused until {@link #close} is called. Use * {@link ProfileSyncService#getSetupInProgressHandle} to create. Please note that * {@link #close} should be called on every instance of this class. */ public final class SyncSetupInProgressHandle { private boolean mClosed; private SyncSetupInProgressHandle() { ThreadUtils.assertOnUiThread(); if (++mSetupInProgressCounter == 1) { setSetupInProgress(true); } } public void close() { ThreadUtils.assertOnUiThread(); if (mClosed) return; mClosed = true; assert mSetupInProgressCounter > 0; if (--mSetupInProgressCounter == 0) { setSetupInProgress(false); // The user has finished setting up sync at least once. setFirstSetupComplete(); } } } /** * Called by the UI to prevent changes in sync settings from taking effect while these settings * are being modified by the user. When sync settings UI is no longer visible, * {@link SyncSetupInProgressHandle#close} has to be invoked for sync settings to be applied. * Sync settings will remain paused as long as there are unclosed objects returned by this * method. Please note that the behavior of SyncSetupInProgressHandle is slightly different from * the equivalent C++ object, as Java instances don't commit sync settings as soon as any * instance of SyncSetupInProgressHandle is closed. */ public SyncSetupInProgressHandle getSetupInProgressHandle() { return new SyncSetupInProgressHandle(); } private void setSetupInProgress(boolean inProgress) { nativeSetSetupInProgress(mNativeProfileSyncServiceAndroid, inProgress); } public void addSyncStateChangedListener(SyncStateChangedListener listener) { ThreadUtils.assertOnUiThread(); mListeners.add(listener); } public void removeSyncStateChangedListener(SyncStateChangedListener listener) { ThreadUtils.assertOnUiThread(); mListeners.remove(listener); } public boolean hasUnrecoverableError() { return nativeHasUnrecoverableError(mNativeProfileSyncServiceAndroid); } /** * Returns whether either personalized or anonymized URL keyed data collection is enabled. * * @param personlized Whether to check for personalized data collection. If false, this will * check for anonymized data collection. * @return Whether URL-keyed data collection is enabled for the current profile. */ public boolean isUrlKeyedDataCollectionEnabled(boolean personalized) { return nativeIsUrlKeyedDataCollectionEnabled( mNativeProfileSyncServiceAndroid, personalized); } /** * Called when the state of the native sync engine has changed, so various * UI elements can update themselves. */ @CalledByNative public void syncStateChanged() { for (SyncStateChangedListener listener : mListeners) { listener.syncStateChanged(); } } /** * Starts the sync engine. */ public void requestStart() { nativeRequestStart(mNativeProfileSyncServiceAndroid); } /** * Stops the sync engine. */ public void requestStop() { nativeRequestStop(mNativeProfileSyncServiceAndroid); } public void setSyncAllowedByPlatform(boolean allowed) { nativeSetSyncAllowedByPlatform(mNativeProfileSyncServiceAndroid, allowed); } /** * Flushes the sync directory. */ public void flushDirectory() { nativeFlushDirectory(mNativeProfileSyncServiceAndroid); } /** * Returns the time when the last sync cycle was completed. * * @return The difference measured in microseconds, between last sync cycle completion time * and 1 January 1970 00:00:00 UTC. */ @VisibleForTesting public long getLastSyncedTimeForTest() { return nativeGetLastSyncedTimeForTest(mNativeProfileSyncServiceAndroid); } /** * Overrides the Sync engine's NetworkResources. This is used to set up the Sync FakeServer for * testing. * * @param networkResources the pointer to the NetworkResources created by the native code. It * is assumed that the Java caller has ownership of this pointer; * ownership is transferred as part of this call. */ @VisibleForTesting public void overrideNetworkResourcesForTest(long networkResources) { nativeOverrideNetworkResourcesForTest(mNativeProfileSyncServiceAndroid, networkResources); } /** * Returns whether this client has previously prompted the user for a * passphrase error via the android system notifications. * * Can be called whether or not sync is initialized. * * @return Whether client has prompted for a passphrase error previously. */ public boolean isPassphrasePrompted() { return nativeIsPassphrasePrompted(mNativeProfileSyncServiceAndroid); } /** * Sets whether this client has previously prompted the user for a * passphrase error via the android system notifications. * * Can be called whether or not sync is initialized. * * @param prompted whether the client has prompted the user previously. */ public void setPassphrasePrompted(boolean prompted) { nativeSetPassphrasePrompted(mNativeProfileSyncServiceAndroid, prompted); } /** * Set the MasterSyncEnabledProvider for ProfileSyncService. * * This method is intentionally package-scope and should only be called once. */ void setMasterSyncEnabledProvider(MasterSyncEnabledProvider masterSyncEnabledProvider) { ThreadUtils.assertOnUiThread(); assert mMasterSyncEnabledProvider == null; mMasterSyncEnabledProvider = masterSyncEnabledProvider; } /** * Returns whether Android's master sync setting is enabled. */ @CalledByNative public boolean isMasterSyncEnabled() { ThreadUtils.assertOnUiThread(); // TODO(maxbogue): ensure that this method is never called before // setMasterSyncEnabledProvider() and change the line below to an assert. // See http://crbug.com/570569 if (mMasterSyncEnabledProvider == null) return true; return mMasterSyncEnabledProvider.isMasterSyncEnabled(); } /** * Invokes the onResult method of the callback from native code. */ @CalledByNative private static void onGetAllNodesResult(GetAllNodesCallback callback, String nodes) { callback.onResult(nodes); } /** * Retrieves a JSON version of local Sync data via the native GetAllNodes method. * This method is asynchronous; the result will be sent to the callback. */ @VisibleForTesting public void getAllNodes(GetAllNodesCallback callback) { nativeGetAllNodes(mNativeProfileSyncServiceAndroid, callback); } // Native methods private native long nativeInit(); private native void nativeRequestStart(long nativeProfileSyncServiceAndroid); private native void nativeRequestStop(long nativeProfileSyncServiceAndroid); private native void nativeSetSyncAllowedByPlatform( long nativeProfileSyncServiceAndroid, boolean allowed); private native void nativeFlushDirectory(long nativeProfileSyncServiceAndroid); private native void nativeSetSyncSessionsId(long nativeProfileSyncServiceAndroid, String tag); private native int nativeGetAuthError(long nativeProfileSyncServiceAndroid); private native int nativeGetProtocolErrorClientAction(long nativeProfileSyncServiceAndroid); private native boolean nativeIsEngineInitialized(long nativeProfileSyncServiceAndroid); private native boolean nativeIsEncryptEverythingAllowed(long nativeProfileSyncServiceAndroid); private native boolean nativeIsEncryptEverythingEnabled(long nativeProfileSyncServiceAndroid); private native void nativeEnableEncryptEverything(long nativeProfileSyncServiceAndroid); private native boolean nativeIsPassphraseRequiredForDecryption( long nativeProfileSyncServiceAndroid); private native boolean nativeIsUsingSecondaryPassphrase(long nativeProfileSyncServiceAndroid); private native boolean nativeSetDecryptionPassphrase( long nativeProfileSyncServiceAndroid, String passphrase); private native void nativeSetEncryptionPassphrase( long nativeProfileSyncServiceAndroid, String passphrase); private native int nativeGetPassphraseType(long nativeProfileSyncServiceAndroid); private native boolean nativeHasExplicitPassphraseTime(long nativeProfileSyncServiceAndroid); private native long nativeGetExplicitPassphraseTime(long nativeProfileSyncServiceAndroid); private native String nativeGetSyncEnterGooglePassphraseBodyWithDateText( long nativeProfileSyncServiceAndroid); private native String nativeGetSyncEnterCustomPassphraseBodyWithDateText( long nativeProfileSyncServiceAndroid); private native String nativeGetCurrentSignedInAccountText(long nativeProfileSyncServiceAndroid); private native String nativeGetSyncEnterCustomPassphraseBodyText( long nativeProfileSyncServiceAndroid); private native int[] nativeGetActiveDataTypes(long nativeProfileSyncServiceAndroid); private native int[] nativeGetChosenDataTypes(long nativeProfileSyncServiceAndroid); private native int[] nativeGetPreferredDataTypes(long nativeProfileSyncServiceAndroid); private native void nativeSetChosenDataTypes( long nativeProfileSyncServiceAndroid, boolean syncEverything, int[] modelTypeArray); private native void nativeSetSetupInProgress( long nativeProfileSyncServiceAndroid, boolean inProgress); private native void nativeSetFirstSetupComplete(long nativeProfileSyncServiceAndroid); private native boolean nativeIsFirstSetupComplete(long nativeProfileSyncServiceAndroid); private native boolean nativeIsSyncRequested(long nativeProfileSyncServiceAndroid); private native boolean nativeCanSyncFeatureStart(long nativeProfileSyncServiceAndroid); private native boolean nativeIsSyncActive(long nativeProfileSyncServiceAndroid); private native boolean nativeHasKeepEverythingSynced(long nativeProfileSyncServiceAndroid); private native boolean nativeHasUnrecoverableError(long nativeProfileSyncServiceAndroid); private native boolean nativeIsUrlKeyedDataCollectionEnabled( long nativeProfileSyncServiceAndroid, boolean personalized); private native boolean nativeIsPassphrasePrompted(long nativeProfileSyncServiceAndroid); private native void nativeSetPassphrasePrompted(long nativeProfileSyncServiceAndroid, boolean prompted); private native long nativeGetLastSyncedTimeForTest(long nativeProfileSyncServiceAndroid); private native void nativeOverrideNetworkResourcesForTest( long nativeProfileSyncServiceAndroid, long networkResources); private native void nativeGetAllNodes( long nativeProfileSyncServiceAndroid, GetAllNodesCallback callback); }
{ "pile_set_name": "Github" }
RUN: llvm-objdump -r %p/Inputs/reloc-addend.obj.macho-aarch64 | FileCheck %s CHECK-DAG: 0000000000000004 ARM64_RELOC_ADDEND 0x999 CHECK-DAG: 0000000000000004 ARM64_RELOC_PAGEOFF12 _stringbuf CHECK-DAG: 0000000000000000 ARM64_RELOC_ADDEND 0x999 CHECK-DAG: 0000000000000000 ARM64_RELOC_PAGE21 _stringbuf
{ "pile_set_name": "Github" }
// Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Eval restrictions should not trigger outside of strict-mode code. var eval = 42; eval = eval++; eval += --eval; eval -= ++eval; eval *= eval--; function eval(eval) {}; try {} catch (eval) {} function strict() { "use strict"; // Reading eval and arguments is allowed. eval(arguments); } var eval = 42; eval = eval++; eval += --eval; eval -= ++eval; eval *= eval--; function eval(eval) {}; try {} catch (eval) {}
{ "pile_set_name": "Github" }
#ifndef FSCONFIGPAGE_H #define FSCONFIGPAGE_H #include "clFileSystemWorkspaceConfig.hpp" #include "clFileSystemWorkspaceDlgBase.h" class FSConfigPage : public FSConfigPageBase { clFileSystemWorkspaceConfig::Ptr_t m_config; protected: virtual void OnEnableRemoteUI(wxUpdateUIEvent& event); virtual void OnSSHAccountChoice(wxCommandEvent& event); virtual void OnSSHBrowse(wxCommandEvent& event); virtual void OnRemoteEnabledUI(wxUpdateUIEvent& event); protected: void DoTargetActivated(); void DoUpdateSSHAcounts(); public: FSConfigPage(wxWindow* parent, clFileSystemWorkspaceConfig::Ptr_t config); virtual ~FSConfigPage(); void Save(); protected: virtual void OnTargetActivated(wxDataViewEvent& event); virtual void OnDelete(wxCommandEvent& event); virtual void OnDeleteUI(wxUpdateUIEvent& event); virtual void OnEditTarget(wxCommandEvent& event); virtual void OnEditTargetUI(wxUpdateUIEvent& event); virtual void OnNewTarget(wxCommandEvent& event); }; #endif // FSCONFIGPAGE_H
{ "pile_set_name": "Github" }
// Copyright 2017 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 // // 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. using UnityEngine; using System.Collections; public class slider2D : manipObject { public Vector2 percent = Vector2.zero; float xBound = 0.125f; float yBound = 0.05f; Material mat; Color customColor; public override void Awake() { base.Awake(); mat = GetComponent<Renderer>().material; customColor = new Color(Random.value, Random.value, Random.value); mat.SetColor("_EmissionColor", customColor * 0.25f); } void Start() { setPercent(percent); } public void forceChange(float value, bool Xaxis) // x axis false if it forces Y { setPercent(new Vector2(value, value), Xaxis, !Xaxis); if (curState == manipState.grabbed) { offset.x = transform.localPosition.x - transform.parent.InverseTransformPoint(manipulatorObj.position).x; offset.y = transform.localPosition.y - transform.parent.InverseTransformPoint(manipulatorObj.position).y; } updatePercent(); } public override void grabUpdate(Transform t) { Vector3 p = transform.localPosition; p.x = Mathf.Clamp(transform.parent.InverseTransformPoint(manipulatorObj.position).x + offset.x, -xBound, xBound); p.y = Mathf.Clamp(transform.parent.InverseTransformPoint(manipulatorObj.position).y + offset.y, -yBound, yBound); transform.localPosition = p; updatePercent(); } public void setPercent(Vector2 p, bool doX = true, bool doY = true) { Vector3 pos = transform.localPosition; if (doX) pos.x = Mathf.Lerp(-xBound, xBound, p.x); if (doY) pos.y = Mathf.Lerp(-yBound, yBound, p.y); transform.localPosition = pos; updatePercent(); } void updatePercent() { percent.x = .5f + transform.localPosition.x / (2 * xBound); percent.y = .5f + transform.localPosition.y / (2 * yBound); } Vector2 offset = Vector2.zero; public override void setState(manipState state) { curState = state; if (curState == manipState.none) { mat.SetColor("_EmissionColor", customColor * 0.25f); } else if (curState == manipState.selected) { mat.SetColor("_EmissionColor", customColor * 0.5f); } else if (curState == manipState.grabbed) { mat.SetColor("_EmissionColor", customColor); offset.x = transform.localPosition.x - transform.parent.InverseTransformPoint(manipulatorObj.position).x; offset.y = transform.localPosition.y - transform.parent.InverseTransformPoint(manipulatorObj.position).y; } } }
{ "pile_set_name": "Github" }
<?php /* Static Name: 404 */ ?> 404
{ "pile_set_name": "Github" }
This is a work-in-progress HTTP/2 implementation for Go. It will eventually live in the Go standard library and won't require any changes to your code to use. It will just be automatic. Status: * The server support is pretty good. A few things are missing but are being worked on. * The client work has just started but shares a lot of code is coming along much quicker. Docs are at https://godoc.org/golang.org/x/net/http2 Demo test server at https://http2.golang.org/ Help & bug reports welcome! Contributing: https://golang.org/doc/contribute.html Bugs: https://golang.org/issue/new?title=x/net/http2:+
{ "pile_set_name": "Github" }
/* * Copyright (C) 2011 Apple 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. */ function LayoutTestResultsLoader(builder) { this._builder = builder; } LayoutTestResultsLoader.prototype = { start: function(buildName, callback, errorCallback) { var cacheKey = 'LayoutTestResultsLoader.' + this._builder.name + '.' + buildName; const currentCachedDataVersion = 8; if (PersistentCache.contains(cacheKey)) { var cachedData = PersistentCache.get(cacheKey); if (cachedData.version === currentCachedDataVersion) { if (cachedData.error) errorCallback(cachedData.tests, cachedData.tooManyFailures); else callback(cachedData.tests, cachedData.tooManyFailures); return; } } var result = { tests: {}, tooManyFailures: false, error: false, version: currentCachedDataVersion }; function cacheParseResultsAndCallCallback(parseResult) { result.tests = parseResult.tests; result.tooManyFailures = parseResult.tooManyFailures; PersistentCache.set(cacheKey, result); callback(result.tests, result.tooManyFailures); } var self = this; self._fetchAndParseNRWTResults(buildName, cacheParseResultsAndCallCallback, function() { self._fetchAndParseORWTResults(buildName, cacheParseResultsAndCallCallback, function() { // We couldn't fetch results for this build. result.error = true; PersistentCache.set(cacheKey, result); errorCallback(result.tests, result.tooManyFailures); }); }); }, _fetchAndParseNRWTResults: function(buildName, successCallback, errorCallback) { getResource(this._builder.resultsDirectoryURL(buildName) + 'full_results.json', function(xhr) { successCallback((new NRWTResultsParser()).parse(xhr.responseText)); }, function(xhr) { errorCallback(); }); }, _fetchAndParseORWTResults: function(buildName, successCallback, errorCallback) { var parsedBuildName = this._builder.buildbot.parseBuildName(buildName); // http://webkit.org/b/62380 was fixed in r89610. var resultsHTMLSupportsTooManyFailuresInfo = parsedBuildName.revision >= 89610; var result = { tests: {}, tooManyFailures: false }; var self = this; function fetchAndParseResultsHTML(successCallback, errorCallback) { getResource(self._builder.resultsPageURL(buildName), function(xhr) { var parseResult = (new ORWTResultsParser()).parse(xhr.responseText); result.tests = parseResult.tests; if (resultsHTMLSupportsTooManyFailuresInfo) result.tooManyFailures = parseResult.tooManyFailures; successCallback(); }, function(xhr) { // We failed to fetch results.html. errorCallback(); }); } function fetchNumberOfFailingTests(successCallback, errorCallback) { self._builder.getNumberOfFailingTests(parsedBuildName.buildNumber, function(failingTestCount, tooManyFailures) { result.tooManyFailures = tooManyFailures; if (failingTestCount < 0) { // The number of failing tests couldn't be determined. errorCallback(); return; } successCallback(failingTestCount); }); } if (resultsHTMLSupportsTooManyFailuresInfo) { fetchAndParseResultsHTML(function() { successCallback(result); }, function() { fetchNumberOfFailingTests(function(failingTestCount) { if (!failingTestCount) { // All tests passed, so no results.html was generated. successCallback(result); return; } // Something went wrong with fetching results. errorCallback(); }, errorCallback); }); return; } fetchNumberOfFailingTests(function(failingTestCount) { if (!failingTestCount) { // All tests passed. successCallback(result); return; } // Find out which tests failed. fetchAndParseResultsHTML(function() { successCallback(result); }, errorCallback); }, errorCallback); }, };
{ "pile_set_name": "Github" }
#ifndef SM_OPTIONS_H #define SM_OPTIONS_H #include <options/options.h> #include "csm/csm_all.h" void sm_options(struct sm_params*p, struct option*ops); #endif
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="2.0dip" android:paddingRight="2.0dip" android:paddingTop="5.0dip" > <TextView android:id="@+id/week" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:gravity="center" android:singleLine="true" android:textColor="@android:color/white" android:textSize="14.0sp" /> <ImageView android:id="@+id/weather_diviver" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/week" android:layout_centerHorizontal="true" /> <ImageView android:id="@+id/weather_img" android:layout_width="60.0dip" android:layout_height="60.0dip" android:layout_below="@id/weather_diviver" android:layout_centerHorizontal="true" android:padding="5.0dip" /> <TextView android:id="@+id/temperature" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/weather_img" android:ellipsize="marquee" android:fadingEdge="horizontal" android:fadingEdgeLength="10dip" android:gravity="center" android:marqueeRepeatLimit="marquee_forever" android:scrollHorizontally="true" android:singleLine="true" android:textColor="@android:color/white" android:textSize="15.0sp" /> <TextView android:id="@+id/climate" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/temperature" android:ellipsize="marquee" android:fadingEdge="horizontal" android:fadingEdgeLength="10dip" android:gravity="center" android:marqueeRepeatLimit="marquee_forever" android:singleLine="true" android:textColor="@android:color/white" android:textSize="13.0sp" /> <TextView android:id="@+id/wind" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/climate" android:ellipsize="marquee" android:fadingEdge="horizontal" android:fadingEdgeLength="10dip" android:gravity="center" android:marqueeRepeatLimit="marquee_forever" android:scrollHorizontally="true" android:singleLine="true" android:textColor="@android:color/white" android:textSize="13.0sp" /> </RelativeLayout>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <alpha xmlns:android="http://schemas.android.com/apk/res/android" android:duration="@integer/feather_config_shortAnimTime" android:fromAlpha="1.0" android:interpolator="@android:anim/accelerate_interpolator" android:toAlpha="0.0" /> <!-- From: file:/Volumes/hujiawei/Users/hujiawei/git/TinyWeibo/TinyWeibo/androidFeather/src/main/res/anim/feather_fade_out_fast.xml -->
{ "pile_set_name": "Github" }
# Copyright 1999-2018 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 EAPI=6 inherit savedconfig toolchain-funcs DESCRIPTION="Simple plaintext presentation tool" HOMEPAGE="https://tools.suckless.org/sent/" SRC_URI="https://dl.suckless.org/tools/${P}.tar.gz" LICENSE="MIT" SLOT="0" KEYWORDS="~amd64" DEPEND=" media-libs/fontconfig x11-libs/libX11 x11-libs/libXft " RDEPEND=" ${DEPEND} !savedconfig? ( media-gfx/farbfeld ) " S=${WORKDIR} src_prepare() { default sed -i \ -e 's|^ @| |g' \ -e 's|@${CC}|$(CC)|g' \ -e '/^ echo/d' \ Makefile || die restore_config config.h } src_compile() { emake CC=$(tc-getCC) } src_install() { emake DESTDIR="${D}" PREFIX="/usr" install save_config config.h }
{ "pile_set_name": "Github" }
import { pipe } from '../../utils/pipe'; /** * Allows to execute hooks in chain, * passing the previous result value to the next hook. */ export const execHooks = async (schema, hookType: 'preHooks' | 'postHooks', hookAction, document?) => { if (schema[hookType] && schema[hookType][hookAction]) { const hooks = schema[hookType][hookAction]; const hooksFn = pipe(...hooks); await hooksFn(document); } };
{ "pile_set_name": "Github" }
Title: Now able to reclassify logwatch messages before forwarding them to the Event Console Level: 2 Component: ec Compatible: compat Version: 1.2.7i1 Date: 1421838593 Class: feature You are now able to apply already existing logwatch patterns to the messages which are sent to the Event Console. Each message can be reclassified to a different alert level and even set to IGNORED, which causes a message not to be sent to the Event Console. This pre-sorting might reduce the load of the Event Console. Keep in mind that the logwatch pattern are configured by host and the logfile name. These restrictions do also apply to the messages intented for the Event Console. So you can configure a logwatch pattern specifially designed for a message from a certain logfile. For example, you can reclassify any messages from a logfile <i>access.log</i> containing "C Login error" to "I Login error". Any message of <i>access.log</i> containing the "Login error" pattern will therefore get ignored and not sent to the Event Console.
{ "pile_set_name": "Github" }
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Nuclide Naming Conventions\n", "==========================\n", "One of the most basic aspects of nuclear software is how to uniquely represent \n", "nuclide names. There exists a large number of different ways that people choose \n", "to spell these names. Functionally, there are three pieces of information that *should* \n", "be included in every radionuclide's name:\n", "\n", "1. **Z Number**: The number of protons.\n", "2. **A Number**: The number of nucleons (neutrons + protons).\n", "3. **S Number**: The internal energy excitation state of the nucleus.\n", "\n", "Some common naming conventions exist. The following are currently supported by PyNE:\n", "\n", " * **id (ZAS)**: This type places the charge of the nucleus out front, then has three\n", " digits for the atomic mass number, and ends with four state digits (0 = ground,\n", " 1 = first metastable state, 2 = second metastable state, etc). Uranium-235 has\n", " 92 protons and an atomic mass number of 235. It would be expressed as '922350000'\n", " This is the canonical form for nuclides.\n", " * **name**: This is the more common, human readable notation. The chemical symbol\n", " (one or two characters long) is first, followed by the atomic weight. Lastly if\n", " the nuclide is metastable, the letter *M* is concatenated to the end. For\n", " example, 'H-1' and 'Am242M' are both valid. Note that nucname will always\n", " return name form with the dash removed and all letters uppercase.\n", " * **zzaaam**: This type places the charge of the nucleus out front, then has three\n", " digits for the atomic mass number, and ends with a metastable flag (0 = ground,\n", " 1 = first excited state, 2 = second excited state, etc). Uranium-235 here would\n", " be expressed as '922350'.\n", " * **SZA**: This type places three state digits out front, the charge of the nucleus in \n", " the middle, and then has three digits for the atomic mass number. Uranium-235M here \n", " would be expressed as '1092235'. \n", " * **MCNP**: The MCNP format for entering nuclides is unfortunately\n", " non-standard. In most ways it is similar to zzaaam form, except that it\n", " lacks the metastable flag. For information on how metastable isotopes are\n", " named, please consult the MCNPX documentation for more information.\n", " * **Serpent**: The serpent naming convention is similar to name form.\n", " However, only the first letter in the chemical symbol is uppercase, the\n", " dash is always present, and the the meta-stable flag is lowercase. For\n", " instance, 'Am-242m' is the valid serpent notation for this nuclide.\n", " * **NIST**: The NIST naming convention is also similar to the Serpent form.\n", " However, this convention contains no metastable information. Moreover, the\n", " A-number comes before the element symbol. For example, '242Am' is the\n", " valid NIST notation.\n", " * **CINDER**: The CINDER format is similar to zzaaam form except that the\n", " placement of the Z- and A-numbers are swapped. Therefore, this format is\n", " effectively aaazzzm. For example, '2420951' is the valid cinder notation\n", " for 'AM242M'.\n", " * **ALARA**: In ALARA format, elements are denoted by the lower case atomic symbol. Isotopes are\n", " specified by appending a semicolon and A-number. For example, \"fe\" and \"fe:56\" represent\n", " elemental iron and iron-56 respectively. No metastable flag exists.\n", " * **state_id**: State id format is similar to **id** except that it refers to each energy level in\n", " the order they are reported in the ENSDF file. This can change between ENSDF releases as more \n", " levels are added so it is not the default id form." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "----------------\n", "\n", "Canonical Form\n", "--------------\n", "A [canonical form](http://en.wikipedia.org/wiki/Canonical_form) is \n", "*\"a representation such that every object has a unique representation.\"*\n", "Since there are many ways to represent nuclides, PyNE chooses one of them\n", "to be *the* canonical form. **Note:** this idea of \n", "canonical forms will come up many times in PyNE.\n", "\n", "The **id** integer form of nuclide names is the fundamental form of nuclide naming because\n", "it accurately captures all of the needed information in the smallest amount of space. Given that the \n", "Z-number may be up to three digits, A-numbers are always three digits, and the excitation level is\n", "4 digits, all possible nuclides are represented on the range ``10000000 < zzaaam < 2130000000``. \n", "This falls well within 32 bit integers.\n", "\n", "The ``id()`` function converts other representations to the id format. " ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from pyne import nucname" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "922350000" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.id('U-235')" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "952420001" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.id('Am-242m')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "While applications and backends should use the **id** form under-the-covers, the **name** form provides an easy way to covert nuclide to a consistent and human readable representation." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'U235'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.name(922350000)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'H1'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.name(10010000)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Cm244M'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.name('CM-244m')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The **name** string representations may be anywhere from two characters (16 bits)\n", "up to six characters (48 bits). So in general, **id** is smaller by 50%. \n", "\n", "Other forms do not necessarily contain all of the required information (``MCNP``) or require additional \n", "storage space (``Serpent``). It may seem pedantic to quibble over the number of bits per nuclide name, \n", "but these identifiers are used everywhere throughout nuclear code, so it behooves us to be as small\n", "and fast as possible." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The other distinct advantage that integer forms have is that you can natively perform arithmetic\n", "on them. For example::" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "95\n", "242\n", "1\n" ] } ], "source": [ "# Am-242m\n", "nuc = 952420001\n", "\n", "# Z-number\n", "z = nuc//10000000\n", "print(z)\n", "\n", "# A-number\n", "a = (nuc//10000)%1000\n", "print(a)\n", "\n", "# state\n", "s = nuc%10000\n", "print(s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Of course, there are built in functions to do exactly this as well." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "95\n", "242\n", "1\n" ] } ], "source": [ "print(nucname.znum(nuc))\n", "print(nucname.anum(nuc))\n", "print(nucname.snum(nuc))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Code internal to PyNE uses **id**, and except for human readability, you should too! Natural elements are specified in this form by having zero A-number and excitation flags." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "920000000" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.id('U')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---------\n", "\n", "# Ambiguous Forms\n", "\n", "For some nuclides and forms, ambiguities may arise. For example \"10000\" is elemental neon in MCNP and elemental hydrogen in ZZAAAM. To resolve such ambiquities when you *know* which form you are coming from, PyNE provides a suite of `*_to_id()` functions. For example:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "100000000" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.mcnp_to_id(10000)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10000000" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.zzaaam_to_id(10000)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "-------------------\n", "\n", "Examples of Use\n", "---------------" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "922350" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.zzaaam('U235')" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'H1'" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.name(10010)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Am-242m'" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.serpent('AM242M')" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "38" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.name_zz['Sr']" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'La'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.zz_name[57]" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'fe:56'" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.alara('FE56')" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "952420002" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nucname.id_to_state_id(952420001)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.9" } }, "nbformat": 4, "nbformat_minor": 1 }
{ "pile_set_name": "Github" }
// Go FIDO U2F Library // Copyright 2015 The Go FIDO U2F Library Authors. All rights reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package u2flib import ( "bytes" "crypto/elliptic" "encoding/hex" "testing" ) const testRegRespHex = "0504b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b657c1cc6b952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2f6d9402a552dfdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3925a6019551bab61d16591659cbaf00b4950f7abfe6660e2e006f76868b772d70c253082013c3081e4a003020102020a47901280001155957352300a06082a8648ce3d0403023017311530130603550403130c476e756262792050696c6f74301e170d3132303831343138323933325a170d3133303831343138323933325a3031312f302d0603550403132650696c6f74476e756262792d302e342e312d34373930313238303030313135353935373335323059301306072a8648ce3d020106082a8648ce3d030107034200048d617e65c9508e64bcc5673ac82a6799da3c1446682c258c463fffdf58dfd2fa3e6c378b53d795c4a4dffb4199edd7862f23abaf0203b4b8911ba0569994e101300a06082a8648ce3d0403020347003044022060cdb6061e9c22262d1aac1d96d8c70829b2366531dda268832cb836bcd30dfa0220631b1459f09e6330055722c8d89b7f48883b9089b88d60d1d9795902b30410df304502201471899bcc3987e62e8202c9b39c33c19033f7340352dba80fcab017db9230e402210082677d673d891933ade6f617e5dbde2e247e70423fd5ad7804a6d3d3961ef871" func TestRegistrationExample(t *testing.T) { // Example 8.1 in FIDO U2F Raw Message Formats. regResp, _ := hex.DecodeString(testRegRespHex) r, sig, err := parseRegistration(regResp) if err != nil { t.Errorf("ParseRegistration error: %v", err) } const expectedKeyHandle = "2a552dfdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3925a6019551bab61d16591659cbaf00b4950f7abfe6660e2e006f76868b772d70c25" actualKeyHandle := hex.EncodeToString(r.KeyHandle) if actualKeyHandle != expectedKeyHandle { t.Errorf("unexpected key handle: %s vs %s", actualKeyHandle, expectedKeyHandle) } const expectedAttestationCert = "3082013c3081e4a003020102020a47901280001155957352300a06082a8648ce3d0403023017311530130603550403130c476e756262792050696c6f74301e170d3132303831343138323933325a170d3133303831343138323933325a3031312f302d0603550403132650696c6f74476e756262792d302e342e312d34373930313238303030313135353935373335323059301306072a8648ce3d020106082a8648ce3d030107034200048d617e65c9508e64bcc5673ac82a6799da3c1446682c258c463fffdf58dfd2fa3e6c378b53d795c4a4dffb4199edd7862f23abaf0203b4b8911ba0569994e101300a06082a8648ce3d0403020347003044022060cdb6061e9c22262d1aac1d96d8c70829b2366531dda268832cb836bcd30dfa0220631b1459f09e6330055722c8d89b7f48883b9089b88d60d1d9795902b30410df" actualAttestationCert := hex.EncodeToString(r.AttestationCert.Raw) if actualAttestationCert != expectedAttestationCert { t.Errorf("unexpected attestation cert: %s vs %s", actualAttestationCert, expectedAttestationCert) } const expectedSig = "304502201471899bcc3987e62e8202c9b39c33c19033f7340352dba80fcab017db9230e402210082677d673d891933ade6f617e5dbde2e247e70423fd5ad7804a6d3d3961ef871" actualSig := hex.EncodeToString(sig) if actualSig != expectedSig { t.Errorf("unexpected signature: %s vs %s", actualSig, expectedSig) } const expectedPubKey = "04b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b657c1cc6b952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2f6d9" actualPubKey := hex.EncodeToString( elliptic.Marshal(r.PubKey.Curve, r.PubKey.X, r.PubKey.Y)) if actualPubKey != expectedPubKey { t.Errorf("unexpected pubkey: %s vs %s", actualPubKey, expectedPubKey) } const appID = "http://example.com" const clientData = "{\"typ\":\"navigator.id.finishEnrollment\",\"challenge\":\"vqrS6WXDe1JUs5_c3i4-LkKIHRr-3XVb3azuA5TifHo\",\"cid_pubkey\":{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":\"HzQwlfXX7Q4S5MtCCnZUNBw3RMzPO9tOyWjBqRl4tJ8\",\"y\":\"XVguGFLIZx1fXg3wNqfdbn75hi4-_7-BxhMljw42Ht4\"},\"origin\":\"http://example.com\"}" err = verifyRegistrationSignature(*r, sig, appID, []byte(clientData)) if err != nil { t.Errorf("VerifySignature error: %v", err) } } func TestSerialize(t *testing.T) { regResp, _ := hex.DecodeString(testRegRespHex) reg, _, err := parseRegistration(regResp) if err != nil { t.Errorf("ParseRegistration error: %v", err) } buf, err := reg.MarshalBinary() if err != nil { t.Errorf("MarshalBinary error: %v", err) } var reg2 Registration if err := reg2.UnmarshalBinary(buf); err != nil { t.Errorf("UnmarshalBinary error: %v", err) } if bytes.Compare(reg.Raw, reg2.Raw) != 0 { t.Errorf("reg.Raw differs") } if bytes.Compare(reg.KeyHandle, reg2.KeyHandle) != 0 { t.Errorf("reg.KeyHandle differs") } if reg.PubKey.Curve != reg2.PubKey.Curve { t.Errorf("reg.PubKey.Curve differs") } if reg.PubKey.X.Cmp(reg2.PubKey.X) != 0 { t.Errorf("reg.PubKey.X differs") } if reg.PubKey.Y.Cmp(reg2.PubKey.Y) != 0 { t.Errorf("reg.PubKey.Y differs") } if bytes.Compare(reg.AttestationCert.Raw, reg2.AttestationCert.Raw) != 0 { t.Errorf("reg.AttestationCert differs") } }
{ "pile_set_name": "Github" }
// license:BSD-3-Clause // copyright-holders:Farfetch'd, R. Belmont // NOTE for bit string / field addressing // ************************************ // m_moddim must be passed as 10 for bit string instructions, // and as 11 for bit field instructions // Addressing mode functions and tables #include "am1.hxx" // ReadAM #include "am2.hxx" // ReadAMAddress #include "am3.hxx" // WriteAM /* Input: m_modadd m_moddim Output: m_amout amLength */ uint32_t v60_device::ReadAM() { m_modm = m_modm?1:0; m_modval = OpRead8(m_modadd); return (this->*s_AMTable1[m_modm][m_modval >> 5])(); } uint32_t v60_device::BitReadAM() { m_modm = m_modm?1:0; m_modval = OpRead8(m_modadd); return (this->*s_BAMTable1[m_modm][m_modval >> 5])(); } /* Input: m_modadd m_moddim Output: m_amout m_amflag amLength */ uint32_t v60_device::ReadAMAddress() { m_modm = m_modm?1:0; m_modval = OpRead8(m_modadd); return (this->*s_AMTable2[m_modm][m_modval >> 5])(); } uint32_t v60_device::BitReadAMAddress() { m_modm = m_modm?1:0; m_modval = OpRead8(m_modadd); return (this->*s_BAMTable2[m_modm][m_modval >> 5])(); } /* Input: m_modadd m_moddim m_modwritevalb / H/W Output: m_amout amLength */ uint32_t v60_device::WriteAM() { m_modm = m_modm?1:0; m_modval = OpRead8(m_modadd); return (this->*s_AMTable3[m_modm][m_modval >> 5])(); }
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0-or-later /* * Hierarchical Budget Worst-case Fair Weighted Fair Queueing * (B-WF2Q+): hierarchical scheduling algorithm by which the BFQ I/O * scheduler schedules generic entities. The latter can represent * either single bfq queues (associated with processes) or groups of * bfq queues (associated with cgroups). */ #include "bfq-iosched.h" /** * bfq_gt - compare two timestamps. * @a: first ts. * @b: second ts. * * Return @a > @b, dealing with wrapping correctly. */ static int bfq_gt(u64 a, u64 b) { return (s64)(a - b) > 0; } static struct bfq_entity *bfq_root_active_entity(struct rb_root *tree) { struct rb_node *node = tree->rb_node; return rb_entry(node, struct bfq_entity, rb_node); } static unsigned int bfq_class_idx(struct bfq_entity *entity) { struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity); return bfqq ? bfqq->ioprio_class - 1 : BFQ_DEFAULT_GRP_CLASS - 1; } unsigned int bfq_tot_busy_queues(struct bfq_data *bfqd) { return bfqd->busy_queues[0] + bfqd->busy_queues[1] + bfqd->busy_queues[2]; } static struct bfq_entity *bfq_lookup_next_entity(struct bfq_sched_data *sd, bool expiration); static bool bfq_update_parent_budget(struct bfq_entity *next_in_service); /** * bfq_update_next_in_service - update sd->next_in_service * @sd: sched_data for which to perform the update. * @new_entity: if not NULL, pointer to the entity whose activation, * requeueing or repositioning triggered the invocation of * this function. * @expiration: id true, this function is being invoked after the * expiration of the in-service entity * * This function is called to update sd->next_in_service, which, in * its turn, may change as a consequence of the insertion or * extraction of an entity into/from one of the active trees of * sd. These insertions/extractions occur as a consequence of * activations/deactivations of entities, with some activations being * 'true' activations, and other activations being requeueings (i.e., * implementing the second, requeueing phase of the mechanism used to * reposition an entity in its active tree; see comments on * __bfq_activate_entity and __bfq_requeue_entity for details). In * both the last two activation sub-cases, new_entity points to the * just activated or requeued entity. * * Returns true if sd->next_in_service changes in such a way that * entity->parent may become the next_in_service for its parent * entity. */ static bool bfq_update_next_in_service(struct bfq_sched_data *sd, struct bfq_entity *new_entity, bool expiration) { struct bfq_entity *next_in_service = sd->next_in_service; bool parent_sched_may_change = false; bool change_without_lookup = false; /* * If this update is triggered by the activation, requeueing * or repositioning of an entity that does not coincide with * sd->next_in_service, then a full lookup in the active tree * can be avoided. In fact, it is enough to check whether the * just-modified entity has the same priority as * sd->next_in_service, is eligible and has a lower virtual * finish time than sd->next_in_service. If this compound * condition holds, then the new entity becomes the new * next_in_service. Otherwise no change is needed. */ if (new_entity && new_entity != sd->next_in_service) { /* * Flag used to decide whether to replace * sd->next_in_service with new_entity. Tentatively * set to true, and left as true if * sd->next_in_service is NULL. */ change_without_lookup = true; /* * If there is already a next_in_service candidate * entity, then compare timestamps to decide whether * to replace sd->service_tree with new_entity. */ if (next_in_service) { unsigned int new_entity_class_idx = bfq_class_idx(new_entity); struct bfq_service_tree *st = sd->service_tree + new_entity_class_idx; change_without_lookup = (new_entity_class_idx == bfq_class_idx(next_in_service) && !bfq_gt(new_entity->start, st->vtime) && bfq_gt(next_in_service->finish, new_entity->finish)); } if (change_without_lookup) next_in_service = new_entity; } if (!change_without_lookup) /* lookup needed */ next_in_service = bfq_lookup_next_entity(sd, expiration); if (next_in_service) { bool new_budget_triggers_change = bfq_update_parent_budget(next_in_service); parent_sched_may_change = !sd->next_in_service || new_budget_triggers_change; } sd->next_in_service = next_in_service; if (!next_in_service) return parent_sched_may_change; return parent_sched_may_change; } #ifdef CONFIG_BFQ_GROUP_IOSCHED struct bfq_group *bfq_bfqq_to_bfqg(struct bfq_queue *bfqq) { struct bfq_entity *group_entity = bfqq->entity.parent; if (!group_entity) group_entity = &bfqq->bfqd->root_group->entity; return container_of(group_entity, struct bfq_group, entity); } /* * Returns true if this budget changes may let next_in_service->parent * become the next_in_service entity for its parent entity. */ static bool bfq_update_parent_budget(struct bfq_entity *next_in_service) { struct bfq_entity *bfqg_entity; struct bfq_group *bfqg; struct bfq_sched_data *group_sd; bool ret = false; group_sd = next_in_service->sched_data; bfqg = container_of(group_sd, struct bfq_group, sched_data); /* * bfq_group's my_entity field is not NULL only if the group * is not the root group. We must not touch the root entity * as it must never become an in-service entity. */ bfqg_entity = bfqg->my_entity; if (bfqg_entity) { if (bfqg_entity->budget > next_in_service->budget) ret = true; bfqg_entity->budget = next_in_service->budget; } return ret; } /* * This function tells whether entity stops being a candidate for next * service, according to the restrictive definition of the field * next_in_service. In particular, this function is invoked for an * entity that is about to be set in service. * * If entity is a queue, then the entity is no longer a candidate for * next service according to the that definition, because entity is * about to become the in-service queue. This function then returns * true if entity is a queue. * * In contrast, entity could still be a candidate for next service if * it is not a queue, and has more than one active child. In fact, * even if one of its children is about to be set in service, other * active children may still be the next to serve, for the parent * entity, even according to the above definition. As a consequence, a * non-queue entity is not a candidate for next-service only if it has * only one active child. And only if this condition holds, then this * function returns true for a non-queue entity. */ static bool bfq_no_longer_next_in_service(struct bfq_entity *entity) { struct bfq_group *bfqg; if (bfq_entity_to_bfqq(entity)) return true; bfqg = container_of(entity, struct bfq_group, entity); /* * The field active_entities does not always contain the * actual number of active children entities: it happens to * not account for the in-service entity in case the latter is * removed from its active tree (which may get done after * invoking the function bfq_no_longer_next_in_service in * bfq_get_next_queue). Fortunately, here, i.e., while * bfq_no_longer_next_in_service is not yet completed in * bfq_get_next_queue, bfq_active_extract has not yet been * invoked, and thus active_entities still coincides with the * actual number of active entities. */ if (bfqg->active_entities == 1) return true; return false; } #else /* CONFIG_BFQ_GROUP_IOSCHED */ struct bfq_group *bfq_bfqq_to_bfqg(struct bfq_queue *bfqq) { return bfqq->bfqd->root_group; } static bool bfq_update_parent_budget(struct bfq_entity *next_in_service) { return false; } static bool bfq_no_longer_next_in_service(struct bfq_entity *entity) { return true; } #endif /* CONFIG_BFQ_GROUP_IOSCHED */ /* * Shift for timestamp calculations. This actually limits the maximum * service allowed in one timestamp delta (small shift values increase it), * the maximum total weight that can be used for the queues in the system * (big shift values increase it), and the period of virtual time * wraparounds. */ #define WFQ_SERVICE_SHIFT 22 struct bfq_queue *bfq_entity_to_bfqq(struct bfq_entity *entity) { struct bfq_queue *bfqq = NULL; if (!entity->my_sched_data) bfqq = container_of(entity, struct bfq_queue, entity); return bfqq; } /** * bfq_delta - map service into the virtual time domain. * @service: amount of service. * @weight: scale factor (weight of an entity or weight sum). */ static u64 bfq_delta(unsigned long service, unsigned long weight) { return div64_ul((u64)service << WFQ_SERVICE_SHIFT, weight); } /** * bfq_calc_finish - assign the finish time to an entity. * @entity: the entity to act upon. * @service: the service to be charged to the entity. */ static void bfq_calc_finish(struct bfq_entity *entity, unsigned long service) { struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity); entity->finish = entity->start + bfq_delta(service, entity->weight); if (bfqq) { bfq_log_bfqq(bfqq->bfqd, bfqq, "calc_finish: serv %lu, w %d", service, entity->weight); bfq_log_bfqq(bfqq->bfqd, bfqq, "calc_finish: start %llu, finish %llu, delta %llu", entity->start, entity->finish, bfq_delta(service, entity->weight)); } } /** * bfq_entity_of - get an entity from a node. * @node: the node field of the entity. * * Convert a node pointer to the relative entity. This is used only * to simplify the logic of some functions and not as the generic * conversion mechanism because, e.g., in the tree walking functions, * the check for a %NULL value would be redundant. */ struct bfq_entity *bfq_entity_of(struct rb_node *node) { struct bfq_entity *entity = NULL; if (node) entity = rb_entry(node, struct bfq_entity, rb_node); return entity; } /** * bfq_extract - remove an entity from a tree. * @root: the tree root. * @entity: the entity to remove. */ static void bfq_extract(struct rb_root *root, struct bfq_entity *entity) { entity->tree = NULL; rb_erase(&entity->rb_node, root); } /** * bfq_idle_extract - extract an entity from the idle tree. * @st: the service tree of the owning @entity. * @entity: the entity being removed. */ static void bfq_idle_extract(struct bfq_service_tree *st, struct bfq_entity *entity) { struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity); struct rb_node *next; if (entity == st->first_idle) { next = rb_next(&entity->rb_node); st->first_idle = bfq_entity_of(next); } if (entity == st->last_idle) { next = rb_prev(&entity->rb_node); st->last_idle = bfq_entity_of(next); } bfq_extract(&st->idle, entity); if (bfqq) list_del(&bfqq->bfqq_list); } /** * bfq_insert - generic tree insertion. * @root: tree root. * @entity: entity to insert. * * This is used for the idle and the active tree, since they are both * ordered by finish time. */ static void bfq_insert(struct rb_root *root, struct bfq_entity *entity) { struct bfq_entity *entry; struct rb_node **node = &root->rb_node; struct rb_node *parent = NULL; while (*node) { parent = *node; entry = rb_entry(parent, struct bfq_entity, rb_node); if (bfq_gt(entry->finish, entity->finish)) node = &parent->rb_left; else node = &parent->rb_right; } rb_link_node(&entity->rb_node, parent, node); rb_insert_color(&entity->rb_node, root); entity->tree = root; } /** * bfq_update_min - update the min_start field of a entity. * @entity: the entity to update. * @node: one of its children. * * This function is called when @entity may store an invalid value for * min_start due to updates to the active tree. The function assumes * that the subtree rooted at @node (which may be its left or its right * child) has a valid min_start value. */ static void bfq_update_min(struct bfq_entity *entity, struct rb_node *node) { struct bfq_entity *child; if (node) { child = rb_entry(node, struct bfq_entity, rb_node); if (bfq_gt(entity->min_start, child->min_start)) entity->min_start = child->min_start; } } /** * bfq_update_active_node - recalculate min_start. * @node: the node to update. * * @node may have changed position or one of its children may have moved, * this function updates its min_start value. The left and right subtrees * are assumed to hold a correct min_start value. */ static void bfq_update_active_node(struct rb_node *node) { struct bfq_entity *entity = rb_entry(node, struct bfq_entity, rb_node); entity->min_start = entity->start; bfq_update_min(entity, node->rb_right); bfq_update_min(entity, node->rb_left); } /** * bfq_update_active_tree - update min_start for the whole active tree. * @node: the starting node. * * @node must be the deepest modified node after an update. This function * updates its min_start using the values held by its children, assuming * that they did not change, and then updates all the nodes that may have * changed in the path to the root. The only nodes that may have changed * are the ones in the path or their siblings. */ static void bfq_update_active_tree(struct rb_node *node) { struct rb_node *parent; up: bfq_update_active_node(node); parent = rb_parent(node); if (!parent) return; if (node == parent->rb_left && parent->rb_right) bfq_update_active_node(parent->rb_right); else if (parent->rb_left) bfq_update_active_node(parent->rb_left); node = parent; goto up; } /** * bfq_active_insert - insert an entity in the active tree of its * group/device. * @st: the service tree of the entity. * @entity: the entity being inserted. * * The active tree is ordered by finish time, but an extra key is kept * per each node, containing the minimum value for the start times of * its children (and the node itself), so it's possible to search for * the eligible node with the lowest finish time in logarithmic time. */ static void bfq_active_insert(struct bfq_service_tree *st, struct bfq_entity *entity) { struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity); struct rb_node *node = &entity->rb_node; #ifdef CONFIG_BFQ_GROUP_IOSCHED struct bfq_sched_data *sd = NULL; struct bfq_group *bfqg = NULL; struct bfq_data *bfqd = NULL; #endif bfq_insert(&st->active, entity); if (node->rb_left) node = node->rb_left; else if (node->rb_right) node = node->rb_right; bfq_update_active_tree(node); #ifdef CONFIG_BFQ_GROUP_IOSCHED sd = entity->sched_data; bfqg = container_of(sd, struct bfq_group, sched_data); bfqd = (struct bfq_data *)bfqg->bfqd; #endif if (bfqq) list_add(&bfqq->bfqq_list, &bfqq->bfqd->active_list); #ifdef CONFIG_BFQ_GROUP_IOSCHED if (bfqg != bfqd->root_group) bfqg->active_entities++; #endif } /** * bfq_ioprio_to_weight - calc a weight from an ioprio. * @ioprio: the ioprio value to convert. */ unsigned short bfq_ioprio_to_weight(int ioprio) { return (IOPRIO_BE_NR - ioprio) * BFQ_WEIGHT_CONVERSION_COEFF; } /** * bfq_weight_to_ioprio - calc an ioprio from a weight. * @weight: the weight value to convert. * * To preserve as much as possible the old only-ioprio user interface, * 0 is used as an escape ioprio value for weights (numerically) equal or * larger than IOPRIO_BE_NR * BFQ_WEIGHT_CONVERSION_COEFF. */ static unsigned short bfq_weight_to_ioprio(int weight) { return max_t(int, 0, IOPRIO_BE_NR * BFQ_WEIGHT_CONVERSION_COEFF - weight); } static void bfq_get_entity(struct bfq_entity *entity) { struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity); if (bfqq) { bfqq->ref++; bfq_log_bfqq(bfqq->bfqd, bfqq, "get_entity: %p %d", bfqq, bfqq->ref); } else bfqg_and_blkg_get(container_of(entity, struct bfq_group, entity)); } /** * bfq_find_deepest - find the deepest node that an extraction can modify. * @node: the node being removed. * * Do the first step of an extraction in an rb tree, looking for the * node that will replace @node, and returning the deepest node that * the following modifications to the tree can touch. If @node is the * last node in the tree return %NULL. */ static struct rb_node *bfq_find_deepest(struct rb_node *node) { struct rb_node *deepest; if (!node->rb_right && !node->rb_left) deepest = rb_parent(node); else if (!node->rb_right) deepest = node->rb_left; else if (!node->rb_left) deepest = node->rb_right; else { deepest = rb_next(node); if (deepest->rb_right) deepest = deepest->rb_right; else if (rb_parent(deepest) != node) deepest = rb_parent(deepest); } return deepest; } /** * bfq_active_extract - remove an entity from the active tree. * @st: the service_tree containing the tree. * @entity: the entity being removed. */ static void bfq_active_extract(struct bfq_service_tree *st, struct bfq_entity *entity) { struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity); struct rb_node *node; #ifdef CONFIG_BFQ_GROUP_IOSCHED struct bfq_sched_data *sd = NULL; struct bfq_group *bfqg = NULL; struct bfq_data *bfqd = NULL; #endif node = bfq_find_deepest(&entity->rb_node); bfq_extract(&st->active, entity); if (node) bfq_update_active_tree(node); #ifdef CONFIG_BFQ_GROUP_IOSCHED sd = entity->sched_data; bfqg = container_of(sd, struct bfq_group, sched_data); bfqd = (struct bfq_data *)bfqg->bfqd; #endif if (bfqq) list_del(&bfqq->bfqq_list); #ifdef CONFIG_BFQ_GROUP_IOSCHED if (bfqg != bfqd->root_group) bfqg->active_entities--; #endif } /** * bfq_idle_insert - insert an entity into the idle tree. * @st: the service tree containing the tree. * @entity: the entity to insert. */ static void bfq_idle_insert(struct bfq_service_tree *st, struct bfq_entity *entity) { struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity); struct bfq_entity *first_idle = st->first_idle; struct bfq_entity *last_idle = st->last_idle; if (!first_idle || bfq_gt(first_idle->finish, entity->finish)) st->first_idle = entity; if (!last_idle || bfq_gt(entity->finish, last_idle->finish)) st->last_idle = entity; bfq_insert(&st->idle, entity); if (bfqq) list_add(&bfqq->bfqq_list, &bfqq->bfqd->idle_list); } /** * bfq_forget_entity - do not consider entity any longer for scheduling * @st: the service tree. * @entity: the entity being removed. * @is_in_service: true if entity is currently the in-service entity. * * Forget everything about @entity. In addition, if entity represents * a queue, and the latter is not in service, then release the service * reference to the queue (the one taken through bfq_get_entity). In * fact, in this case, there is really no more service reference to * the queue, as the latter is also outside any service tree. If, * instead, the queue is in service, then __bfq_bfqd_reset_in_service * will take care of putting the reference when the queue finally * stops being served. */ static void bfq_forget_entity(struct bfq_service_tree *st, struct bfq_entity *entity, bool is_in_service) { struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity); entity->on_st_or_in_serv = false; st->wsum -= entity->weight; if (is_in_service) return; if (bfqq) bfq_put_queue(bfqq); else bfqg_and_blkg_put(container_of(entity, struct bfq_group, entity)); } /** * bfq_put_idle_entity - release the idle tree ref of an entity. * @st: service tree for the entity. * @entity: the entity being released. */ void bfq_put_idle_entity(struct bfq_service_tree *st, struct bfq_entity *entity) { bfq_idle_extract(st, entity); bfq_forget_entity(st, entity, entity == entity->sched_data->in_service_entity); } /** * bfq_forget_idle - update the idle tree if necessary. * @st: the service tree to act upon. * * To preserve the global O(log N) complexity we only remove one entry here; * as the idle tree will not grow indefinitely this can be done safely. */ static void bfq_forget_idle(struct bfq_service_tree *st) { struct bfq_entity *first_idle = st->first_idle; struct bfq_entity *last_idle = st->last_idle; if (RB_EMPTY_ROOT(&st->active) && last_idle && !bfq_gt(last_idle->finish, st->vtime)) { /* * Forget the whole idle tree, increasing the vtime past * the last finish time of idle entities. */ st->vtime = last_idle->finish; } if (first_idle && !bfq_gt(first_idle->finish, st->vtime)) bfq_put_idle_entity(st, first_idle); } struct bfq_service_tree *bfq_entity_service_tree(struct bfq_entity *entity) { struct bfq_sched_data *sched_data = entity->sched_data; unsigned int idx = bfq_class_idx(entity); return sched_data->service_tree + idx; } /* * Update weight and priority of entity. If update_class_too is true, * then update the ioprio_class of entity too. * * The reason why the update of ioprio_class is controlled through the * last parameter is as follows. Changing the ioprio class of an * entity implies changing the destination service trees for that * entity. If such a change occurred when the entity is already on one * of the service trees for its previous class, then the state of the * entity would become more complex: none of the new possible service * trees for the entity, according to bfq_entity_service_tree(), would * match any of the possible service trees on which the entity * is. Complex operations involving these trees, such as entity * activations and deactivations, should take into account this * additional complexity. To avoid this issue, this function is * invoked with update_class_too unset in the points in the code where * entity may happen to be on some tree. */ struct bfq_service_tree * __bfq_entity_update_weight_prio(struct bfq_service_tree *old_st, struct bfq_entity *entity, bool update_class_too) { struct bfq_service_tree *new_st = old_st; if (entity->prio_changed) { struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity); unsigned int prev_weight, new_weight; struct bfq_data *bfqd = NULL; struct rb_root_cached *root; #ifdef CONFIG_BFQ_GROUP_IOSCHED struct bfq_sched_data *sd; struct bfq_group *bfqg; #endif if (bfqq) bfqd = bfqq->bfqd; #ifdef CONFIG_BFQ_GROUP_IOSCHED else { sd = entity->my_sched_data; bfqg = container_of(sd, struct bfq_group, sched_data); bfqd = (struct bfq_data *)bfqg->bfqd; } #endif /* Matches the smp_wmb() in bfq_group_set_weight. */ smp_rmb(); old_st->wsum -= entity->weight; if (entity->new_weight != entity->orig_weight) { if (entity->new_weight < BFQ_MIN_WEIGHT || entity->new_weight > BFQ_MAX_WEIGHT) { pr_crit("update_weight_prio: new_weight %d\n", entity->new_weight); if (entity->new_weight < BFQ_MIN_WEIGHT) entity->new_weight = BFQ_MIN_WEIGHT; else entity->new_weight = BFQ_MAX_WEIGHT; } entity->orig_weight = entity->new_weight; if (bfqq) bfqq->ioprio = bfq_weight_to_ioprio(entity->orig_weight); } if (bfqq && update_class_too) bfqq->ioprio_class = bfqq->new_ioprio_class; /* * Reset prio_changed only if the ioprio_class change * is not pending any longer. */ if (!bfqq || bfqq->ioprio_class == bfqq->new_ioprio_class) entity->prio_changed = 0; /* * NOTE: here we may be changing the weight too early, * this will cause unfairness. The correct approach * would have required additional complexity to defer * weight changes to the proper time instants (i.e., * when entity->finish <= old_st->vtime). */ new_st = bfq_entity_service_tree(entity); prev_weight = entity->weight; new_weight = entity->orig_weight * (bfqq ? bfqq->wr_coeff : 1); /* * If the weight of the entity changes, and the entity is a * queue, remove the entity from its old weight counter (if * there is a counter associated with the entity). */ if (prev_weight != new_weight && bfqq) { root = &bfqd->queue_weights_tree; __bfq_weights_tree_remove(bfqd, bfqq, root); } entity->weight = new_weight; /* * Add the entity, if it is not a weight-raised queue, * to the counter associated with its new weight. */ if (prev_weight != new_weight && bfqq && bfqq->wr_coeff == 1) { /* If we get here, root has been initialized. */ bfq_weights_tree_add(bfqd, bfqq, root); } new_st->wsum += entity->weight; if (new_st != old_st) entity->start = new_st->vtime; } return new_st; } /** * bfq_bfqq_served - update the scheduler status after selection for * service. * @bfqq: the queue being served. * @served: bytes to transfer. * * NOTE: this can be optimized, as the timestamps of upper level entities * are synchronized every time a new bfqq is selected for service. By now, * we keep it to better check consistency. */ void bfq_bfqq_served(struct bfq_queue *bfqq, int served) { struct bfq_entity *entity = &bfqq->entity; struct bfq_service_tree *st; if (!bfqq->service_from_backlogged) bfqq->first_IO_time = jiffies; if (bfqq->wr_coeff > 1) bfqq->service_from_wr += served; bfqq->service_from_backlogged += served; for_each_entity(entity) { st = bfq_entity_service_tree(entity); entity->service += served; st->vtime += bfq_delta(served, st->wsum); bfq_forget_idle(st); } bfq_log_bfqq(bfqq->bfqd, bfqq, "bfqq_served %d secs", served); } /** * bfq_bfqq_charge_time - charge an amount of service equivalent to the length * of the time interval during which bfqq has been in * service. * @bfqd: the device * @bfqq: the queue that needs a service update. * @time_ms: the amount of time during which the queue has received service * * If a queue does not consume its budget fast enough, then providing * the queue with service fairness may impair throughput, more or less * severely. For this reason, queues that consume their budget slowly * are provided with time fairness instead of service fairness. This * goal is achieved through the BFQ scheduling engine, even if such an * engine works in the service, and not in the time domain. The trick * is charging these queues with an inflated amount of service, equal * to the amount of service that they would have received during their * service slot if they had been fast, i.e., if their requests had * been dispatched at a rate equal to the estimated peak rate. * * It is worth noting that time fairness can cause important * distortions in terms of bandwidth distribution, on devices with * internal queueing. The reason is that I/O requests dispatched * during the service slot of a queue may be served after that service * slot is finished, and may have a total processing time loosely * correlated with the duration of the service slot. This is * especially true for short service slots. */ void bfq_bfqq_charge_time(struct bfq_data *bfqd, struct bfq_queue *bfqq, unsigned long time_ms) { struct bfq_entity *entity = &bfqq->entity; unsigned long timeout_ms = jiffies_to_msecs(bfq_timeout); unsigned long bounded_time_ms = min(time_ms, timeout_ms); int serv_to_charge_for_time = (bfqd->bfq_max_budget * bounded_time_ms) / timeout_ms; int tot_serv_to_charge = max(serv_to_charge_for_time, entity->service); /* Increase budget to avoid inconsistencies */ if (tot_serv_to_charge > entity->budget) entity->budget = tot_serv_to_charge; bfq_bfqq_served(bfqq, max_t(int, 0, tot_serv_to_charge - entity->service)); } static void bfq_update_fin_time_enqueue(struct bfq_entity *entity, struct bfq_service_tree *st, bool backshifted) { struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity); /* * When this function is invoked, entity is not in any service * tree, then it is safe to invoke next function with the last * parameter set (see the comments on the function). */ st = __bfq_entity_update_weight_prio(st, entity, true); bfq_calc_finish(entity, entity->budget); /* * If some queues enjoy backshifting for a while, then their * (virtual) finish timestamps may happen to become lower and * lower than the system virtual time. In particular, if * these queues often happen to be idle for short time * periods, and during such time periods other queues with * higher timestamps happen to be busy, then the backshifted * timestamps of the former queues can become much lower than * the system virtual time. In fact, to serve the queues with * higher timestamps while the ones with lower timestamps are * idle, the system virtual time may be pushed-up to much * higher values than the finish timestamps of the idle * queues. As a consequence, the finish timestamps of all new * or newly activated queues may end up being much larger than * those of lucky queues with backshifted timestamps. The * latter queues may then monopolize the device for a lot of * time. This would simply break service guarantees. * * To reduce this problem, push up a little bit the * backshifted timestamps of the queue associated with this * entity (only a queue can happen to have the backshifted * flag set): just enough to let the finish timestamp of the * queue be equal to the current value of the system virtual * time. This may introduce a little unfairness among queues * with backshifted timestamps, but it does not break * worst-case fairness guarantees. * * As a special case, if bfqq is weight-raised, push up * timestamps much less, to keep very low the probability that * this push up causes the backshifted finish timestamps of * weight-raised queues to become higher than the backshifted * finish timestamps of non weight-raised queues. */ if (backshifted && bfq_gt(st->vtime, entity->finish)) { unsigned long delta = st->vtime - entity->finish; if (bfqq) delta /= bfqq->wr_coeff; entity->start += delta; entity->finish += delta; } bfq_active_insert(st, entity); } /** * __bfq_activate_entity - handle activation of entity. * @entity: the entity being activated. * @non_blocking_wait_rq: true if entity was waiting for a request * * Called for a 'true' activation, i.e., if entity is not active and * one of its children receives a new request. * * Basically, this function updates the timestamps of entity and * inserts entity into its active tree, after possibly extracting it * from its idle tree. */ static void __bfq_activate_entity(struct bfq_entity *entity, bool non_blocking_wait_rq) { struct bfq_service_tree *st = bfq_entity_service_tree(entity); bool backshifted = false; unsigned long long min_vstart; /* See comments on bfq_fqq_update_budg_for_activation */ if (non_blocking_wait_rq && bfq_gt(st->vtime, entity->finish)) { backshifted = true; min_vstart = entity->finish; } else min_vstart = st->vtime; if (entity->tree == &st->idle) { /* * Must be on the idle tree, bfq_idle_extract() will * check for that. */ bfq_idle_extract(st, entity); entity->start = bfq_gt(min_vstart, entity->finish) ? min_vstart : entity->finish; } else { /* * The finish time of the entity may be invalid, and * it is in the past for sure, otherwise the queue * would have been on the idle tree. */ entity->start = min_vstart; st->wsum += entity->weight; /* * entity is about to be inserted into a service tree, * and then set in service: get a reference to make * sure entity does not disappear until it is no * longer in service or scheduled for service. */ bfq_get_entity(entity); entity->on_st_or_in_serv = true; } #ifdef CONFIG_BFQ_GROUP_IOSCHED if (!bfq_entity_to_bfqq(entity)) { /* bfq_group */ struct bfq_group *bfqg = container_of(entity, struct bfq_group, entity); struct bfq_data *bfqd = bfqg->bfqd; if (!entity->in_groups_with_pending_reqs) { entity->in_groups_with_pending_reqs = true; bfqd->num_groups_with_pending_reqs++; } } #endif bfq_update_fin_time_enqueue(entity, st, backshifted); } /** * __bfq_requeue_entity - handle requeueing or repositioning of an entity. * @entity: the entity being requeued or repositioned. * * Requeueing is needed if this entity stops being served, which * happens if a leaf descendant entity has expired. On the other hand, * repositioning is needed if the next_inservice_entity for the child * entity has changed. See the comments inside the function for * details. * * Basically, this function: 1) removes entity from its active tree if * present there, 2) updates the timestamps of entity and 3) inserts * entity back into its active tree (in the new, right position for * the new values of the timestamps). */ static void __bfq_requeue_entity(struct bfq_entity *entity) { struct bfq_sched_data *sd = entity->sched_data; struct bfq_service_tree *st = bfq_entity_service_tree(entity); if (entity == sd->in_service_entity) { /* * We are requeueing the current in-service entity, * which may have to be done for one of the following * reasons: * - entity represents the in-service queue, and the * in-service queue is being requeued after an * expiration; * - entity represents a group, and its budget has * changed because one of its child entities has * just been either activated or requeued for some * reason; the timestamps of the entity need then to * be updated, and the entity needs to be enqueued * or repositioned accordingly. * * In particular, before requeueing, the start time of * the entity must be moved forward to account for the * service that the entity has received while in * service. This is done by the next instructions. The * finish time will then be updated according to this * new value of the start time, and to the budget of * the entity. */ bfq_calc_finish(entity, entity->service); entity->start = entity->finish; /* * In addition, if the entity had more than one child * when set in service, then it was not extracted from * the active tree. This implies that the position of * the entity in the active tree may need to be * changed now, because we have just updated the start * time of the entity, and we will update its finish * time in a moment (the requeueing is then, more * precisely, a repositioning in this case). To * implement this repositioning, we: 1) dequeue the * entity here, 2) update the finish time and requeue * the entity according to the new timestamps below. */ if (entity->tree) bfq_active_extract(st, entity); } else { /* The entity is already active, and not in service */ /* * In this case, this function gets called only if the * next_in_service entity below this entity has * changed, and this change has caused the budget of * this entity to change, which, finally implies that * the finish time of this entity must be * updated. Such an update may cause the scheduling, * i.e., the position in the active tree, of this * entity to change. We handle this change by: 1) * dequeueing the entity here, 2) updating the finish * time and requeueing the entity according to the new * timestamps below. This is the same approach as the * non-extracted-entity sub-case above. */ bfq_active_extract(st, entity); } bfq_update_fin_time_enqueue(entity, st, false); } static void __bfq_activate_requeue_entity(struct bfq_entity *entity, struct bfq_sched_data *sd, bool non_blocking_wait_rq) { struct bfq_service_tree *st = bfq_entity_service_tree(entity); if (sd->in_service_entity == entity || entity->tree == &st->active) /* * in service or already queued on the active tree, * requeue or reposition */ __bfq_requeue_entity(entity); else /* * Not in service and not queued on its active tree: * the activity is idle and this is a true activation. */ __bfq_activate_entity(entity, non_blocking_wait_rq); } /** * bfq_activate_requeue_entity - activate or requeue an entity representing a * bfq_queue, and activate, requeue or reposition * all ancestors for which such an update becomes * necessary. * @entity: the entity to activate. * @non_blocking_wait_rq: true if this entity was waiting for a request * @requeue: true if this is a requeue, which implies that bfqq is * being expired; thus ALL its ancestors stop being served and must * therefore be requeued * @expiration: true if this function is being invoked in the expiration path * of the in-service queue */ static void bfq_activate_requeue_entity(struct bfq_entity *entity, bool non_blocking_wait_rq, bool requeue, bool expiration) { struct bfq_sched_data *sd; for_each_entity(entity) { sd = entity->sched_data; __bfq_activate_requeue_entity(entity, sd, non_blocking_wait_rq); if (!bfq_update_next_in_service(sd, entity, expiration) && !requeue) break; } } /** * __bfq_deactivate_entity - update sched_data and service trees for * entity, so as to represent entity as inactive * @entity: the entity being deactivated. * @ins_into_idle_tree: if false, the entity will not be put into the * idle tree. * * If necessary and allowed, puts entity into the idle tree. NOTE: * entity may be on no tree if in service. */ bool __bfq_deactivate_entity(struct bfq_entity *entity, bool ins_into_idle_tree) { struct bfq_sched_data *sd = entity->sched_data; struct bfq_service_tree *st; bool is_in_service; if (!entity->on_st_or_in_serv) /* * entity never activated, or * already inactive */ return false; /* * If we get here, then entity is active, which implies that * bfq_group_set_parent has already been invoked for the group * represented by entity. Therefore, the field * entity->sched_data has been set, and we can safely use it. */ st = bfq_entity_service_tree(entity); is_in_service = entity == sd->in_service_entity; bfq_calc_finish(entity, entity->service); if (is_in_service) sd->in_service_entity = NULL; else /* * Non in-service entity: nobody will take care of * resetting its service counter on expiration. Do it * now. */ entity->service = 0; if (entity->tree == &st->active) bfq_active_extract(st, entity); else if (!is_in_service && entity->tree == &st->idle) bfq_idle_extract(st, entity); if (!ins_into_idle_tree || !bfq_gt(entity->finish, st->vtime)) bfq_forget_entity(st, entity, is_in_service); else bfq_idle_insert(st, entity); return true; } /** * bfq_deactivate_entity - deactivate an entity representing a bfq_queue. * @entity: the entity to deactivate. * @ins_into_idle_tree: true if the entity can be put into the idle tree * @expiration: true if this function is being invoked in the expiration path * of the in-service queue */ static void bfq_deactivate_entity(struct bfq_entity *entity, bool ins_into_idle_tree, bool expiration) { struct bfq_sched_data *sd; struct bfq_entity *parent = NULL; for_each_entity_safe(entity, parent) { sd = entity->sched_data; if (!__bfq_deactivate_entity(entity, ins_into_idle_tree)) { /* * entity is not in any tree any more, so * this deactivation is a no-op, and there is * nothing to change for upper-level entities * (in case of expiration, this can never * happen). */ return; } if (sd->next_in_service == entity) /* * entity was the next_in_service entity, * then, since entity has just been * deactivated, a new one must be found. */ bfq_update_next_in_service(sd, NULL, expiration); if (sd->next_in_service || sd->in_service_entity) { /* * The parent entity is still active, because * either next_in_service or in_service_entity * is not NULL. So, no further upwards * deactivation must be performed. Yet, * next_in_service has changed. Then the * schedule does need to be updated upwards. * * NOTE If in_service_entity is not NULL, then * next_in_service may happen to be NULL, * although the parent entity is evidently * active. This happens if 1) the entity * pointed by in_service_entity is the only * active entity in the parent entity, and 2) * according to the definition of * next_in_service, the in_service_entity * cannot be considered as * next_in_service. See the comments on the * definition of next_in_service for details. */ break; } /* * If we get here, then the parent is no more * backlogged and we need to propagate the * deactivation upwards. Thus let the loop go on. */ /* * Also let parent be queued into the idle tree on * deactivation, to preserve service guarantees, and * assuming that who invoked this function does not * need parent entities too to be removed completely. */ ins_into_idle_tree = true; } /* * If the deactivation loop is fully executed, then there are * no more entities to touch and next loop is not executed at * all. Otherwise, requeue remaining entities if they are * about to stop receiving service, or reposition them if this * is not the case. */ entity = parent; for_each_entity(entity) { /* * Invoke __bfq_requeue_entity on entity, even if * already active, to requeue/reposition it in the * active tree (because sd->next_in_service has * changed) */ __bfq_requeue_entity(entity); sd = entity->sched_data; if (!bfq_update_next_in_service(sd, entity, expiration) && !expiration) /* * next_in_service unchanged or not causing * any change in entity->parent->sd, and no * requeueing needed for expiration: stop * here. */ break; } } /** * bfq_calc_vtime_jump - compute the value to which the vtime should jump, * if needed, to have at least one entity eligible. * @st: the service tree to act upon. * * Assumes that st is not empty. */ static u64 bfq_calc_vtime_jump(struct bfq_service_tree *st) { struct bfq_entity *root_entity = bfq_root_active_entity(&st->active); if (bfq_gt(root_entity->min_start, st->vtime)) return root_entity->min_start; return st->vtime; } static void bfq_update_vtime(struct bfq_service_tree *st, u64 new_value) { if (new_value > st->vtime) { st->vtime = new_value; bfq_forget_idle(st); } } /** * bfq_first_active_entity - find the eligible entity with * the smallest finish time * @st: the service tree to select from. * @vtime: the system virtual to use as a reference for eligibility * * This function searches the first schedulable entity, starting from the * root of the tree and going on the left every time on this side there is * a subtree with at least one eligible (start <= vtime) entity. The path on * the right is followed only if a) the left subtree contains no eligible * entities and b) no eligible entity has been found yet. */ static struct bfq_entity *bfq_first_active_entity(struct bfq_service_tree *st, u64 vtime) { struct bfq_entity *entry, *first = NULL; struct rb_node *node = st->active.rb_node; while (node) { entry = rb_entry(node, struct bfq_entity, rb_node); left: if (!bfq_gt(entry->start, vtime)) first = entry; if (node->rb_left) { entry = rb_entry(node->rb_left, struct bfq_entity, rb_node); if (!bfq_gt(entry->min_start, vtime)) { node = node->rb_left; goto left; } } if (first) break; node = node->rb_right; } return first; } /** * __bfq_lookup_next_entity - return the first eligible entity in @st. * @st: the service tree. * * If there is no in-service entity for the sched_data st belongs to, * then return the entity that will be set in service if: * 1) the parent entity this st belongs to is set in service; * 2) no entity belonging to such parent entity undergoes a state change * that would influence the timestamps of the entity (e.g., becomes idle, * becomes backlogged, changes its budget, ...). * * In this first case, update the virtual time in @st too (see the * comments on this update inside the function). * * In contrast, if there is an in-service entity, then return the * entity that would be set in service if not only the above * conditions, but also the next one held true: the currently * in-service entity, on expiration, * 1) gets a finish time equal to the current one, or * 2) is not eligible any more, or * 3) is idle. */ static struct bfq_entity * __bfq_lookup_next_entity(struct bfq_service_tree *st, bool in_service) { struct bfq_entity *entity; u64 new_vtime; if (RB_EMPTY_ROOT(&st->active)) return NULL; /* * Get the value of the system virtual time for which at * least one entity is eligible. */ new_vtime = bfq_calc_vtime_jump(st); /* * If there is no in-service entity for the sched_data this * active tree belongs to, then push the system virtual time * up to the value that guarantees that at least one entity is * eligible. If, instead, there is an in-service entity, then * do not make any such update, because there is already an * eligible entity, namely the in-service one (even if the * entity is not on st, because it was extracted when set in * service). */ if (!in_service) bfq_update_vtime(st, new_vtime); entity = bfq_first_active_entity(st, new_vtime); return entity; } /** * bfq_lookup_next_entity - return the first eligible entity in @sd. * @sd: the sched_data. * @expiration: true if we are on the expiration path of the in-service queue * * This function is invoked when there has been a change in the trees * for sd, and we need to know what is the new next entity to serve * after this change. */ static struct bfq_entity *bfq_lookup_next_entity(struct bfq_sched_data *sd, bool expiration) { struct bfq_service_tree *st = sd->service_tree; struct bfq_service_tree *idle_class_st = st + (BFQ_IOPRIO_CLASSES - 1); struct bfq_entity *entity = NULL; int class_idx = 0; /* * Choose from idle class, if needed to guarantee a minimum * bandwidth to this class (and if there is some active entity * in idle class). This should also mitigate * priority-inversion problems in case a low priority task is * holding file system resources. */ if (time_is_before_jiffies(sd->bfq_class_idle_last_service + BFQ_CL_IDLE_TIMEOUT)) { if (!RB_EMPTY_ROOT(&idle_class_st->active)) class_idx = BFQ_IOPRIO_CLASSES - 1; /* About to be served if backlogged, or not yet backlogged */ sd->bfq_class_idle_last_service = jiffies; } /* * Find the next entity to serve for the highest-priority * class, unless the idle class needs to be served. */ for (; class_idx < BFQ_IOPRIO_CLASSES; class_idx++) { /* * If expiration is true, then bfq_lookup_next_entity * is being invoked as a part of the expiration path * of the in-service queue. In this case, even if * sd->in_service_entity is not NULL, * sd->in_service_entity at this point is actually not * in service any more, and, if needed, has already * been properly queued or requeued into the right * tree. The reason why sd->in_service_entity is still * not NULL here, even if expiration is true, is that * sd->in_service_entity is reset as a last step in the * expiration path. So, if expiration is true, tell * __bfq_lookup_next_entity that there is no * sd->in_service_entity. */ entity = __bfq_lookup_next_entity(st + class_idx, sd->in_service_entity && !expiration); if (entity) break; } if (!entity) return NULL; return entity; } bool next_queue_may_preempt(struct bfq_data *bfqd) { struct bfq_sched_data *sd = &bfqd->root_group->sched_data; return sd->next_in_service != sd->in_service_entity; } /* * Get next queue for service. */ struct bfq_queue *bfq_get_next_queue(struct bfq_data *bfqd) { struct bfq_entity *entity = NULL; struct bfq_sched_data *sd; struct bfq_queue *bfqq; if (bfq_tot_busy_queues(bfqd) == 0) return NULL; /* * Traverse the path from the root to the leaf entity to * serve. Set in service all the entities visited along the * way. */ sd = &bfqd->root_group->sched_data; for (; sd ; sd = entity->my_sched_data) { /* * WARNING. We are about to set the in-service entity * to sd->next_in_service, i.e., to the (cached) value * returned by bfq_lookup_next_entity(sd) the last * time it was invoked, i.e., the last time when the * service order in sd changed as a consequence of the * activation or deactivation of an entity. In this * respect, if we execute bfq_lookup_next_entity(sd) * in this very moment, it may, although with low * probability, yield a different entity than that * pointed to by sd->next_in_service. This rare event * happens in case there was no CLASS_IDLE entity to * serve for sd when bfq_lookup_next_entity(sd) was * invoked for the last time, while there is now one * such entity. * * If the above event happens, then the scheduling of * such entity in CLASS_IDLE is postponed until the * service of the sd->next_in_service entity * finishes. In fact, when the latter is expired, * bfq_lookup_next_entity(sd) gets called again, * exactly to update sd->next_in_service. */ /* Make next_in_service entity become in_service_entity */ entity = sd->next_in_service; sd->in_service_entity = entity; /* * If entity is no longer a candidate for next * service, then it must be extracted from its active * tree, so as to make sure that it won't be * considered when computing next_in_service. See the * comments on the function * bfq_no_longer_next_in_service() for details. */ if (bfq_no_longer_next_in_service(entity)) bfq_active_extract(bfq_entity_service_tree(entity), entity); /* * Even if entity is not to be extracted according to * the above check, a descendant entity may get * extracted in one of the next iterations of this * loop. Such an event could cause a change in * next_in_service for the level of the descendant * entity, and thus possibly back to this level. * * However, we cannot perform the resulting needed * update of next_in_service for this level before the * end of the whole loop, because, to know which is * the correct next-to-serve candidate entity for each * level, we need first to find the leaf entity to set * in service. In fact, only after we know which is * the next-to-serve leaf entity, we can discover * whether the parent entity of the leaf entity * becomes the next-to-serve, and so on. */ } bfqq = bfq_entity_to_bfqq(entity); /* * We can finally update all next-to-serve entities along the * path from the leaf entity just set in service to the root. */ for_each_entity(entity) { struct bfq_sched_data *sd = entity->sched_data; if (!bfq_update_next_in_service(sd, NULL, false)) break; } return bfqq; } /* returns true if the in-service queue gets freed */ bool __bfq_bfqd_reset_in_service(struct bfq_data *bfqd) { struct bfq_queue *in_serv_bfqq = bfqd->in_service_queue; struct bfq_entity *in_serv_entity = &in_serv_bfqq->entity; struct bfq_entity *entity = in_serv_entity; bfq_clear_bfqq_wait_request(in_serv_bfqq); hrtimer_try_to_cancel(&bfqd->idle_slice_timer); bfqd->in_service_queue = NULL; /* * When this function is called, all in-service entities have * been properly deactivated or requeued, so we can safely * execute the final step: reset in_service_entity along the * path from entity to the root. */ for_each_entity(entity) entity->sched_data->in_service_entity = NULL; /* * in_serv_entity is no longer in service, so, if it is in no * service tree either, then release the service reference to * the queue it represents (taken with bfq_get_entity). */ if (!in_serv_entity->on_st_or_in_serv) { /* * If no process is referencing in_serv_bfqq any * longer, then the service reference may be the only * reference to the queue. If this is the case, then * bfqq gets freed here. */ int ref = in_serv_bfqq->ref; bfq_put_queue(in_serv_bfqq); if (ref == 1) return true; } return false; } void bfq_deactivate_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq, bool ins_into_idle_tree, bool expiration) { struct bfq_entity *entity = &bfqq->entity; bfq_deactivate_entity(entity, ins_into_idle_tree, expiration); } void bfq_activate_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq) { struct bfq_entity *entity = &bfqq->entity; bfq_activate_requeue_entity(entity, bfq_bfqq_non_blocking_wait_rq(bfqq), false, false); bfq_clear_bfqq_non_blocking_wait_rq(bfqq); } void bfq_requeue_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq, bool expiration) { struct bfq_entity *entity = &bfqq->entity; bfq_activate_requeue_entity(entity, false, bfqq == bfqd->in_service_queue, expiration); } /* * Called when the bfqq no longer has requests pending, remove it from * the service tree. As a special case, it can be invoked during an * expiration. */ void bfq_del_bfqq_busy(struct bfq_data *bfqd, struct bfq_queue *bfqq, bool expiration) { bfq_log_bfqq(bfqd, bfqq, "del from busy"); bfq_clear_bfqq_busy(bfqq); bfqd->busy_queues[bfqq->ioprio_class - 1]--; if (bfqq->wr_coeff > 1) bfqd->wr_busy_queues--; bfqg_stats_update_dequeue(bfqq_group(bfqq)); bfq_deactivate_bfqq(bfqd, bfqq, true, expiration); if (!bfqq->dispatched) bfq_weights_tree_remove(bfqd, bfqq); } /* * Called when an inactive queue receives a new request. */ void bfq_add_bfqq_busy(struct bfq_data *bfqd, struct bfq_queue *bfqq) { bfq_log_bfqq(bfqd, bfqq, "add to busy"); bfq_activate_bfqq(bfqd, bfqq); bfq_mark_bfqq_busy(bfqq); bfqd->busy_queues[bfqq->ioprio_class - 1]++; if (!bfqq->dispatched) if (bfqq->wr_coeff == 1) bfq_weights_tree_add(bfqd, bfqq, &bfqd->queue_weights_tree); if (bfqq->wr_coeff > 1) bfqd->wr_busy_queues++; }
{ "pile_set_name": "Github" }
/* Copyright 2017 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 printers import ( "fmt" "io" "reflect" "strings" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) // NamePrinter is an implementation of ResourcePrinter which outputs "resource/name" pair of an object. type NamePrinter struct { // ShortOutput indicates whether an operation should be // printed along side the "resource/name" pair for an object. ShortOutput bool // Operation describes the name of the action that // took place on an object, to be included in the // finalized "successful" message. Operation string } // PrintObj is an implementation of ResourcePrinter.PrintObj which decodes the object // and print "resource/name" pair. If the object is a List, print all items in it. func (p *NamePrinter) PrintObj(obj runtime.Object, w io.Writer) error { switch castObj := obj.(type) { case *metav1.WatchEvent: obj = castObj.Object.Object } // we use reflect.Indirect here in order to obtain the actual value from a pointer. // using reflect.Indirect indiscriminately is valid here, as all runtime.Objects are supposed to be pointers. // we need an actual value in order to retrieve the package path for an object. if InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj)).Type().PkgPath()) { return fmt.Errorf(InternalObjectPrinterErr) } if meta.IsListType(obj) { // we allow unstructured lists for now because they always contain the GVK information. We should chase down // callers and stop them from passing unflattened lists // TODO chase the caller that is setting this and remove it. if _, ok := obj.(*unstructured.UnstructuredList); !ok { return fmt.Errorf("list types are not supported by name printing: %T", obj) } items, err := meta.ExtractList(obj) if err != nil { return err } for _, obj := range items { if err := p.PrintObj(obj, w); err != nil { return err } } return nil } if obj.GetObjectKind().GroupVersionKind().Empty() { return fmt.Errorf("missing apiVersion or kind; try GetObjectKind().SetGroupVersionKind() if you know the type") } name := "<unknown>" if acc, err := meta.Accessor(obj); err == nil { if n := acc.GetName(); len(n) > 0 { name = n } } return printObj(w, name, p.Operation, p.ShortOutput, GetObjectGroupKind(obj)) } func GetObjectGroupKind(obj runtime.Object) schema.GroupKind { if obj == nil { return schema.GroupKind{Kind: "<unknown>"} } groupVersionKind := obj.GetObjectKind().GroupVersionKind() if len(groupVersionKind.Kind) > 0 { return groupVersionKind.GroupKind() } if uns, ok := obj.(*unstructured.Unstructured); ok { if len(uns.GroupVersionKind().Kind) > 0 { return uns.GroupVersionKind().GroupKind() } } return schema.GroupKind{Kind: "<unknown>"} } func printObj(w io.Writer, name string, operation string, shortOutput bool, groupKind schema.GroupKind) error { if len(groupKind.Kind) == 0 { return fmt.Errorf("missing kind for resource with name %v", name) } if len(operation) > 0 { operation = " " + operation } if shortOutput { operation = "" } if len(groupKind.Group) == 0 { fmt.Fprintf(w, "%s/%s%s\n", strings.ToLower(groupKind.Kind), name, operation) return nil } fmt.Fprintf(w, "%s.%s/%s%s\n", strings.ToLower(groupKind.Kind), groupKind.Group, name, operation) return nil }
{ "pile_set_name": "Github" }
% Copyright 2011 Zdenek Kalal % % This file is part of TLD. % % TLD 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. % % TLD 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 TLD. If not, see <http://www.gnu.org/licenses/>. function idx = pseudorandom_indexes(N,k) start = randi(k,1,1); idx = start:k:N;
{ "pile_set_name": "Github" }
import { Splitter } from '../../src/splitter/splitter'; let splitObj: Splitter = new Splitter({ height: '250px', paneSettings: [ { size: '30%', min: '20%', max: '60%' }, { size: '40%', min: '20%', max: '90%' }, { size: '30%', min: '20%', max: '70%' } ], width: '100%' }); splitObj.appendTo('#splitter');
{ "pile_set_name": "Github" }
$(function() { var sourceView = null; /** * if we are in console mode, show the console. */ if (CONSOLE_MODE && EVALEX) { openShell(null, $('div.console div.inner').empty(), 0); } $('div.traceback div.frame').each(function() { var target = $('pre', this) .click(function() { sourceButton.click(); }), consoleNode = null, source = null, frameID = this.id.substring(6); /** * Add an interactive console to the frames */ if (EVALEX) $('<img src="?__debugger__=yes&cmd=resource&f=console.png">') .attr('title', 'Open an interactive python shell in this frame') .click(function() { consoleNode = openShell(consoleNode, target, frameID); return false; }) .prependTo(target); /** * Show sourcecode */ var sourceButton = $('<img src="?__debugger__=yes&cmd=resource&f=source.png">') .attr('title', 'Display the sourcecode for this frame') .click(function() { if (!sourceView) $('h2', sourceView = $('<div class="box"><h2>View Source</h2><div class="sourceview">' + '<table></table></div>') .insertBefore('div.explanation')) .css('cursor', 'pointer') .click(function() { sourceView.slideUp('fast'); }); $.get(document.location.pathname, {__debugger__: 'yes', cmd: 'source', frm: frameID, s: SECRET}, function(data) { $('table', sourceView) .replaceWith(data); if (!sourceView.is(':visible')) sourceView.slideDown('fast', function() { focusSourceBlock(); }); else focusSourceBlock(); }); return false; }) .prependTo(target); }); /** * toggle traceback types on click. */ $('h2.traceback').click(function() { $(this).next().slideToggle('fast'); $('div.plain').slideToggle('fast'); }).css('cursor', 'pointer'); $('div.plain').hide(); /** * Add extra info (this is here so that only users with JavaScript * enabled see it.) */ $('span.nojavascript') .removeClass('nojavascript') .html('<p>To switch between the interactive traceback and the plaintext ' + 'one, you can click on the "Traceback" headline. From the text ' + 'traceback you can also create a paste of it. ' + (!EVALEX ? '' : 'For code execution mouse-over the frame you want to debug and ' + 'click on the console icon on the right side.' + '<p>You can execute arbitrary Python code in the stack frames and ' + 'there are some extra helpers available for introspection:' + '<ul><li><code>dump()</code> shows all variables in the frame' + '<li><code>dump(obj)</code> dumps all that\'s known about the object</ul>')); /** * Add the pastebin feature */ $('div.plain form') .submit(function() { var label = $('input[type="submit"]', this); var old_val = label.val(); label.val('submitting...'); $.ajax({ dataType: 'json', url: document.location.pathname, data: {__debugger__: 'yes', tb: TRACEBACK, cmd: 'paste', s: SECRET}, success: function(data) { $('div.plain span.pastemessage') .removeClass('pastemessage') .text('Paste created: ') .append($('<a>#' + data.id + '</a>').attr('href', data.url)); }, error: function() { alert('Error: Could not submit paste. No network connection?'); label.val(old_val); } }); return false; }); // if we have javascript we submit by ajax anyways, so no need for the // not scaling textarea. var plainTraceback = $('div.plain textarea'); plainTraceback.replaceWith($('<pre>').text(plainTraceback.text())); }); /** * Helper function for shell initialization */ function openShell(consoleNode, target, frameID) { if (consoleNode) return consoleNode.slideToggle('fast'); consoleNode = $('<pre class="console">') .appendTo(target.parent()) .hide() var historyPos = 0, history = ['']; var output = $('<div class="output">[console ready]</div>') .appendTo(consoleNode); var form = $('<form>&gt;&gt;&gt; </form>') .submit(function() { var cmd = command.val(); $.get(document.location.pathname, { __debugger__: 'yes', cmd: cmd, frm: frameID, s: SECRET}, function(data) { var tmp = $('<div>').html(data); $('span.extended', tmp).each(function() { var hidden = $(this).wrap('<span>').hide(); hidden .parent() .append($('<a href="#" class="toggle">&nbsp;&nbsp;</a>') .click(function() { hidden.toggle(); $(this).toggleClass('open') return false; })); }); output.append(tmp); command.focus(); consoleNode.scrollTop(command.position().top); var old = history.pop(); history.push(cmd); if (typeof old != 'undefined') history.push(old); historyPos = history.length - 1; }); command.val(''); return false; }). appendTo(consoleNode); var command = $('<input type="text">') .appendTo(form) .keydown(function(e) { if (e.charCode == 100 && e.ctrlKey) { output.text('--- screen cleared ---'); return false; } else if (e.charCode == 0 && (e.keyCode == 38 || e.keyCode == 40)) { if (e.keyCode == 38 && historyPos > 0) historyPos--; else if (e.keyCode == 40 && historyPos < history.length) historyPos++; command.val(history[historyPos]); return false; } }); return consoleNode.slideDown('fast', function() { command.focus(); }); } /** * Focus the current block in the source view. */ function focusSourceBlock() { var tmp, line = $('table.source tr.current'); for (var i = 0; i < 7; i++) { tmp = line.prev(); if (!(tmp && tmp.is('.in-frame'))) break line = tmp; } var container = $('div.sourceview'); container.scrollTop(line.offset().top); }
{ "pile_set_name": "Github" }
Content-language: cs Content-type: text/html; charset=UTF-8 Body:----------cs-- Pokud si myslíte, že toto je chyba serveru, kontaktujte, prosím, <a href="mailto:<!--#echo encoding="url" var="SERVER_ADMIN" -->">webmastera</a>. ----------cs-- Content-language: de Content-type: text/html; charset=UTF-8 Body:----------de-- Sofern Sie dies f&uuml;r eine Fehlfunktion des Servers halten, informieren Sie bitte den <a href="mailto:<!--#echo encoding="url" var="SERVER_ADMIN" -->">Webmaster</a> hier&uuml;ber. ----------de-- Content-language: en Content-type: text/html; charset=UTF-8 Body:----------en-- If you think this is a server error, please contact the <a href="mailto:<!--#echo encoding="url" var="SERVER_ADMIN" -->">webmaster</a>. ----------en-- Content-language: es Content-type: text/html Body:----------es-- Si usted cree que esto es un error del servidor, por favor comun&iacute;queselo al <a href="mailto:<!--#echo encoding="none" var="SERVER_ADMIN" -->">administrador del portal</a>. ----------es-- Content-language: fr Content-type: text/html; charset=UTF-8 Body:----------fr-- Si vous pensez qu'il s'agit d'une erreur du serveur, veuillez contacter le <a href="mailto:<!--#echo encoding="url" var="SERVER_ADMIN" -->">webmestre</a>. ----------fr-- Content-language: ga Content-type: text/html; charset=UTF-8 Body:----------ga-- M&aacute; cheapann t&uacute; gur earr&aacute;id fhreastala&iacute; &iacute; seo, t&eacute;igh i dteagmh&aacute;il leis an <a href="mailto:<!--#echo encoding="url" var="SERVER_ADMIN" -->"> sti&uacute;rth&oacute;ir gr&eacute;as&aacute;in</a>, le do thoil. ----------ga-- Content-language: it Content-type: text/html; charset=UTF-8 Body:----------it-- Se pensi che questo sia un errore del server, per favore contatta il <a href="mailto:<!--#echo encoding="url" var="SERVER_ADMIN" -->">webmaster</a>. ----------it-- Content-language: ja Content-type: text/html; charset=UTF-8 Body:----------ja-- サーバーの障害と思われる場合は、<a href="mailto:<!--#echo encoding="none" var="SERVER_ADMIN" -->" >ウェブ管理者</a>までご連絡ください。 ----------ja-- Content-language: ko Content-type: text/html; charset=UTF-8 Body:----------ko-- 만약 이것이 서버 오류라고 생각되면, <a href="mailto:<!--#echo encoding="none" var="SERVER_ADMIN" -->">웹 관리자</a>에게 연락하시기 바랍니다. ----------ko-- Content-language: nl Content-type: text/html; charset=UTF-8 Body:----------nl-- Indien u van oordeel bent dat deze server in fout is, gelieve de <a href="mailto:<!--#echo encoding="url" var="SERVER_ADMIN" -->">webmaster</a> te contacteren. ----------nl-- Content-language: nb Content-type: text/html; charset=UTF-8 Body:----------nb-- Om du tror dette skyldes en serverfeil, venligst kontakt <a href="mailto:<!--#echo encoding="url" var="SERVER_ADMIN" -->">webansvarlig</a>. ----------nb-- Content-language: pl Content-type: text/html; charset=UTF-8 Body:----------pl-- Je&#347;li my&#347;lisz, &#380;e jest to b&#322;&#261;d tego serwera, skontaktuj si&#281; z <a href="mailto:<!--#echo encoding="url" var="SERVER_ADMIN" -->">administratorem</a>. ----------pl-- Content-language: pt-br Content-type: text/html; charset=UTF-8 Body:-------pt-br-- Se voc&ecirc; acredita ter encontrado um problema no servidor, por favor entre em contato com o <a href="mailto:<!--#echo encoding="url" var="SERVER_ADMIN" -->">webmaster</a>. -------pt-br-- Content-language: ro Content-type: text/html; charset=UTF-8 Body:----------ro-- Va rugam sa il contactati pe <a href="mailto:<!--#echo encoding="url" var="SERVER_ADMIN" -->">webmaster</a> in cazul in care credeti ca aceasta este o eroare a serverului. ----------ro-- Content-language: sr Content-type: text/html; charset=UTF-8 Body:----------sr-- Ако мислите да је ово грешка сервера, молимо обавестите <a href="mailto:<!--#echo encoding="url" var="SERVER_ADMIN" -->">вебмастера</a>. ----------sr-- Content-language: sv Content-type: text/html; charset=UTF-8 Body:----------sv-- Om du tror att detta beror p&aring; ett serverfel, v&auml;nligen kontakta <a href="mailto:<!--#echo encoding="url" var="SERVER_ADMIN" -->">webbansvarig</a>. ----------sv-- Content-language: tr Content-type: text/html; charset=UTF-8 Body:----------tr-- Bunun bir sunucu hatas&#305; oldu&#287;unu dü&#351;ünüyorsan&#305;z, lütfen <a href="mailto:<!--#echo encoding="url" var="SERVER_ADMIN" -->">site yöneticisi</a> ile ileti&#351;ime geçin. ----------tr--
{ "pile_set_name": "Github" }
<?php declare(strict_types = 1); /* * Copyright 2012-2019 Damien Seguy – Exakat SAS <contact(at)exakat.io> * This file is part of Exakat. * * Exakat is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Exakat is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Exakat. If not, see <http://www.gnu.org/licenses/>. * * The latest code can be found at <http://exakat.io/>. * */ namespace Exakat\Query\DSL; use Exakat\Analyzer\Analyzer; class NoDelimiterIs extends DSL { public function run(): Command { assert(func_num_args() <= 2, 'Too many arguments for ' . __METHOD__); switch (func_num_args()) { case 2: list($code, $caseSensitive) = func_get_args(); break; case 1: list($code) = func_get_args(); $caseSensitive = Analyzer::CASE_INSENSITIVE; break; default: assert(false, 'No enought arguments for ' . __METHOD__); } $return = new Command('has("noDelimiter")'); $propertyIs = $this->dslfactory->factory('propertyIs'); $code = makeArray($code); return $return->add($propertyIs->run('noDelimiter', $code, $caseSensitive)); } } ?>
{ "pile_set_name": "Github" }
/* * QLogic iSCSI HBA Driver * Copyright (c) 2003-2013 QLogic Corporation * * See LICENSE.qla4xxx for copyright and licensing details. */ /* * * qla4xxx_lookup_ddb_by_fw_index * This routine locates a device handle given the firmware device * database index. If device doesn't exist, returns NULL. * * Input: * ha - Pointer to host adapter structure. * fw_ddb_index - Firmware's device database index * * Returns: * Pointer to the corresponding internal device database structure */ static inline struct ddb_entry * qla4xxx_lookup_ddb_by_fw_index(struct scsi_qla_host *ha, uint32_t fw_ddb_index) { struct ddb_entry *ddb_entry = NULL; if ((fw_ddb_index < MAX_DDB_ENTRIES) && (ha->fw_ddb_index_map[fw_ddb_index] != (struct ddb_entry *) INVALID_ENTRY)) { ddb_entry = ha->fw_ddb_index_map[fw_ddb_index]; } DEBUG3(printk("scsi%d: %s: ddb [%d], ddb_entry = %p\n", ha->host_no, __func__, fw_ddb_index, ddb_entry)); return ddb_entry; } static inline void __qla4xxx_enable_intrs(struct scsi_qla_host *ha) { if (is_qla4022(ha) | is_qla4032(ha)) { writel(set_rmask(IMR_SCSI_INTR_ENABLE), &ha->reg->u1.isp4022.intr_mask); readl(&ha->reg->u1.isp4022.intr_mask); } else { writel(set_rmask(CSR_SCSI_INTR_ENABLE), &ha->reg->ctrl_status); readl(&ha->reg->ctrl_status); } set_bit(AF_INTERRUPTS_ON, &ha->flags); } static inline void __qla4xxx_disable_intrs(struct scsi_qla_host *ha) { if (is_qla4022(ha) | is_qla4032(ha)) { writel(clr_rmask(IMR_SCSI_INTR_ENABLE), &ha->reg->u1.isp4022.intr_mask); readl(&ha->reg->u1.isp4022.intr_mask); } else { writel(clr_rmask(CSR_SCSI_INTR_ENABLE), &ha->reg->ctrl_status); readl(&ha->reg->ctrl_status); } clear_bit(AF_INTERRUPTS_ON, &ha->flags); } static inline void qla4xxx_enable_intrs(struct scsi_qla_host *ha) { unsigned long flags; spin_lock_irqsave(&ha->hardware_lock, flags); __qla4xxx_enable_intrs(ha); spin_unlock_irqrestore(&ha->hardware_lock, flags); } static inline void qla4xxx_disable_intrs(struct scsi_qla_host *ha) { unsigned long flags; spin_lock_irqsave(&ha->hardware_lock, flags); __qla4xxx_disable_intrs(ha); spin_unlock_irqrestore(&ha->hardware_lock, flags); } static inline int qla4xxx_get_chap_type(struct ql4_chap_table *chap_entry) { int type; if (chap_entry->flags & BIT_7) type = LOCAL_CHAP; else type = BIDI_CHAP; return type; }
{ "pile_set_name": "Github" }
cs.utexas.edu!geraldo.cc.utexas.edu!portal.austin.ibm.com!awdprime.austin.ibm.com!karner Subject: Re: Islamic marriage? From: [email protected] (F. Karner) <[email protected]> <[email protected]> Organization: IBM Advanced Workstation Division Originator: [email protected] Lines: 50 In article <[email protected]>, [email protected] (Masud Khan) writes: > In article <[email protected]> [email protected] (F. Karner) writes: > > > >Okay. So you want me to name names? There are obviously no official > >records of these pseudo-marriages because they are performed for > >convenience. What happens typically is that the woman is willing to move > >in with her lover without any scruples or legal contracts to speak of. > >The man is merely utilizing a loophole by entering into a temporary > >religious "marriage" contract in order to have sex. Nobody complains, > >nobody cares, nobody needs to know. > > > >Perhaps you should alert your imam. It could be that this practice is > >far more widespread than you may think. Or maybe it takes 4 muslim men > >to witness the penetration to decide if the practice exists! > >-- > > > > Again you astound me with the level of ignorance you display, Muslims > are NOT allowed to enter temporary marriages, got that? There is > no evidence for it it an outlawed practise so get your facts > straight buddy. Give me references for it or just tell everyone you > were lying. It is not a widespread as you may think (fantasise) in > fact contrary to your fantasies it is not practised at all amongst > Muslims. First of all, I'm not your buddy! Second, read what I wrote. I'm not talking about what muslims are ALLOWED to do, merely what *SOME* practice. They consider themselves as muslim as you, so don't retort with the old and tired "they MUST NOT BE TRUE MUSLIMS" bullshit. If I gave you the names what will you do with this information? Is a fatwa going to be leashed out against the perpetrators? Do you honestly think that someone who did it would voluntarily come forward and confess? With the kind of extremism shown by your co-religionaries? Fat chance. At any rate, there can be no conclusive "proof" by the very nature of the act. Perhaps people that indulge in this practice agree with you in theory, but hope that Allah will forgive them in the end. I think it's rather arrogant of you to pretend to speak for all muslims in this regard. Also, kind of silly. Are you insinuating that because the Koranic law forbids it, there are no criminals in muslim countries? This is as far as I care to go on this subject. The weakness of your arguments are for all netters to see. Over and out... -- DISCLAIMER: The opinions expressed in this posting are mine solely and do not represent my employer in any way. F. A. Karner AIX Technical Support | [email protected]
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <refentry xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svg="http://www.w3.org/2000/svg" xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:db="http://docbook.org/ns/docbook" xmlns:scilab="http://www.scilab.org" xml:lang="ja" xml:id="uigetdir"> <refnamediv> <refname>uigetdir</refname> <refpurpose>ディレクトリを選択するダイアログ</refpurpose> </refnamediv> <refsynopsisdiv> <title>呼び出し手順</title> <synopsis> directory = uigetdir() directory = uigetdir(start_path) directory = uigetdir(start_path, title) </synopsis> </refsynopsisdiv> <refsection> <title>引数</title> <variablelist> <varlistentry> <term>start_path</term> <listitem> <para> 選択用の初期ディレクトリを指定する文字列. デフォルトでuigetdirはカレントのワーキングディレクトリを 使用します. </para> </listitem> </varlistentry> <varlistentry> <term>title</term> <listitem> <para>uigetdirウインドウの表題.</para> </listitem> </varlistentry> <varlistentry> <term>directory</term> <listitem> <para> ユーザが"Ok"を実行した場合はユーザが選択した ディレクトリ, ユーザがキャンセルした場合は " "文字列. </para> </listitem> </varlistentry> </variablelist> </refsection> <refsection> <title>説明</title> <para> ディレクトリを選択するダイアログウインドウを作成します. </para> </refsection> <refsection> <title>例</title> <programlisting role="example"><![CDATA[ uigetdir() uigetdir("SCI/modules/") uigetdir("SCI/modules/", "Choose a directory") ]]></programlisting> </refsection> <refsection role="see also"> <title>参照</title> <simplelist type="inline"> <member> <link linkend="uigetfile">uigetfile</link> </member> <member> <link linkend="uiputfile">uiputfile</link> </member> </simplelist> </refsection> </refentry>
{ "pile_set_name": "Github" }
describe "Array#clone", -> xit "copies frozen status from the original", -> # a = [1, 2, 3, 4] # b = [1, 2, 3, 4] # a.freeze # aa = a.clone # bb = b.clone # aa.frozen?.should == true # bb.frozen?.should == false it "copies singleton methods", -> # a = [1, 2, 3, 4] # b = [1, 2, 3, 4] # def a.a_singleton_method; end # aa = a.clone # bb = b.clone # a.respond_to?(:a_singleton_method).should be_true # b.respond_to?(:a_singleton_method).should be_false # aa.respond_to?(:a_singleton_method).should be_true # bb.respond_to?(:a_singleton_method).should be_false xit "returns an Array or a subclass instance", -> # [].send(@method).should be_kind_of(Array) # ArraySpecs.MyArray[1, 2].send(@method).should be_kind_of(ArraySpecs.MyArray) it "produces a shallow copy where the references are directly copied", -> a = R([new Object(), new Object()]) b = a.clone() expect( b.first() is a.first() ).toEqual true expect( b.last() is a.last() ).toEqual true it "creates a new array containing all elements or the original", -> a = R([1, 2, 3, 4]) b = a.clone() expect( b ).toEqual a # b.__id__.should_not == a.__id__ xit "copies taint status from the original", -> # a = [1, 2, 3, 4] # b = [1, 2, 3, 4] # a.taint # aa = a.send @method # bb = b.send @method # aa.tainted?.should == true # bb.tainted?.should == false # ruby_version_is '1.9' do xit "copies untrusted status from the original", -> # a = [1, 2, 3, 4] # b = [1, 2, 3, 4] # a.untrust # aa = a.send @method # bb = b.send @method # aa.untrusted?.should == true # bb.untrusted?.should == false
{ "pile_set_name": "Github" }
{ "name" : "websocket-client", "version" : "1.0.0", "description" : "An HTML5 Web Sockets client", "author" : "Peter Griess <[email protected]>", "engines" : { "node" : ">=0.1.98" }, "repositories" : [ { "type" : "git", "url" : "http://github.com/pgriess/node-websocket-client.git" } ], "licenses" : [ { "type" : "BSD", "url" : "http://github.com/pgriess/node-websocket-client/blob/master/LICENSE" } ], "main" : "./lib/websocket" }
{ "pile_set_name": "Github" }
<?php /** * ♔ TestLink Open Source Project - http://testlink.sourceforge.net/ * This script is distributed under the GNU General Public License 2 or later. * * Localization: English (en_GB) texts - default development localization (World-wide English) * * * The file contains global variables with html text. These variables are used as * HELP or DESCRIPTION. To avoid override of other globals we are using "Test Link String" * prefix '$TLS_hlp_' or '$TLS_txt_'. This must be a reserved prefix. * * Contributors howto: * Add your localization to TestLink tracker as attachment to update the next release * for your language. * * No revision is stored for the the file - see CVS history * * * @package TestLink * @author Martin Havlat * @copyright 2003-2009, TestLink community * @version CVS: $Id: description.php,v 1.2 2010/06/24 17:25:53 asimon83 Exp $ * @link http://www.teamst.org/index.php * * @internal Revisions: * 20100409 - eloff - BUGID 3050 - Update execution help text **/ // printFilter.html $TLS_hlp_generateDocOptions = "<h2>Opties voor een gegenereerd document</h2> <p>In deze tabel kan de gebruiker testcases filteren voordat ze worden bekeken. Geselecteerde (aangevinkte) gegevens zullen worden getoond. Om de voorgestelde gegevens te wijzigen, , vink aan of uit, klikt u op Filter, en selecteer het gewenste data niveau van de boom.</p> <p><b>Document Hoofding:</b> Gebruikers kunnen informatie in de hoofding filteren. Document hoofding informatie omvat: inleiding, bereik, referenties, testmethodologie en test beperkingen.</p> <p><b>Testcase Body:</b> Gebruikers kunnen testcase body informatie filteren. Testcase Body informatie bestaat uit: samenvatting, stappen, verwachte resultaten en sleutelwoorden </p> <p><b>Testcase samenvatting:</b> Gebruikers kunnen testcase samenvattingen filteren van de testcase titel, ze kunnen echter geen informatie uit de testcase samenvatting testcase body. Testcase samenvatting is slechts gedeeltelijk gescheiden van testcase body ter ondersteuning van het bekijken van de titels met een korte samenvatting en het ontbreken van stappen, verwachte resultaten en trefwoorden. Als een gebruiker besluit om een testcase body te bekijken , zal de tescase samenvatting altijd worden opgenomen. </p> <p><b>Inhoudsopgave:</b> TestLink voegt een overzicht toe van alle geselecteerde titels met interne hyperlinks</p> <p><b>Uitvoerformaat:</b> Er zijn twee mogelijkheden: HTML en MS Word. Browser roept MS Word component aan in het tweede geval.</p>"; // testPlan.html $TLS_hlp_testPlan = "<h2>Testplan</h2> <h3>Algemeen</h3> <p>Een testplan is een systematische aanpak voor het testen van een systeem zoals software. U kunt het testen van de activiteit organiseren met bepaalde builds van het product in de tijd en resultaten traceren.</p> <h3>Tests Uitvoeren</h3> <p>Dit gedeelte is waar de gebruikers testcases kunnen uitvoeren (testresultaten schrijven) en een testcase suite van het testplan afdrukken. Deze sectie is waar gebruikers de resultaten kunnen bijhouden van het uitvoeren van een testcase. </p> <h2>Testplan beheer</h2> <p>Deze sectie, die alleen toegankelijk is voor leiders, stelt gebruikers in staat om testplannen te beheren. Administratie van testplannen omvat het maken/bewerken/verwijderen van de plannen, toevoegen/bewerken/verwijderen/updaten van testcases in de plannen, builds creëren evenals bepalen wie welke plannen kan zien.<br /> Gebruikers met leider permissies kunnen ook de prioriteit/risico en de eigendom van testcase suites (categorieën) en test mijlpalen maken.</p> <p>Opmerking: Het is mogelijk dat gebruikers geen dropdown met testplannen kunnen zien. In deze situatie zullen alle links (behalve deze geactiveerd door een leider) losgekoppeld zijn. Als u zich in deze situatie bent moet u contact opnemen met een leider of administrator om u de juiste rechten voor het testplan toe te kennen or een testplan voor u aan te maken.</p>"; // custom_fields.html $TLS_hlp_customFields = "<h2>Gebruikersvelden</h2> <p>Hier volgen enkele feiten over de implementatie van de gebruikersvelden: </p> <ul> <li>Gebruikersvelden worden gedefinieerd het hele systeem.</li> <li>Gebruikersvelden zijn gekoppeld aan een type element (Testsuite, Testcase)</li> <li>Gebruikersvelden kunnen worden gekoppeld aan meerdere testprojecten.</li> <li>De volgorde van de weergave van gebruikersvelden kunnen verschillen per testproject.</li> <li>Gebruikersvelden kunnen inactief worden gezet voor een specifiek testproject.</li> <li>Het aantal gebruikersvelden is onbeperkt.</li> <ul> <p>De definitie van een gebruikersveld bevat de volgende logische attributen:</p> <ul> <li>Gebruikersveld naam</li> <li>Bijschrift naam van de variabele (bijvoorbeeld: Dit is de waarde die geleverd wordt aan lang_get () API, of zo weergegeven wordt als deze niet wordt gevonden in een taalbestand).</li> <li>Type gebruikersveld (string, numeric, float, enum, e-mail)</li> <li>Het bepalen mogelijke waarden (bijvoorbeeld: ROOD|GEEL|BLAUW), die van toepassing zijn in een lijst en combo types.<br/> <i>Gebruik het pijp ('|') karakter om mogelijke waarden voor een opsomming te scheiden. Een mogelijke waarde kan een lege tekenreeks zijn. </i> </li> <li>Standaard waarde: NOG NIET GEIMPLEMENTEERD</li> <li>Minimum/maximum lengte voor de gebruikersveld waarde (gebruik 0 om uit te schakelen). (NOG NIET GEIMPLEMENTEERD)</li> <li>Reguliere expressie te gebruiken voor het valideren van input van de gebruiker (<a href=\"http://au.php.net/manual/en/function.ereg.php\">ereg()</a> syntaxis). <b>(NOG NIET GEIMPLEMENTEERD)</b></li> <li>Alle gebruikersvelden worden momenteel opgeslagen in een veld van het type VARCHAR (255) in de database.</li> <li>Toon in testspecificatie.</li> <li>Aanpassen bij testspecificatie. De gebruiker kan tijdens het testcase specificatie ontwerp de waarde veranderen</li> <li>Toon bij testuitvoering. </li> <li>Aanpassen bij testuitvoering. De gebruiker kan tijdens testcase uitvoering de waarde veranderen</li> <li>Toon op testplan ontwerp.</li> <li>Aanpassen bij testplan ontwerp. De gebruiker kan de waarde veranderen tijdens het testplan ontwerp (testgevallen aan testplan toevoegen)</li> <li>Beschikbaar voor. De gebruiker kan kiezen om wat voor soort punt het veld gaat.</li> <ul> "; // execMain.html $TLS_hlp_executeMain = "<h2>Testcases uitvoeren</h2> <p>Hiermee kunnen gebruikers testcases 'uitvoeren'. Uitvoeren zelf is louter het toewijzen van resultaat aan een testcase (OK, gefaald, geblokkeerd) in een geselecteerde build. </p> <p>De toegang tot een bug tracking systeem kan worden geconfigureerd. De gebruiker kan dan direct nieuwe bugs toevoegen en door bestaande bladeren. Zie installatiehandleiding voor meer informatie.</p> "; //bug_add.html $TLS_hlp_btsIntegration = "<h2>Bugs toevoegen aan een testcase </h2> <p><i>(alleen als dit geconfigureerd is)</i> TestLink heeft een zeer eenvoudige integratie met Bug Tracking Systems (BTS), zonder te een verzoek om een bug aan te maken te versturen aan BTS, noch het terugkrijgen bug id. De integratie wordt gedaan met behulp van links naar pagina's op BTS, die de volgende functies oproepen: <ul> <li>Nieuwe bug toevoegen.</li> <li>Toon bestaande bug info.</li> <ul> </p>  <h3> Proces om een bug toe te voegen </h3> </p>    <ul>    <li>Stap 1: Gebruik de link naar BTS openen naar een nieuwe bug in te voegen.</li>    <li>Stap 2: Noteer de BUGID toegewezen door BTS</li>    <li>Stap 3: Schrijf BUGID in het invoerveld</li>    <li>Stap 4: Gebruik bug  toevoegen knop</li>    <ul>  Na het sluiten van de bug toevoegen pagina vindt u de relevante bug gegevens op de tests uitvoeren pagina te zien. </p> "; // execFilter.html $TLS_hlp_executeFilter = "<h2>Instellingen</h2> <p>In instellingen kunt u het testplan, build en platform (indien aanwezig) om uit te voeren selecteren </p> <h3>Testplan</h3> <p>U kunt het gewenste testplan kiezen. Volgens de gekozen testplan zullen de geschikte builds worden getoond. Na het kiezen van een testplan zullen filters gereset worden.</p> <h3>Platform</h3> <p>Als de functie platformen wordt gebruikt, moet u het juiste platform te kiezen om een test uit te voeren.</p> <h3>Uit te voeren build</h3> <p>U kunt de build kiezen waarvoore u de testcases wukt uitvoeren.</p> <h2>Filters</h2> <p>Filters bieden de mogelijkheid de set van de getoonde testcases verder te beinvloeden voor ze uit te voeren. U kunt de set van getoonde testcases verkleinen door filters op te geven en op de \"Apply\" knop te klikken.</p> <p>Met geavanceerde filters kunt u een reeks waarden opgeven voor de filters door CTRL-klik te gebruiken in de multi-select listbox.</p> <h3>Trefwoord filter</h3> <p>U kunt testcases filteren op de trefwoorden die eraan zijn toegewezen. Je kan meerdere trefwoorden kiezen " . "met CTRL-klik. Als u meer dan één trefwoord koos kun je ". "beslissen of alleen testcases worden getoond waaraan alle gekozen trefwoorden zijn toegewezen". "(Radiobutton \"en\") of ten minste één van de gekozen trefwoorden (radioknop \"Of\"). </p> <h3>Prioriteitsfilter</h3> <p>U kunt testcases filteren op test prioriteit. De test prioriteit is \"testcase belang\" ". "gecombineerd met \"test dringendheid\" in het huidige testplan.</p> <h3>Gebruiker filter</h3> <p>U kunt testcases filteren die niet zijn toegewezen (\"Niemand\") of toegewezen aan \"Iemand\". ". "Je kunt ook testcases filteren die aan een specifieke tester zijn toegewezen. Als je een specifieke tester kiest ". "heb je ook de mogelijkheid om testcases die niet toegewezen zijn erbij te laten zien". "(geavanceerde filters zijn beschikbaar). </p> <h3>Resultaat filter</h3> <p>U kunt testcases filteren op resultaat (geavanceerde filters zijn beschikbaar). U kunt filteren op ". "Resultaat \"op gekozen build \", \"op de nieuwste uitvoering\", \"op ALLE builds\", ". "\"op om het even welke build\" en \"op specifieke build\". Als \"specifieke build\" gekozen is dan kan u". "de build opgeven.</p>"; // newest_tcversions.html $TLS_hlp_planTcModified = "<h2>De nieuwste versies van gekoppelde testcases</h2> <p>De hele set testcases gekoppeld aan testplan wordt geanalyseerd, en een lijst van testcases waarvan de nieuwste versie wordt weergegeven (vergeleken met de huidige set van het testplan). </p>"; // requirementsCoverage.html $TLS_hlp_requirementsCoverage = "<h3>Vereisten dekking</h3> <br /> <p>Deze functie maakt het mogelijk om de ​​dekking in kaart te brengen van de gebruiker- of systeemvereisten door testcases Openen via link \"Vereisten specificatie\" in het hoofdscherm.</p> <h3>Vereisten specificatie</h3> <p>Vereisten worden gegroepeerd door een 'Vereisten specificatie' document dat betrekking heeft op het testproject. <br /> TestLink ondersteunt geen versiebeheer voor vereisten specificaties  of vereisten. Dus moet de versie van document worden toegevoegd na een specificatie <b>Titel</b>. Een gebruiker kan eenvoudige beschrijvingen of opmerkingen toevoegen aan het <b>Bereik</b> veld.</p> <p><b><a name='total_count'>Overschreven telling van vereisten</a></b> dient voor evaluatie van vereisten dekking in het geval dat niet aan alle vereisten toegevoegd (of geïmporteerd) zijn. De waarde <b> 0 </b> betekent dat de huidige telling van eisen wordt gebruikt voor de statistieken.</p> <p><i>Bv SRS omvat 200 vereisten, maar slechts 50 worden toegevoegd in TestLink. Test dekking is 25% (indien alle toegevoegde vereisten worden getest).</i></p> <h3><a name=\"req\">Vereisten</a></h3> <p>Klik op de titel van een bestaande Vereisten specificatie. U kunt vereisten maken, bewerken, verwijderen of importeren voor het document. Elke vereiste heeft een titel, bereik en status. Status moet \"normaal\" of \"Niet toetsbaar\" zijn. Niet toetsbare vereisten worden niet meegeteld in statistieken. Deze parameter moet worden gebruikt voor niet geïmplementeerde functies en verkeerd ontworpen vereisten.</p> <p>U kunt nieuwe testcases voor de vereisten aanmaken door het gebruik van multi actie met gecontroleerde vereisten in het specificaties scherm. Deze testcases worden gemaakt in testsuite met de naam opgegeven in configuratie <i>(standaard is: &#36;tlCfg->req_cfg->default_testsuite_name = \"Test suite created by Requirement - Auto\";) </i>. Titel en bereik worden gekopieerd naar deze testcases. </p> "; $TLS_hlp_req_coverage_table = "<h3>Dekking:</h3> Een waarde van bijvoorbeeld \"40% (8/20)\" betekent dat 20 testcases moeten worden gemaakt om deze vereiste volledig testen. 8 ervan al zijn gemaakt en gekoppeld aan deze vereiste, die zo een dekking van 40 procent uitmaken. "; // planAddTC_m1.tpl $TLS_hlp_planAddTC = "<h2> Metbetrekking tot 'Gebruikersvelden opslaan'</h2> Als u gebruikersvelden met <br/> 'Toon bij testplan ontwerp'<br/> en 'Beschikbaar bij testplan ontwerp' <br/> hebt gedefinieerd en toegewezen aan een testproject, <br /> zult u deze op deze pagina alleen zien voor testcases gekoppeld aan het testplan. "; // xxx.html // $TLS_hlp_xxx = ""; // ----- END ------------------------------------------------------------------ ?>
{ "pile_set_name": "Github" }
@import '../../../assets/css/mixin.less'; @import '../../../assets/css/theme.less'; .row { width: 100%; background-color: @fill-body; margin-bottom: 20px; border-radius: 4px; overflow: hidden; box-shadow: 0px 6px 5px -5px rgba(0,0,0,.1); .body { width: 100%; height: 168px; background-color: @fill-body; display: flex; position: relative; &::after, &::before{ position: absolute; content: '' !important; display: block; border: 12px solid @fill-body-darken; border-radius: 100%; z-index: 2; } &::after { left: -12px; bottom: -12px; } &::before { right: -12px; bottom: -12px; } .icon { position: absolute; font-size: @font-size-large-x; top: 0; left: 0; color: @badge-color-open; } .left { flex: 0 0 190px; width: 190px; display: flex; flex-direction: column; justify-content: center; .amount { text-align: center; color: #ff0025; font-size: @font-size-large-x; span { font-weight: 700; } .unit { font-size: @font-size-small; margin-right: 10px; } } .desc { font-size: @font-size-small; font-weight: @font-weight-small; color: @color-base; text-align: center; transform: scale(.9); transform-origin: center center; margin-top: 10px; } } .center { flex: 1; width: 0; display: flex; flex-direction: column; justify-content: center; margin: 0 10px; .title { font-size: @font-size-medium; color: @color-title; margin-bottom: 10px; } .desc { font-size: @font-size-small; font-weight: @font-weight-small; color: @color-base; transform: scale(.9); margin-bottom: 6px; transform-origin: 0; } } .right { flex: 0 0 150px; width: 150px; display: flex; flex-direction: column; justify-content: center; .title { text-align: center; font-size: @font-size-small; color: #ff0025; margin-bottom: 10px; } .btn { outline: none; margin: 0 auto; border: none; text-align: center; width: 110px; line-height: 46px; color: #fff; background-color: #ff0025; border-radius: 46px; } } } .bottom { width: 100%; height: 74px; background-color: #fcfcfc; box-sizing: border-box; border-top: 1px dotted @border-color; padding: 0 30px; .desc { width: 100%; height: 100%; position: relative; span { position: absolute; left: 0; right: -120px; top: 50%; display: block; font-size: @font-size-small; font-weight: @font-weight-small; transform: scale(.8) translateY(-50%); transform-origin: 0 0; color: @color-base; .no-wrap; } } } }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2017 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. */ public class Main { public static void main(String[] args) throws Exception { art.Test915.run(); } }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2003, 2008, 2009 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. * */ #ifndef ScopeChain_h #define ScopeChain_h #include "FastAllocBase.h" namespace JSC { class JSGlobalData; class JSGlobalObject; class JSObject; class MarkStack; class ScopeChainIterator; class ScopeChainNode : public FastAllocBase { public: ScopeChainNode(ScopeChainNode* next, JSObject* object, JSGlobalData* globalData, JSGlobalObject* globalObject, JSObject* globalThis) : next(next) , object(object) , globalData(globalData) , globalObject(globalObject) , globalThis(globalThis) , refCount(1) { ASSERT(globalData); ASSERT(globalObject); } #ifndef NDEBUG // Due to the number of subtle and timing dependent bugs that have occurred due // to deleted but still "valid" ScopeChainNodes we now deliberately clobber the // contents in debug builds. ~ScopeChainNode() { next = 0; object = 0; globalData = 0; globalObject = 0; globalThis = 0; } #endif ScopeChainNode* next; JSObject* object; JSGlobalData* globalData; JSGlobalObject* globalObject; JSObject* globalThis; int refCount; void deref() { ASSERT(refCount); if (--refCount == 0) { release();} } void ref() { ASSERT(refCount); ++refCount; } void release(); // Before calling "push" on a bare ScopeChainNode, a client should // logically "copy" the node. Later, the client can "deref" the head // of its chain of ScopeChainNodes to reclaim all the nodes it added // after the logical copy, leaving nodes added before the logical copy // (nodes shared with other clients) untouched. ScopeChainNode* copy() { ref(); return this; } ScopeChainNode* push(JSObject*); ScopeChainNode* pop(); ScopeChainIterator begin() const; ScopeChainIterator end() const; #ifndef NDEBUG void print() const; #endif }; inline ScopeChainNode* ScopeChainNode::push(JSObject* o) { ASSERT(o); return new ScopeChainNode(this, o, globalData, globalObject, globalThis); } inline ScopeChainNode* ScopeChainNode::pop() { ASSERT(next); ScopeChainNode* result = next; if (--refCount != 0) ++result->refCount; else delete this; return result; } inline void ScopeChainNode::release() { // This function is only called by deref(), // Deref ensures these conditions are true. ASSERT(refCount == 0); ScopeChainNode* n = this; do { ScopeChainNode* next = n->next; delete n; n = next; } while (n && --n->refCount == 0); } class ScopeChainIterator { public: ScopeChainIterator(const ScopeChainNode* node) : m_node(node) { } JSObject* const & operator*() const { return m_node->object; } JSObject* const * operator->() const { return &(operator*()); } ScopeChainIterator& operator++() { m_node = m_node->next; return *this; } // postfix ++ intentionally omitted bool operator==(const ScopeChainIterator& other) const { return m_node == other.m_node; } bool operator!=(const ScopeChainIterator& other) const { return m_node != other.m_node; } private: const ScopeChainNode* m_node; }; inline ScopeChainIterator ScopeChainNode::begin() const { return ScopeChainIterator(this); } inline ScopeChainIterator ScopeChainNode::end() const { return ScopeChainIterator(0); } class NoScopeChain {}; class ScopeChain { friend class JIT; public: ScopeChain(NoScopeChain) : m_node(0) { } ScopeChain(JSObject* o, JSGlobalData* globalData, JSGlobalObject* globalObject, JSObject* globalThis) : m_node(new ScopeChainNode(0, o, globalData, globalObject, globalThis)) { } ScopeChain(const ScopeChain& c) : m_node(c.m_node->copy()) { } ScopeChain& operator=(const ScopeChain& c); explicit ScopeChain(ScopeChainNode* node) : m_node(node->copy()) { } ~ScopeChain() { if (m_node) m_node->deref(); #ifndef NDEBUG m_node = 0; #endif } void swap(ScopeChain&); ScopeChainNode* node() const { return m_node; } JSObject* top() const { return m_node->object; } ScopeChainIterator begin() const { return m_node->begin(); } ScopeChainIterator end() const { return m_node->end(); } void push(JSObject* o) { m_node = m_node->push(o); } void pop() { m_node = m_node->pop(); } void clear() { m_node->deref(); m_node = 0; } JSGlobalObject* globalObject() const { return m_node->globalObject; } void markAggregate(MarkStack&) const; // Caution: this should only be used if the codeblock this is being used // with needs a full scope chain, otherwise this returns the depth of // the preceeding call frame // // Returns the depth of the current call frame's scope chain int localDepth() const; #ifndef NDEBUG void print() const { m_node->print(); } #endif private: ScopeChainNode* m_node; }; inline void ScopeChain::swap(ScopeChain& o) { ScopeChainNode* tmp = m_node; m_node = o.m_node; o.m_node = tmp; } inline ScopeChain& ScopeChain::operator=(const ScopeChain& c) { ScopeChain tmp(c); swap(tmp); return *this; } } // namespace JSC #endif // ScopeChain_h
{ "pile_set_name": "Github" }
namespace ApiTemplate.ViewModels { using System.Collections.Generic; #if Swagger /// <summary> /// A paged collection of items. /// </summary> /// <typeparam name="T">The type of the items.</typeparam> #endif public class Connection<T> { public Connection() => this.Items = new List<T>(); #if Swagger /// <summary> /// Gets or sets the total count of items. /// </summary> /// <example>100</example> #endif public int TotalCount { get; set; } #if Swagger /// <summary> /// Gets or sets the page information. /// </summary> #endif public PageInfo PageInfo { get; set; } #if Swagger /// <summary> /// Gets the items. /// </summary> #endif public List<T> Items { get; } } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head><!-- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX This file is generated from xml source: DO NOT EDIT XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX --> <title>mod_deflate - Apache HTTP Server</title> <link href="../style/css/manual.css" rel="stylesheet" media="all" type="text/css" title="Main stylesheet" /> <link href="../style/css/manual-loose-100pc.css" rel="alternate stylesheet" media="all" type="text/css" title="No Sidebar - Default font size" /> <link href="../style/css/manual-print.css" rel="stylesheet" media="print" type="text/css" /> <link href="../images/favicon.ico" rel="shortcut icon" /></head> <body> <div id="page-header"> <p class="menu"><a href="../mod/">Modules</a> | <a href="../mod/directives.html">Directives</a> | <a href="../faq/">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p> <p class="apache">Apache HTTP Server Version 2.2</p> <img alt="" src="../images/feather.gif" /></div> <div class="up"><a href="./"><img title="&lt;-" alt="&lt;-" src="../images/left.gif" /></a></div> <div id="path"> <a href="http://www.apache.org/">Apache</a> &gt; <a href="http://httpd.apache.org/">HTTP Server</a> &gt; <a href="http://httpd.apache.org/docs/">Documentation</a> &gt; <a href="../">Version 2.2</a> &gt; <a href="./">Modules</a></div> <div id="page-content"> <div id="preamble"><h1>Apache Module mod_deflate</h1> <div class="toplang"> <p><span>Available Languages: </span><a href="../en/mod/mod_deflate.html" title="English">&nbsp;en&nbsp;</a> | <a href="../ja/mod/mod_deflate.html" hreflang="ja" rel="alternate" title="Japanese">&nbsp;ja&nbsp;</a> | <a href="../ko/mod/mod_deflate.html" hreflang="ko" rel="alternate" title="Korean">&nbsp;ko&nbsp;</a></p> </div> <table class="module"><tr><th><a href="module-dict.html#Description">Description:</a></th><td>Compress content before it is delivered to the client</td></tr> <tr><th><a href="module-dict.html#Status">Status:</a></th><td>Extension</td></tr> <tr><th><a href="module-dict.html#ModuleIdentifier">Module Identifier:</a></th><td>deflate_module</td></tr> <tr><th><a href="module-dict.html#SourceFile">Source File:</a></th><td>mod_deflate.c</td></tr></table> <h3>Summary</h3> <p>The <code class="module"><a href="../mod/mod_deflate.html">mod_deflate</a></code> module provides the <code>DEFLATE</code> output filter that allows output from your server to be compressed before being sent to the client over the network.</p> </div> <div id="quickview"><h3 class="directives">Directives</h3> <ul id="toc"> <li><img alt="" src="../images/down.gif" /> <a href="#deflatebuffersize">DeflateBufferSize</a></li> <li><img alt="" src="../images/down.gif" /> <a href="#deflatecompressionlevel">DeflateCompressionLevel</a></li> <li><img alt="" src="../images/down.gif" /> <a href="#deflatefilternote">DeflateFilterNote</a></li> <li><img alt="" src="../images/down.gif" /> <a href="#deflatememlevel">DeflateMemLevel</a></li> <li><img alt="" src="../images/down.gif" /> <a href="#deflatewindowsize">DeflateWindowSize</a></li> </ul> <h3>Topics</h3> <ul id="topics"> <li><img alt="" src="../images/down.gif" /> <a href="#recommended">Sample Configurations</a></li> <li><img alt="" src="../images/down.gif" /> <a href="#enable">Enabling Compression</a></li> <li><img alt="" src="../images/down.gif" /> <a href="#proxies">Dealing with proxy servers</a></li> </ul><h3>See also</h3> <ul class="seealso"> <li><a href="../filter.html">Filters</a></li> </ul></div> <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div> <div class="section"> <h2><a name="recommended" id="recommended">Sample Configurations</a></h2> <p>This is a simple sample configuration for the impatient.</p> <div class="example"><h3>Compress only a few types</h3><p><code> AddOutputFilterByType DEFLATE text/html text/plain text/xml </code></p></div> <p>The following configuration, while resulting in more compressed content, is also much more complicated. Do not use this unless you fully understand all the configuration details.</p> <div class="example"><h3>Compress everything except images</h3><p><code> &lt;Location /&gt;<br /> <span class="indent"> # Insert filter<br /> SetOutputFilter DEFLATE<br /> <br /> # Netscape 4.x has some problems...<br /> BrowserMatch ^Mozilla/4 gzip-only-text/html<br /> <br /> # Netscape 4.06-4.08 have some more problems<br /> BrowserMatch ^Mozilla/4\.0[678] no-gzip<br /> <br /> # MSIE masquerades as Netscape, but it is fine<br /> BrowserMatch \bMSIE !no-gzip !gzip-only-text/html<br /> # Don't compress images<br /> SetEnvIfNoCase Request_URI \<br /> <span class="indent"> \.(?:gif|jpe?g|png)$ no-gzip dont-vary<br /> </span> <br /> # Make sure proxies don't deliver the wrong content<br /> Header append Vary User-Agent env=!dont-vary<br /> </span> &lt;/Location&gt; </code></p></div> </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div> <div class="section"> <h2><a name="enable" id="enable">Enabling Compression</a></h2> <h3><a name="output" id="output">Output Compression</a></h3> <p>Compression is implemented by the <code>DEFLATE</code> <a href="../filter.html">filter</a>. The following directive will enable compression for documents in the container where it is placed:</p> <div class="example"><p><code> SetOutputFilter DEFLATE </code></p></div> <p>Some popular browsers cannot handle compression of all content so you may want to set the <code>gzip-only-text/html</code> note to <code>1</code> to only allow html files to be compressed (see below). If you set this to <em>anything but <code>1</code></em> it will be ignored.</p> <p>If you want to restrict the compression to particular MIME types in general, you may use the <code class="directive"><a href="../mod/core.html#addoutputfilterbytype">AddOutputFilterByType</a></code> directive. Here is an example of enabling compression only for the html files of the Apache documentation:</p> <div class="example"><p><code> &lt;Directory "/your-server-root/manual"&gt;<br /> <span class="indent"> AddOutputFilterByType DEFLATE text/html<br /> </span> &lt;/Directory&gt; </code></p></div> <p>For browsers that have problems even with compression of all file types, use the <code class="directive"><a href="../mod/mod_setenvif.html#browsermatch">BrowserMatch</a></code> directive to set the <code>no-gzip</code> note for that particular browser so that no compression will be performed. You may combine <code>no-gzip</code> with <code>gzip-only-text/html</code> to get the best results. In that case the former overrides the latter. Take a look at the following excerpt from the <a href="#recommended">configuration example</a> defined in the section above:</p> <div class="example"><p><code> BrowserMatch ^Mozilla/4 gzip-only-text/html<br /> BrowserMatch ^Mozilla/4\.0[678] no-gzip<br /> BrowserMatch \bMSIE !no-gzip !gzip-only-text/html </code></p></div> <p>At first we probe for a <code>User-Agent</code> string that indicates a Netscape Navigator version of 4.x. These versions cannot handle compression of types other than <code>text/html</code>. The versions 4.06, 4.07 and 4.08 also have problems with decompressing html files. Thus, we completely turn off the deflate filter for them.</p> <p>The third <code class="directive"><a href="../mod/mod_setenvif.html#browsermatch">BrowserMatch</a></code> directive fixes the guessed identity of the user agent, because the Microsoft Internet Explorer identifies itself also as "Mozilla/4" but is actually able to handle requested compression. Therefore we match against the additional string "MSIE" (<code>\b</code> means "word boundary") in the <code>User-Agent</code> Header and turn off the restrictions defined before.</p> <div class="note"><h3>Note</h3> The <code>DEFLATE</code> filter is always inserted after RESOURCE filters like PHP or SSI. It never touches internal subrequests. </div> <div class="note"><h3>Note</h3> There is a environment variable <code>force-gzip</code>, set via <code class="directive"><a href="../mod/core.html#setenv">SetEnv</a></code>, which will ignore the accept-encoding setting of your browser and will send compressed output. </div> <h3><a name="inflate" id="inflate">Output Decompression</a></h3> <p>The <code class="module"><a href="../mod/mod_deflate.html">mod_deflate</a></code> module also provides a filter for inflating/uncompressing a gzip compressed response body. In order to activate this feature you have to insert the <code>INFLATE</code> filter into the outputfilter chain using <code class="directive"><a href="../mod/core.html#setoutputfilter">SetOutputFilter</a></code> or <code class="directive"><a href="../mod/mod_mime.html#addoutputfilter">AddOutputFilter</a></code>, for example:</p> <div class="example"><p><code> &lt;Location /dav-area&gt;<br /> <span class="indent"> ProxyPass http://example.com/<br /> SetOutputFilter INFLATE<br /> </span> &lt;/Location&gt; </code></p></div> <p>This Example will uncompress gzip'ed output from example.com, so other filters can do further processing with it. </p> <h3><a name="input" id="input">Input Decompression</a></h3> <p>The <code class="module"><a href="../mod/mod_deflate.html">mod_deflate</a></code> module also provides a filter for decompressing a gzip compressed request body . In order to activate this feature you have to insert the <code>DEFLATE</code> filter into the input filter chain using <code class="directive"><a href="../mod/core.html#setinputfilter">SetInputFilter</a></code> or <code class="directive"><a href="../mod/mod_mime.html#addinputfilter">AddInputFilter</a></code>, for example:</p> <div class="example"><p><code> &lt;Location /dav-area&gt;<br /> <span class="indent"> SetInputFilter DEFLATE<br /> </span> &lt;/Location&gt; </code></p></div> <p>Now if a request contains a <code>Content-Encoding: gzip</code> header, the body will be automatically decompressed. Few browsers have the ability to gzip request bodies. However, some special applications actually do support request compression, for instance some <a href="http://www.webdav.org">WebDAV</a> clients.</p> <div class="warning"><h3>Note on Content-Length</h3> <p>If you evaluate the request body yourself, <em>don't trust the <code>Content-Length</code> header!</em> The Content-Length header reflects the length of the incoming data from the client and <em>not</em> the byte count of the decompressed data stream.</p> </div> </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div> <div class="section"> <h2><a name="proxies" id="proxies">Dealing with proxy servers</a></h2> <p>The <code class="module"><a href="../mod/mod_deflate.html">mod_deflate</a></code> module sends a <code>Vary: Accept-Encoding</code> HTTP response header to alert proxies that a cached response should be sent only to clients that send the appropriate <code>Accept-Encoding</code> request header. This prevents compressed content from being sent to a client that will not understand it.</p> <p>If you use some special exclusions dependent on, for example, the <code>User-Agent</code> header, you must manually configure an addition to the <code>Vary</code> header to alert proxies of the additional restrictions. For example, in a typical configuration where the addition of the <code>DEFLATE</code> filter depends on the <code>User-Agent</code>, you should add:</p> <div class="example"><p><code> Header append Vary User-Agent </code></p></div> <p>If your decision about compression depends on other information than request headers (<em>e.g.</em> HTTP version), you have to set the <code>Vary</code> header to the value <code>*</code>. This prevents compliant proxies from caching entirely.</p> <div class="example"><h3>Example</h3><p><code> Header set Vary * </code></p></div> </div> <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div> <div class="directive-section"><h2><a name="DeflateBufferSize" id="DeflateBufferSize">DeflateBufferSize</a> <a name="deflatebuffersize" id="deflatebuffersize">Directive</a></h2> <table class="directive"> <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Fragment size to be compressed at one time by zlib</td></tr> <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>DeflateBufferSize <var>value</var></code></td></tr> <tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>DeflateBufferSize 8096</code></td></tr> <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host</td></tr> <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr> <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_deflate</td></tr> </table> <p>The <code class="directive">DeflateBufferSize</code> directive specifies the size in bytes of the fragments that zlib should compress at one time.</p> </div> <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div> <div class="directive-section"><h2><a name="DeflateCompressionLevel" id="DeflateCompressionLevel">DeflateCompressionLevel</a> <a name="deflatecompressionlevel" id="deflatecompressionlevel">Directive</a></h2> <table class="directive"> <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>How much compression do we apply to the output</td></tr> <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>DeflateCompressionLevel <var>value</var></code></td></tr> <tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>Zlib's default</code></td></tr> <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host</td></tr> <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr> <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_deflate</td></tr> <tr><th><a href="directive-dict.html#Compatibility">Compatibility:</a></th><td>This directive is available since Apache 2.0.45</td></tr> </table> <p>The <code class="directive">DeflateCompressionLevel</code> directive specifies what level of compression should be used, the higher the value, the better the compression, but the more CPU time is required to achieve this.</p> <p>The value must between 1 (less compression) and 9 (more compression).</p> </div> <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div> <div class="directive-section"><h2><a name="DeflateFilterNote" id="DeflateFilterNote">DeflateFilterNote</a> <a name="deflatefilternote" id="deflatefilternote">Directive</a></h2> <table class="directive"> <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Places the compression ratio in a note for logging</td></tr> <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>DeflateFilterNote [<var>type</var>] <var>notename</var></code></td></tr> <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host</td></tr> <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr> <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_deflate</td></tr> <tr><th><a href="directive-dict.html#Compatibility">Compatibility:</a></th><td><var>type</var> is available since Apache 2.0.45</td></tr> </table> <p>The <code class="directive">DeflateFilterNote</code> directive specifies that a note about compression ratios should be attached to the request. The name of the note is the value specified for the directive. You can use that note for statistical purposes by adding the value to your <a href="../logs.html#accesslog">access log</a>.</p> <div class="example"><h3>Example</h3><p><code> DeflateFilterNote ratio<br /> <br /> LogFormat '"%r" %b (%{ratio}n) "%{User-agent}i"' deflate<br /> CustomLog logs/deflate_log deflate </code></p></div> <p>If you want to extract more accurate values from your logs, you can use the <var>type</var> argument to specify the type of data left as note for logging. <var>type</var> can be one of:</p> <dl> <dt><code>Input</code></dt> <dd>Store the byte count of the filter's input stream in the note.</dd> <dt><code>Output</code></dt> <dd>Store the byte count of the filter's output stream in the note.</dd> <dt><code>Ratio</code></dt> <dd>Store the compression ratio (<code>output/input * 100</code>) in the note. This is the default, if the <var>type</var> argument is omitted.</dd> </dl> <p>Thus you may log it this way:</p> <div class="example"><h3>Accurate Logging</h3><p><code> DeflateFilterNote Input instream<br /> DeflateFilterNote Output outstream<br /> DeflateFilterNote Ratio ratio<br /> <br /> LogFormat '"%r" %{outstream}n/%{instream}n (%{ratio}n%%)' deflate<br /> CustomLog logs/deflate_log deflate </code></p></div> <h3>See also</h3> <ul> <li><code class="module"><a href="../mod/mod_log_config.html">mod_log_config</a></code></li> </ul> </div> <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div> <div class="directive-section"><h2><a name="DeflateMemLevel" id="DeflateMemLevel">DeflateMemLevel</a> <a name="deflatememlevel" id="deflatememlevel">Directive</a></h2> <table class="directive"> <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>How much memory should be used by zlib for compression</td></tr> <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>DeflateMemLevel <var>value</var></code></td></tr> <tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>DeflateMemLevel 9</code></td></tr> <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host</td></tr> <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr> <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_deflate</td></tr> </table> <p>The <code class="directive">DeflateMemLevel</code> directive specifies how much memory should be used by zlib for compression (a value between 1 and 9).</p> </div> <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div> <div class="directive-section"><h2><a name="DeflateWindowSize" id="DeflateWindowSize">DeflateWindowSize</a> <a name="deflatewindowsize" id="deflatewindowsize">Directive</a></h2> <table class="directive"> <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Zlib compression window size</td></tr> <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>DeflateWindowSize <var>value</var></code></td></tr> <tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>DeflateWindowSize 15</code></td></tr> <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host</td></tr> <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr> <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_deflate</td></tr> </table> <p>The <code class="directive">DeflateWindowSize</code> directive specifies the zlib compression window size (a value between 1 and 15). Generally, the higher the window size, the higher can the compression ratio be expected.</p> </div> </div> <div class="bottomlang"> <p><span>Available Languages: </span><a href="../en/mod/mod_deflate.html" title="English">&nbsp;en&nbsp;</a> | <a href="../ja/mod/mod_deflate.html" hreflang="ja" rel="alternate" title="Japanese">&nbsp;ja&nbsp;</a> | <a href="../ko/mod/mod_deflate.html" hreflang="ko" rel="alternate" title="Korean">&nbsp;ko&nbsp;</a></p> </div><div id="footer"> <p class="apache">Copyright 2012 The Apache Software Foundation.<br />Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>.</p> <p class="menu"><a href="../mod/">Modules</a> | <a href="../mod/directives.html">Directives</a> | <a href="../faq/">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p></div> </body></html>
{ "pile_set_name": "Github" }
/* * Copyright (C) 2007 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following condition * 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 Apple Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "config.h" #include "SQLValue.h" namespace WebCore { SQLValue::SQLValue(const SQLValue& val) : m_type(val.m_type) , m_number(val.m_number) , m_string(val.m_string.isolatedCopy()) { } String SQLValue::string() const { ASSERT(m_type == StringValue); // Must return a copy since ref-shared Strings are not thread safe return m_string.isolatedCopy(); } double SQLValue::number() const { ASSERT(m_type == NumberValue); return m_number; } }
{ "pile_set_name": "Github" }
require 'thread' require 'digest/sha1' require 'timeout' module Roma class AsyncMessage attr_accessor :event attr_accessor :args attr_accessor :callback def initialize(ev, ag = nil, &cb) @event = ev @args = ag @callback = cb @retry_count = 0 @retry_max = 10 @retry_wait = 0.1 end def retry? @retry_max > @retry_count end def incr_count @retry_count += 1 end def wait sleep(@retry_wait) end end module AsyncProcess @@async_queue = Queue.new @@async_queue_latency = Queue.new def self.queue @@async_queue end def self.queue_latency @@async_queue_latency end def start_async_process @async_thread = Thread.new do async_process_loop end @async_thread[:name] = __method__ @async_thread_latency = Thread.new do async_process_loop_for_latency end @async_thread_latency[:name] = __method__ rescue => e @log.error("#{e}\n#{$ERROR_POSITION}") end private def stop_async_process count = 0 while @@async_queue.empty? == false && count < 100 count += 1 sleep 0.1 end @async_thread.exit count = 0 while @@async_queue_latency.empty? == false && count < 100 count += 1 sleep 0.1 end @async_thread_latency.exit end def async_process_loop loop do while msg = @@async_queue.pop if send("asyncev_#{msg.event}", msg.args) msg.callback.call(msg, true) if msg.callback else if msg.retry? t = Thread.new do msg.wait msg.incr_count @@async_queue.push(msg) end t[:name] = __method__ else @log.error("async process retry out:#{msg.inspect}") msg.callback.call(msg, false) if msg.callback end end end end rescue => e @log.error("#{e}\n#{$ERROR_POSITION}") retry end def async_process_loop_for_latency loop do while msg = @@async_queue_latency.pop if send("asyncev_#{msg.event}", msg.args) msg.callback.call(msg, true) if msg.callback else if msg.retry? t = Thread.new do msg.wait msg.incr_count @@async_queue_latency.push(msg) end t[:name] = __method__ else @log.error("async process retry out:#{msg.inspect}") msg.callback.call(msg, false) if msg.callback end end end end rescue => e @log.error("#{e}\n#{$ERROR_POSITION}") retry end def asyncev_broadcast_cmd(args) @log.debug("#{__method__} #{args.inspect}") cmd, nids, tout = args t = Thread.new do async_broadcast_cmd("#{cmd}\r\n", nids, tout) end t[:name] = __method__ true end def asyncev_start_join_process(_args) @log.debug(__method__) if @stats.run_join @log.error("#{__method__}:join process running") return true end if @stats.run_recover @log.error("#{__method__}:recover process running") return true end if @stats.run_balance @log.error("#{__method__}:balance process running") return true end @stats.run_join = true t = Thread.new do begin join_process rescue => e @log.error("#{__method__}:#{e.inspect} #{$ERROR_POSITION}") ensure @stats.run_join = false @stats.join_ap = nil end end t[:name] = __method__ true end def asyncev_start_balance_process(_args) @log.debug(__method__) if @stats.run_join @log.error("#{__method__}:join process running") return true end if @stats.run_recover @log.error("#{__method__}:recover process running") return true end if @stats.run_balance @log.error("#{__method__}:balance process running") return true end @stats.run_balance = true t = Thread.new do begin balance_process rescue => e @log.error("#{__method__}:#{e.inspect} #{$ERROR_POSITION}") ensure @stats.run_balance = false end end t[:name] = __method__ true end def asyncev_redundant(args) nid, hname, k, d, clk, expt, v = args @log.debug("#{__method__} #{args.inspect}") unless @rttable.nodes.include?(nid) @log.warn("async redundant failed:#{nid} does not found in routing table.#{k}\e#{hname} #{d} #{clk} #{expt} #{v.length}") return true # no retry end res = async_send_cmd(nid, "rset #{k}\e#{hname} #{d} #{clk} #{expt} #{v.length}\r\n#{v}\r\n", 10) if res.nil? || res.start_with?('ERROR') @log.warn("async redundant failed:#{k}\e#{hname} #{d} #{clk} #{expt} #{v.length} -> #{nid}") return false # retry end true end def asyncev_zredundant(args) nid, hname, k, d, clk, expt, zv = args @log.debug("#{__method__} #{args.inspect}") unless @rttable.nodes.include?(nid) @log.warn("async zredundant failed:#{nid} does not found in routing table.#{k}\e#{hname} #{d} #{clk} #{expt} #{zv.length}") return true # no retry end res = async_send_cmd(nid, "rzset #{k}\e#{hname} #{d} #{clk} #{expt} #{zv.length}\r\n#{zv}\r\n", 10) if res.nil? || res.start_with?('ERROR') @log.warn("async zredundant failed:#{k}\e#{hname} #{d} #{clk} #{expt} #{v.length} -> #{nid}") return false # retry end true end def asyncev_rdelete(args) nid, hname, k, clk = args @log.debug("#{__method__} #{args.inspect}") unless @rttable.nodes.include?(nid) @log.warn("async rdelete failed:#{nid} does not found in routing table.#{k}\e#{hname} #{clk}") return true # no retry end res = async_send_cmd(nid, "rdelete #{k}\e#{hname} #{clk}\r\n", 10) unless res @log.warn("async redundant failed:#{k}\e#{hname} #{clk} -> #{nid}") return false # retry end true end def asyncev_reqpushv(args) vn, nid, p = args @log.debug("#{__method__} #{args.inspect}") if @stats.run_iterate_storage @log.warn("#{__method__}:already be iterated storage process.") else @stats.run_iterate_storage = true t = Thread.new do begin sync_a_vnode(vn.to_i, nid, p == 'true') rescue => e @log.error("#{__method__}:#{e.inspect} #{$ERROR_POSITION}") ensure @stats.run_iterate_storage = false end end t[:name] = __method__ end end def asyncev_start_recover_process(args) @log.debug("#{__method__} #{args.inspect}") if @stats.run_join @log.error("#{__method__}:join process running") return true end if @stats.run_recover @log.error("#{__method__}:recover process running.") return false end if @stats.run_balance @log.error("#{__method__}:balance process running") return true end @stats.run_recover = true t = Thread.new do begin acquired_recover_process rescue => e @log.error("#{__method__}:#{e.inspect} #{$ERROR_POSITION}") ensure @stats.run_recover = false end end t[:name] = __method__ end def asyncev_start_auto_recover_process(args) @log.debug("#{__method__} #{args.inspect}") # ##run_join don't have possibility to be true in this case. # if @stats.run_join # @log.error("#{__method__}:join process running") # return true # end if @stats.run_recover @log.error("#{__method__}:recover process running.") return false end if @stats.run_balance @log.error("#{__method__}:balance process running") return true end @rttable.auto_recover_status = 'preparing' t = Thread.new do begin Timeout.timeout(@rttable.auto_recover_time)do loop do sleep 1 break if @rttable.auto_recover_status != 'preparing' # break if @stats.run_join #run_join don't have possibility to be true in this case. break if @stats.run_recover break if @stats.run_balance end end @log.debug('inactivated AUTO_RECOVER') rescue case @rttable.lost_action when :auto_assign, :shutdown @stats.run_recover = true @rttable.auto_recover_status = 'executing' begin @log.debug('auto recover start') acquired_recover_process rescue => e @log.error("#{__method__}:#{e.inspect} #{$ERROR_POSITION}") ensure @stats.run_recover = false @rttable.auto_recover_status = 'waiting' end when :no_action @log.debug('auto recover NOT start. Because lost action is [no_action]') end end end t[:name] = __method__ end def asyncev_start_release_process(args) @log.debug("#{__method__} #{args}") if @stats.run_iterate_storage @log.warn("#{__method__}:already be iterated storage process.") else @stats.run_release = true @stats.run_iterate_storage = true @stats.spushv_protection = true t = Thread.new do begin release_process rescue => e @log.error("#{__method__}:#{e.inspect} #{$ERROR_POSITION}") ensure @stats.run_iterate_storage = false @stats.run_release = false end end t[:name] = __method__ end end def acquired_recover_process @log.info("#{__method__}:start") exclude_nodes = @rttable.exclude_nodes_for_recover(@stats.ap_str, @stats.rep_host) @do_acquired_recover_process = true loop do break unless @do_acquired_recover_process break if @rttable.num_of_vn(@stats.ap_str)[2] == 0 # short vnodes vn, nodes, is_primary = @rttable.select_vn_for_recover(exclude_nodes, @stats.rep_host) break unless vn if nodes.length != 0 ret = req_push_a_vnode(vn, nodes[0], is_primary) if ret == :rejected sleep 1 elsif ret == false break end sleep 1 end end @log.info("#{__method__} has done.") rescue => e @log.error("#{e.inspect} #{$ERROR_POSITION}") ensure @do_acquired_recover_process = false end def join_process @log.info("#{__method__}:start") count = 0 nv = @rttable.v_idx.length exclude_nodes = @rttable.exclude_nodes_for_join(@stats.ap_str, @stats.rep_host) @do_join_process = true while @rttable.vnode_balance(@stats.ap_str) == :less && count < nv break unless @do_join_process vn, nodes, is_primary = @rttable.select_vn_for_join(exclude_nodes, @stats.rep_host) unless vn @log.warn("#{__method__}:vnode does not found") return false end ret = req_push_a_vnode(vn, nodes[0], is_primary) if ret == :rejected sleep 5 else sleep 1 count += 1 end end rescue => e @log.error("#{e.inspect} #{$ERROR_POSITION}") ensure @log.info("#{__method__} has done.") @do_join_process = false end def balance_process @log.info("#{__method__}:start") count = 0 nv = @rttable.v_idx.length exclude_nodes = @rttable.exclude_nodes_for_balance(@stats.ap_str, @stats.rep_host) @do_balance_process = true while @rttable.vnode_balance(@stats.ap_str) == :less && count < nv break unless @do_balance_process vn, nodes, is_primary = @rttable.select_vn_for_balance(exclude_nodes, @stats.rep_host) unless vn @log.warn("#{__method__}:vnode does not found") return false end ret = req_push_a_vnode(vn, nodes[0], is_primary) if ret == :rejected sleep 5 else sleep 1 count += 1 end end @log.info("#{__method__} has done.") rescue => e @log.error("#{e.inspect} #{$ERROR_POSITION}") ensure @do_balance_process = false end def req_push_a_vnode(vn, src_nid, is_primary) con = Roma::Messaging::ConPool.instance.get_connection(src_nid) con.write("reqpushv #{vn} #{@stats.ap_str} #{is_primary}\r\n") res = con.gets # receive 'PUSHED\r\n' | 'REJECTED\r\n' | 'ERROR\r\n' if res == "REJECTED\r\n" @log.warn("#{__method__}:request was rejected from #{src_nid}.") Roma::Messaging::ConPool.instance.return_connection(src_nid, con) return :rejected elsif res != "PUSHED\r\n" @log.warn("#{__method__}:#{res}") return :rejected end Roma::Messaging::ConPool.instance.return_connection(src_nid, con) # waiting for pushv count = 0 while @rttable.search_nodes(vn).include?(@stats.ap_str) == false && count < @stats.reqpushv_timeout_count sleep 0.1 count += 1 end if count >= @stats.reqpushv_timeout_count @log.warn("#{__method__}:request has been time-out.vn=#{vn} nid=#{src_nid}") return :timeout end true rescue => e @log.error("#{__method__}:#{e.inspect} #{$ERROR_POSITION}") @rttable.proc_failed(src_nid) false end def release_process @log.info("#{__method__}:start.") if @rttable.can_i_release?(@stats.ap_str, @stats.rep_host) @log.error("#{__method__}:Sufficient nodes do not found.") return end @do_release_process = true while @rttable.has_node?(@stats.ap_str) break unless @do_release_process @rttable.each_vnode do |vn, nids| break unless @do_release_process if nids.include?(@stats.ap_str) to_nid, new_nids = @rttable.select_node_for_release(@stats.ap_str, @stats.rep_host, nids) res = sync_a_vnode_for_release(vn, to_nid, new_nids) if res == :abort @log.error("#{__method__}:release_process aborted due to SERVER_ERROR received.") @do_release_process = false end if res == false @log.warn("#{__method__}:error at vn=#{vn} to_nid=#{to_nid} new_nid=#{new_nids}") redo end end end end @log.info("#{__method__} has done.") rescue => e @log.error("#{e}\n#{$ERROR_POSITION}") ensure @do_release_process = false Roma::Messaging::ConPool.instance.close_all end def sync_a_vnode_for_release(vn, to_nid, new_nids) nids = @rttable.search_nodes(vn) if nids.include?(to_nid) == false @log.debug("#{__method__}:#{vn} #{to_nid}") # change routing data at the vnode and synchronize a data nids << to_nid return false unless @rttable.transaction(vn, nids) # synchronize a data @storages.each_key do |hname| res = push_a_vnode_stream(hname, vn, to_nid) if res != 'STORED' @rttable.rollback(vn) @log.error("#{__method__}:push_a_vnode was failed:hname=#{hname} vn=#{vn}:#{res}") return :abort if res.start_with?('SERVER_ERROR') return false end end if (clk = @rttable.commit(vn)) == false @rttable.rollback(vn) @log.error("#{__method__}:routing table commit failed") return false end clk = @rttable.set_route(vn, clk, new_nids) if clk.is_a?(Integer) == false clk, new_nids = @rttable.search_nodes_with_clk(vn) end cmd = "setroute #{vn} #{clk - 1}" new_nids.each { |nn| cmd << " #{nn}" } res = async_broadcast_cmd("#{cmd}\r\n") @log.debug("#{__method__}:async_broadcast_cmd(#{cmd}) #{res}") end return true rescue => e @log.error("#{e}\n#{$ERROR_POSITION}") false end def sync_a_vnode(vn, to_nid, is_primary = nil) nids = @rttable.search_nodes(vn) if nids.include?(to_nid) == false || (is_primary && nids[0] != to_nid) @log.debug("#{__method__}:#{vn} #{to_nid} #{is_primary}") # change routing data at the vnode and synchronize a data nids << to_nid return false unless @rttable.transaction(vn, nids) # synchronize a data @storages.each_key do |hname| res = push_a_vnode_stream(hname, vn, to_nid) if res != 'STORED' @rttable.rollback(vn) @log.error("#{__method__}:push_a_vnode was failed:hname=#{hname} vn=#{vn}:#{res}") return false end end if (clk = @rttable.commit(vn)) == false @rttable.rollback(vn) @log.error("#{__method__}:routing table commit failed") return false end nids = edit_nodes(nids, to_nid, is_primary) clk = @rttable.set_route(vn, clk, nids) if clk.is_a?(Integer) == false clk, nids = @rttable.search_nodes_with_clk(vn) end cmd = "setroute #{vn} #{clk - 1}" nids.each { |nn| cmd << " #{nn}" } res = async_broadcast_cmd("#{cmd}\r\n") @log.debug("#{__method__}:async_broadcast_cmd(#{cmd}) #{res}") else # synchronize a data @storages.each_key do |hname| res = push_a_vnode_stream(hname, vn, to_nid) if res != 'STORED' @log.error("#{__method__}:push_a_vnode was failed:hname=#{hname} vn=#{vn}:#{res}") return false end end end return true rescue => e @log.error("#{e}\n#{$ERROR_POSITION}") false end def edit_nodes(nodes, new_nid, is_primary) if @rttable.rn == 1 return [new_nid] end # [node_a, node_b, new_nid] nodes.delete(new_nid) # [node_a, node_b] if nodes.length >= @rttable.rn host = new_nid.split(/[:_]/)[0] buf = [] # list of a same host nodes.each do |nid| buf << nid if nid.split(/[:_]/)[0] == host end if buf.length > 0 # include same host # delete a last one, due to save a primary node nodes.delete(buf.last) else nodes.delete(nodes.last) end end if is_primary # [new_nid, node_a] nodes.insert(0, new_nid) else # [node_a, new_nid] nodes << new_nid end nodes end def push_a_vnode_stream(hname, vn, nid) @log.debug("#{__method__}:hname=#{hname} vn=#{vn} nid=#{nid}") stop_clean_up con = Roma::Messaging::ConPool.instance.get_connection(nid) @do_push_a_vnode_stream = true con.write("spushv #{hname} #{vn}\r\n") res = con.gets # READY\r\n or error string if res != "READY\r\n" con.close return res.chomp end res_dump = @storages[hname].each_vn_dump(vn) do |data| unless @do_push_a_vnode_stream con.close @log.error("#{__method__}:canceled in hname=#{hname} vn=#{vn} nid=#{nid}") return 'CANCELED' end con.write(data) sleep @stats.stream_copy_wait_param end con.write("\0" * 20) # end of stream res = con.gets # STORED\r\n or error string Roma::Messaging::ConPool.instance.return_connection(nid, con) res.chomp! if res if res_dump == false @log.error("#{__method__}:each_vn_dump in hname=#{hname} vn=#{vn} nid=#{nid}") return 'CANCELED' end res rescue => e @log.error("#{e}\n#{$ERROR_POSITION}") e.to_s end def asyncev_start_storage_clean_up_process(_args) # @log.info("#{__method__}") if @stats.run_storage_clean_up @log.error("#{__method__}:already in being") return end @stats.run_storage_clean_up = true t = Thread.new do begin storage_clean_up_process rescue => e @log.error("#{__method__}:#{e.inspect} #{$ERROR_POSITION}") ensure @stats.last_clean_up = Time.now @stats.run_storage_clean_up = false end end t[:name] = __method__ end def storage_clean_up_process @log.info("#{__method__}:start") me = @stats.ap_str vnhash = {} @rttable.each_vnode do |vn, nids| if nids.include?(me) if nids[0] == me vnhash[vn] = :primary else vnhash[vn] = "secondary#{nids.index(me)}".to_sym end end end t = Time.now.to_i - Roma::Config::STORAGE_DELMARK_EXPTIME count = 0 @storages.each_pair do |hname, st| break unless @stats.do_clean_up? st.each_clean_up(t, vnhash) do |key, vn| # @log.debug("#{__method__}:key=#{key} vn=#{vn}") if @stats.run_receive_a_vnode.key?("#{hname}_#{vn}") false else nodes = @rttable.search_nodes_for_write(vn) if nodes && nodes.length > 1 nodes[1..-1].each do |nid| res = async_send_cmd(nid, "out #{key}\e#{hname} #{vn}\r\n") unless res @log.warn("send out command failed:#{key}\e#{hname} #{vn} -> #{nid}") end # @log.debug("#{__method__}:res=#{res}") end end count += 1 @stats.out_count += 1 true end end end if count > 0 @log.info("#{__method__}:#{count} keys deleted.") end # delete @rttable.logs if @stats.gui_run_gather_logs || @rttable.logs.empty? false else gathered_time = @rttable.logs[0] # delete gathering log data after 5min @rttable.logs.clear if gathered_time.to_i < Time.now.to_i - (60 * 5) end ensure @log.info("#{__method__}:stop") end def asyncev_calc_latency_average(args) latency, cmd = args # @log.debug(__method__) unless @stats.latency_data.key?(cmd) # only first execute target cmd @stats.latency_data[cmd].store('latency', []) @stats.latency_data[cmd].store('latency_max', {}) @stats.latency_data[cmd]['latency_max'].store('current', 0) @stats.latency_data[cmd].store('latency_min', {}) @stats.latency_data[cmd]['latency_min'].store('current', 99_999) @stats.latency_data[cmd].store('time', Time.now.to_i) end begin @stats.latency_data[cmd]['latency'].delete_at(0) if @stats.latency_data[cmd]['latency'].length >= 10 @stats.latency_data[cmd]['latency'].push(latency) @stats.latency_data[cmd]['latency_max']['current'] = latency if latency > @stats.latency_data[cmd]['latency_max']['current'] @stats.latency_data[cmd]['latency_min']['current'] = latency if latency < @stats.latency_data[cmd]['latency_min']['current'] rescue => e @log.error("#{__method__}:#{e.inspect} #{$ERROR_POSITION}") ensure if @stats.latency_check_time_count && Time.now.to_i - @stats.latency_data[cmd]['time'] > @stats.latency_check_time_count average = @stats.latency_data[cmd]['latency'].inject(0.0) { |r, i| r += i } / @stats.latency_data[cmd]['latency'].size max = @stats.latency_data[cmd]['latency_max']['current'] min = @stats.latency_data[cmd]['latency_min']['current'] @log.debug("Latency average[#{cmd}]: #{sprintf('%.8f', average)}"\ "(denominator=#{@stats.latency_data[cmd]['latency'].length}"\ " max=#{sprintf('%.8f', max)}"\ " min=#{sprintf('%.8f', min)})" ) @stats.latency_data[cmd]['time'] = Time.now.to_i @stats.latency_data[cmd]['latency_past'] = @stats.latency_data[cmd]['latency'] @stats.latency_data[cmd]['latency'] = [] @stats.latency_data[cmd]['latency_max']['past'] = @stats.latency_data[cmd]['latency_max']['current'] @stats.latency_data[cmd]['latency_max']['current'] = 0 @stats.latency_data[cmd]['latency_min']['past'] = @stats.latency_data[cmd]['latency_min']['current'] @stats.latency_data[cmd]['latency_min']['current'] = 99_999 end end true end def asyncev_start_storage_flush_process(args) hname, dn = args @log.debug("#{__method__} #{args.inspect}") st = @storages[hname] if st.dbs[dn] != :safecopy_flushing @log.error("Can not flush storage. stat = #{st.dbs[dn]}") return true end t = Thread.new do begin st.flush_db(dn) st.set_db_stat(dn, :safecopy_flushed) @log.info("#{__method__}:storage has flushed. (#{hname}, #{dn})") rescue => e @log.error("#{__method__}:#{e.inspect} #{$ERROR_POSITION}") ensure end end t[:name] = __method__ true end def asyncev_start_storage_cachecleaning_process(args) hname, dn = args @log.debug("#{__method__} #{args.inspect}") st = @storages[hname] if st.dbs[dn] != :cachecleaning @log.error("Can not start cachecleaning process. stat = #{st.dbs[dn]}") return true end t = Thread.new do begin storage_cachecleaning_process(hname, dn) rescue => e @log.error("#{__method__}:#{e.inspect} #{$ERROR_POSITION}") ensure end end t[:name] = __method__ true end def storage_cachecleaning_process(hname, dn) count = 0 rcount = 0 st = @storages[hname] @do_storage_cachecleaning_process = true loop do # get keys in a cache up to 100 kyes keys = st.get_keys_in_cache(dn) break if keys.nil? || keys.length == 0 break unless @do_storage_cachecleaning_process # @log.debug("#{__method__}:#{keys.length} keys found") # copy cache -> db st.each_cache_by_keys(dn, keys) do |vn, last, clk, expt, k, v| break unless @do_storage_cachecleaning_process if st.load_stream_dump_for_cachecleaning(vn, last, clk, expt, k, v) count += 1 # @log.debug("#{__method__}:[#{vn} #{last} #{clk} #{expt} #{k}] was stored.") else rcount += 1 # @log.debug("#{__method__}:[#{vn} #{last} #{clk} #{expt} #{k}] was rejected.") end end # remove keys in a cache keys.each { |key| st.out_cache(dn, key) } end if @do_storage_cachecleaning_process == false @log.warn("#{__method__}:uncompleted") else st.set_db_stat(dn, :normal) end @log.debug("#{__method__}:#{count} keys loaded.") @log.debug("#{__method__}:#{rcount} keys rejected.") if rcount > 0 ensure @do_storage_cachecleaning_process = false end def asyncev_start_get_routing_event(args) @log.debug("#{__method__} #{args}") t = Thread.new do begin get_routing_event rescue => e @log.error("#{__method__}:#{e.inspect} #{$ERROR_POSITION}") ensure end end t[:name] = __method__ end def get_routing_event @log.info("#{__method__}:start.") routing_path = Config::RTTABLE_PATH f_list = Dir.glob("#{routing_path}/#{@stats.ap_str}*") f_list.each do|fname| IO.foreach(fname)do|line| if line =~ /join|leave/ @rttable.event.shift if @rttable.event.size >= @rttable.event_limit_line @rttable.event << line.chomp end end end @log.info("#{__method__} has done.") rescue => e @log.error("#{e}\n#{$ERROR_POSITION}") end def asyncev_start_get_logs(args) @log.debug("#{__method__} #{args}") t = Thread.new do begin get_logs(args) rescue => e @log.error("#{__method__}:#{e.inspect} #{$ERROR_POSITION}") ensure @stats.gui_run_gather_logs = false end end t[:name] = __method__ end def get_logs(args) @log.debug("#{__method__}:start.") log_path = Config::LOG_PATH log_file = "#{log_path}/#{@stats.ap_str}.log" target_logs = [] File.open(log_file)do|f| start_point = get_point(f, args[0], 'start') end_point = get_point(f, args[1], 'end') ## read target logs f.seek(start_point, IO::SEEK_SET) target_logs = f.read(end_point - start_point) target_logs = target_logs.each_line.map(&:chomp) target_logs.delete('.') end @rttable.logs = target_logs # set gathered date for expiration @rttable.logs.unshift(Time.now) @log.debug("#{__method__} has done.") rescue => e @rttable.logs = [] @log.error("#{e}\n#{$ERROR_POSITION}") ensure @stats.gui_run_gather_logs = false end def get_point(f, target_time, type, latency_time = Time.now, current_pos = 0, new_pos = f.size / 2) # hilatency check ps = Time.now - latency_time if ps > 5 @log.warn('gather_logs process was failed.') fail end # initialize read size read_size = 2048 # first check unless target_time.class == Time # in case of not set end_date return f.size if target_time == 'current' target_time =~ (/(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)/) target_time = Time.mktime(Regexp.last_match[1], Regexp.last_match[2], Regexp.last_match[3], Regexp.last_match[4], Regexp.last_match[5], Regexp.last_match[6], 000000) # check outrange or not f.seek(0, IO::SEEK_SET) begining_log = f.read(read_size) pos = begining_log.index(/[IDEW],\s\[(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)\.(\d+)/) begining_time = Time.mktime(Regexp.last_match[1], Regexp.last_match[2], Regexp.last_match[3], Regexp.last_match[4], Regexp.last_match[5], Regexp.last_match[6], Regexp.last_match[7]) f.seek(-read_size, IO::SEEK_END) end_log = f.read(read_size) pos = end_log.rindex(/[IDEW],\s\[(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)\.(\d+)/) end_time = Time.mktime(Regexp.last_match[1], Regexp.last_match[2], Regexp.last_match[3], Regexp.last_match[4], Regexp.last_match[5], Regexp.last_match[6], Regexp.last_match[7]) case type when 'start' if target_time < begining_time return 0 elsif target_time > end_time @log.error('irregular time was set.') fail end when 'end' if target_time > end_time return f.size elsif target_time < begining_time @log.error('irregular time was set.') fail end end end # read half sector size f.seek(new_pos, IO::SEEK_SET) sector_log = f.read(read_size) # grep date date_a = sector_log.scan(/[IDEW],\s\[(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)\.(\d+)/) time_a = [] date_a.each do|time| time_a.push(Time.mktime(time[0], time[1], time[2], time[3], time[4], time[5], time[6])) end sector_time_first = time_a[0] sector_time_last = time_a[-1] if target_time.between?(sector_time_first, sector_time_last) time_a.each do|time| if target_time <= time time_string = time.strftime('%Y-%m-%dT%H:%M:%S') target_index = sector_log.index(/[IDEW],\s\[#{time_string}/) return new_pos + target_index end end elsif sector_time_first > target_time target_pos = new_pos - ((new_pos - current_pos).abs / 2) elsif sector_time_first < target_time target_pos = new_pos + ((new_pos - current_pos).abs / 2) end get_point(f, target_time, type, latency_time, new_pos, target_pos) end def asyncev_start_replicate_existing_data_process(args) # args is [$roma.cr_writer.replica_rttable]) t = Thread.new do begin $roma.cr_writer.run_existing_data_replication = true replicate_existing_data_process(args) rescue => e @log.error("#{__method__}:#{e.inspect} #{$ERROR_POSITION}") ensure $roma.cr_writer.run_existing_data_replication = false end end t[:name] = __method__ end def replicate_existing_data_process(args) @log.info("#{__method__} :start.") @storages.each_key do |hname| @rttable.v_idx.each_key do |vn| raise unless $roma.cr_writer.run_existing_data_replication args[0].v_idx[vn].each do |replica_nid| res = push_a_vnode_stream(hname, vn, replica_nid) if res != 'STORED' @log.error("#{__method__}:push_a_vnode was failed:hname=#{hname} vn=#{vn}:#{res}") return false end end end end @log.info("#{__method__} has done.") rescue => e @log.error("#{e}\n#{$ERROR_POSITION}") end end # module AsyncProcess end # module Roma
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <LocalDebuggerCommandArguments>/mLE q.rel</LocalDebuggerCommandArguments> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> </PropertyGroup> </Project>
{ "pile_set_name": "Github" }
/* * Copyright 2009, Axel Dörfler, [email protected]. * Distributed under the terms of the MIT License. */ #include "PositionToolTip.h" #include <stdio.h> #include <StringView.h> #include "DurationToString.h" class PositionToolTip::PositionView : public BStringView { public: PositionView() : BStringView("position", ""), fPosition(0), fDuration(0) { } virtual ~PositionView() { } virtual void AttachedToWindow() { BStringView::AttachedToWindow(); AdoptParentColors(); Update(-1, -1); } void Update(bigtime_t position, bigtime_t duration) { if (!LockLooper()) return; if (position != -1) { position /= 1000000L; duration /= 1000000L; if (position == fPosition && duration == fDuration) { UnlockLooper(); return; } fPosition = position; fDuration = duration; } char positionText[32]; duration_to_string(fPosition, positionText, sizeof(positionText)); char durationText[32]; duration_to_string(fDuration, durationText, sizeof(durationText)); char text[66]; snprintf(text, sizeof(text), "%s / %s", positionText, durationText); SetText(text); UnlockLooper(); } private: time_t fPosition; time_t fDuration; }; // #pragma mark - PositionToolTip::PositionToolTip() { fView = new PositionView(); } PositionToolTip::~PositionToolTip() { delete fView; } BView* PositionToolTip::View() const { return fView; } void PositionToolTip::Update(bigtime_t position, bigtime_t duration) { fView->Update(position, duration); }
{ "pile_set_name": "Github" }
/* IASKLocalizable.strings Where To Created by Ortwin Gentz on 20.10.14. Copyright (c) 2014 FutureTap. All rights reserved. */ "Privacy" = "Integritetsskydd"; // iOS 8+ Privacy cell: title "Open in Settings app" = ""; // iOS 8+ Privacy cell: subtitle (TODO)
{ "pile_set_name": "Github" }
:title: External Methods of Ingesting Data :type: dataManagement :status: published :summary: External methods of ingesting data. :parent: Ingesting Data :order: 03 == {title} Third-party tools, such as https://curl.haxx.se/[cURL.exe] {external-link} and the https://advancedrestclient.com/[Chrome Advanced Rest Client] {external-link}, can be used to send files to ${branding} for ingest. .Windows Example ---- curl -H "Content-type: application/json;id=geojson" -i -X POST -d ${at-symbol}"C:\path\to\geojson_valid.json" ${secure_url}/services/catalog ---- .*NIX Example ---- curl -H "Content-type: application/json;id=geojson" -i -X POST -d ${at-symbol}geojson_valid.json ${secure_url}/services/catalog ---- Where: + *-H* adds an HTTP header. In this case, Content-type header `application/json;id=geojson` is added to match the data being sent in the request. + *-i* requests that HTTP headers are displayed in the response. + *-X* specifies the type of HTTP operation. For this example, it is necessary to POST (ingest) data to the server. + *-d* specifies the data sent in the POST request. The `${at-symbol}` character is necessary to specify that the data is a file. + The last parameter is the URL of the server that will receive the data. This should return a response similar to the following (the actual catalog ID in the id and Location URL fields will be different): .Sample Response [source,http,linenums] ---- HTTP/1.1 201 Created Content-Length: 0 Date: Mon, 22 Apr 2015 22:02:22 GMT id: 44dc84da101c4f9d9f751e38d9c4d97b Location: ${secure_url}/services/catalog/44dc84da101c4f9d9f751e38d9c4d97b Server: Jetty(7.5.4.v20111024) ---- . Use a web browser to verify a file was successfully ingested. Enter the URL returned in the response's HTTP header in a web browser. For instance in our example, it was `/services/catalog/44dc84da101c4f9d9f751e38d9c4d97b`. The browser will display the catalog entry as XML in the browser. . Verify the catalog entry exists by executing a query via the OpenSearch endpoint. . Enter the following URL in a browser `/services/catalog/query?q=${branding-lowercase}`. A single result, in Atom format, should be returned. A resource can also be ingested with metacard metadata associated with it using the multipart/mixed content type. .Example ---- curl -k -X POST -i -H "Content-Type: multipart/mixed" -F parse.resource=@/path/to/resource -F parse.metadata=@/path/to/metacard ${secure_url}/services/catalog ---- More information about the ingest operations can be found in the ingest log. The default location of the log is `${home_directory}/data/log/ingest_error.log`.
{ "pile_set_name": "Github" }
/* * Copyright © 2014 Intel Corporation * * 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 (including the next * paragraph) 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. * * Generated by: intel-gpu-tools-1.19-177-g68e2eab2 */ #include "intel_renderstate.h" static const u32 gen9_null_state_relocs[] = { 0x000007a8, 0x000007b4, 0x000007bc, 0x000007cc, -1, }; static const u32 gen9_null_state_batch[] = { 0x7a000004, 0x01000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x69040300, 0x78140000, 0x04000000, 0x7820000a, 0x00000000, 0x00000000, 0x80000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x78130002, 0x00000000, 0x00000000, 0x02001808, 0x781f0004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x78510009, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x78100007, 0x00000000, 0x00000000, 0x00010000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x781b0007, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000800, 0x00000000, 0x78110008, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x781e0003, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x781d0009, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x78120002, 0x00000000, 0x00000000, 0x00000000, 0x78500003, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x781c0002, 0x00000000, 0x00000000, 0x00000000, 0x780c0000, 0x00000000, 0x78520003, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x78300000, 0x08010040, 0x78310000, 0x1e000000, 0x78320000, 0x1e000000, 0x78330000, 0x1e000000, 0x79190002, 0x00000000, 0x00000000, 0x00000000, 0x791a0002, 0x00000000, 0x00000000, 0x00000000, 0x791b0002, 0x00000000, 0x00000000, 0x00000000, 0x79120000, 0x00000000, 0x79130000, 0x00000000, 0x79140000, 0x00000000, 0x79150000, 0x00000000, 0x79160000, 0x00000000, 0x78150009, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x78190009, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x781a0009, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x78160009, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x78170009, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x78490001, 0x00000000, 0x00000000, 0x784a0000, 0x00000000, 0x784b0000, 0x00000004, 0x79170101, 0x00000000, 0x00000080, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x79180006, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x79180006, 0x20000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x79180006, 0x40000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x79180006, 0x60000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x61010011, 0x00000001, /* reloc */ 0x00000000, 0x00000000, 0x00000001, /* reloc */ 0x00000000, 0x00000001, /* reloc */ 0x00000000, 0x00000001, 0x00000000, 0x00000001, /* reloc */ 0x00000000, 0x00001001, 0x00001001, 0x00000001, 0x00001001, 0x00000000, 0x00000000, 0x00000000, 0x61020001, 0x00000000, 0x00000000, 0x79000002, 0x00000000, 0x00000000, 0x00000000, 0x78050006, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x79040002, 0x00000000, 0x00000000, 0x00000000, 0x79040002, 0x40000000, 0x00000000, 0x00000000, 0x79040002, 0x80000000, 0x00000000, 0x00000000, 0x79040002, 0xc0000000, 0x00000000, 0x00000000, 0x79080001, 0x00000000, 0x00000000, 0x790a0001, 0x00000000, 0x00000000, 0x78060003, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x78070003, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x78040001, 0x00000000, 0x00000000, 0x79110000, 0x00000000, 0x780d0000, 0x00000000, 0x79060000, 0x00000000, 0x7907001f, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x7902000f, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x790c000f, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x780a0003, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x78080083, 0x00004000, 0x00000000, 0x00000000, 0x00000000, 0x04004000, 0x00000000, 0x00000000, 0x00000000, 0x08004000, 0x00000000, 0x00000000, 0x00000000, 0x0c004000, 0x00000000, 0x00000000, 0x00000000, 0x10004000, 0x00000000, 0x00000000, 0x00000000, 0x14004000, 0x00000000, 0x00000000, 0x00000000, 0x18004000, 0x00000000, 0x00000000, 0x00000000, 0x1c004000, 0x00000000, 0x00000000, 0x00000000, 0x20004000, 0x00000000, 0x00000000, 0x00000000, 0x24004000, 0x00000000, 0x00000000, 0x00000000, 0x28004000, 0x00000000, 0x00000000, 0x00000000, 0x2c004000, 0x00000000, 0x00000000, 0x00000000, 0x30004000, 0x00000000, 0x00000000, 0x00000000, 0x34004000, 0x00000000, 0x00000000, 0x00000000, 0x38004000, 0x00000000, 0x00000000, 0x00000000, 0x3c004000, 0x00000000, 0x00000000, 0x00000000, 0x40004000, 0x00000000, 0x00000000, 0x00000000, 0x44004000, 0x00000000, 0x00000000, 0x00000000, 0x48004000, 0x00000000, 0x00000000, 0x00000000, 0x4c004000, 0x00000000, 0x00000000, 0x00000000, 0x50004000, 0x00000000, 0x00000000, 0x00000000, 0x54004000, 0x00000000, 0x00000000, 0x00000000, 0x58004000, 0x00000000, 0x00000000, 0x00000000, 0x5c004000, 0x00000000, 0x00000000, 0x00000000, 0x60004000, 0x00000000, 0x00000000, 0x00000000, 0x64004000, 0x00000000, 0x00000000, 0x00000000, 0x68004000, 0x00000000, 0x00000000, 0x00000000, 0x6c004000, 0x00000000, 0x00000000, 0x00000000, 0x70004000, 0x00000000, 0x00000000, 0x00000000, 0x74004000, 0x00000000, 0x00000000, 0x00000000, 0x78004000, 0x00000000, 0x00000000, 0x00000000, 0x7c004000, 0x00000000, 0x00000000, 0x00000000, 0x80004000, 0x00000000, 0x00000000, 0x00000000, 0x78090043, 0x02000000, 0x22220000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x78550003, 0x0000000f, 0x00000000, 0x00000000, 0x00000000, 0x680b0001, 0x780e0000, 0x00000e01, 0x78240000, 0x00000e41, 0x784f0000, 0x80000100, 0x784d0000, 0x40000000, 0x782b0000, 0x00000000, 0x782c0000, 0x00000000, 0x782d0000, 0x00000000, 0x782e0000, 0x00000000, 0x782f0000, 0x00000000, 0x780f0000, 0x00000000, 0x78230000, 0x00000ea0, 0x78210000, 0x00000ec0, 0x78260000, 0x00000000, 0x78270000, 0x00000000, 0x78280000, 0x00000000, 0x78290000, 0x00000000, 0x782a0000, 0x00000000, 0x7b000005, 0x00000004, 0x00000001, 0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x05000000, /* cmds end */ 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, /* state start */ 0x00000000, 0x3f800000, 0x3f800000, 0x3f800000, 0x3f800000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, /* state end */ }; RO_RENDERSTATE(9);
{ "pile_set_name": "Github" }
package handshake import "encoding/json" type strategy struct { Rendezvous storage Storage storage Cipher cipher } // strategyPeerConfig is a a struct that encapsulates the shared strategy settings for handshake type strategyPeerConfig struct { Rendezvous peerStorage `json:"rendezvous"` Storage peerStorage `json:"storage"` Cipher peerCipher `json:"cipher"` } // strategyConfig is a struct that encapsulates internal chat strategy settings type strategyConfig struct { Rendezvous storageConfig Storage storageConfig Cipher cipherConfig } // Share returns the strategyPeerConfig for the strategy func (s strategy) Share() (config strategyPeerConfig, err error) { if config.Rendezvous, err = s.Rendezvous.share(); err != nil { return } if config.Storage, err = s.Storage.share(); err != nil { return } if config.Cipher, err = s.Cipher.share(); err != nil { return } return } // Share returns the strategyPeerConfig for the strategy func (s strategy) Export() (config strategyConfig, err error) { if config.Rendezvous, err = s.Rendezvous.export(); err != nil { return } if config.Storage, err = s.Storage.export(); err != nil { return } if config.Cipher, err = s.Cipher.export(); err != nil { return } return } func strategyFromPeerConfig(config strategyPeerConfig) (s strategy, err error) { if s.Rendezvous, err = newStorageFromPeer(config.Rendezvous); err != nil { return } if s.Storage, err = newStorageFromPeer(config.Storage); err != nil { return } if s.Cipher, err = newCipherFromPeer(config.Cipher); err != nil { return } return } func strategyFromConfig(config strategyConfig) (s strategy, err error) { if s.Rendezvous, err = newStorageFromConfig(config.Rendezvous); err != nil { return } if s.Storage, err = newStorageFromConfig(config.Storage); err != nil { return } if s.Cipher, err = newCipherFromConfig(config.Cipher); err != nil { return } return } // ConfigJSONBytes marshall's the strategyPeerConfig as a json file func (s strategy) ShareJSONBytes() ([]byte, error) { config, err := s.Share() if err != nil { return []byte{}, err } return json.Marshal(config) } func newDefaultStrategy() strategy { return strategy{ Rendezvous: newDefaultRendezvous(), Storage: newDefaultMessageStorage(), Cipher: newDefaultCipher(), } }
{ "pile_set_name": "Github" }
// Copyright 2005-2009 Daniel James. // 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) #if !defined(BOOST_FUNCTIONAL_HASH_DETAIL_FLOAT_FUNCTIONS_HPP) #define BOOST_FUNCTIONAL_HASH_DETAIL_FLOAT_FUNCTIONS_HPP #include <boost/config.hpp> #if defined(BOOST_HAS_PRAGMA_ONCE) #pragma once #endif #include <boost/config/no_tr1/cmath.hpp> // Set BOOST_HASH_CONFORMANT_FLOATS to 1 for libraries known to have // sufficiently good floating point support to not require any // workarounds. // // When set to 0, the library tries to automatically // use the best available implementation. This normally works well, but // breaks when ambiguities are created by odd namespacing of the functions. // // Note that if this is set to 0, the library should still take full // advantage of the platform's floating point support. #if defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION) # define BOOST_HASH_CONFORMANT_FLOATS 0 #elif defined(__LIBCOMO__) # define BOOST_HASH_CONFORMANT_FLOATS 0 #elif defined(__STD_RWCOMPILER_H__) || defined(_RWSTD_VER) // Rogue Wave library: # define BOOST_HASH_CONFORMANT_FLOATS 0 #elif defined(_LIBCPP_VERSION) // libc++ # define BOOST_HASH_CONFORMANT_FLOATS 1 #elif defined(__GLIBCPP__) || defined(__GLIBCXX__) // GNU libstdc++ 3 # if defined(__GNUC__) && __GNUC__ >= 4 # define BOOST_HASH_CONFORMANT_FLOATS 1 # else # define BOOST_HASH_CONFORMANT_FLOATS 0 # endif #elif defined(__STL_CONFIG_H) // generic SGI STL # define BOOST_HASH_CONFORMANT_FLOATS 0 #elif defined(__MSL_CPP__) // MSL standard lib: # define BOOST_HASH_CONFORMANT_FLOATS 0 #elif defined(__IBMCPP__) // VACPP std lib (probably conformant for much earlier version). # if __IBMCPP__ >= 1210 # define BOOST_HASH_CONFORMANT_FLOATS 1 # else # define BOOST_HASH_CONFORMANT_FLOATS 0 # endif #elif defined(MSIPL_COMPILE_H) // Modena C++ standard library # define BOOST_HASH_CONFORMANT_FLOATS 0 #elif (defined(_YVALS) && !defined(__IBMCPP__)) || defined(_CPPLIB_VER) // Dinkumware Library (this has to appear after any possible replacement libraries): # if _CPPLIB_VER >= 405 # define BOOST_HASH_CONFORMANT_FLOATS 1 # else # define BOOST_HASH_CONFORMANT_FLOATS 0 # endif #else # define BOOST_HASH_CONFORMANT_FLOATS 0 #endif #if BOOST_HASH_CONFORMANT_FLOATS // The standard library is known to be compliant, so don't use the // configuration mechanism. namespace boost { namespace hash_detail { template <typename Float> struct call_ldexp { typedef Float float_type; inline Float operator()(Float x, int y) const { return std::ldexp(x, y); } }; template <typename Float> struct call_frexp { typedef Float float_type; inline Float operator()(Float x, int* y) const { return std::frexp(x, y); } }; template <typename Float> struct select_hash_type { typedef Float type; }; } } #else // BOOST_HASH_CONFORMANT_FLOATS == 0 // The C++ standard requires that the C float functions are overloarded // for float, double and long double in the std namespace, but some of the older // library implementations don't support this. On some that don't, the C99 // float functions (frexpf, frexpl, etc.) are available. // // The following tries to automatically detect which are available. namespace boost { namespace hash_detail { // Returned by dummy versions of the float functions. struct not_found { // Implicitly convertible to float and long double in order to avoid // a compile error when the dummy float functions are used. inline operator float() const { return 0; } inline operator long double() const { return 0; } }; // A type for detecting the return type of functions. template <typename T> struct is; template <> struct is<float> { char x[10]; }; template <> struct is<double> { char x[20]; }; template <> struct is<long double> { char x[30]; }; template <> struct is<boost::hash_detail::not_found> { char x[40]; }; // Used to convert the return type of a function to a type for sizeof. template <typename T> is<T> float_type(T); // call_ldexp // // This will get specialized for float and long double template <typename Float> struct call_ldexp { typedef double float_type; inline double operator()(double a, int b) const { using namespace std; return ldexp(a, b); } }; // call_frexp // // This will get specialized for float and long double template <typename Float> struct call_frexp { typedef double float_type; inline double operator()(double a, int* b) const { using namespace std; return frexp(a, b); } }; } } // A namespace for dummy functions to detect when the actual function we want // isn't available. ldexpl, ldexpf etc. might be added tby the macros below. // // AFAICT these have to be outside of the boost namespace, as if they're in // the boost namespace they'll always be preferable to any other function // (since the arguments are built in types, ADL can't be used). namespace boost_hash_detect_float_functions { template <class Float> boost::hash_detail::not_found ldexp(Float, int); template <class Float> boost::hash_detail::not_found frexp(Float, int*); } // Macros for generating specializations of call_ldexp and call_frexp. // // check_cpp and check_c99 check if the C++ or C99 functions are available. // // Then the call_* functions select an appropriate implementation. // // I used c99_func in a few places just to get a unique name. // // Important: when using 'using namespace' at namespace level, include as // little as possible in that namespace, as Visual C++ has an odd bug which // can cause the namespace to be imported at the global level. This seems to // happen mainly when there's a template in the same namesapce. #define BOOST_HASH_CALL_FLOAT_FUNC(cpp_func, c99_func, type1, type2) \ namespace boost_hash_detect_float_functions { \ template <class Float> \ boost::hash_detail::not_found c99_func(Float, type2); \ } \ \ namespace boost { \ namespace hash_detail { \ namespace c99_func##_detect { \ using namespace std; \ using namespace boost_hash_detect_float_functions; \ \ struct check { \ static type1 x; \ static type2 y; \ BOOST_STATIC_CONSTANT(bool, cpp = \ sizeof(float_type(cpp_func(x,y))) \ == sizeof(is<type1>)); \ BOOST_STATIC_CONSTANT(bool, c99 = \ sizeof(float_type(c99_func(x,y))) \ == sizeof(is<type1>)); \ }; \ } \ \ template <bool x> \ struct call_c99_##c99_func : \ boost::hash_detail::call_##cpp_func<double> {}; \ \ template <> \ struct call_c99_##c99_func<true> { \ typedef type1 float_type; \ \ template <typename T> \ inline type1 operator()(type1 a, T b) const \ { \ using namespace std; \ return c99_func(a, b); \ } \ }; \ \ template <bool x> \ struct call_cpp_##c99_func : \ call_c99_##c99_func< \ ::boost::hash_detail::c99_func##_detect::check::c99 \ > {}; \ \ template <> \ struct call_cpp_##c99_func<true> { \ typedef type1 float_type; \ \ template <typename T> \ inline type1 operator()(type1 a, T b) const \ { \ using namespace std; \ return cpp_func(a, b); \ } \ }; \ \ template <> \ struct call_##cpp_func<type1> : \ call_cpp_##c99_func< \ ::boost::hash_detail::c99_func##_detect::check::cpp \ > {}; \ } \ } #define BOOST_HASH_CALL_FLOAT_MACRO(cpp_func, c99_func, type1, type2) \ namespace boost { \ namespace hash_detail { \ \ template <> \ struct call_##cpp_func<type1> { \ typedef type1 float_type; \ inline type1 operator()(type1 x, type2 y) const { \ return c99_func(x, y); \ } \ }; \ } \ } #if defined(ldexpf) BOOST_HASH_CALL_FLOAT_MACRO(ldexp, ldexpf, float, int) #else BOOST_HASH_CALL_FLOAT_FUNC(ldexp, ldexpf, float, int) #endif #if defined(ldexpl) BOOST_HASH_CALL_FLOAT_MACRO(ldexp, ldexpl, long double, int) #else BOOST_HASH_CALL_FLOAT_FUNC(ldexp, ldexpl, long double, int) #endif #if defined(frexpf) BOOST_HASH_CALL_FLOAT_MACRO(frexp, frexpf, float, int*) #else BOOST_HASH_CALL_FLOAT_FUNC(frexp, frexpf, float, int*) #endif #if defined(frexpl) BOOST_HASH_CALL_FLOAT_MACRO(frexp, frexpl, long double, int*) #else BOOST_HASH_CALL_FLOAT_FUNC(frexp, frexpl, long double, int*) #endif #undef BOOST_HASH_CALL_FLOAT_MACRO #undef BOOST_HASH_CALL_FLOAT_FUNC namespace boost { namespace hash_detail { template <typename Float1, typename Float2> struct select_hash_type_impl { typedef double type; }; template <> struct select_hash_type_impl<float, float> { typedef float type; }; template <> struct select_hash_type_impl<long double, long double> { typedef long double type; }; // select_hash_type // // If there is support for a particular floating point type, use that // otherwise use double (there's always support for double). template <typename Float> struct select_hash_type : select_hash_type_impl< BOOST_DEDUCED_TYPENAME call_ldexp<Float>::float_type, BOOST_DEDUCED_TYPENAME call_frexp<Float>::float_type > {}; } } #endif // BOOST_HASH_CONFORMANT_FLOATS #endif
{ "pile_set_name": "Github" }
@echo off echo Generating x86 assember echo Bignum cd crypto\bn\asm perl x86.pl win32n > bn-win32.asm cd ..\..\.. echo DES cd crypto\des\asm perl des-586.pl win32n > d-win32.asm cd ..\..\.. echo "crypt(3)" cd crypto\des\asm perl crypt586.pl win32n > y-win32.asm cd ..\..\.. echo Blowfish cd crypto\bf\asm perl bf-586.pl win32n > b-win32.asm cd ..\..\.. echo CAST5 cd crypto\cast\asm perl cast-586.pl win32n > c-win32.asm cd ..\..\.. echo RC4 cd crypto\rc4\asm perl rc4-586.pl win32n > r4-win32.asm cd ..\..\.. echo MD5 cd crypto\md5\asm perl md5-586.pl win32n > m5-win32.asm cd ..\..\.. echo SHA1 cd crypto\sha\asm perl sha1-586.pl win32n > s1-win32.asm cd ..\..\.. echo RIPEMD160 cd crypto\ripemd\asm perl rmd-586.pl win32n > rm-win32.asm cd ..\..\.. echo RC5\32 cd crypto\rc5\asm perl rc5-586.pl win32n > r5-win32.asm cd ..\..\.. echo on
{ "pile_set_name": "Github" }
auto Emulator::attach(higan::Node::Object node) -> void { if(interface && node->is<higan::Node::Screen>()) { screens = root->find<higan::Node::Screen>(); } if(interface && node->is<higan::Node::Stream>()) { streams = root->find<higan::Node::Stream>(); } } auto Emulator::detach(higan::Node::Object node) -> void { if(interface && node->is<higan::Node::Screen>()) { screens = root->find<higan::Node::Screen>(); } if(interface && node->is<higan::Node::Stream>()) { streams = root->find<higan::Node::Stream>(); } if(auto location = node->attribute("location")) { file::write({location, "settings.bml"}, node->save()); } } auto Emulator::open(higan::Node::Object node, string name, vfs::file::mode mode, bool required) -> shared_pointer<vfs::file> { auto location = node->attribute("location"); if(name == "manifest.bml") { if(!file::exists({location, name}) && directory::exists(location)) { if(auto manifest = execute("icarus", "--system", node->name(), "--manifest", location).output) { return vfs::memory::open(manifest.data<uint8_t>(), manifest.size()); } } } if(auto result = vfs::disk::open({location, name}, mode)) return result; if(required) { //attempt to pull required system firmware (boot ROMs, etc) from system template if(location == emulator.system.data) { if(file::exists({emulator.system.templates, name})) { file::copy({emulator.system.templates, name}, {emulator.system.data, name}); if(auto result = vfs::disk::open({location, name}, mode)) return result; } } if(MessageDialog() .setTitle("Warning") .setText({"Missing required file:\n", location, name, "\n\n", "Would you like to browse for this file now?"}) .setAlignment(Alignment::Center) .question() == "No") return {}; if(auto source = BrowserDialog() .setTitle({"Load ", name}) .setPath(location) .setAlignment(Alignment::Center) .openFile() ) { if(auto input = vfs::memory::open(source, true)) { if(auto output = file::open({location, name}, file::mode::write)) { output.write({input->data(), (uint)input->size()}); } } if(auto result = vfs::disk::open({location, name}, mode)) return result; } } return {}; } auto Emulator::event(higan::Event event) -> void { if(event == higan::Event::Power) { events.power = true; } } auto Emulator::log(string_view message) -> void { if(!system.log) { directory::create({"/tmp/Logs/", system.name, "/"}); string datetime = chrono::local::datetime().transform("-: ", " _").replace(" ", ""); system.log.open({"/tmp/Logs/", system.name, "/event-", datetime, ".log"}, file::mode::write); } system.log.print(message); } auto Emulator::video(higan::Node::Screen node, const uint32_t* data, uint pitch, uint width, uint height) -> void { if(requests.captureScreenshot) { requests.captureScreenshot = false; captureScreenshot(data, pitch, width, height); } uint videoWidth = node->width() * node->scaleX(); uint videoHeight = node->height() * node->scaleY(); if(settings.video.aspectCorrection) { videoWidth = videoWidth * node->aspectX() / node->aspectY(); } if(node->rotation() == 90 || node->rotation() == 270) { swap(videoWidth, videoHeight); } auto [viewportWidth, viewportHeight] = videoInstance.size(); uint multiplierX = viewportWidth / videoWidth; uint multiplierY = viewportHeight / videoHeight; uint multiplier = min(multiplierX, multiplierY); uint outputWidth = videoWidth * multiplier; uint outputHeight = videoHeight * multiplier; if(multiplier == 0 || settings.video.output == "Scale") { float multiplierX = (float)viewportWidth / (float)videoWidth; float multiplierY = (float)viewportHeight / (float)videoHeight; float multiplier = min(multiplierX, multiplierY); outputWidth = videoWidth * multiplier; outputHeight = videoHeight * multiplier; } if(settings.video.output == "Stretch") { outputWidth = viewportWidth; outputHeight = viewportHeight; } pitch >>= 2; if(auto [output, length] = videoInstance.acquire(width, height); output) { length >>= 2; for(auto y : range(height)) { memory::copy<uint32>(output + y * length, data + y * pitch, width); } videoInstance.release(); videoInstance.output(outputWidth, outputHeight); } static uint frameCounter = 0; static uint64_t previous, current; frameCounter++; current = chrono::timestamp(); if(current != previous) { previous = current; setCaption({frameCounter, " fps"}); frameCounter = 0; } } auto Emulator::audio(higan::Node::Stream) -> void { if(!streams) return; //should never occur //process all pending frames (there may be more than one waiting) while(true) { //only process a frame if all streams have at least one pending frame for(auto& stream : streams) { if(!stream->pending()) return; } //mix all frames together double samples[2] = {0.0, 0.0}; for(auto& stream : streams) { double buffer[2]; uint channels = stream->read(buffer); if(channels == 1) { //monaural -> stereo mixing samples[0] += buffer[0]; samples[1] += buffer[0]; } else { //stereo mixing samples[0] += buffer[0]; samples[1] += buffer[1]; } } //apply volume, balance, and clamping to the output frame double volume = !settings.audio.mute ? settings.audio.volume : 0.0; double balance = settings.audio.balance; for(uint c : range(2)) { samples[c] = max(-1.0, min(+1.0, samples[c] * volume)); if(balance < 0.0) samples[1] *= 1.0 + balance; if(balance > 0.0) samples[0] *= 1.0 - balance; } //send frame to the audio output device audioInstance.output(samples); } } auto Emulator::input(higan::Node::Input input) -> void { inputManager.poll(); bool allow = program.viewport.focused(); if(settings.input.unfocused == "Allow") allow = true; if(videoInstance.exclusive()) allow = true; if(auto button = input->cast<higan::Node::Button>()) { button->setValue(0); if(auto instance = button->attribute<shared_pointer<InputButton>>("instance")) { if(allow) button->setValue(instance->value()); } } if(auto axis = input->cast<higan::Node::Axis>()) { axis->setValue(0); if(auto instance = axis->attribute<shared_pointer<InputAxis>>("instance")) { if(allow) axis->setValue(instance->value()); } } }
{ "pile_set_name": "Github" }
var convert = require('./convert'), func = convert('toLower', require('../toLower'), require('./_falseOptions')); func.placeholder = require('./placeholder'); module.exports = func;
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: faea95117e191814893c0ab3c089a552 TextureImporter: fileIDToRecycleName: {} externalObjects: {} serializedVersion: 5 mipmaps: mipMapMode: 0 enableMipMap: 1 sRGBTexture: 1 linearTexture: 0 fadeOut: 0 borderMipMap: 0 mipMapsPreserveCoverage: 0 alphaTestReferenceValue: 0.5 mipMapFadeDistanceStart: 1 mipMapFadeDistanceEnd: 3 bumpmap: convertToNormalMap: 0 externalNormalMap: 0 heightScale: 0.25 normalMapFilter: 0 isReadable: 0 grayScaleToAlpha: 0 generateCubemap: 6 cubemapConvolution: 0 seamlessCubemap: 0 textureFormat: 1 maxTextureSize: 2048 textureSettings: serializedVersion: 2 filterMode: -1 aniso: -1 mipBias: -1 wrapU: -1 wrapV: -1 wrapW: -1 nPOTScale: 1 lightmap: 0 compressionQuality: 50 spriteMode: 0 spriteExtrude: 1 spriteMeshType: 1 alignment: 0 spritePivot: {x: 0.5, y: 0.5} spritePixelsToUnits: 100 spriteBorder: {x: 0, y: 0, z: 0, w: 0} spriteGenerateFallbackPhysicsShape: 1 alphaUsage: 1 alphaIsTransparency: 0 spriteTessellationDetail: -1 textureType: 0 textureShape: 1 singleChannelComponent: 0 maxTextureSizeSet: 0 compressionQualitySet: 0 textureFormatSet: 0 platformSettings: - serializedVersion: 2 buildTarget: DefaultTexturePlatform maxTextureSize: 2048 resizeAlgorithm: 0 textureFormat: -1 textureCompression: 1 compressionQuality: 50 crunchedCompression: 0 allowsAlphaSplitting: 0 overridden: 0 androidETC2FallbackOverride: 0 spriteSheet: serializedVersion: 2 sprites: [] outline: [] physicsShape: [] bones: [] spriteID: vertices: [] indices: edges: [] weights: [] spritePackingTag: userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
// Code generated by linux/mkall.go generatePtracePair("386", "amd64"). DO NOT EDIT. // +build linux // +build 386 amd64 package unix import "unsafe" // PtraceRegs386 is the registers used by 386 binaries. type PtraceRegs386 struct { Ebx int32 Ecx int32 Edx int32 Esi int32 Edi int32 Ebp int32 Eax int32 Xds int32 Xes int32 Xfs int32 Xgs int32 Orig_eax int32 Eip int32 Xcs int32 Eflags int32 Esp int32 Xss int32 } // PtraceGetRegs386 fetches the registers used by 386 binaries. func PtraceGetRegs386(pid int, regsout *PtraceRegs386) error { return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout))) } // PtraceSetRegs386 sets the registers used by 386 binaries. func PtraceSetRegs386(pid int, regs *PtraceRegs386) error { return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs))) } // PtraceRegsAmd64 is the registers used by amd64 binaries. type PtraceRegsAmd64 struct { R15 uint64 R14 uint64 R13 uint64 R12 uint64 Rbp uint64 Rbx uint64 R11 uint64 R10 uint64 R9 uint64 R8 uint64 Rax uint64 Rcx uint64 Rdx uint64 Rsi uint64 Rdi uint64 Orig_rax uint64 Rip uint64 Cs uint64 Eflags uint64 Rsp uint64 Ss uint64 Fs_base uint64 Gs_base uint64 Ds uint64 Es uint64 Fs uint64 Gs uint64 } // PtraceGetRegsAmd64 fetches the registers used by amd64 binaries. func PtraceGetRegsAmd64(pid int, regsout *PtraceRegsAmd64) error { return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout))) } // PtraceSetRegsAmd64 sets the registers used by amd64 binaries. func PtraceSetRegsAmd64(pid int, regs *PtraceRegsAmd64) error { return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs))) }
{ "pile_set_name": "Github" }
{ "name": "gtkextra", "full_name": "gtkextra", "oldname": null, "aliases": [ ], "versioned_formulae": [ ], "desc": "Widgets for creating GUIs for GTK+", "license": null, "homepage": "https://gtkextra.sourceforge.io/", "versions": { "stable": "3.3.4", "head": null, "bottle": true }, "urls": { "stable": { "url": "https://downloads.sourceforge.net/project/gtkextra/3.3/gtkextra-3.3.4.tar.gz", "tag": null, "revision": null } }, "revision": 2, "version_scheme": 0, "bottle": { "stable": { "rebuild": 1, "cellar": ":any", "prefix": "/home/linuxbrew/.linuxbrew", "root_url": "https://linuxbrew.bintray.com/bottles", "files": { "catalina": { "url": "https://linuxbrew.bintray.com/bottles/gtkextra-3.3.4_2.catalina.bottle.1.tar.gz", "sha256": "06663d6dcee70c6a18e9b29a32df23a6ac513c071f109ca190bc5ec3b7c2d0dd" }, "mojave": { "url": "https://linuxbrew.bintray.com/bottles/gtkextra-3.3.4_2.mojave.bottle.1.tar.gz", "sha256": "c38010856fc21985142ce72c0b07be8aba4d8b2d24e7a29fee497383d131efbc" }, "high_sierra": { "url": "https://linuxbrew.bintray.com/bottles/gtkextra-3.3.4_2.high_sierra.bottle.1.tar.gz", "sha256": "a18ed1a1fe359d9572ac5f334b522b175c0309168dbe1274f25884f9d062282e" }, "sierra": { "url": "https://linuxbrew.bintray.com/bottles/gtkextra-3.3.4_2.sierra.bottle.1.tar.gz", "sha256": "021592c075825331cf707f79c010fa75f1e688f821acfe167543236f8cdcc556" }, "x86_64_linux": { "url": "https://linuxbrew.bintray.com/bottles/gtkextra-3.3.4_2.x86_64_linux.bottle.1.tar.gz", "sha256": "cc74372f074fcc08530dcf52dcbfdb7f9250a5f1596a6907dd820bd7f222062d" } } } }, "keg_only": false, "bottle_disabled": false, "options": [ ], "build_dependencies": [ "pkg-config" ], "dependencies": [ "gtk+" ], "recommended_dependencies": [ ], "optional_dependencies": [ ], "uses_from_macos": [ ], "requirements": [ ], "conflicts_with": [ ], "caveats": null, "installed": [ ], "linked_keg": null, "pinned": false, "outdated": false, "deprecated": false, "disabled": false }
{ "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_222) on Wed Aug 14 11:24:52 AEST 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.eclipse.rdf4j.model.util.Statements (RDF4J 2.5.4 API)</title> <meta name="date" content="2019-08-14"> <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 Class org.eclipse.rdf4j.model.util.Statements (RDF4J 2.5.4 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="../../../../../../org/eclipse/rdf4j/model/util/Statements.html" title="class in org.eclipse.rdf4j.model.util">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> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/eclipse/rdf4j/model/util/class-use/Statements.html" target="_top">Frames</a></li> <li><a href="Statements.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;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 Class org.eclipse.rdf4j.model.util.Statements" class="title">Uses of Class<br>org.eclipse.rdf4j.model.util.Statements</h2> </div> <div class="classUseContainer">No usage of org.eclipse.rdf4j.model.util.Statements</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="../../../../../../org/eclipse/rdf4j/model/util/Statements.html" title="class in org.eclipse.rdf4j.model.util">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> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/eclipse/rdf4j/model/util/class-use/Statements.html" target="_top">Frames</a></li> <li><a href="Statements.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;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 ======= --> <p class="legalCopy"><small>Copyright &#169; 2015-2019 <a href="https://www.eclipse.org/">Eclipse Foundation</a>. All Rights Reserved.</small></p> </body> </html>
{ "pile_set_name": "Github" }
# func Sprintln(a ...interface{}) string 参数列表 - a... 值变量列表 返回值: - 返回打印字符串 功能说明: 这个函数主要是用来根据默认格式字符串和参数表生成一个打印字符串并带换行 代码实例: package main import "fmt" func main() { fmt.Sprintln("默认格式打印出字符串并带换行!") }
{ "pile_set_name": "Github" }
/** \page plans Plans \tableofcontents No specific plans at the moment. */
{ "pile_set_name": "Github" }
<?php namespace Bitrix\Conversion; final class RateManager extends Internals\TypeManager { static protected $event = 'OnGetRateTypes'; static protected $types = array(); static protected $ready = false; static protected $checkModule = true; /** @internal */ static public function getRatesCounters(array $types) { $counters = array(); foreach ($types as $type) { $counters = array_merge($counters, $type['COUNTERS']); } return array_unique($counters); } static public function getRatesCalculated(array $types, array $counters) { $rates = array(); foreach ($types as $name => $type) { $rates[$name] = $type['CALCULATE']($counters); } return $rates; } }
{ "pile_set_name": "Github" }
/** * Copyright (c) 2017-present, zhenglibao, Inc. * email: [email protected] * All rights reserved. * * This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. */ #import "UITextField+Flex.h" #import "UIView+Flex.h" #import <objc/runtime.h> #import "../FlexUtils.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunguarded-availability" static NameValue _align[] = { {"left", NSTextAlignmentLeft}, {"center", NSTextAlignmentCenter}, {"right", NSTextAlignmentRight}, {"justified", NSTextAlignmentJustified}, {"natural", NSTextAlignmentNatural}, }; static NameValue _gBorderStyle[] = { {"none", UITextBorderStyleNone}, {"line", UITextBorderStyleLine}, {"bezel", UITextBorderStyleBezel}, {"roundRect", UITextBorderStyleRoundedRect}, }; static NameValue _gKeyboardType[] = { {"default", UIKeyboardTypeDefault}, {"asciiCapable", UIKeyboardTypeASCIICapable}, {"numberAndPunct", UIKeyboardTypeNumbersAndPunctuation}, {"url", UIKeyboardTypeURL}, {"numberPad", UIKeyboardTypeNumberPad}, {"phonePad", UIKeyboardTypePhonePad}, {"namePhonePad", UIKeyboardTypeNamePhonePad}, {"emailAddress", UIKeyboardTypeEmailAddress}, {"decimalPad", UIKeyboardTypeDecimalPad}, {"twitter", UIKeyboardTypeTwitter}, {"webSearch", UIKeyboardTypeWebSearch}, {"asciiCapableNumberPad", UIKeyboardTypeASCIICapableNumberPad}, }; static NameValue _gTextFieldMode[] = { {"never", UITextFieldViewModeNever}, {"whileEditing", UITextFieldViewModeWhileEditing}, {"unlessEditing", UITextFieldViewModeUnlessEditing}, {"always", UITextFieldViewModeAlways}, }; static NameValue _gAutocaptializationType[] = { {"none", UITextAutocapitalizationTypeNone}, {"words", UITextAutocapitalizationTypeWords}, {"sentences", UITextAutocapitalizationTypeSentences}, {"allCharacters", UITextAutocapitalizationTypeAllCharacters}, }; static NameValue _gAutocorrectionType[] = { {"default", UITextAutocorrectionTypeDefault}, {"no", UITextAutocorrectionTypeNo}, {"yes", UITextAutocorrectionTypeYes}, }; static NameValue _gSpellCheckType[] = { {"default", UITextSpellCheckingTypeDefault}, {"no", UITextSpellCheckingTypeNo}, {"yes", UITextSpellCheckingTypeYes}, }; static NameValue _gKeyboardAppearance[] = { {"default", UIKeyboardAppearanceDefault}, {"dark", UIKeyboardAppearanceDark}, {"light", UIKeyboardAppearanceLight}, {"alert", UIKeyboardAppearanceAlert}, }; static NameValue _gReturnKeyType[] = { {"default", UIReturnKeyDefault}, {"go", UIReturnKeyGo}, {"google", UIReturnKeyGoogle}, {"join", UIReturnKeyJoin}, {"next", UIReturnKeyNext}, {"route", UIReturnKeyRoute}, {"search", UIReturnKeySearch}, {"send", UIReturnKeySend}, {"yahoo", UIReturnKeyYahoo}, {"done", UIReturnKeyDone}, {"emergencyCall", UIReturnKeyEmergencyCall}, {"continue", UIReturnKeyContinue}, }; @implementation UITextField (Flex) FLEXSET(text) { self.text = sValue ; } //暂时保留兼容老版本 FLEXSET(placeHolder) { self.placeholder = sValue ; } FLEXSET(placeholder) { self.placeholder = sValue ; } FLEXSET(fontSize) { float nSize = [sValue floatValue]; if(nSize > 0){ UIFont* font = [UIFont systemFontOfSize:nSize]; self.font = font; } } FLEXSET(color) { UIColor* clr = colorFromString(sValue,owner); if(clr!=nil){ self.textColor = clr ; } } FLEXSET(textAlign) { self.textAlignment = (NSTextAlignment)NSString2Int(sValue, _align, sizeof(_align)/sizeof(NameValue)); } FLEXSET(boderStyle) { self.borderStyle = (UITextBorderStyle)NSString2Int(sValue, _gBorderStyle, sizeof(_gBorderStyle)/sizeof(NameValue)); } FLEXSET(interactEnable) { self.userInteractionEnabled = String2BOOL(sValue); } FLEXSET(adjustFontSize) { self.adjustsFontSizeToFitWidth = String2BOOL(sValue); } FLEXSETENUM(autocapitalizationType, _gAutocaptializationType) FLEXSETENUM(autocorrectionType, _gAutocorrectionType) FLEXSETENUM(spellCheckingType, _gSpellCheckType) FLEXSETBOOL(secureTextEntry) FLEXSETENUM(keyboardType, _gKeyboardType) FLEXSETENUM(keyboardAppearance, _gKeyboardAppearance) FLEXSETENUM(returnKeyType, _gReturnKeyType) FLEXSETENUM(clearButtonMode, _gTextFieldMode) FLEXSETBOOL(enablesReturnKeyAutomatically) FLEXSETENUM(leftViewMode, _gTextFieldMode) FLEXSETENUM(rightViewMode, _gTextFieldMode) FLEXSET(value) { self.text = sValue; } @end #pragma clang diagnostic pop
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace Aga.Controls.Threading { public sealed class WorkItem { private WaitCallback _callback; private object _state; private ExecutionContext _ctx; internal WorkItem(WaitCallback wc, object state, ExecutionContext ctx) { _callback = wc; _state = state; _ctx = ctx; } internal WaitCallback Callback { get { return _callback; } } internal object State { get { return _state; } } internal ExecutionContext Context { get { return _ctx; } } } }
{ "pile_set_name": "Github" }
[colors] # Base16 Brewer # Author: Timothée Poisot (http://github.com/tpoisot) foreground = #b7b8b9 foreground_bold = #b7b8b9 cursor = #b7b8b9 cursor_foreground = #0c0d0e background = #0c0d0e # 16 color space # Black, Gray, Silver, White color0 = #0c0d0e color8 = #737475 color7 = #b7b8b9 color15 = #fcfdfe # Red color1 = #e31a1c color9 = #e31a1c # Green color2 = #31a354 color10 = #31a354 # Yellow color3 = #dca060 color11 = #dca060 # Blue color4 = #3182bd color12 = #3182bd # Purple color5 = #756bb1 color13 = #756bb1 # Teal color6 = #80b1d3 color14 = #80b1d3 # Extra colors color16 = #e6550d color17 = #b15928 color18 = #2e2f30 color19 = #515253 color20 = #959697 color21 = #dadbdc
{ "pile_set_name": "Github" }
set(spacegroup_srcs spacegroup.cpp ) set(spacegroup_uis ) avogadro_plugin(SpaceGroup "Space group features for crystals." ExtensionPlugin spacegroup.h SpaceGroup "${spacegroup_srcs}" "${spacegroup_uis}" )
{ "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. using System; using System.IO.Pipes; using System.Threading; using System.Threading.Tasks; namespace Thrift.Transports.Server { // ReSharper disable once InconsistentNaming public class TNamedPipeServerTransport : TServerTransport { /// <summary> /// This is the address of the Pipe on the localhost. /// </summary> private readonly string _pipeAddress; private bool _asyncMode = true; private volatile bool _isPending = true; private NamedPipeServerStream _stream = null; public TNamedPipeServerTransport(string pipeAddress) { _pipeAddress = pipeAddress; } public override void Listen() { // nothing to do here } public override void Close() { if (_stream != null) { try { //TODO: check for disconection _stream.Disconnect(); _stream.Dispose(); } finally { _stream = null; _isPending = false; } } } public override bool IsClientPending() { return _isPending; } private void EnsurePipeInstance() { if (_stream == null) { var direction = PipeDirection.InOut; var maxconn = 254; var mode = PipeTransmissionMode.Byte; var options = _asyncMode ? PipeOptions.Asynchronous : PipeOptions.None; var inbuf = 4096; var outbuf = 4096; // TODO: security try { _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf); } catch (NotImplementedException) // Mono still does not support async, fallback to sync { if (_asyncMode) { options &= (~PipeOptions.Asynchronous); _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf); _asyncMode = false; } else { throw; } } } } protected override async Task<TClientTransport> AcceptImplementationAsync(CancellationToken cancellationToken) { try { EnsurePipeInstance(); await _stream.WaitForConnectionAsync(cancellationToken); var trans = new ServerTransport(_stream); _stream = null; // pass ownership to ServerTransport //_isPending = false; return trans; } catch (TTransportException) { Close(); throw; } catch (Exception e) { Close(); throw new TTransportException(TTransportException.ExceptionType.NotOpen, e.Message); } } private class ServerTransport : TClientTransport { private readonly NamedPipeServerStream _stream; public ServerTransport(NamedPipeServerStream stream) { _stream = stream; } public override bool IsOpen => _stream != null && _stream.IsConnected; public override async Task OpenAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override void Close() { _stream?.Dispose(); } public override async Task<int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { if (_stream == null) { throw new TTransportException(TTransportException.ExceptionType.NotOpen); } return await _stream.ReadAsync(buffer, offset, length, cancellationToken); } public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { if (_stream == null) { throw new TTransportException(TTransportException.ExceptionType.NotOpen); } await _stream.WriteAsync(buffer, offset, length, cancellationToken); } public override async Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } protected override void Dispose(bool disposing) { _stream?.Dispose(); } } } }
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright (c) 1991, 2014 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ * or the Apache License, Version 2.0 which accompanies this distribution and * is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following * Secondary Licenses when the conditions for such availability set * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU * General Public License, version 2 with the GNU Classpath * Exception [1] and GNU General Public License, version 2 with the * OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ #ifndef jnicheck_h #define jnicheck_h #include "jnichk_internal.h" IDATA J9VMDllMain(J9JavaVM* vm, IDATA stage, void* reserved); #endif /* jnicheck_h */
{ "pile_set_name": "Github" }
"2.title" = "Preferences"; "95.label" = "Key server"; "95.paletteLabel" = "Key server"; "96.label" = "Updates"; "96.paletteLabel" = "Updates"; "2ej-dR-Wsz.title" = "Include beta builds"; "3hc-yG-IHp.title" = "When no key is found on keys.openpgp.org continue search using the old key servers."; "6Ga-Wh-yR1.title" = "Use old key servers as fallback"; "6dC-8Q-OUi.title" = "Secring:"; "V9B-OJ-uc3.title" = "Beta builds are published more often. New features and improvements are less tested."; "VZM-cX-rx2.title" = "Move secring"; "YLF-tV-RRH.title" = "Check Now"; "YlP-Zk-RFe.label" = "Keyring"; "YlP-Zk-RFe.paletteLabel" = "Keyring"; "bRS-kx-SJ7.title" = "Automatically check for updates"; "dgp-VD-IvJ.title" = "Bla bla bla"; "eD7-Sw-uHU.title" = "Show Release Notes"; "u5F-TJ-cmV.title" = "Show revoked and expired keys in search results";
{ "pile_set_name": "Github" }
local capi = {tag=tag,mouse=mouse,screen=screen} local setmetatable = setmetatable local tag = require( "awful.tag" ) local config = require( "forgotten" ) local wibox = require( "wibox" ) local color = require( "gears.color" ) local radical = require( "radical" ) local data = {} local aTagMenu = nil local items = {} local function get_icon(state) if state == "locked" then return config.iconPath .. "locked.png" elseif state == "exclusive" then return config.iconPath .. "exclusive.png" elseif state == "fallback" then return config.iconPath .. "fallback.png" elseif state == "inclusive" then return config.iconPath .. "inclusive.png" end end local function get_state(t) local locked = tag.getproperty(t,"locked") and "locked" local exclusive = tag.getproperty(t,"exclusive") and "exclusive" local fallback = tag.getproperty(t,"fallback") and "fallback" return fallback or locked or exclusive or "inclusive" end local function toggleVisibility(t,state) if not t or not t.selected or not data[t.screen] then return end local w = data[t.screen] if w and t.selected then w.icon = color.apply_mask(get_icon(state or get_state(t))) end end local function next_state(t) local state = get_state(t) if state == "locked" then --Exclusive tag.setproperty(t,"locked" ,false ) tag.setproperty(t,"exclusive",true ) tag.setproperty(t,"fallback" ,false ) elseif state == "exclusive" then --Fallback tag.setproperty(t,"locked" ,false ) tag.setproperty(t,"exclusive",false ) tag.setproperty(t,"fallback" ,true ) elseif state == "fallback" then -- Inclusive tag.setproperty(t,"locked" ,false ) tag.setproperty(t,"exclusive",false ) tag.setproperty(t,"fallback" ,false ) elseif state == "inclusive" then -- Locked tag.setproperty(t,"locked" ,true ) tag.setproperty(t,"exclusive",false ) tag.setproperty(t,"fallback" ,false ) end toggleVisibility(t) end local function select_next() local t = capi.mouse.screen.selected_tag next_state(t) local state = get_state(t) items[state].selected = true return true end local function hide(m) m.visible = false return false end local function show_menu(t) local t = t or capi.screen[capi.mouse.screen].selected_tag if not aTagMenu then aTagMenu = radical.box { layout=radical.layout.horizontal, item_width=140, item_height=140, icon_size=100, item_style=radical.item.style.rounded, item_layout = radical.item.layout.icon, } aTagMenu.margins.left = 10 aTagMenu.margins.right = 5 items.locked = aTagMenu:add_item({text = "<b>Locked</b>" ,icon =config.iconPath .. "locked.png",button1=function() capi.client.focus = v end}) items.exclusive = aTagMenu:add_item({text = "<b>Exclusive</b>",icon =config.iconPath .. "exclusive.png",button1=function() capi.client.focus = v end}) items.fallback = aTagMenu:add_item({text = "<b>Fallback</b>" ,icon =config.iconPath .. "fallback.png",button1=function() capi.client.focus = v end}) items.inclusive = aTagMenu:add_item({text = "<b>Inclusive</b>",icon =config.iconPath .. "inclusive.png",button1=function() capi.client.focus = v end}) aTagMenu:add_key_hook({}, "Tab", "press", select_next) aTagMenu:add_key_hook({}, "Control_L", "release", hide) aTagMenu:add_key_hook({}, "Mod4", "release", hide) end local state = get_state(t) items[state].selected = true aTagMenu.visible = true return aTagMenu end local function new(screen, parent_menu) local screen = screen or 1 if data[capi.screen[screen]] then return data[capi.screen[screen]] end local t = capi.screen[screen].selected_tag local function btn() local t = capi.screen[screen].selected_tag next_state(t) end if not parent_menu then return end local item = parent_menu:add_item { tooltip = "Tag state", button1 = btn, button4 = btn, button5 = btn, } data[capi.screen[screen]] = item toggleVisibility(t) item.state[radical.base.item_flags.USED] = true return item end capi.tag.connect_signal("property::selected" , toggleVisibility) capi.tag.connect_signal("property::activated", toggleVisibility) return setmetatable({show_menu=show_menu}, { __call = function(_, ...) return new(...) end }) -- kate: space-indent on; indent-width 2; replace-tabs on;
{ "pile_set_name": "Github" }
{ "name": "flatbuffers", "version": "1.10.2", "description": "Memory Efficient Serialization Library", "files": [ "js/flatbuffers.js", "js/flatbuffers.mjs" ], "main": "js/flatbuffers", "module": "js/flatbuffers.mjs", "directories": { "doc": "docs", "test": "tests" }, "scripts": { "test": "tests/JavaScriptTest.sh", "append-esm-export": "sed \"s/this.flatbuffers = flatbuffers;/export { flatbuffers };/\" js/flatbuffers.js > js/flatbuffers.mjs", "prepublishOnly": "npm run append-esm-export" }, "repository": { "type": "git", "url": "git+https://github.com/google/flatbuffers.git" }, "keywords": [ "flatbuffers" ], "author": "The FlatBuffers project", "license": "SEE LICENSE IN LICENSE.txt", "bugs": { "url": "https://github.com/google/flatbuffers/issues" }, "homepage": "https://google.github.io/flatbuffers/", "dependencies": {} }
{ "pile_set_name": "Github" }
var DEFAULTS = { '*': { colors: { opacity: true // rgba / hsla }, properties: { backgroundClipMerging: true, // background-clip to shorthand backgroundOriginMerging: true, // background-origin to shorthand backgroundSizeMerging: true, // background-size to shorthand colors: true, // any kind of color transformations, like `#ff00ff` to `#f0f` or `#fff` into `red` ieBangHack: false, // !ie suffix hacks on IE<8 ieFilters: false, // whether to preserve `filter` and `-ms-filter` properties iePrefixHack: false, // underscore / asterisk prefix hacks on IE ieSuffixHack: false, // \9 suffix hacks on IE6-9 merging: true, // merging properties into one shorterLengthUnits: false, // optimize pixel units into `pt`, `pc` or `in` units spaceAfterClosingBrace: true, // 'url() no-repeat' to 'url()no-repeat' urlQuotes: false, // whether to wrap content of `url()` into quotes or not zeroUnits: true // 0[unit] -> 0 }, selectors: { adjacentSpace: false, // div+ nav Android stock browser hack ie7Hack: false, // *+html hack mergeablePseudoClasses: [ ':active', ':after', ':before', ':empty', ':checked', ':disabled', ':empty', ':enabled', ':first-child', ':first-letter', ':first-line', ':first-of-type', ':focus', ':hover', ':lang', ':last-child', ':last-of-type', ':link', ':not', ':nth-child', ':nth-last-child', ':nth-last-of-type', ':nth-of-type', ':only-child', ':only-of-type', ':root', ':target', ':visited' ], // selectors with these pseudo-classes can be merged as these are universally supported mergeablePseudoElements: [ '::after', '::before', '::first-letter', '::first-line' ], // selectors with these pseudo-elements can be merged as these are universally supported mergeLimit: 8191, // number of rules that can be safely merged together multiplePseudoMerging: true }, units: { ch: true, in: true, pc: true, pt: true, rem: true, vh: true, vm: true, // vm is vmin on IE9+ see https://developer.mozilla.org/en-US/docs/Web/CSS/length vmax: true, vmin: true, vw: true } } }; DEFAULTS.ie11 = DEFAULTS['*']; DEFAULTS.ie10 = DEFAULTS['*']; DEFAULTS.ie9 = merge(DEFAULTS['*'], { properties: { ieFilters: true, ieSuffixHack: true } }); DEFAULTS.ie8 = merge(DEFAULTS.ie9, { colors: { opacity: false }, properties: { backgroundClipMerging: false, backgroundOriginMerging: false, backgroundSizeMerging: false, iePrefixHack: true, merging: false }, selectors: { mergeablePseudoClasses: [ ':after', ':before', ':first-child', ':first-letter', ':focus', ':hover', ':visited' ], mergeablePseudoElements: [] }, units: { ch: false, rem: false, vh: false, vm: false, vmax: false, vmin: false, vw: false } }); DEFAULTS.ie7 = merge(DEFAULTS.ie8, { properties: { ieBangHack: true }, selectors: { ie7Hack: true, mergeablePseudoClasses: [ ':first-child', ':first-letter', ':hover', ':visited' ] }, }); function compatibilityFrom(source) { return merge(DEFAULTS['*'], calculateSource(source)); } function merge(source, target) { for (var key in source) { var value = source[key]; if (typeof value === 'object' && !Array.isArray(value)) { target[key] = merge(value, target[key] || {}); } else { target[key] = key in target ? target[key] : value; } } return target; } function calculateSource(source) { if (typeof source == 'object') return source; if (!/[,\+\-]/.test(source)) return DEFAULTS[source] || DEFAULTS['*']; var parts = source.split(','); var template = parts[0] in DEFAULTS ? DEFAULTS[parts.shift()] : DEFAULTS['*']; source = {}; parts.forEach(function (part) { var isAdd = part[0] == '+'; var key = part.substring(1).split('.'); var group = key[0]; var option = key[1]; source[group] = source[group] || {}; source[group][option] = isAdd; }); return merge(template, source); } module.exports = compatibilityFrom;
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <objc/NSObject.h> @class NSArray, NSString; @interface FPTask : NSObject { NSArray *_argv; NSString *_redirectStdoutToFileAtPath; int _redirectStdoutToFileDescriptor; NSString *_redirectStderrToFileAtPath; int _redirectStderrToFileDescriptor; int _waitStatus; } + (id)sanitizeStringForFilename:(id)arg1; + (id)taskWithArguments:(id)arg1; + (id)taskWithCommandWithArguments:(id)arg1; + (id)taskWithCommand:(id)arg1; + (id)taskWithRedirectedOutputAndCommand:(id)arg1; - (void).cxx_destruct; @property(readonly, nonatomic) int waitStatus; // @synthesize waitStatus=_waitStatus; @property(nonatomic) int redirectStderrToFileDescriptor; // @synthesize redirectStderrToFileDescriptor=_redirectStderrToFileDescriptor; @property(retain, nonatomic) NSString *redirectStderrToFileAtPath; // @synthesize redirectStderrToFileAtPath=_redirectStderrToFileAtPath; @property(nonatomic) int redirectStdoutToFileDescriptor; // @synthesize redirectStdoutToFileDescriptor=_redirectStdoutToFileDescriptor; @property(retain, nonatomic) NSString *redirectStdoutToFileAtPath; // @synthesize redirectStdoutToFileAtPath=_redirectStdoutToFileAtPath; @property(retain, nonatomic) NSArray *argv; // @synthesize argv=_argv; - (void)resetRedirect; - (int)exec; - (int)execAsync; - (int)_prepareRedirections:(void **)arg1; - (void)setCommandWithArguments:(id)arg1; - (void)setCommand:(id)arg1; - (id)init; @end
{ "pile_set_name": "Github" }
#!/usr/bin/env python # -*- Mode: python -*- # Copyright (c) 2009, Andrew McNabb # Copyright (c) 2003-2008, Brent N. Chun """Parallel ssh to the set of nodes in hosts.txt. For each node, this essentially does an "ssh host -l user prog [arg0] [arg1] ...". The -o option can be used to store stdout from each remote node in a directory. Each output file in that directory will be named by the corresponding remote node's hostname or IP address. """ import os import sys parent, bindir = os.path.split(os.path.dirname(os.path.abspath(sys.argv[0]))) if os.path.exists(os.path.join(parent, 'psshlib')): sys.path.insert(0, parent) from psshlib import psshutil from psshlib.manager import Manager from psshlib.task import Task from psshlib.cli import common_parser, common_defaults _DEFAULT_TIMEOUT = 60 def option_parser(): parser = common_parser() parser.usage = "%prog [OPTIONS] command [...]" parser.epilog = "Example: pssh -h hosts.txt -l irb2 -o /tmp/foo uptime" parser.add_option('-i', '--inline', dest='inline', action='store_true', help='inline aggregated output for each server') parser.add_option('-I', '--send-input', dest='send_input', action='store_true', help='read from standard input and send as input to ssh') parser.add_option('-P', '--print', dest='print_out', action='store_true', help='print output as we get it') return parser def parse_args(): parser = option_parser() defaults = common_defaults(timeout=_DEFAULT_TIMEOUT) parser.set_defaults(**defaults) opts, args = parser.parse_args() if len(args) == 0 and not opts.send_input: parser.error('Command not specified.') if not opts.host_files and not opts.host_entries: parser.error('Hosts not specified.') return opts, args def buffer_input(): """Read any immediately available data from standard input. Doesn't work if stdin blocks for any reason. This needs to be deprecated. """ import fcntl fileno = sys.stdin.fileno() origfl = fcntl.fcntl(fileno, fcntl.F_GETFL) fcntl.fcntl(fileno, fcntl.F_SETFL, origfl | os.O_NONBLOCK) try: # Python 3 read_stdin = sys.stdin.buffer.read except AttributeError: # Python 2 read_stdin = sys.stdin.read try: stdin = read_stdin() except IOError: # Stdin contained no information stdin = "" fcntl.fcntl(fileno, fcntl.F_SETFL, origfl) return stdin def do_pssh(hosts, cmdline, opts): if opts.outdir and not os.path.exists(opts.outdir): os.makedirs(opts.outdir) if opts.errdir and not os.path.exists(opts.errdir): os.makedirs(opts.errdir) if opts.send_input: stdin = sys.stdin.read() else: stdin = buffer_input() if stdin: sys.stderr.write('Automatic reading from stdin is deprecated. ' 'Please use the -I option.\n') manager = Manager(opts) for host, port, user in hosts: cmd = ['ssh', host, '-o', 'NumberOfPasswordPrompts=1', '-o', 'SendEnv=PSSH_NODENUM'] if not opts.verbose: cmd.append('-q') if opts.options: cmd += ['-o', opts.options] if user: cmd += ['-l', user] if port: cmd += ['-p', port] if opts.extra: cmd.extend(opts.extra) if cmdline: cmd.append(cmdline) t = Task(host, port, user, cmd, opts, stdin) manager.add_task(t) manager.run() if __name__ == "__main__": opts, args = parse_args() cmdline = " ".join(args) hosts = psshutil.read_hosts(opts.host_files, default_user=opts.user) if opts.host_entries: for entry in opts.host_entries: hosts.append(psshutil.parse_host(entry, default_user=opts.user)) do_pssh(hosts, cmdline, opts)
{ "pile_set_name": "Github" }
/* * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #ifndef JDK_UTIL_MD_H #define JDK_UTIL_MD_H // checking for nanness #ifdef __solaris__ #include <ieeefp.h> #define ISNANF(f) isnanf(f) #define ISNAND(d) isnand(d) #elif defined(MACOSX) #include <math.h> #define ISNANF(f) isnan(f) #define ISNAND(d) isnan(d) #elif defined(__linux__) || defined(_ALLBSD_SOURCE) #include <math.h> #define ISNANF(f) isnanf(f) #define ISNAND(d) isnan(d) #elif defined(_AIX) #include <math.h> #define ISNANF(f) _isnanf(f) #define ISNAND(d) _isnan(d) #else #error "missing platform-specific definition here" #endif #endif /* JDK_UTIL_MD_H */
{ "pile_set_name": "Github" }
## Top Ranked Startups in Macedonia 1. [dock-name](http://www.startupranking.com/dock-name) 2. [g6](http://www.startupranking.com/g6) 3. [marko](http://www.startupranking.com/marko)
{ "pile_set_name": "Github" }
// #####Using gzip compression: res, err := goreq.Request{ Method: "POST", Uri: "http://www.google.com", Body: item, Compression: goreq.Gzip(), }.Do() // #####Using deflate/zlib compression: res, err := goreq.Request{ Method: "POST", Uri: "http://www.google.com", Body: item, Compression: goreq.Deflate(), }.Do() type Item struct { Id int Name string } res, err := goreq.Request{ Method: "POST", Uri: "http://www.google.com", Body: item, Compression: goreq.Gzip(), }.Do() var item Item res.Body.FromJsonTo(&item)
{ "pile_set_name": "Github" }
import React from 'react' import cx from 'classnames' import styles from './logo.css' import { AnimationComponent, ClassicText } from 'light-ui' const _LogoText = (props) => { const { status, className } = props const textClassName = cx( className, styles.logoContainer, styles[`logoContainer-${status}`] ) return ( <ClassicText {...props} className={textClassName} text={props.text || 'hacknical'} /> ) } const LogoText = props => ( <AnimationComponent> <_LogoText {...props} /> </AnimationComponent> ) export default LogoText
{ "pile_set_name": "Github" }