text
stringlengths
2
99.9k
meta
dict
#include "HLSLSupport.cginc" #define UNITY_VERTEX_OUTPUT_STEREO // So that templates compile
{ "pile_set_name": "Github" }
/* * stateless-future * Copyright 2014 深圳岂凡网络有限公司 (Shenzhen QiFun Network Corp., LTD) * * 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.qifun.statelessFuture import scala.runtime.AbstractPartialFunction import scala.reflect.macros.Context import scala.util.control.Exception.Catcher import scala.util.control.TailCalls._ import scala.concurrent.ExecutionContext import scala.util.Success import scala.util.Failure /** * Used internally only. */ object ANormalForm { abstract class AbstractAwaitable[+AwaitResult, TailRecResult] extends Awaitable.Stateless[AwaitResult, TailRecResult] @inline final def forceOnComplete[TailRecResult](future: Awaitable[Any, TailRecResult], handler: Nothing => TailRec[TailRecResult])(implicit catcher: Catcher[TailRec[TailRecResult]]): TailRec[TailRecResult] = { future.onComplete(handler.asInstanceOf[Any => TailRec[TailRecResult]]) } final class TryCatchFinally[AwaitResult, TailRecResult](tryFuture: Awaitable[AwaitResult, TailRecResult], getCatcherFuture: Catcher[Awaitable[AwaitResult, TailRecResult]], finallyBlock: => Unit) extends AbstractAwaitable[AwaitResult, TailRecResult] { @inline override final def onComplete(rest: AwaitResult => TailRec[TailRecResult])(implicit catcher: Catcher[TailRec[TailRecResult]]) = { tryFuture.onComplete { a => // 成功执行 try try { finallyBlock tailcall(rest(a)) } catch { case e if catcher.isDefinedAt(e) => { // 执行finally时出错 tailcall(catcher(e)) } } } { case e if getCatcherFuture.isDefinedAt(e) => { // 执行 try 失败,用getCatcherFuture进行恢复 val catcherFuture = getCatcherFuture(e) catcherFuture.onComplete { a => // 成功恢复 try { finallyBlock tailcall(rest(a)) } catch { case e if catcher.isDefinedAt(e) => { // 执行finally时出错 tailcall(catcher(e)) } } } { case e if catcher.isDefinedAt(e) => { // 执行 try 失败,getCatcherFuture恢复失败,触发外层异常 try { finallyBlock tailcall(catcher(e)) } catch { case e if catcher.isDefinedAt(e) => { // 执行finally时出错 tailcall(catcher(e)) } } } case e: Throwable => { finallyBlock throw e } } } case e if catcher.isDefinedAt(e) => { // 执行 try 失败,getCatcherFuture不支持恢复,触发外层异常 try { finallyBlock tailcall(catcher(e)) } catch { case e if catcher.isDefinedAt(e) => { // 执行finally时出错 tailcall(catcher(e)) } } } case e: Throwable => { // 执行 try 失败,getCatcherFuture不支持恢复,外层异常 finallyBlock throw e } } } } def applyMacro(c: Context)(block: c.Expr[Any]): c.Expr[Nothing] = { import c.universe._ c.macroApplication match { case Apply(TypeApply(_, List(t)), _) => { applyMacroWithType(c)(block, t, Ident(typeOf[Unit].typeSymbol)) } case Apply(TypeApply(_, List(t, tailRecResultTypeTree)), _) => { applyMacroWithType(c)(block, t, tailRecResultTypeTree) } } } def applyMacroWithType(c: Context)(futureBody: c.Expr[Any], macroAwaitResultTypeTree: c.Tree, tailRecResultTypeTree: c.Tree): c.Expr[Nothing] = { import c.universe.Flag._ import c.universe._ import compat._ def unchecked(tree: Tree) = { Annotated(Apply(Select(New(TypeTree(typeOf[unchecked])), nme.CONSTRUCTOR), List()), tree) } val abstractPartialFunction = typeOf[AbstractPartialFunction[_, _]] val futureType = typeOf[Awaitable[_, _]] val statelessFutureType = typeOf[Awaitable.Stateless[_, _]] val futureClassType = typeOf[AbstractAwaitable[_, _]] val function1Type = typeOf[_ => _] val function1Symbol = function1Type.typeSymbol val tailRecType = typeOf[TailRec[_]] val tailRecSymbol = tailRecType.typeSymbol val uncheckedSymbol = typeOf[scala.unchecked].typeSymbol val AndSymbol = typeOf[Boolean].declaration(newTermName("&&").encodedName) val OrSymbol = typeOf[Boolean].declaration(newTermName("||").encodedName) val tailRecTypeTree = AppliedTypeTree(Ident(tailRecSymbol), List(tailRecResultTypeTree)) val catcherTypeTree = AppliedTypeTree(Ident(typeOf[PartialFunction[_, _]].typeSymbol), List(Ident(typeOf[Throwable].typeSymbol), tailRecTypeTree)) val resultTypeTree = AppliedTypeTree(Ident(statelessFutureType.typeSymbol), List(macroAwaitResultTypeTree, tailRecResultTypeTree)) def checkNakedAwait(tree: Tree, errorMessage: String) { for (subTree @ Select(future, await) <- tree if await.decoded == "await" && future.tpe <:< futureType) { c.error(subTree.pos, errorMessage) } } def transformParameterList(isByNameParam: List[Boolean], trees: List[Tree], catcher: Tree, rest: (List[Tree]) => Tree)(implicit forceAwait: Set[Name]): Tree = { trees match { case Nil => rest(Nil) case head :: tail => { head match { case Typed(origin, typeTree) => transform(origin, catcher, new NotTailcall { override final def apply(transformedOrigin: Tree) = { val parameterName = newTermName(c.fresh("yangBoParameter")) Block( List(ValDef(Modifiers(), parameterName, TypeTree(), transformedOrigin).setPos(origin.pos)), transformParameterList(if (isByNameParam.nonEmpty) isByNameParam.tail else Nil, tail, catcher, { transformedTail => rest(treeCopy.Typed(head, Ident(parameterName), typeTree) :: transformedTail) })) } }) case _ if isByNameParam.nonEmpty && isByNameParam.head => { checkNakedAwait(head, "await must not be used under a by-name argument.") transformParameterList(isByNameParam.tail, tail, catcher, { (transformedTail) => rest(head :: transformedTail) }) } case _ => transform(head, catcher, new NotTailcall { override final def apply(transformedHead: Tree) = { val parameterName = newTermName(c.fresh("yangBoParameter")) Block( List(ValDef(Modifiers(), parameterName, TypeTree(), transformedHead).setPos(head.pos)), transformParameterList(if (isByNameParam.nonEmpty) isByNameParam.tail else Nil, tail, catcher, { transformedTail => rest(Ident(parameterName) :: transformedTail) })) } }) } } } } def newCatcher(cases: List[CaseDef], typeTree: Tree): Tree = { val catcherClassName = newTypeName(c.fresh("YangBoCatcher")) val isDefinedCases = ((for (originCaseDef @ CaseDef(pat, guard, _) <- cases.view) yield { treeCopy.CaseDef(originCaseDef, pat, guard, Literal(Constant(true))) }) :+ CaseDef(Ident(nme.WILDCARD), EmptyTree, Literal(Constant(false)))).toList val defaultName = newTermName(c.fresh("default")) val throwableName = newTermName(c.fresh("throwable")) val applyOrElseCases = cases :+ CaseDef(Ident(nme.WILDCARD), EmptyTree, Apply(Ident(defaultName), List(Ident(throwableName)))) Block( List( ClassDef( Modifiers(FINAL), catcherClassName, List(), Template( List( AppliedTypeTree( Ident(abstractPartialFunction.typeSymbol), List( TypeTree(typeOf[Throwable]), typeTree))), emptyValDef, List( DefDef( Modifiers(), nme.CONSTRUCTOR, List(), List(List()), TypeTree(), Block( List( Apply(Select(Super(This(tpnme.EMPTY), tpnme.EMPTY), nme.CONSTRUCTOR), List())), Literal(Constant(())))), DefDef( Modifiers(OVERRIDE | FINAL), newTermName("applyOrElse"), List( TypeDef(Modifiers(PARAM), newTypeName("A1"), List(), TypeBoundsTree(TypeTree(typeOf[Nothing]), TypeTree(typeOf[Throwable]))), TypeDef(Modifiers(PARAM), newTypeName("B1"), List(), TypeBoundsTree(typeTree, TypeTree(typeOf[Any])))), List(List( ValDef( Modifiers(PARAM), throwableName, Ident(newTypeName("A1")), EmptyTree), ValDef( Modifiers(PARAM), defaultName, AppliedTypeTree(Ident(function1Symbol), List(Ident(newTypeName("A1")), Ident(newTypeName("B1")))), EmptyTree))), Ident(newTypeName("B1")), Match( Annotated( Apply(Select(New(Ident(uncheckedSymbol)), nme.CONSTRUCTOR), List()), Ident(throwableName)), applyOrElseCases)), DefDef( Modifiers(OVERRIDE | FINAL), newTermName("isDefinedAt"), List(), List(List(ValDef(Modifiers(PARAM), throwableName, TypeTree(typeOf[Throwable]), EmptyTree))), TypeTree(typeOf[Boolean]), Match( Annotated( Apply(Select(New(Ident(uncheckedSymbol)), nme.CONSTRUCTOR), List()), Ident(throwableName)), isDefinedCases)))))), Apply(Select(New(Ident(catcherClassName)), nme.CONSTRUCTOR), List())) } sealed trait Rest { def apply(former: Tree): Tree def transformAwait(future: Tree, awaitTypeTree: TypTree, catcher: Tree)(implicit forceAwait: Set[Name]): Tree } // ClassFormatError will be thrown if changing NotTailcall to a trait. scalac's Bug? abstract class NotTailcall extends Rest { override final def transformAwait(future: Tree, awaitTypeTree: TypTree, catcher: Tree)(implicit forceAwait: Set[Name]): Tree = { val nextFutureName = newTermName(c.fresh("yangBoNextFuture")) val futureExpr = c.Expr(ValDef(Modifiers(), nextFutureName, TypeTree(), future)) val AwaitResult = newTermName(c.fresh("awaitValue")) val catcherExpr = c.Expr[Catcher[Nothing]](catcher) val ANormalFormTree = reify(_root_.com.qifun.statelessFuture.ANormalForm).tree val ForceOnCompleteName = newTermName("forceOnComplete") val CatcherTree = catcher val onCompleteCallExpr = c.Expr( Apply( Apply( TypeApply( Select(ANormalFormTree, ForceOnCompleteName), List(tailRecResultTypeTree)), List( Ident(nextFutureName), { val restTree = NotTailcall.this(Ident(AwaitResult)) val tailcallSymbol = reify(scala.util.control.TailCalls).tree.symbol val TailcallName = newTermName("tailcall") val ApplyName = newTermName("apply") val AsInstanceOfName = newTermName("asInstanceOf") def function(awaitValDef: ValDef, restTree: Tree) = { val functionName = newTermName(c.fresh("yangBoHandler")) val restExpr = c.Expr(restTree) Block( List( DefDef( Modifiers(NoFlags, nme.EMPTY, List(Apply(Select(New(Ident(typeOf[scala.inline].typeSymbol)), nme.CONSTRUCTOR), List()))), functionName, List(), List(List(awaitValDef)), TypeTree(), reify { try { restExpr.splice } catch { case e if catcherExpr.splice.isDefinedAt(e) => { _root_.scala.util.control.TailCalls.tailcall(catcherExpr.splice(e)) } } }.tree)), Ident(functionName)) } restTree match { case Block(List(oldVal @ ValDef(_, capturedResultName, _, Ident(AwaitResult))), expr) => { // 参数名优化 function(treeCopy.ValDef(oldVal, Modifiers(PARAM), capturedResultName, awaitTypeTree, EmptyTree), expr) } case Block(List(oldVal @ ValDef(_, capturedResultName, _, Ident(AwaitResult)), restStates @ _*), expr) => { // 参数名优化 function(treeCopy.ValDef(oldVal, Modifiers(PARAM), capturedResultName, awaitTypeTree, EmptyTree), Block(restStates.toList, expr)) } case _ => { function(ValDef(Modifiers(PARAM), AwaitResult, awaitTypeTree, EmptyTree), restTree) } } })), List(catcher))) reify { futureExpr.splice @inline def yangBoTail = onCompleteCallExpr.splice _root_.scala.util.control.TailCalls.tailcall { yangBoTail } }.tree } } def transform(tree: Tree, catcher: Tree, rest: Rest)(implicit forceAwait: Set[Name]): Tree = { tree match { case Try(block, catches, finalizer) => { val futureName = newTermName(c.fresh("tryCatchFinallyFuture")) Block( List( ValDef(Modifiers(), futureName, TypeTree(), Apply( Select( New( AppliedTypeTree( Select(reify(_root_.com.qifun.statelessFuture.ANormalForm).tree, newTypeName("TryCatchFinally")), List(TypeTree(tree.tpe), tailRecResultTypeTree))), nme.CONSTRUCTOR), List( newFuture(block).tree, newCatcher( for (cd @ CaseDef(pat, guard, body) <- catches) yield { treeCopy.CaseDef(cd, pat, guard, newFuture(body).tree) }, AppliedTypeTree( Ident(futureType.typeSymbol), List(TypeTree(tree.tpe), tailRecResultTypeTree))), if (finalizer.isEmpty) { Literal(Constant(())) } else { checkNakedAwait(finalizer, "await must not be used under a finally.") finalizer })))), rest.transformAwait(Ident(futureName), TypeTree(tree.tpe), catcher)) } case ClassDef(mods, _, _, _) => { if (mods.hasFlag(TRAIT)) { checkNakedAwait(tree, "await must not be used under a nested trait.") } else { checkNakedAwait(tree, "await must not be used under a nested class.") } rest(tree) } case _: ModuleDef => { checkNakedAwait(tree, "await must not be used under a nested object.") rest(tree) } case DefDef(mods, _, _, _, _, _) => { if (mods.hasFlag(LAZY)) { checkNakedAwait(tree, "await must not be used under a lazy val initializer.") } else { checkNakedAwait(tree, "await must not be used under a nested method.") } rest(tree) } case _: Function => { checkNakedAwait(tree, "await must not be used under a nested function.") rest(tree) } case EmptyTree | _: New | _: Ident | _: Literal | _: Super | _: This | _: TypTree | _: New | _: TypeDef | _: Import | _: ImportSelector => { rest(tree) } case Select(future, await) if await.decoded == "await" && future.tpe <:< futureType => { transform(future, catcher, new NotTailcall { override final def apply(transformedFuture: Tree) = rest.transformAwait(transformedFuture, TypeTree(tree.tpe), catcher) }) } case Select(instance, field) => { transform(instance, catcher, new NotTailcall { override final def apply(transformedInstance: Tree) = rest(treeCopy.Select(tree, transformedInstance, field)) }) } case TypeApply(method, parameters) => { transform(method, catcher, new NotTailcall { override final def apply(transformedMethod: Tree) = rest(treeCopy.TypeApply(tree, transformedMethod, parameters)) }) } case Apply(method @ Ident(name), parameters) if forceAwait(name) => { transformParameterList(Nil, parameters, catcher, { (transformedParameters) => rest.transformAwait(treeCopy.Apply(tree, Ident(name), transformedParameters), TypeTree(tree.tpe).asInstanceOf[TypTree], catcher) }) } case Apply(method, parameters) => { transform(method, catcher, new NotTailcall { override final def apply(transformedMethod: Tree) = { val isByNameParam = method.symbol match { case AndSymbol | OrSymbol => { List(true) } case _ => { method.tpe match { case MethodType(params, _) => { for (param <- params) yield { param.asTerm.isByNameParam } } case _ => { Nil } } } } transformParameterList(isByNameParam, parameters, catcher, { (transformedParameters) => rest(treeCopy.Apply( tree, transformedMethod, transformedParameters)) }) } }) } case Block(stats, expr) => { def addHead(head: Tree, tuple: (Tree, Boolean)): Tree = { val (tail, mergeable) = tuple tail match { case Block(stats, expr) if mergeable => { treeCopy.Block(tree, head :: stats, expr) } case _ => { treeCopy.Block(tree, List(head), tail) } } } def transformBlock(stats: List[Tree])(implicit forceAwait: Set[Name]): (Tree, Boolean) = { stats match { case Nil => { (transform(expr, catcher, new Rest { override final def transformAwait(future: Tree, awaitTypeTree: TypTree, catcher: Tree)(implicit forceAwait: Set[Name]): Tree = { Block(Nil, rest.transformAwait(future, awaitTypeTree, catcher)) } override final def apply(transformedExpr: Tree) = Block(Nil, rest(transformedExpr)) }), false) } case head :: tail => { (transform(head, catcher, new NotTailcall { override final def apply(transformedHead: Tree) = transformedHead match { case _: Ident | _: Literal => { val (block, _) = transformBlock(tail) block } case _ => { addHead(transformedHead, transformBlock(tail)) } } }), true) } } } Block(Nil, transformBlock(stats)._1) } case ValDef(mods, name, tpt, rhs) => { transform(rhs, catcher, new NotTailcall { override final def apply(transformedRhs: Tree) = rest(treeCopy.ValDef(tree, mods, name, tpt, transformedRhs)) }) } case Assign(left, right) => { transform(left, catcher, new NotTailcall { override final def apply(transformedLeft: Tree) = transform(right, catcher, new NotTailcall { override final def apply(transformedRight: Tree) = rest(treeCopy.Assign(tree, transformedLeft, transformedRight)) }) }) } case Match(selector, cases) => { transform(selector, catcher, new NotTailcall { override final def apply(transformedSelector: Tree) = rest.transformAwait( treeCopy.Match( tree, transformedSelector, for (originCaseDef @ CaseDef(pat, guard, body) <- cases) yield { checkNakedAwait(guard, "await must not be used under a pattern guard.") treeCopy.CaseDef(originCaseDef, pat, guard, newFutureAsType(body, TypeTree(tree.tpe)).tree) }), TypeTree(tree.tpe), catcher) }) } case If(cond, thenp, elsep) => { transform(cond, catcher, new NotTailcall { override final def apply(transformedCond: Tree) = rest.transformAwait( If( transformedCond, newFuture(thenp).tree, newFuture(elsep).tree), TypeTree(tree.tpe), catcher) }) } case Throw(throwable) => { transform(throwable, catcher, new NotTailcall { override final def apply(transformedThrowable: Tree) = rest(treeCopy.Throw(tree, transformedThrowable)) }) } case Typed(expr, tpt@Ident(tpnme.WILDCARD_STAR)) => { transform(expr, catcher, new NotTailcall { override final def apply(transformedExpr: Tree) = rest(treeCopy.Typed(tree, transformedExpr, tpt)) }) } case Typed(expr, tpt) => { transform(expr, catcher, new NotTailcall { override final def apply(transformedExpr: Tree) = rest(treeCopy.Typed(tree, transformedExpr, TypeTree(tpt.tpe))) }) } case Annotated(annot, arg) => { transform(arg, catcher, new NotTailcall { override final def apply(transformedArg: Tree) = rest(treeCopy.Annotated(tree, annot, transformedArg)) }) } case LabelDef(name, params, rhs) => { Block( List( DefDef(Modifiers(), name, List(), List( for (p <- params) yield { ValDef(Modifiers(PARAM), p.name.toTermName, TypeTree(p.tpe), EmptyTree) }), AppliedTypeTree(Ident(futureType.typeSymbol), List(TypeTree(tree.tpe), tailRecResultTypeTree)), newFuture(rhs)(forceAwait + name).tree)), rest.transformAwait( Apply( Ident(name), params), TypeTree(tree.tpe), catcher)) } case _: Return => { c.error(tree.pos, "return is illegal.") rest(tree) } case _: PackageDef | _: Template | _: CaseDef | _: Alternative | _: Star | _: Bind | _: UnApply | _: AssignOrNamedArg | _: ReferenceToBoxed => { c.error(tree.pos, s"Unexpected expression in a `Future` block") rest(tree) } } } def newFutureAsType(tree: Tree, awaitValueTypeTree: Tree)(implicit forceAwait: Set[Name]): c.Expr[Awaitable.Stateless[Nothing, _]] = { val statelessFutureTypeTree = AppliedTypeTree(Ident(statelessFutureType.typeSymbol), List(awaitValueTypeTree, tailRecResultTypeTree)) val futureClassTypeTree = AppliedTypeTree(Ident(futureClassType.typeSymbol), List(awaitValueTypeTree, tailRecResultTypeTree)) val ANormalFormTree = reify(_root_.com.qifun.statelessFuture.ANormalForm).tree val ForceOnCompleteName = newTermName("forceOnComplete") val futureName = newTypeName(c.fresh("YangBoFuture")) val returnName = newTermName(c.fresh("yangBoReturn")) val catcherName = newTermName(c.fresh("yangBoCatcher")) c.Expr( Block( List( ClassDef( Modifiers(FINAL), futureName, List(), Template( List(futureClassTypeTree), emptyValDef, List( DefDef( Modifiers(), nme.CONSTRUCTOR, List(), List(List()), TypeTree(), Block(List(Apply(Select(Super(This(tpnme.EMPTY), tpnme.EMPTY), nme.CONSTRUCTOR), List())), Literal(Constant(())))), DefDef(Modifiers(OVERRIDE | FINAL), newTermName("onComplete"), List(), List( List(ValDef( Modifiers(PARAM), returnName, AppliedTypeTree(Ident(function1Symbol), List(awaitValueTypeTree, tailRecTypeTree)), EmptyTree)), List(ValDef( Modifiers(IMPLICIT | PARAM), catcherName, catcherTypeTree, EmptyTree))), tailRecTypeTree, { val catcherExpr = c.Expr[Catcher[TailRec[Nothing]]](Ident(catcherName)) val tryBodyExpr = c.Expr(transform( tree, Ident(catcherName), new Rest { override final def transformAwait(future: Tree, awaitTypeTree: TypTree, catcher: Tree)(implicit forceAwait: Set[Name]): Tree = { val nextFutureName = newTermName(c.fresh("yangBoNextFuture")) val futureExpr = c.Expr(ValDef(Modifiers(), nextFutureName, TypeTree(), future)) val onCompleteCallExpr = c.Expr( Apply( Apply( TypeApply( Select(ANormalFormTree, ForceOnCompleteName), List(tailRecResultTypeTree)), List( Ident(nextFutureName), Ident(returnName))), List(catcher))) reify { futureExpr.splice @inline def yangBoTail = onCompleteCallExpr.splice _root_.scala.util.control.TailCalls.tailcall { yangBoTail } }.tree } override final def apply(x: Tree) = { val resultExpr = c.Expr(x) val returnExpr = c.Expr[Any => Nothing](Ident(returnName)) reify { val result = resultExpr.splice // Workaround for some nested Future blocks. _root_.scala.util.control.TailCalls.tailcall((returnExpr.splice).asInstanceOf[Any => _root_.scala.util.control.TailCalls.TailRec[Nothing]].apply(result)) }.tree } })) reify { try { tryBodyExpr.splice } catch { case e if catcherExpr.splice.isDefinedAt(e) => { _root_.scala.util.control.TailCalls.tailcall(catcherExpr.splice(e)) } } }.tree }))))), Typed( Apply(Select(New(Ident(futureName)), nme.CONSTRUCTOR), List()), unchecked(statelessFutureTypeTree)))) } def newFuture(tree: Tree)(implicit forceAwait: Set[Name]): c.Expr[Awaitable.Stateless[Nothing, _]] = { newFutureAsType(tree, TypeTree(tree.tpe.widen)) } val result = newFutureAsType(futureBody.tree, macroAwaitResultTypeTree)(Set.empty) // c.warning(c.enclosingPosition, show(result)) c.Expr( TypeApply( Select( c.resetLocalAttrs(result.tree), newTermName("asInstanceOf")), List(resultTypeTree))) } }
{ "pile_set_name": "Github" }
""" Copyright © 2017 Bilal Elmoussaoui <[email protected]> This file is part of Authenticator. Authenticator 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. Authenticator 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 Authenticator. If not, see <http://www.gnu.org/licenses/>. """ from .add import AddAccountWindow from .list import AccountsWidget, AccountsList, EmptyAccountsList, AccountsListState from .row import AccountRow
{ "pile_set_name": "Github" }
<!-- doc/src/sgml/ref/drop_opclass.sgml PostgreSQL documentation --> <refentry id="sql-dropopclass"> <indexterm zone="sql-dropopclass"> <primary>DROP OPERATOR CLASS</primary> </indexterm> <refmeta> <refentrytitle>DROP OPERATOR CLASS</refentrytitle> <manvolnum>7</manvolnum> <refmiscinfo>SQL - Language Statements</refmiscinfo> </refmeta> <refnamediv> <refname>DROP OPERATOR CLASS</refname> <refpurpose>remove an operator class</refpurpose> </refnamediv> <refsynopsisdiv> <synopsis> DROP OPERATOR CLASS [ IF EXISTS ] <replaceable class="parameter">name</replaceable> USING <replaceable class="parameter">index_method</replaceable> [ CASCADE | RESTRICT ] </synopsis> </refsynopsisdiv> <refsect1> <title>Description</title> <para> <command>DROP OPERATOR CLASS</command> drops an existing operator class. To execute this command you must be the owner of the operator class. </para> <para> <command>DROP OPERATOR CLASS</command> does not drop any of the operators or functions referenced by the class. If there are any indexes depending on the operator class, you will need to specify <literal>CASCADE</literal> for the drop to complete. </para> </refsect1> <refsect1> <title>Parameters</title> <variablelist> <varlistentry> <term><literal>IF EXISTS</literal></term> <listitem> <para> Do not throw an error if the operator class does not exist. A notice is issued in this case. </para> </listitem> </varlistentry> <varlistentry> <term><replaceable class="parameter">name</replaceable></term> <listitem> <para> The name (optionally schema-qualified) of an existing operator class. </para> </listitem> </varlistentry> <varlistentry> <term><replaceable class="parameter">index_method</replaceable></term> <listitem> <para> The name of the index access method the operator class is for. </para> </listitem> </varlistentry> <varlistentry> <term><literal>CASCADE</literal></term> <listitem> <para> Automatically drop objects that depend on the operator class (such as indexes), and in turn all objects that depend on those objects (see <xref linkend="ddl-depend"/>). </para> </listitem> </varlistentry> <varlistentry> <term><literal>RESTRICT</literal></term> <listitem> <para> Refuse to drop the operator class if any objects depend on it. This is the default. </para> </listitem> </varlistentry> </variablelist> </refsect1> <refsect1> <title>Notes</title> <para> <command>DROP OPERATOR CLASS</command> will not drop the operator family containing the class, even if there is nothing else left in the family (in particular, in the case where the family was implicitly created by <command>CREATE OPERATOR CLASS</command>). An empty operator family is harmless, but for the sake of tidiness you might wish to remove the family with <command>DROP OPERATOR FAMILY</command>; or perhaps better, use <command>DROP OPERATOR FAMILY</command> in the first place. </para> </refsect1> <refsect1> <title>Examples</title> <para> Remove the B-tree operator class <literal>widget_ops</literal>: <programlisting> DROP OPERATOR CLASS widget_ops USING btree; </programlisting> This command will not succeed if there are any existing indexes that use the operator class. Add <literal>CASCADE</literal> to drop such indexes along with the operator class. </para> </refsect1> <refsect1> <title>Compatibility</title> <para> There is no <command>DROP OPERATOR CLASS</command> statement in the SQL standard. </para> </refsect1> <refsect1> <title>See Also</title> <simplelist type="inline"> <member><xref linkend="sql-alteropclass"/></member> <member><xref linkend="sql-createopclass"/></member> <member><xref linkend="sql-dropopfamily"/></member> </simplelist> </refsect1> </refentry>
{ "pile_set_name": "Github" }
SUMMARY="A set of libraries for the C++ programming language" DESCRIPTION="Boost is a set of libraries for the C++ programming language \ that provide support for tasks and structures such as linear algebra, \ pseudorandom number generation, multithreading, image processing, regular \ expressions, and unit testing. It contains over eighty individual libraries." HOMEPAGE="https://www.boost.org/" SOURCE_URI="https://dl.bintray.com/boostorg/release/$portVersion/source/boost_${portVersion//./_}.tar.bz2" CHECKSUM_SHA256="8f32d4617390d1c2d16f26a27ab60d97807b35440d45891fa340fc2648b04406" REVISION="2" LICENSE="Boost v1.0" COPYRIGHT="1998-2018 Beman Dawes, David Abrahams, Rene Rivera, et al." SOURCE_DIR="boost_${portVersion//./_}" PATCHES="boost-$portVersion.patchset" ARCHITECTURES="!x86_gcc2 ?x86 x86_64" SECONDARY_ARCHITECTURES="x86" libVersion="$portVersion compat >= 1.69.0" PROVIDES=" boost169$secondaryArchSuffix = $portVersion lib:libboost_atomic$secondaryArchSuffix = $libVersion lib:libboost_chrono$secondaryArchSuffix = $libVersion lib:libboost_container$secondaryArchSuffix = $libVersion lib:libboost_context$secondaryArchSuffix = $libVersion lib:libboost_contract$secondaryArchSuffix = $libVersion lib:libboost_coroutine$secondaryArchSuffix = $libVersion lib:libboost_date_time$secondaryArchSuffix = $libVersion lib:libboost_filesystem$secondaryArchSuffix = $libVersion lib:libboost_graph$secondaryArchSuffix = $libVersion lib:libboost_iostreams$secondaryArchSuffix = $libVersion lib:libboost_locale$secondaryArchSuffix = $libVersion lib:libboost_log_setup$secondaryArchSuffix = $libVersion lib:libboost_log$secondaryArchSuffix = $libVersion lib:libboost_math_c99$secondaryArchSuffix = $libVersion lib:libboost_math_c99f$secondaryArchSuffix = $libVersion lib:libboost_math_tr1$secondaryArchSuffix = $libVersion lib:libboost_math_tr1f$secondaryArchSuffix = $libVersion lib:libboost_prg_exec_monitor$secondaryArchSuffix = $libVersion lib:libboost_program_options$secondaryArchSuffix = $libVersion lib:libboost_random$secondaryArchSuffix = $libVersion lib:libboost_regex$secondaryArchSuffix = $libVersion lib:libboost_serialization$secondaryArchSuffix = $libVersion lib:libboost_stacktrace_basic$secondaryArchSuffix = $libVersion lib:libboost_stacktrace_noop$secondaryArchSuffix = $libVersion lib:libboost_system$secondaryArchSuffix = $libVersion lib:libboost_thread$secondaryArchSuffix = $libVersion lib:libboost_timer$secondaryArchSuffix = $libVersion lib:libboost_type_erasure$secondaryArchSuffix = $libVersion lib:libboost_unit_test_framework$secondaryArchSuffix = $libVersion lib:libboost_wave$secondaryArchSuffix = $libVersion lib:libboost_wserialization$secondaryArchSuffix = $libVersion " REQUIRES=" haiku$secondaryArchSuffix lib:libbz2$secondaryArchSuffix lib:libicudata$secondaryArchSuffix >= 66 lib:libicui18n$secondaryArchSuffix >= 66 lib:libicuuc$secondaryArchSuffix >= 66 lib:libz$secondaryArchSuffix " # List of devel entries matching an actual library (for use in prepareInstalledDevelLibs) # Boost also provides header-only libraries (because templates) devel_libs=" devel:libboost_atomic$secondaryArchSuffix = $portVersion devel:libboost_chrono$secondaryArchSuffix = $portVersion devel:libboost_container$secondaryArchSuffix = $portVersion devel:libboost_context$secondaryArchSuffix = $portVersion devel:libboost_contract$secondaryArchSuffix = $portVersion devel:libboost_coroutine$secondaryArchSuffix = $portVersion devel:libboost_date_time$secondaryArchSuffix = $portVersion devel:libboost_exception$secondaryArchSuffix = $portVersion devel:libboost_filesystem$secondaryArchSuffix = $portVersion devel:libboost_graph$secondaryArchSuffix = $portVersion devel:libboost_iostreams$secondaryArchSuffix = $portVersion devel:libboost_locale$secondaryArchSuffix = $portVersion devel:libboost_log_setup$secondaryArchSuffix = $portVersion devel:libboost_log$secondaryArchSuffix = $portVersion devel:libboost_math_c99$secondaryArchSuffix = $portVersion devel:libboost_math_c99f$secondaryArchSuffix = $portVersion devel:libboost_math_tr1$secondaryArchSuffix = $portVersion devel:libboost_math_tr1f$secondaryArchSuffix = $portVersion devel:libboost_prg_exec_monitor$secondaryArchSuffix = $portVersion devel:libboost_program_options$secondaryArchSuffix = $portVersion devel:libboost_random$secondaryArchSuffix = $portVersion devel:libboost_regex$secondaryArchSuffix = $portVersion devel:libboost_serialization$secondaryArchSuffix = $portVersion devel:libboost_stacktrace_basic$secondaryArchSuffix = $portVersion devel:libboost_stacktrace_noop$secondaryArchSuffix = $portVersion devel:libboost_system$secondaryArchSuffix = $portVersion devel:libboost_test_exec_monitor$secondaryArchSuffix = $portVersion devel:libboost_thread$secondaryArchSuffix = $portVersion devel:libboost_timer$secondaryArchSuffix = $portVersion devel:libboost_type_erasure$secondaryArchSuffix = $portVersion devel:libboost_unit_test_framework$secondaryArchSuffix = $portVersion devel:libboost_wave$secondaryArchSuffix = $portVersion devel:libboost_wserialization$secondaryArchSuffix = $portVersion " PROVIDES_devel=" boost169${secondaryArchSuffix}_devel = $portVersion $devel_libs devel:libboost_config$secondaryArchSuffix = $portVersion " REQUIRES_devel=" boost169$secondaryArchSuffix == $portVersion base " BUILD_REQUIRES=" haiku${secondaryArchSuffix}_devel >= r1~alpha4_pm_hrev51470 devel:libbz2$secondaryArchSuffix devel:libicudata$secondaryArchSuffix >= 66 devel:libicui18n$secondaryArchSuffix >= 66 devel:libicuuc$secondaryArchSuffix >= 66 devel:libz$secondaryArchSuffix " BUILD_PREREQUIRES=" cmd:gcc$secondaryArchSuffix cmd:ld$secondaryArchSuffix cmd:sed cmd:which " defineDebugInfoPackage boost169$secondaryArchSuffix \ "$libDir"/libboost_atomic.so.$portVersion \ "$libDir"/libboost_chrono.so.$portVersion \ "$libDir"/libboost_container.so.$portVersion \ "$libDir"/libboost_context.so.$portVersion \ "$libDir"/libboost_contract.so.$portVersion \ "$libDir"/libboost_coroutine.so.$portVersion \ "$libDir"/libboost_date_time.so.$portVersion \ "$libDir"/libboost_filesystem.so.$portVersion \ "$libDir"/libboost_graph.so.$portVersion \ "$libDir"/libboost_iostreams.so.$portVersion \ "$libDir"/libboost_locale.so.$portVersion \ "$libDir"/libboost_log_setup.so.$portVersion \ "$libDir"/libboost_log.so.$portVersion \ "$libDir"/libboost_math_c99.so.$portVersion \ "$libDir"/libboost_math_c99f.so.$portVersion \ "$libDir"/libboost_math_tr1.so.$portVersion \ "$libDir"/libboost_math_tr1f.so.$portVersion \ "$libDir"/libboost_prg_exec_monitor.so.$portVersion \ "$libDir"/libboost_program_options.so.$portVersion \ "$libDir"/libboost_random.so.$portVersion \ "$libDir"/libboost_regex.so.$portVersion \ "$libDir"/libboost_serialization.so.$portVersion \ "$libDir"/libboost_stacktrace_basic.so.$portVersion \ "$libDir"/libboost_stacktrace_noop.so.$portVersion \ "$libDir"/libboost_system.so.$portVersion \ "$libDir"/libboost_thread.so.$portVersion \ "$libDir"/libboost_timer.so.$portVersion \ "$libDir"/libboost_type_erasure.so.$portVersion \ "$libDir"/libboost_unit_test_framework.so.$portVersion \ "$libDir"/libboost_wave.so.$portVersion \ "$libDir"/libboost_wserialization.so.$portVersion BUILD() { ./bootstrap.sh \ --prefix=$prefix \ --exec-prefix=$binDir \ --libdir=$libDir \ --includedir=$includeDir ./b2 -q $jobArgs \ --without-mpi \ --enable-threads=posix \ --enable-thread-local-alloc \ --enable-parallel-mark \ inlining=on \ threading=multi \ variant=release \ link=static,shared \ runtime-link=shared \ --without-python } INSTALL() { ./b2 -q $jobArgs \ --without-mpi \ --enable-threads=posix \ --enable-thread-local-alloc \ --enable-parallel-mark \ inlining=on \ threading=multi \ variant=release \ link=static,shared \ runtime-link=shared \ --without-python \ install prepareInstalledDevelLibs `echo "$devel_libs" | sed -n \ -e "s/devel:\(.*\)$secondaryArchSuffix =.*/\1/p"` packageEntries devel $developDir } TEST() { cd status ../bjam $jobArgs }
{ "pile_set_name": "Github" }
{ IBClasses = ( {CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; }, { ACTIONS = { help = id; newGame = id; openGame = id; prefsMenu = id; saveGame = id; saveGameAs = id; }; CLASS = SDLMain; LANGUAGE = ObjC; SUPERCLASS = NSObject; } ); IBVersion = 1; }
{ "pile_set_name": "Github" }
// Regression test to catch problem where orthogonal segments from the same // connector were being merged with others going through checkpoints and // being simplified so as not to pass the checkpoint anymore. // Based on ec00232. #include "libavoid/libavoid.h" using namespace Avoid; int main(void) { Router *router = new Router( PolyLineRouting | OrthogonalRouting); router->setRoutingParameter((RoutingParameter)0, 50); router->setRoutingParameter((RoutingParameter)1, 0); router->setRoutingParameter((RoutingParameter)2, 0); router->setRoutingParameter((RoutingParameter)3, 4000); router->setRoutingParameter((RoutingParameter)4, 0); router->setRoutingParameter((RoutingParameter)5, 100); router->setRoutingParameter((RoutingParameter)6, 0); router->setRoutingParameter((RoutingParameter)7, 4); router->setRoutingOption((RoutingOption)0, true); router->setRoutingOption((RoutingOption)1, true); router->setRoutingOption((RoutingOption)2, false); router->setRoutingOption((RoutingOption)3, false); Polygon polygon; ConnRef *connRef = nullptr; ConnEnd srcPt; ConnEnd dstPt; #if ALL // shapeRef1 polygon = Polygon(4); polygon.ps[0] = Point(-80.18071812011561, 825.315092940984); polygon.ps[1] = Point(-80.18071812011561, 887.315092940984); polygon.ps[2] = Point(-142.1807181201156, 887.315092940984); polygon.ps[3] = Point(-142.1807181201156, 825.315092940984); new ShapeRef(router, polygon, 1); #endif // shapeRef2 polygon = Polygon(4); polygon.ps[0] = Point(620.1049961655988, -86.0182403953493); polygon.ps[1] = Point(620.1049961655988, -24.0182403953493); polygon.ps[2] = Point(558.1049961655988, -24.0182403953493); polygon.ps[3] = Point(558.1049961655988, -86.0182403953493); new ShapeRef(router, polygon, 2); #if ALL // shapeRef3 polygon = Polygon(4); polygon.ps[0] = Point(1044.504996167599, 719.315092940984); polygon.ps[1] = Point(1044.504996167599, 781.315092940984); polygon.ps[2] = Point(982.5049961675986, 781.315092940984); polygon.ps[3] = Point(982.5049961675986, 719.315092940984); new ShapeRef(router, polygon, 3); // shapeRef4 polygon = Polygon(4); polygon.ps[0] = Point(1153.104996167599, 759.315092940984); polygon.ps[1] = Point(1153.104996167599, 821.315092940984); polygon.ps[2] = Point(1091.104996167599, 821.315092940984); polygon.ps[3] = Point(1091.104996167599, 759.315092940984); new ShapeRef(router, polygon, 4); // shapeRef5 polygon = Polygon(4); polygon.ps[0] = Point(1044.504996167599, 495.9817596066507); polygon.ps[1] = Point(1044.504996167599, 557.9817596066507); polygon.ps[2] = Point(982.5049961675986, 557.9817596066507); polygon.ps[3] = Point(982.5049961675986, 495.9817596066507); new ShapeRef(router, polygon, 5); // shapeRef6 polygon = Polygon(4); polygon.ps[0] = Point(968.1049961675988, 759.315092940984); polygon.ps[1] = Point(968.1049961675988, 821.315092940984); polygon.ps[2] = Point(906.1049961675988, 821.315092940984); polygon.ps[3] = Point(906.1049961675988, 759.315092940984); new ShapeRef(router, polygon, 6); // shapeRef7 polygon = Polygon(4); polygon.ps[0] = Point(1044.504996167599, 792.315092940984); polygon.ps[1] = Point(1044.504996167599, 854.315092940984); polygon.ps[2] = Point(982.5049961675986, 854.315092940984); polygon.ps[3] = Point(982.5049961675986, 792.315092940984); new ShapeRef(router, polygon, 7); // shapeRef8 polygon = Polygon(4); polygon.ps[0] = Point(349.8192818798844, 1008.815092941984); polygon.ps[1] = Point(349.8192818798844, 1070.815092941984); polygon.ps[2] = Point(287.8192818798844, 1070.815092941984); polygon.ps[3] = Point(287.8192818798844, 1008.815092941984); new ShapeRef(router, polygon, 8); // shapeRef9 polygon = Polygon(4); polygon.ps[0] = Point(349.8192818798844, 617.315092940984); polygon.ps[1] = Point(349.8192818798844, 679.315092940984); polygon.ps[2] = Point(287.8192818798844, 679.315092940984); polygon.ps[3] = Point(287.8192818798844, 617.315092940984); new ShapeRef(router, polygon, 9); // shapeRef10 polygon = Polygon(4); polygon.ps[0] = Point(288.8192818798844, 371.9817596066507); polygon.ps[1] = Point(288.8192818798844, 433.9817596066507); polygon.ps[2] = Point(226.8192818798844, 433.9817596066507); polygon.ps[3] = Point(226.8192818798844, 371.9817596066507); new ShapeRef(router, polygon, 10); #endif // shapeRef11 polygon = Polygon(4); polygon.ps[0] = Point(103.8192818798844, 975.8150929419839); polygon.ps[1] = Point(103.8192818798844, 995.8150929419839); polygon.ps[2] = Point(71.81928187988439, 995.8150929419839); polygon.ps[3] = Point(71.81928187988439, 975.8150929419839); new ShapeRef(router, polygon, 11); // shapeRef12 polygon = Polygon(4); polygon.ps[0] = Point(103.8192818798844, 1017.815092941984); polygon.ps[1] = Point(103.8192818798844, 1037.815092941984); polygon.ps[2] = Point(71.81928187988439, 1037.815092941984); polygon.ps[3] = Point(71.81928187988439, 1017.815092941984); new ShapeRef(router, polygon, 12); #if ALL // shapeRef13 polygon = Polygon(4); polygon.ps[0] = Point(328.8192818798844, 957.8150929419839); polygon.ps[1] = Point(328.8192818798844, 989.8150929419839); polygon.ps[2] = Point(308.8192818798844, 989.8150929419839); polygon.ps[3] = Point(308.8192818798844, 957.8150929419839); new ShapeRef(router, polygon, 13); // shapeRef14 polygon = Polygon(4); polygon.ps[0] = Point(12.81928187988439, 901.815092940984); polygon.ps[1] = Point(12.81928187988439, 921.815092940984); polygon.ps[2] = Point(-19.18071812011561, 921.815092940984); polygon.ps[3] = Point(-19.18071812011561, 901.815092940984); new ShapeRef(router, polygon, 14); // shapeRef15 polygon = Polygon(4); polygon.ps[0] = Point(466.8192818798844, 840.315092940984); polygon.ps[1] = Point(466.8192818798844, 872.315092940984); polygon.ps[2] = Point(446.8192818798844, 872.315092940984); polygon.ps[3] = Point(446.8192818798844, 840.315092940984); new ShapeRef(router, polygon, 15); // shapeRef16 polygon = Polygon(4); polygon.ps[0] = Point(1023.504996167599, 572.9817596076507); polygon.ps[1] = Point(1023.504996167599, 604.9817596076507); polygon.ps[2] = Point(1003.504996167599, 604.9817596076507); polygon.ps[3] = Point(1003.504996167599, 572.9817596076507); new ShapeRef(router, polygon, 16); // shapeRef17 polygon = Polygon(4); polygon.ps[0] = Point(887.1049961675988, 638.315092940984); polygon.ps[1] = Point(887.1049961675988, 658.315092940984); polygon.ps[2] = Point(855.1049961675988, 658.315092940984); polygon.ps[3] = Point(855.1049961675988, 638.315092940984); new ShapeRef(router, polygon, 17); // shapeRef18 polygon = Polygon(4); polygon.ps[0] = Point(472.8192818798844, 671.315092940984); polygon.ps[1] = Point(472.8192818798844, 691.315092940984); polygon.ps[2] = Point(440.8192818798844, 691.315092940984); polygon.ps[3] = Point(440.8192818798844, 671.315092940984); new ShapeRef(router, polygon, 18); // shapeRef19 polygon = Polygon(4); polygon.ps[0] = Point(142.8192818798844, 638.315092940984); polygon.ps[1] = Point(142.8192818798844, 658.315092940984); polygon.ps[2] = Point(110.8192818798844, 658.315092940984); polygon.ps[3] = Point(110.8192818798844, 638.315092940984); new ShapeRef(router, polygon, 19); // shapeRef20 polygon = Polygon(4); polygon.ps[0] = Point(599.1049961655988, 419.9817596066507); polygon.ps[1] = Point(599.1049961655988, 451.9817596066507); polygon.ps[2] = Point(579.1049961655988, 451.9817596066507); polygon.ps[3] = Point(579.1049961655988, 419.9817596066507); new ShapeRef(router, polygon, 20); // shapeRef21 polygon = Polygon(4); polygon.ps[0] = Point(472.8192818798844, 483.9817596066507); polygon.ps[1] = Point(472.8192818798844, 503.9817596066507); polygon.ps[2] = Point(440.8192818798844, 503.9817596066507); polygon.ps[3] = Point(440.8192818798844, 483.9817596066507); new ShapeRef(router, polygon, 21); // shapeRef22 polygon = Polygon(4); polygon.ps[0] = Point(472.8192818798844, 134.9817596056507); polygon.ps[1] = Point(472.8192818798844, 154.9817596056507); polygon.ps[2] = Point(440.8192818798844, 154.9817596056507); polygon.ps[3] = Point(440.8192818798844, 134.9817596056507); new ShapeRef(router, polygon, 22); // shapeRef23 polygon = Polygon(4); polygon.ps[0] = Point(1023.504996167599, 419.9817596066507); polygon.ps[1] = Point(1023.504996167599, 451.9817596066507); polygon.ps[2] = Point(1003.504996167599, 451.9817596066507); polygon.ps[3] = Point(1003.504996167599, 419.9817596066507); new ShapeRef(router, polygon, 23); // shapeRef24 polygon = Polygon(4); polygon.ps[0] = Point(751.1049961665988, 276.9817596056507); polygon.ps[1] = Point(751.1049961665988, 296.9817596056507); polygon.ps[2] = Point(719.1049961665988, 296.9817596056507); polygon.ps[3] = Point(719.1049961665988, 276.9817596056507); new ShapeRef(router, polygon, 24); // shapeRef25 polygon = Polygon(4); polygon.ps[0] = Point(472.8192818798844, 209.9817596056507); polygon.ps[1] = Point(472.8192818798844, 229.9817596056507); polygon.ps[2] = Point(440.8192818798844, 229.9817596056507); polygon.ps[3] = Point(440.8192818798844, 209.9817596056507); new ShapeRef(router, polygon, 25); // shapeRef26 polygon = Polygon(4); polygon.ps[0] = Point(751.1049961665988, 318.9817596056507); polygon.ps[1] = Point(751.1049961665988, 338.9817596056507); polygon.ps[2] = Point(719.1049961665988, 338.9817596056507); polygon.ps[3] = Point(719.1049961665988, 318.9817596056507); new ShapeRef(router, polygon, 26); // shapeRef27 polygon = Polygon(4); polygon.ps[0] = Point(472.8192818798844, -181.0182403963493); polygon.ps[1] = Point(472.8192818798844, -161.0182403963493); polygon.ps[2] = Point(440.8192818798844, -161.0182403963493); polygon.ps[3] = Point(440.8192818798844, -181.0182403963493); new ShapeRef(router, polygon, 27); // shapeRef28 polygon = Polygon(4); polygon.ps[0] = Point(599.1049961655988, -199.0182403963493); polygon.ps[1] = Point(599.1049961655988, -167.0182403963493); polygon.ps[2] = Point(579.1049961655988, -167.0182403963493); polygon.ps[3] = Point(579.1049961655988, -199.0182403963493); new ShapeRef(router, polygon, 28); // shapeRef29 polygon = Polygon(4); polygon.ps[0] = Point(472.8192818798844, 251.9817596056507); polygon.ps[1] = Point(472.8192818798844, 271.9817596056507); polygon.ps[2] = Point(440.8192818798844, 271.9817596056507); polygon.ps[3] = Point(440.8192818798844, 251.9817596056507); new ShapeRef(router, polygon, 29); // shapeRef30 polygon = Polygon(4); polygon.ps[0] = Point(142.8192818798844, -65.0182403953493); polygon.ps[1] = Point(142.8192818798844, -45.0182403953493); polygon.ps[2] = Point(110.8192818798844, -45.0182403953493); polygon.ps[3] = Point(110.8192818798844, -65.0182403953493); new ShapeRef(router, polygon, 30); // shapeRef31 polygon = Polygon(4); polygon.ps[0] = Point(-20.18071812011561, -65.0182403953493); polygon.ps[1] = Point(-20.18071812011561, -45.0182403953493); polygon.ps[2] = Point(-52.18071812011561, -45.0182403953493); polygon.ps[3] = Point(-52.18071812011561, -65.0182403953493); new ShapeRef(router, polygon, 31); // shapeRef32 polygon = Polygon(4); polygon.ps[0] = Point(267.8192818798844, 324.9817596056507); polygon.ps[1] = Point(267.8192818798844, 356.9817596056507); polygon.ps[2] = Point(247.8192818798844, 356.9817596056507); polygon.ps[3] = Point(247.8192818798844, 324.9817596056507); new ShapeRef(router, polygon, 32); // shapeRef33 polygon = Polygon(4); polygon.ps[0] = Point(136.8192818798844, 258.9817596056507); polygon.ps[1] = Point(136.8192818798844, 290.9817596056507); polygon.ps[2] = Point(116.8192818798844, 290.9817596056507); polygon.ps[3] = Point(116.8192818798844, 258.9817596056507); new ShapeRef(router, polygon, 33); // shapeRef34 polygon = Polygon(4); polygon.ps[0] = Point(472.8192818798844, -32.0182403953493); polygon.ps[1] = Point(472.8192818798844, -12.0182403953493); polygon.ps[2] = Point(440.8192818798844, -12.0182403953493); polygon.ps[3] = Point(440.8192818798844, -32.0182403953493); new ShapeRef(router, polygon, 34); // shapeRef35 polygon = Polygon(4); polygon.ps[0] = Point(1001.104996167599, 276.9817596056507); polygon.ps[1] = Point(1001.104996167599, 338.9817596056507); polygon.ps[2] = Point(939.1049961675988, 338.9817596056507); polygon.ps[3] = Point(939.1049961675988, 276.9817596056507); new ShapeRef(router, polygon, 35); // shapeRef36 polygon = Polygon(4); polygon.ps[0] = Point(854.1049961675988, 144.9817596056507); polygon.ps[1] = Point(854.1049961675988, 164.9817596056507); polygon.ps[2] = Point(822.1049961675988, 164.9817596056507); polygon.ps[3] = Point(822.1049961675988, 144.9817596056507); new ShapeRef(router, polygon, 36); // shapeRef37 polygon = Polygon(4); polygon.ps[0] = Point(854.1049961675988, 186.9817596056507); polygon.ps[1] = Point(854.1049961675988, 206.9817596056507); polygon.ps[2] = Point(822.1049961675988, 206.9817596056507); polygon.ps[3] = Point(822.1049961675988, 186.9817596056507); new ShapeRef(router, polygon, 37); // shapeRef38 polygon = Polygon(4); polygon.ps[0] = Point(472.8192818798844, -139.0182403963493); polygon.ps[1] = Point(472.8192818798844, -119.0182403963493); polygon.ps[2] = Point(440.8192818798844, -119.0182403963493); polygon.ps[3] = Point(440.8192818798844, -139.0182403963493); new ShapeRef(router, polygon, 38); // shapeRef39 polygon = Polygon(4); polygon.ps[0] = Point(854.1049961675988, 69.98175960565069); polygon.ps[1] = Point(854.1049961675988, 89.98175960565069); polygon.ps[2] = Point(822.1049961675988, 89.98175960565069); polygon.ps[3] = Point(822.1049961675988, 69.98175960565069); new ShapeRef(router, polygon, 39); // shapeRef40 polygon = Polygon(4); polygon.ps[0] = Point(-51.68071812011561, 455.4817596066507); polygon.ps[1] = Point(-51.68071812011561, 619.4817596066507); polygon.ps[2] = Point(-170.6807181201156, 619.4817596066507); polygon.ps[3] = Point(-170.6807181201156, 455.4817596066507); new ShapeRef(router, polygon, 40); // shapeRef41 polygon = Polygon(4); polygon.ps[0] = Point(31.81928187988439, -317.5182403973492); polygon.ps[1] = Point(31.81928187988439, -282.5182403973492); polygon.ps[2] = Point(-164.1807181201156, -282.5182403973492); polygon.ps[3] = Point(-164.1807181201156, -317.5182403973492); new ShapeRef(router, polygon, 41); // shapeRef42 polygon = Polygon(4); polygon.ps[0] = Point(752.8192818798843, 768.315092940984); polygon.ps[1] = Point(752.8192818798843, 812.315092940984); polygon.ps[2] = Point(664.8192818798843, 812.315092940984); polygon.ps[3] = Point(664.8192818798843, 768.315092940984); new ShapeRef(router, polygon, 42); // shapeRef43 polygon = Polygon(4); polygon.ps[0] = Point(349.8192818798844, 880.815092940984); polygon.ps[1] = Point(349.8192818798844, 942.815092940984); polygon.ps[2] = Point(287.8192818798844, 942.815092940984); polygon.ps[3] = Point(287.8192818798844, 880.815092940984); new ShapeRef(router, polygon, 43); // shapeRef44 polygon = Polygon(4); polygon.ps[0] = Point(349.8192818798844, -181.0182403963493); polygon.ps[1] = Point(349.8192818798844, -119.0182403963493); polygon.ps[2] = Point(287.8192818798844, -119.0182403963493); polygon.ps[3] = Point(287.8192818798844, -181.0182403963493); new ShapeRef(router, polygon, 44); // shapeRef45 polygon = Polygon(4); polygon.ps[0] = Point(935.1049961675988, -276.0182403973492); polygon.ps[1] = Point(935.1049961675988, -214.0182403973492); polygon.ps[2] = Point(873.1049961675988, -214.0182403973492); polygon.ps[3] = Point(873.1049961675988, -276.0182403973492); new ShapeRef(router, polygon, 45); // shapeRef46 polygon = Polygon(4); polygon.ps[0] = Point(620.1049961655988, 276.9817596056507); polygon.ps[1] = Point(620.1049961655988, 338.9817596056507); polygon.ps[2] = Point(558.1049961655988, 338.9817596056507); polygon.ps[3] = Point(558.1049961655988, 276.9817596056507); new ShapeRef(router, polygon, 46); // shapeRef47 polygon = Polygon(4); polygon.ps[0] = Point(620.1049961655988, 617.315092940984); polygon.ps[1] = Point(620.1049961655988, 679.315092940984); polygon.ps[2] = Point(558.1049961655988, 679.315092940984); polygon.ps[3] = Point(558.1049961655988, 617.315092940984); new ShapeRef(router, polygon, 47); #endif // shapeRef48 polygon = Polygon(4); polygon.ps[0] = Point(78.81928187988439, -86.0182403953493); polygon.ps[1] = Point(78.81928187988439, -24.0182403953493); polygon.ps[2] = Point(16.81928187988439, -24.0182403953493); polygon.ps[3] = Point(16.81928187988439, -86.0182403953493); new ShapeRef(router, polygon, 48); #if ALL // shapeRef49 polygon = Polygon(4); polygon.ps[0] = Point(-80.18071812011561, -86.0182403953493); polygon.ps[1] = Point(-80.18071812011561, -24.0182403953493); polygon.ps[2] = Point(-142.1807181201156, -24.0182403953493); polygon.ps[3] = Point(-142.1807181201156, -86.0182403953493); new ShapeRef(router, polygon, 49); // shapeRef50 polygon = Polygon(4); polygon.ps[0] = Point(620.1049961655988, -276.0182403973492); polygon.ps[1] = Point(620.1049961655988, -214.0182403973492); polygon.ps[2] = Point(558.1049961655988, -214.0182403973492); polygon.ps[3] = Point(558.1049961655988, -276.0182403973492); new ShapeRef(router, polygon, 50); // shapeRef51 polygon = Polygon(4); polygon.ps[0] = Point(349.8192818798844, -86.0182403953493); polygon.ps[1] = Point(349.8192818798844, -24.0182403953493); polygon.ps[2] = Point(287.8192818798844, -24.0182403953493); polygon.ps[3] = Point(287.8192818798844, -86.0182403953493); new ShapeRef(router, polygon, 51); // shapeRef52 polygon = Polygon(4); polygon.ps[0] = Point(620.1049961655988, 495.9817596066507); polygon.ps[1] = Point(620.1049961655988, 557.9817596066507); polygon.ps[2] = Point(558.1049961655988, 557.9817596066507); polygon.ps[3] = Point(558.1049961655988, 495.9817596066507); new ShapeRef(router, polygon, 52); // shapeRef53 polygon = Polygon(4); polygon.ps[0] = Point(115.8192818798844, 915.8150929419839); polygon.ps[1] = Point(115.8192818798844, 975.8150929419839); polygon.ps[2] = Point(59.81928187988439, 975.8150929419839); polygon.ps[3] = Point(59.81928187988439, 915.8150929419839); new ShapeRef(router, polygon, 53); // shapeRef54 polygon = Polygon(4); polygon.ps[0] = Point(115.8192818798844, 1037.815092941984); polygon.ps[1] = Point(115.8192818798844, 1097.815092941984); polygon.ps[2] = Point(59.81928187988439, 1097.815092941984); polygon.ps[3] = Point(59.81928187988439, 1037.815092941984); new ShapeRef(router, polygon, 54); // shapeRef55 polygon = Polygon(4); polygon.ps[0] = Point(404.8192818798844, 953.8150929419839); polygon.ps[1] = Point(404.8192818798844, 993.8150929419839); polygon.ps[2] = Point(328.8192818798844, 993.8150929419839); polygon.ps[3] = Point(328.8192818798844, 953.8150929419839); new ShapeRef(router, polygon, 55); #endif // shapeRef56 polygon = Polygon(4); polygon.ps[0] = Point(24.81928187988439, 841.815092940984); polygon.ps[1] = Point(24.81928187988439, 901.815092940984); polygon.ps[2] = Point(-31.18071812011561, 901.815092940984); polygon.ps[3] = Point(-31.18071812011561, 841.815092940984); new ShapeRef(router, polygon, 56); #if ALL // shapeRef57 polygon = Polygon(4); polygon.ps[0] = Point(542.8192818798843, 836.315092940984); polygon.ps[1] = Point(542.8192818798843, 876.315092940984); polygon.ps[2] = Point(466.8192818798844, 876.315092940984); polygon.ps[3] = Point(466.8192818798844, 836.315092940984); new ShapeRef(router, polygon, 57); // shapeRef58 polygon = Polygon(4); polygon.ps[0] = Point(1099.504996167599, 568.9817596076507); polygon.ps[1] = Point(1099.504996167599, 608.9817596076507); polygon.ps[2] = Point(1023.504996167599, 608.9817596076507); polygon.ps[3] = Point(1023.504996167599, 568.9817596076507); new ShapeRef(router, polygon, 58); // shapeRef59 polygon = Polygon(4); polygon.ps[0] = Point(899.1049961675988, 578.315092940984); polygon.ps[1] = Point(899.1049961675988, 638.315092940984); polygon.ps[2] = Point(843.1049961675988, 638.315092940984); polygon.ps[3] = Point(843.1049961675988, 578.315092940984); new ShapeRef(router, polygon, 59); // shapeRef60 polygon = Polygon(4); polygon.ps[0] = Point(484.8192818798844, 691.315092940984); polygon.ps[1] = Point(484.8192818798844, 751.315092940984); polygon.ps[2] = Point(428.8192818798844, 751.315092940984); polygon.ps[3] = Point(428.8192818798844, 691.315092940984); new ShapeRef(router, polygon, 60); // shapeRef61 polygon = Polygon(4); polygon.ps[0] = Point(154.8192818798844, 578.315092940984); polygon.ps[1] = Point(154.8192818798844, 638.315092940984); polygon.ps[2] = Point(98.81928187988439, 638.315092940984); polygon.ps[3] = Point(98.81928187988439, 578.315092940984); new ShapeRef(router, polygon, 61); // shapeRef62 polygon = Polygon(4); polygon.ps[0] = Point(675.1049961655988, 415.9817596066507); polygon.ps[1] = Point(675.1049961655988, 455.9817596066507); polygon.ps[2] = Point(599.1049961655988, 455.9817596066507); polygon.ps[3] = Point(599.1049961655988, 415.9817596066507); new ShapeRef(router, polygon, 62); // shapeRef63 polygon = Polygon(4); polygon.ps[0] = Point(484.8192818798844, 423.9817596066507); polygon.ps[1] = Point(484.8192818798844, 483.9817596066507); polygon.ps[2] = Point(428.8192818798844, 483.9817596066507); polygon.ps[3] = Point(428.8192818798844, 423.9817596066507); new ShapeRef(router, polygon, 63); // shapeRef64 polygon = Polygon(4); polygon.ps[0] = Point(484.8192818798844, 74.98175960565069); polygon.ps[1] = Point(484.8192818798844, 134.9817596056507); polygon.ps[2] = Point(428.8192818798844, 134.9817596056507); polygon.ps[3] = Point(428.8192818798844, 74.98175960565069); new ShapeRef(router, polygon, 64); // shapeRef65 polygon = Polygon(4); polygon.ps[0] = Point(1099.504996167599, 415.9817596066507); polygon.ps[1] = Point(1099.504996167599, 455.9817596066507); polygon.ps[2] = Point(1023.504996167599, 455.9817596066507); polygon.ps[3] = Point(1023.504996167599, 415.9817596066507); new ShapeRef(router, polygon, 65); // shapeRef66 polygon = Polygon(4); polygon.ps[0] = Point(763.1049961665988, 216.9817596056507); polygon.ps[1] = Point(763.1049961665988, 276.9817596056507); polygon.ps[2] = Point(707.1049961665988, 276.9817596056507); polygon.ps[3] = Point(707.1049961665988, 216.9817596056507); new ShapeRef(router, polygon, 66); // shapeRef67 polygon = Polygon(4); polygon.ps[0] = Point(484.8192818798844, 149.9817596056507); polygon.ps[1] = Point(484.8192818798844, 209.9817596056507); polygon.ps[2] = Point(428.8192818798844, 209.9817596056507); polygon.ps[3] = Point(428.8192818798844, 149.9817596056507); new ShapeRef(router, polygon, 67); // shapeRef68 polygon = Polygon(4); polygon.ps[0] = Point(763.1049961665988, 338.9817596056507); polygon.ps[1] = Point(763.1049961665988, 398.9817596056507); polygon.ps[2] = Point(707.1049961665988, 398.9817596056507); polygon.ps[3] = Point(707.1049961665988, 338.9817596056507); new ShapeRef(router, polygon, 68); // shapeRef69 polygon = Polygon(4); polygon.ps[0] = Point(484.8192818798844, -241.0182403963493); polygon.ps[1] = Point(484.8192818798844, -181.0182403963493); polygon.ps[2] = Point(428.8192818798844, -181.0182403963493); polygon.ps[3] = Point(428.8192818798844, -241.0182403963493); new ShapeRef(router, polygon, 69); // shapeRef70 polygon = Polygon(4); polygon.ps[0] = Point(675.1049961655988, -203.0182403963493); polygon.ps[1] = Point(675.1049961655988, -163.0182403963493); polygon.ps[2] = Point(599.1049961655988, -163.0182403963493); polygon.ps[3] = Point(599.1049961655988, -203.0182403963493); new ShapeRef(router, polygon, 70); // shapeRef71 polygon = Polygon(4); polygon.ps[0] = Point(484.8192818798844, 271.9817596056507); polygon.ps[1] = Point(484.8192818798844, 331.9817596056507); polygon.ps[2] = Point(428.8192818798844, 331.9817596056507); polygon.ps[3] = Point(428.8192818798844, 271.9817596056507); new ShapeRef(router, polygon, 71); // shapeRef72 polygon = Polygon(4); polygon.ps[0] = Point(154.8192818798844, -125.0182403953493); polygon.ps[1] = Point(154.8192818798844, -65.0182403953493); polygon.ps[2] = Point(98.81928187988439, -65.0182403953493); polygon.ps[3] = Point(98.81928187988439, -125.0182403953493); new ShapeRef(router, polygon, 72); // shapeRef73 polygon = Polygon(4); polygon.ps[0] = Point(-8.180718120115614, -125.0182403953493); polygon.ps[1] = Point(-8.180718120115614, -65.0182403953493); polygon.ps[2] = Point(-64.18071812011561, -65.0182403953493); polygon.ps[3] = Point(-64.18071812011561, -125.0182403953493); new ShapeRef(router, polygon, 73); // shapeRef74 polygon = Polygon(4); polygon.ps[0] = Point(343.8192818798844, 320.9817596056507); polygon.ps[1] = Point(343.8192818798844, 360.9817596056507); polygon.ps[2] = Point(267.8192818798844, 360.9817596056507); polygon.ps[3] = Point(267.8192818798844, 320.9817596056507); new ShapeRef(router, polygon, 74); // shapeRef75 polygon = Polygon(4); polygon.ps[0] = Point(212.8192818798844, 254.9817596056507); polygon.ps[1] = Point(212.8192818798844, 294.9817596056507); polygon.ps[2] = Point(136.8192818798844, 294.9817596056507); polygon.ps[3] = Point(136.8192818798844, 254.9817596056507); new ShapeRef(router, polygon, 75); // shapeRef76 polygon = Polygon(4); polygon.ps[0] = Point(484.8192818798844, -12.0182403953493); polygon.ps[1] = Point(484.8192818798844, 47.9817596046507); polygon.ps[2] = Point(428.8192818798844, 47.9817596046507); polygon.ps[3] = Point(428.8192818798844, -12.0182403953493); new ShapeRef(router, polygon, 76); // shapeRef77 polygon = Polygon(4); polygon.ps[0] = Point(866.1049961675988, 84.98175960565069); polygon.ps[1] = Point(866.1049961675988, 144.9817596056507); polygon.ps[2] = Point(810.1049961675988, 144.9817596056507); polygon.ps[3] = Point(810.1049961675988, 84.98175960565069); new ShapeRef(router, polygon, 77); // shapeRef78 polygon = Polygon(4); polygon.ps[0] = Point(866.1049961675988, 206.9817596056507); polygon.ps[1] = Point(866.1049961675988, 266.9817596056507); polygon.ps[2] = Point(810.1049961675988, 266.9817596056507); polygon.ps[3] = Point(810.1049961675988, 206.9817596056507); new ShapeRef(router, polygon, 78); // shapeRef79 polygon = Polygon(4); polygon.ps[0] = Point(484.8192818798844, -119.0182403963493); polygon.ps[1] = Point(484.8192818798844, -59.01824039634928); polygon.ps[2] = Point(428.8192818798844, -59.01824039634928); polygon.ps[3] = Point(428.8192818798844, -119.0182403963493); new ShapeRef(router, polygon, 79); // shapeRef80 polygon = Polygon(4); polygon.ps[0] = Point(866.1049961675988, 9.981759605650694); polygon.ps[1] = Point(866.1049961675988, 69.98175960565069); polygon.ps[2] = Point(810.1049961675988, 69.98175960565069); polygon.ps[3] = Point(810.1049961675988, 9.981759605650694); new ShapeRef(router, polygon, 80); // shapeRef81 polygon = Polygon(4); polygon.ps[0] = Point(-91.18071812011561, 455.9817596066507); polygon.ps[1] = Point(-91.18071812011561, 515.9817596066507); polygon.ps[2] = Point(-131.1807181201156, 515.9817596066507); polygon.ps[3] = Point(-131.1807181201156, 455.9817596066507); new ShapeRef(router, polygon, 81); // shapeRef82 polygon = Polygon(4); polygon.ps[0] = Point(-91.18071812011561, 559.9817596066507); polygon.ps[1] = Point(-91.18071812011561, 619.9817596066507); polygon.ps[2] = Point(-131.1807181201156, 619.9817596066507); polygon.ps[3] = Point(-131.1807181201156, 559.9817596066507); new ShapeRef(router, polygon, 82); // shapeRef83 polygon = Polygon(4); polygon.ps[0] = Point(876.0049961675987, 79.98175960565069); polygon.ps[1] = Point(876.0049961675987, 196.9817596056507); polygon.ps[2] = Point(800.2049961675988, 196.9817596056507); polygon.ps[3] = Point(800.2049961675988, 79.98175960565069); new ShapeRef(router, polygon, 83); #endif // shapeRef84 polygon = Polygon(4); polygon.ps[0] = Point(125.7192818798844, 985.8150929419839); polygon.ps[1] = Point(125.7192818798844, 1027.815092941984); polygon.ps[2] = Point(49.91928187988439, 1027.815092941984); polygon.ps[3] = Point(49.91928187988439, 985.8150929419839); new ShapeRef(router, polygon, 84); #if ALL // shapeRef85 polygon = Polygon(4); polygon.ps[0] = Point(494.7192818798844, -171.0182403963493); polygon.ps[1] = Point(494.7192818798844, -129.0182403963493); polygon.ps[2] = Point(418.9192818798844, -129.0182403963493); polygon.ps[3] = Point(418.9192818798844, -171.0182403963493); new ShapeRef(router, polygon, 85); // shapeRef86 polygon = Polygon(4); polygon.ps[0] = Point(773.0049961665987, 286.9817596056507); polygon.ps[1] = Point(773.0049961665987, 328.9817596056507); polygon.ps[2] = Point(697.2049961665988, 328.9817596056507); polygon.ps[3] = Point(697.2049961665988, 286.9817596056507); new ShapeRef(router, polygon, 86); // shapeRef87 polygon = Polygon(4); polygon.ps[0] = Point(494.7192818798844, 144.9817596056507); polygon.ps[1] = Point(494.7192818798844, 261.9817596056507); polygon.ps[2] = Point(418.9192818798844, 261.9817596056507); polygon.ps[3] = Point(418.9192818798844, 144.9817596056507); new ShapeRef(router, polygon, 87); // connRef88 connRef = new ConnRef(router, 88); srcPt = ConnEnd(Point(111.8192818798844, 648.315092940984), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(-111.1807181201156, 856.315092940984), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef89 connRef = new ConnRef(router, 89); srcPt = ConnEnd(Point(126.8192818798844, 289.9817596056507), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(-111.1807181201156, 856.315092940984), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); #endif // connRef90 connRef = new ConnRef(router, 90); srcPt = ConnEnd(Point(72.81928187988439, 985.8150929419839), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, -55.0182403953493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints90(1); checkpoints90[0] = Checkpoint(Point(49.81928187988439, 1006.815092941984), (ConnDirFlags) 15, (ConnDirFlags) 4); connRef->setRoutingCheckpoints(checkpoints90); Avoid::ConnRef *connRef90 = connRef; // connRef91 connRef = new ConnRef(router, 91); srcPt = ConnEnd(Point(72.81928187988439, 1027.815092941984), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, -55.0182403953493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints91(1); checkpoints91[0] = Checkpoint(Point(49.81928187988439, 1006.815092941984), (ConnDirFlags) 15, (ConnDirFlags) 4); connRef->setRoutingCheckpoints(checkpoints91); Avoid::ConnRef *connRef91 = connRef; #if ALL // connRef92 connRef = new ConnRef(router, 92); srcPt = ConnEnd(Point(471.8192818798844, -171.0182403963493), 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, -55.0182403953493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints92(1); checkpoints92[0] = Checkpoint(Point(494.8192818798844, -150.0182403963493), (ConnDirFlags) 15, (ConnDirFlags) 8); connRef->setRoutingCheckpoints(checkpoints92); // connRef93 connRef = new ConnRef(router, 93); srcPt = ConnEnd(Point(589.1049961655988, -55.0182403953493), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, -168.0182403963493), 2); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef94 connRef = new ConnRef(router, 94); srcPt = ConnEnd(Point(589.1049961655988, -55.0182403953493), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(471.8192818798844, -22.0182403953493), 8); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef95 connRef = new ConnRef(router, 95); srcPt = ConnEnd(Point(823.1049961675988, 154.9817596056507), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, -55.0182403953493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints95(1); checkpoints95[0] = Checkpoint(Point(800.1049961675988, 175.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 4); connRef->setRoutingCheckpoints(checkpoints95); // connRef96 connRef = new ConnRef(router, 96); srcPt = ConnEnd(Point(823.1049961675988, 196.9817596056507), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, -55.0182403953493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints96(1); checkpoints96[0] = Checkpoint(Point(800.1049961675988, 175.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 4); connRef->setRoutingCheckpoints(checkpoints96); // connRef97 connRef = new ConnRef(router, 97); srcPt = ConnEnd(Point(471.8192818798844, -129.0182403963493), 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, -55.0182403953493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints97(1); checkpoints97[0] = Checkpoint(Point(494.8192818798844, -150.0182403963493), (ConnDirFlags) 15, (ConnDirFlags) 8); connRef->setRoutingCheckpoints(checkpoints97); // connRef98 connRef = new ConnRef(router, 98); srcPt = ConnEnd(Point(823.1049961675988, 79.98175960565069), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, -55.0182403953493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints98(1); checkpoints98[0] = Checkpoint(Point(800.1049961675988, 175.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 4); connRef->setRoutingCheckpoints(checkpoints98); // connRef99 connRef = new ConnRef(router, 99); srcPt = ConnEnd(Point(1013.504996167599, 526.9817596066507), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(1013.504996167599, 573.9817596076507), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef100 connRef = new ConnRef(router, 100); srcPt = ConnEnd(Point(1013.504996167599, 450.9817596066507), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(1013.504996167599, 526.9817596066507), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef101 connRef = new ConnRef(router, 101); srcPt = ConnEnd(Point(318.8192818798844, 648.315092940984), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(141.8192818798844, 648.315092940984), 8); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef102 connRef = new ConnRef(router, 102); srcPt = ConnEnd(Point(441.8192818798844, 493.9817596066507), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, 648.315092940984), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef103 connRef = new ConnRef(router, 103); srcPt = ConnEnd(Point(102.8192818798844, 985.8150929419839), 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, 911.815092940984), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints103(1); checkpoints103[0] = Checkpoint(Point(125.8192818798844, 1006.815092941984), (ConnDirFlags) 15, (ConnDirFlags) 8); connRef->setRoutingCheckpoints(checkpoints103); // connRef104 connRef = new ConnRef(router, 104); srcPt = ConnEnd(Point(102.8192818798844, 1027.815092941984), 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, 911.815092940984), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints104(1); checkpoints104[0] = Checkpoint(Point(125.8192818798844, 1006.815092941984), (ConnDirFlags) 15, (ConnDirFlags) 8); connRef->setRoutingCheckpoints(checkpoints104); // connRef105 connRef = new ConnRef(router, 105); srcPt = ConnEnd(Point(318.8192818798844, 988.8150929419839), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, 1039.815092941984), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef106 connRef = new ConnRef(router, 106); srcPt = ConnEnd(Point(318.8192818798844, 911.815092940984), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, 958.8150929419839), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef107 connRef = new ConnRef(router, 107); srcPt = ConnEnd(Point(-18.18071812011561, 911.815092940984), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(-111.1807181201156, 856.315092940984), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef108 connRef = new ConnRef(router, 108); srcPt = ConnEnd(Point(318.8192818798844, 911.815092940984), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(11.81928187988439, 911.815092940984), 8); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef109 connRef = new ConnRef(router, 109); srcPt = ConnEnd(Point(456.8192818798844, 871.315092940984), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, 911.815092940984), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef110 connRef = new ConnRef(router, 110); srcPt = ConnEnd(Point(589.1049961655988, 648.315092940984), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(456.8192818798844, 841.315092940984), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef111 connRef = new ConnRef(router, 111); srcPt = ConnEnd(Point(1013.504996167599, 603.9817596076507), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(1013.504996167599, 750.315092940984), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef112 connRef = new ConnRef(router, 112); srcPt = ConnEnd(Point(970.1049961675988, 307.9817596056507), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(886.1049961675988, 648.315092940984), 8); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef113 connRef = new ConnRef(router, 113); srcPt = ConnEnd(Point(856.1049961675988, 648.315092940984), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, 648.315092940984), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef114 connRef = new ConnRef(router, 114); srcPt = ConnEnd(Point(441.8192818798844, 681.315092940984), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, 648.315092940984), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef115 connRef = new ConnRef(router, 115); srcPt = ConnEnd(Point(589.1049961655988, 307.9817596056507), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, 420.9817596066507), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef116 connRef = new ConnRef(router, 116); srcPt = ConnEnd(Point(589.1049961655988, 450.9817596066507), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, 526.9817596066507), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef117 connRef = new ConnRef(router, 117); srcPt = ConnEnd(Point(589.1049961655988, 307.9817596056507), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(471.8192818798844, 493.9817596066507), 8); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef118 connRef = new ConnRef(router, 118); srcPt = ConnEnd(Point(471.8192818798844, 144.9817596056507), 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, 307.9817596056507), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints118(1); checkpoints118[0] = Checkpoint(Point(494.8192818798844, 240.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 8); connRef->setRoutingCheckpoints(checkpoints118); // connRef119 connRef = new ConnRef(router, 119); srcPt = ConnEnd(Point(441.8192818798844, 144.9817596056507), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, -55.0182403953493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints119(1); checkpoints119[0] = Checkpoint(Point(418.8192818798844, 240.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 4); connRef->setRoutingCheckpoints(checkpoints119); // connRef120 connRef = new ConnRef(router, 120); srcPt = ConnEnd(Point(970.1049961675988, 307.9817596056507), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(1013.504996167599, 420.9817596066507), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef121 connRef = new ConnRef(router, 121); srcPt = ConnEnd(Point(750.1049961665988, 286.9817596056507), 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(970.1049961675988, 307.9817596056507), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints121(1); checkpoints121[0] = Checkpoint(Point(773.1049961665988, 307.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 8); connRef->setRoutingCheckpoints(checkpoints121); // connRef122 connRef = new ConnRef(router, 122); srcPt = ConnEnd(Point(720.1049961665988, 286.9817596056507), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, 307.9817596056507), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints122(1); checkpoints122[0] = Checkpoint(Point(697.1049961665988, 307.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 4); connRef->setRoutingCheckpoints(checkpoints122); // connRef123 connRef = new ConnRef(router, 123); srcPt = ConnEnd(Point(471.8192818798844, 219.9817596056507), 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, 307.9817596056507), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints123(1); checkpoints123[0] = Checkpoint(Point(494.8192818798844, 240.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 8); connRef->setRoutingCheckpoints(checkpoints123); // connRef124 connRef = new ConnRef(router, 124); srcPt = ConnEnd(Point(441.8192818798844, 219.9817596056507), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, -55.0182403953493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints124(1); checkpoints124[0] = Checkpoint(Point(418.8192818798844, 240.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 4); connRef->setRoutingCheckpoints(checkpoints124); // connRef125 connRef = new ConnRef(router, 125); srcPt = ConnEnd(Point(750.1049961665988, 328.9817596056507), 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(970.1049961675988, 307.9817596056507), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints125(1); checkpoints125[0] = Checkpoint(Point(773.1049961665988, 307.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 8); connRef->setRoutingCheckpoints(checkpoints125); // connRef126 connRef = new ConnRef(router, 126); srcPt = ConnEnd(Point(441.8192818798844, -171.0182403963493), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, -150.0182403963493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints126(1); checkpoints126[0] = Checkpoint(Point(418.8192818798844, -150.0182403963493), (ConnDirFlags) 15, (ConnDirFlags) 4); connRef->setRoutingCheckpoints(checkpoints126); // connRef127 connRef = new ConnRef(router, 127); srcPt = ConnEnd(Point(589.1049961655988, -198.0182403963493), 1); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, -245.0182403973492), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef128 connRef = new ConnRef(router, 128); srcPt = ConnEnd(Point(471.8192818798844, 261.9817596056507), 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, 307.9817596056507), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints128(1); checkpoints128[0] = Checkpoint(Point(494.8192818798844, 240.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 8); connRef->setRoutingCheckpoints(checkpoints128); // connRef129 connRef = new ConnRef(router, 129); srcPt = ConnEnd(Point(441.8192818798844, 261.9817596056507), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, -55.0182403953493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints129(1); checkpoints129[0] = Checkpoint(Point(418.8192818798844, 240.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 4); connRef->setRoutingCheckpoints(checkpoints129); #endif // connRef130 connRef = new ConnRef(router, 130); srcPt = ConnEnd(Point(47.81928187988439, -55.0182403953493), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(111.8192818798844, -55.0182403953493), 4); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); #if ALL // connRef131 connRef = new ConnRef(router, 131); srcPt = ConnEnd(Point(141.8192818798844, -55.0182403953493), 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, -55.0182403953493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef132 connRef = new ConnRef(router, 132); srcPt = ConnEnd(Point(-21.18071812011561, -55.0182403953493), 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(47.81928187988439, -55.0182403953493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef133 connRef = new ConnRef(router, 133); srcPt = ConnEnd(Point(-111.1807181201156, -55.0182403953493), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(-51.18071812011561, -55.0182403953493), 4); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef134 connRef = new ConnRef(router, 134); srcPt = ConnEnd(Point(257.8192818798844, 355.9817596056507), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(257.8192818798844, 402.9817596066507), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef135 connRef = new ConnRef(router, 135); srcPt = ConnEnd(Point(318.8192818798844, -55.0182403953493), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(257.8192818798844, 325.9817596056507), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef136 connRef = new ConnRef(router, 136); srcPt = ConnEnd(Point(318.8192818798844, -55.0182403953493), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(126.8192818798844, 259.9817596056507), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef137 connRef = new ConnRef(router, 137); srcPt = ConnEnd(Point(441.8192818798844, -22.0182403953493), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, -55.0182403953493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef138 connRef = new ConnRef(router, 138); srcPt = ConnEnd(Point(853.1049961675988, 154.9817596056507), 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(970.1049961675988, 307.9817596056507), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints138(1); checkpoints138[0] = Checkpoint(Point(876.1049961675988, 175.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 8); connRef->setRoutingCheckpoints(checkpoints138); // connRef139 connRef = new ConnRef(router, 139); srcPt = ConnEnd(Point(853.1049961675988, 196.9817596056507), 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(970.1049961675988, 307.9817596056507), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints139(1); checkpoints139[0] = Checkpoint(Point(876.1049961675988, 175.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 8); connRef->setRoutingCheckpoints(checkpoints139); // connRef140 connRef = new ConnRef(router, 140); srcPt = ConnEnd(Point(853.1049961675988, 79.98175960565069), 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(970.1049961675988, 307.9817596056507), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints140(1); checkpoints140[0] = Checkpoint(Point(876.1049961675988, 175.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 8); connRef->setRoutingCheckpoints(checkpoints140); // connRef141 connRef = new ConnRef(router, 141); srcPt = ConnEnd(Point(441.8192818798844, -129.0182403963493), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, -150.0182403963493), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints141(1); checkpoints141[0] = Checkpoint(Point(418.8192818798844, -150.0182403963493), (ConnDirFlags) 15, (ConnDirFlags) 4); connRef->setRoutingCheckpoints(checkpoints141); // connRef142 connRef = new ConnRef(router, 142); srcPt = ConnEnd(Point(720.1049961665988, 328.9817596056507), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, 307.9817596056507), 15); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); std::vector<Checkpoint> checkpoints142(1); checkpoints142[0] = Checkpoint(Point(697.1049961665988, 307.9817596056507), (ConnDirFlags) 15, (ConnDirFlags) 4); connRef->setRoutingCheckpoints(checkpoints142); // connRef143 connRef = new ConnRef(router, 143); srcPt = ConnEnd(Point(589.1049961655988, 648.315092940984), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(471.8192818798844, 681.315092940984), 8); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef144 connRef = new ConnRef(router, 144); srcPt = ConnEnd(Point(87.81928187988439, 935.8150929419839), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(87.81928187988439, 985.8150929419839), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef145 connRef = new ConnRef(router, 145); srcPt = ConnEnd(Point(87.81928187988439, 1077.815092941984), 1); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(87.81928187988439, 1027.815092941984), 2); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef146 connRef = new ConnRef(router, 146); srcPt = ConnEnd(Point(376.8192818798844, 973.8150929419839), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(318.8192818798844, 973.8150929419839), 8); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef147 connRef = new ConnRef(router, 147); srcPt = ConnEnd(Point(-3.180718120115614, 861.815092940984), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(-3.180718120115614, 911.815092940984), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef148 connRef = new ConnRef(router, 148); srcPt = ConnEnd(Point(514.8192818798843, 856.315092940984), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(456.8192818798844, 856.315092940984), 8); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef149 connRef = new ConnRef(router, 149); srcPt = ConnEnd(Point(1071.504996167599, 588.9817596076507), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(1013.504996167599, 588.9817596076507), 8); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef150 connRef = new ConnRef(router, 150); srcPt = ConnEnd(Point(871.1049961675988, 598.315092940984), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(871.1049961675988, 648.315092940984), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef151 connRef = new ConnRef(router, 151); srcPt = ConnEnd(Point(456.8192818798844, 731.315092940984), 1); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(456.8192818798844, 681.315092940984), 2); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef152 connRef = new ConnRef(router, 152); srcPt = ConnEnd(Point(126.8192818798844, 598.315092940984), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(126.8192818798844, 648.315092940984), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef153 connRef = new ConnRef(router, 153); srcPt = ConnEnd(Point(647.1049961655988, 435.9817596066507), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, 435.9817596066507), 8); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef154 connRef = new ConnRef(router, 154); srcPt = ConnEnd(Point(456.8192818798844, 443.9817596066507), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(456.8192818798844, 493.9817596066507), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef155 connRef = new ConnRef(router, 155); srcPt = ConnEnd(Point(456.8192818798844, 94.98175960565069), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(456.8192818798844, 144.9817596056507), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef156 connRef = new ConnRef(router, 156); srcPt = ConnEnd(Point(1071.504996167599, 435.9817596066507), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(1013.504996167599, 435.9817596066507), 8); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef157 connRef = new ConnRef(router, 157); srcPt = ConnEnd(Point(735.1049961665988, 236.9817596056507), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(735.1049961665988, 286.9817596056507), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef158 connRef = new ConnRef(router, 158); srcPt = ConnEnd(Point(456.8192818798844, 169.9817596056507), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(456.8192818798844, 219.9817596056507), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef159 connRef = new ConnRef(router, 159); srcPt = ConnEnd(Point(735.1049961665988, 378.9817596056507), 1); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(735.1049961665988, 328.9817596056507), 2); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef160 connRef = new ConnRef(router, 160); srcPt = ConnEnd(Point(456.8192818798844, -221.0182403963493), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(456.8192818798844, -171.0182403963493), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef161 connRef = new ConnRef(router, 161); srcPt = ConnEnd(Point(647.1049961655988, -183.0182403963493), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(589.1049961655988, -183.0182403963493), 8); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef162 connRef = new ConnRef(router, 162); srcPt = ConnEnd(Point(456.8192818798844, 311.9817596056507), 1); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(456.8192818798844, 261.9817596056507), 2); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef163 connRef = new ConnRef(router, 163); srcPt = ConnEnd(Point(126.8192818798844, -105.0182403953493), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(126.8192818798844, -55.0182403953493), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef164 connRef = new ConnRef(router, 164); srcPt = ConnEnd(Point(-36.18071812011561, -105.0182403953493), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(-36.18071812011561, -55.0182403953493), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef165 connRef = new ConnRef(router, 165); srcPt = ConnEnd(Point(315.8192818798844, 340.9817596056507), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(257.8192818798844, 340.9817596056507), 8); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef166 connRef = new ConnRef(router, 166); srcPt = ConnEnd(Point(184.8192818798844, 274.9817596056507), 4); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(126.8192818798844, 274.9817596056507), 8); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef167 connRef = new ConnRef(router, 167); srcPt = ConnEnd(Point(456.8192818798844, 27.9817596046507), 1); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(456.8192818798844, -22.0182403953493), 2); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef168 connRef = new ConnRef(router, 168); srcPt = ConnEnd(Point(838.1049961675988, 104.9817596056507), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(838.1049961675988, 154.9817596056507), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef169 connRef = new ConnRef(router, 169); srcPt = ConnEnd(Point(838.1049961675988, 246.9817596056507), 1); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(838.1049961675988, 196.9817596056507), 2); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef170 connRef = new ConnRef(router, 170); srcPt = ConnEnd(Point(456.8192818798844, -79.01824039634928), 1); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(456.8192818798844, -129.0182403963493), 2); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef171 connRef = new ConnRef(router, 171); srcPt = ConnEnd(Point(838.1049961675988, 29.98175960565069), 2); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(838.1049961675988, 79.98175960565069), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef172 connRef = new ConnRef(router, 172); srcPt = ConnEnd(Point(-111.1807181201156, -55.0182403953493), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(-111.1807181201156, 460.9817596066507), 1); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef173 connRef = new ConnRef(router, 173); srcPt = ConnEnd(Point(-111.1807181201156, 856.315092940984), 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(Point(-111.1807181201156, 614.9817596066507), 2); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); #endif router->processTransaction(); router->outputDiagram("output/nudgingSkipsCheckpoint01"); Avoid::PolyLine route90 = connRef90->displayRoute(); Avoid::PolyLine route91 = connRef91->displayRoute(); delete router; return (route90.size() == 7 && route91.size() == 7) ? 0 : 1; };
{ "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. */ #include "config.h" #if ENABLE(VIDEO_TRACK) #include "CachedTextTrack.h" #include "CachedResourceClient.h" #include "CachedResourceClientWalker.h" #include "CachedResourceLoader.h" #include "SharedBuffer.h" #include "TextResourceDecoder.h" namespace WebCore { CachedTextTrack::CachedTextTrack(CachedResourceRequest&& request, const PAL::SessionID& sessionID, const CookieJar* cookieJar) : CachedResource(WTFMove(request), Type::TextTrackResource, sessionID, cookieJar) { } void CachedTextTrack::doUpdateBuffer(SharedBuffer* data) { ASSERT(dataBufferingPolicy() == DataBufferingPolicy::BufferData); m_data = data; setEncodedSize(data ? data->size() : 0); CachedResourceClientWalker<CachedResourceClient> walker(m_clients); while (CachedResourceClient* client = walker.next()) client->deprecatedDidReceiveCachedResource(*this); } void CachedTextTrack::updateBuffer(SharedBuffer& data) { doUpdateBuffer(&data); CachedResource::updateBuffer(data); } void CachedTextTrack::finishLoading(SharedBuffer* data) { doUpdateBuffer(data); CachedResource::finishLoading(data); } } #endif
{ "pile_set_name": "Github" }
<div class="control-group"> <label>{{ __('velocity::app.admin.general.locale_logo') }}</label> @if (isset($locale) && $locale->locale_image) <image-wrapper :multiple="false" input-name="locale_image" :images='"{{ Storage:: url($locale->locale_image) }}"' :button-label="'{{ __('admin::app.catalog.products.add-image-btn-title') }}'"> </image-wrapper> @else <image-wrapper :multiple="false" input-name="locale_image" :button-label="'{{ __('admin::app.catalog.products.add-image-btn-title') }}'"> </image-wrapper> @endif </div>
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <doc> <assembly> <name>System.Threading.Tasks</name> </assembly> <members> <member name="T:System.Runtime.CompilerServices.AsyncMethodBuilderCore"> <summary>Holds state related to the builder's IAsyncStateMachine.</summary> <remarks>This is a mutable struct. Be very delicate with it.</remarks> </member> <member name="F:System.Runtime.CompilerServices.AsyncMethodBuilderCore.m_stateMachine"> <summary>A reference to the heap-allocated state machine object associated with this builder.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start``1(``0@)"> <summary>Initiates the builder's execution with the associated state machine.</summary> <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> <param name="stateMachine">The state machine instance, passed by reference.</param> <exception cref="T:System.ArgumentNullException">The <paramref name="stateMachine"/> argument is null (Nothing in Visual Basic).</exception> </member> <member name="M:System.Runtime.CompilerServices.AsyncMethodBuilderCore.SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine)"> <summary>Associates the builder with the state machine it represents.</summary> <param name="stateMachine">The heap-allocated state machine object.</param> <exception cref="T:System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> <exception cref="T:System.InvalidOperationException">The builder is incorrectly initialized.</exception> </member> <member name="M:System.Runtime.CompilerServices.AsyncMethodBuilderCore.GetCompletionAction``2(``0@,``1@)"> <summary> Gets the Action to use with an awaiter's OnCompleted or UnsafeOnCompleted method. On first invocation, the supplied state machine will be boxed. </summary> <typeparam name="TMethodBuilder">Specifies the type of the method builder used.</typeparam> <typeparam name="TStateMachine">Specifies the type of the state machine used.</typeparam> <param name="builder">The builder.</param> <param name="stateMachine">The state machine.</param> <returns>An Action to provide to the awaiter.</returns> </member> <member name="T:System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner"> <summary>Provides the ability to invoke a state machine's MoveNext method under a supplied ExecutionContext.</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.m_context"> <summary>The context with which to run MoveNext.</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.m_stateMachine"> <summary>The state machine whose MoveNext method should be invoked.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.#ctor(System.ExecutionContextLightup)"> <summary>Initializes the runner.</summary> <param name="context">The context with which to run MoveNext.</param> </member> <member name="M:System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run"> <summary>Invokes MoveNext under the provided context.</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.s_invokeMoveNext"> <summary>Cached delegate used with ExecutionContext.Run.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.InvokeMoveNext(System.Object)"> <summary>Invokes the MoveNext method on the supplied IAsyncStateMachine.</summary> <param name="stateMachine">The IAsyncStateMachine machine instance.</param> </member> <member name="T:System.Runtime.CompilerServices.AsyncMethodTaskCache`1"> <summary>Provides a base class used to cache tasks of a specific return type.</summary> <typeparam name="TResult">Specifies the type of results the cached tasks return.</typeparam> </member> <member name="F:System.Runtime.CompilerServices.AsyncMethodTaskCache`1.Singleton"> <summary> A singleton cache for this result type. This may be null if there are no cached tasks for this TResult. </summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncMethodTaskCache`1.CreateCompleted(`0)"> <summary>Creates a non-disposable task.</summary> <param name="result">The result for the task.</param> <returns>The cacheable task.</returns> </member> <member name="M:System.Runtime.CompilerServices.AsyncMethodTaskCache`1.CreateCache"> <summary>Creates a cache.</summary> <returns>A task cache for this result type.</returns> </member> <member name="M:System.Runtime.CompilerServices.AsyncMethodTaskCache`1.FromResult(`0)"> <summary>Gets a cached task if one exists.</summary> <param name="result">The result for which we want a cached task.</param> <returns>A cached task if one exists; otherwise, null.</returns> </member> <member name="T:System.Runtime.CompilerServices.AsyncMethodTaskCache`1.AsyncMethodBooleanTaskCache"> <summary>Provides a cache for Boolean tasks.</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncMethodTaskCache`1.AsyncMethodBooleanTaskCache.m_true"> <summary>A true task.</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncMethodTaskCache`1.AsyncMethodBooleanTaskCache.m_false"> <summary>A false task.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncMethodTaskCache`1.AsyncMethodBooleanTaskCache.FromResult(System.Boolean)"> <summary>Gets a cached task for the Boolean result.</summary> <param name="result">true or false</param> <returns>A cached task for the Boolean result.</returns> </member> <member name="T:System.Runtime.CompilerServices.AsyncMethodTaskCache`1.AsyncMethodInt32TaskCache"> <summary>Provides a cache for zero Int32 tasks.</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncMethodTaskCache`1.AsyncMethodInt32TaskCache.INCLUSIVE_INT32_MIN"> <summary>The minimum value, inclusive, for which we want a cached task.</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncMethodTaskCache`1.AsyncMethodInt32TaskCache.EXCLUSIVE_INT32_MAX"> <summary>The maximum value, exclusive, for which we want a cached task.</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncMethodTaskCache`1.AsyncMethodInt32TaskCache.Int32Tasks"> <summary>The cache of Task{Int32}.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncMethodTaskCache`1.AsyncMethodInt32TaskCache.CreateInt32Tasks"> <summary>Creates an array of cached tasks for the values in the range [INCLUSIVE_MIN,EXCLUSIVE_MAX).</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncMethodTaskCache`1.AsyncMethodInt32TaskCache.FromResult(System.Int32)"> <summary>Gets a cached task for the zero Int32 result.</summary> <param name="result">The integer value</param> <returns>A cached task for the Int32 result or null if not cached.</returns> </member> <member name="M:System.Runtime.CompilerServices.AsyncServices.ThrowAsync(System.Exception,System.Threading.SynchronizationContext)"> <summary>Throws the exception on the ThreadPool.</summary> <param name="exception">The exception to propagate.</param> <param name="targetContext">The target context on which to propagate the exception. Null to use the ThreadPool.</param> </member> <member name="M:System.Runtime.CompilerServices.AsyncServices.PrepareExceptionForRethrow(System.Exception)"> <summary>Copies the exception's stack trace so its stack trace isn't overwritten.</summary> <param name="exc">The exception to prepare.</param> </member> <member name="T:System.Runtime.CompilerServices.AsyncTaskMethodBuilder"> <summary> Provides a builder for asynchronous methods that return <see cref="T:System.Threading.Tasks.Task"/>. This type is intended for compiler use only. </summary> <remarks> AsyncTaskMethodBuilder is a value type, and thus it is copied by value. Prior to being copied, one of its Task, SetResult, or SetException members must be accessed, or else the copies may end up building distinct Task instances. </remarks> </member> <member name="T:System.Runtime.CompilerServices.IAsyncMethodBuilder"> <summary>Represents an asynchronous method builder.</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncTaskMethodBuilder.s_cachedCompleted"> <summary>A cached VoidTaskResult task used for builders that complete synchronously.</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncTaskMethodBuilder.m_builder"> <summary>The generic builder object to which this non-generic instance delegates.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Create"> <summary>Initializes a new <see cref="T:System.Runtime.CompilerServices.AsyncTaskMethodBuilder"/>.</summary> <returns>The initialized <see cref="T:System.Runtime.CompilerServices.AsyncTaskMethodBuilder"/>.</returns> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start``1(``0@)"> <summary>Initiates the builder's execution with the associated state machine.</summary> <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> <param name="stateMachine">The state machine instance, passed by reference.</param> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine)"> <summary>Associates the builder with the state machine it represents.</summary> <param name="stateMachine">The heap-allocated state machine object.</param> <exception cref="T:System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> <exception cref="T:System.InvalidOperationException">The builder is incorrectly initialized.</exception> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder.System#Runtime#CompilerServices#IAsyncMethodBuilder#PreBoxInitialization"> <summary>Perform any initialization necessary prior to lifting the builder to the heap.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitOnCompleted``2(``0@,``1@)"> <summary> Schedules the specified state machine to be pushed forward when the specified awaiter completes. </summary> <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> <param name="awaiter">The awaiter.</param> <param name="stateMachine">The state machine.</param> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted``2(``0@,``1@)"> <summary> Schedules the specified state machine to be pushed forward when the specified awaiter completes. </summary> <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> <param name="awaiter">The awaiter.</param> <param name="stateMachine">The state machine.</param> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult"> <summary> Completes the <see cref="T:System.Threading.Tasks.Task"/> in the <see cref="T:System.Threading.Tasks.TaskStatus">RanToCompletion</see> state. </summary> <exception cref="T:System.InvalidOperationException">The builder is not initialized.</exception> <exception cref="T:System.InvalidOperationException">The task has already completed.</exception> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"> <summary> Completes the <see cref="T:System.Threading.Tasks.Task"/> in the <see cref="T:System.Threading.Tasks.TaskStatus">Faulted</see> state with the specified exception. </summary> <param name="exception">The <see cref="T:System.Exception"/> to use to fault the task.</param> <exception cref="T:System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception> <exception cref="T:System.InvalidOperationException">The builder is not initialized.</exception> <exception cref="T:System.InvalidOperationException">The task has already completed.</exception> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetNotificationForWaitCompletion(System.Boolean)"> <summary> Called by the debugger to request notification when the first wait operation (await, Wait, Result, etc.) on this builder's task completes. </summary> <param name="enabled"> true to enable notification; false to disable a previously set notification. </param> </member> <member name="P:System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Task"> <summary>Gets the <see cref="T:System.Threading.Tasks.Task"/> for this builder.</summary> <returns>The <see cref="T:System.Threading.Tasks.Task"/> representing the builder's asynchronous operation.</returns> <exception cref="T:System.InvalidOperationException">The builder is not initialized.</exception> </member> <member name="P:System.Runtime.CompilerServices.AsyncTaskMethodBuilder.ObjectIdForDebugger"> <summary> Gets an object that may be used to uniquely identify this builder to the debugger. </summary> <remarks> This property lazily instantiates the ID in a non-thread-safe manner. It must only be used by the debugger, and only in a single-threaded manner when no other threads are in the middle of accessing this property or this.Task. </remarks> </member> <member name="T:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1"> <summary> Provides a builder for asynchronous methods that return <see cref="T:System.Threading.Tasks.Task`1"/>. This type is intended for compiler use only. </summary> <remarks> AsyncTaskMethodBuilder{TResult} is a value type, and thus it is copied by value. Prior to being copied, one of its Task, SetResult, or SetException members must be accessed, or else the copies may end up building distinct Task instances. </remarks> </member> <member name="F:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.s_defaultResultTask"> <summary>A cached task for default(TResult).</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.m_coreState"> <summary>State related to the IAsyncStateMachine.</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.m_task"> <summary>The lazily-initialized task.</summary> <remarks>Must be named m_task for debugger step-over to work correctly.</remarks> </member> <member name="F:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.m_taskCompletionSource"> <summary>The lazily-initialized task completion source.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.#cctor"> <summary>Temporary support for disabling crashing if tasks go unobserved.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Create"> <summary>Initializes a new <see cref="T:System.Runtime.CompilerServices.AsyncTaskMethodBuilder"/>.</summary> <returns>The initialized <see cref="T:System.Runtime.CompilerServices.AsyncTaskMethodBuilder"/>.</returns> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start``1(``0@)"> <summary>Initiates the builder's execution with the associated state machine.</summary> <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> <param name="stateMachine">The state machine instance, passed by reference.</param> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine)"> <summary>Associates the builder with the state machine it represents.</summary> <param name="stateMachine">The heap-allocated state machine object.</param> <exception cref="T:System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> <exception cref="T:System.InvalidOperationException">The builder is incorrectly initialized.</exception> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.System#Runtime#CompilerServices#IAsyncMethodBuilder#PreBoxInitialization"> <summary>Perform any initialization necessary prior to lifting the builder to the heap.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AwaitOnCompleted``2(``0@,``1@)"> <summary> Schedules the specified state machine to be pushed forward when the specified awaiter completes. </summary> <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> <param name="awaiter">The awaiter.</param> <param name="stateMachine">The state machine.</param> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AwaitUnsafeOnCompleted``2(``0@,``1@)"> <summary> Schedules the specified state machine to be pushed forward when the specified awaiter completes. </summary> <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> <param name="awaiter">The awaiter.</param> <param name="stateMachine">The state machine.</param> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.SetResult(`0)"> <summary> Completes the <see cref="T:System.Threading.Tasks.Task`1"/> in the <see cref="T:System.Threading.Tasks.TaskStatus">RanToCompletion</see> state with the specified result. </summary> <param name="result">The result to use to complete the task.</param> <exception cref="T:System.InvalidOperationException">The task has already completed.</exception> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.SetResult(System.Threading.Tasks.TaskCompletionSource{`0})"> <summary> Completes the builder by using either the supplied completed task, or by completing the builder's previously accessed task using default(TResult). </summary> <param name="completedTask">A task already completed with the value default(TResult).</param> <exception cref="T:System.InvalidOperationException">The task has already completed.</exception> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.SetException(System.Exception)"> <summary> Completes the <see cref="T:System.Threading.Tasks.Task`1"/> in the <see cref="T:System.Threading.Tasks.TaskStatus">Faulted</see> state with the specified exception. </summary> <param name="exception">The <see cref="T:System.Exception"/> to use to fault the task.</param> <exception cref="T:System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception> <exception cref="T:System.InvalidOperationException">The task has already completed.</exception> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.SetNotificationForWaitCompletion(System.Boolean)"> <summary> Called by the debugger to request notification when the first wait operation (await, Wait, Result, etc.) on this builder's task completes. </summary> <param name="enabled"> true to enable notification; false to disable a previously set notification. </param> <remarks> This should only be invoked from within an asynchronous method, and only by the debugger. </remarks> </member> <member name="M:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.GetTaskForResult(`0)"> <summary> Gets a task for the specified result. This will either be a cached or new task, never null. </summary> <param name="result">The result for which we need a task.</param> <returns>The completed task containing the result.</returns> </member> <member name="P:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.CompletionSource"> <summary>Gets the lazily-initialized TaskCompletionSource.</summary> </member> <member name="P:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Task"> <summary>Gets the <see cref="T:System.Threading.Tasks.Task`1"/> for this builder.</summary> <returns>The <see cref="T:System.Threading.Tasks.Task`1"/> representing the builder's asynchronous operation.</returns> </member> <member name="P:System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.ObjectIdForDebugger"> <summary> Gets an object that may be used to uniquely identify this builder to the debugger. </summary> <remarks> This property lazily instantiates the ID in a non-thread-safe manner. It must only be used by the debugger, and only in a single-threaded manner when no other threads are in the middle of accessing this property or this.Task. </remarks> </member> <member name="T:System.Runtime.CompilerServices.AsyncVoidMethodBuilder"> <summary> Provides a builder for asynchronous methods that return void. This type is intended for compiler use only. </summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.m_synchronizationContext"> <summary>The synchronization context associated with this operation.</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.m_coreState"> <summary>State related to the IAsyncStateMachine.</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.m_objectIdForDebugger"> <summary>An object used by the debugger to uniquely identify this builder. Lazily initialized.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.#cctor"> <summary>Temporary support for disabling crashing if tasks go unobserved.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.PreventUnobservedTaskExceptions"> <summary>Registers with UnobservedTaskException to suppress exception crashing.</summary> </member> <member name="F:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.s_preventUnobservedTaskExceptionsInvoked"> <summary>Non-zero if PreventUnobservedTaskExceptions has already been invoked.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Create"> <summary>Initializes a new <see cref="T:System.Runtime.CompilerServices.AsyncVoidMethodBuilder"/>.</summary> <returns>The initialized <see cref="T:System.Runtime.CompilerServices.AsyncVoidMethodBuilder"/>.</returns> </member> <member name="M:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.#ctor(System.Threading.SynchronizationContext)"> <summary>Initializes the <see cref="T:System.Runtime.CompilerServices.AsyncVoidMethodBuilder"/>.</summary> <param name="synchronizationContext">The synchronizationContext associated with this operation. This may be null.</param> </member> <member name="M:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start``1(``0@)"> <summary>Initiates the builder's execution with the associated state machine.</summary> <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> <param name="stateMachine">The state machine instance, passed by reference.</param> <exception cref="T:System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> </member> <member name="M:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine)"> <summary>Associates the builder with the state machine it represents.</summary> <param name="stateMachine">The heap-allocated state machine object.</param> <exception cref="T:System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> <exception cref="T:System.InvalidOperationException">The builder is incorrectly initialized.</exception> </member> <member name="M:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.System#Runtime#CompilerServices#IAsyncMethodBuilder#PreBoxInitialization"> <summary>Perform any initialization necessary prior to lifting the builder to the heap.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted``2(``0@,``1@)"> <summary> Schedules the specified state machine to be pushed forward when the specified awaiter completes. </summary> <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> <param name="awaiter">The awaiter.</param> <param name="stateMachine">The state machine.</param> </member> <member name="M:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted``2(``0@,``1@)"> <summary> Schedules the specified state machine to be pushed forward when the specified awaiter completes. </summary> <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> <param name="awaiter">The awaiter.</param> <param name="stateMachine">The state machine.</param> </member> <member name="M:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult"> <summary>Completes the method builder successfully.</summary> </member> <member name="M:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"> <summary>Faults the method builder with an exception.</summary> <param name="exception">The exception that is the cause of this fault.</param> <exception cref="T:System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception> <exception cref="T:System.InvalidOperationException">The builder is not initialized.</exception> </member> <member name="M:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.NotifySynchronizationContextOfCompletion"> <summary>Notifies the current synchronization context that the operation completed.</summary> </member> <member name="P:System.Runtime.CompilerServices.AsyncVoidMethodBuilder.ObjectIdForDebugger"> <summary> Gets an object that may be used to uniquely identify this builder to the debugger. </summary> <remarks> This property lazily instantiates the ID in a non-thread-safe manner. It must only be used by the debugger and only in a single-threaded manner. </remarks> </member> <member name="T:System.Runtime.CompilerServices.IAsyncStateMachine"> <summary> Represents state machines generated for asynchronous methods. This type is intended for compiler use only. </summary> </member> <member name="M:System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext"> <summary>Moves the state machine to its next state.</summary> </member> <member name="M:System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine)"> <summary>Configures the state machine with a heap-allocated replica.</summary> <param name="stateMachine">The heap-allocated replica.</param> </member> <member name="T:System.Runtime.CompilerServices.ICriticalNotifyCompletion"> <summary> Represents an awaiter used to schedule continuations when an await operation completes. </summary> </member> <member name="T:System.Runtime.CompilerServices.INotifyCompletion"> <summary> Represents an operation that will schedule continuations when the operation completes. </summary> </member> <member name="M:System.Runtime.CompilerServices.INotifyCompletion.OnCompleted(System.Action)"> <summary>Schedules the continuation action to be invoked when the instance completes.</summary> <param name="continuation">The action to invoke when the operation completes.</param> <exception cref="T:System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> </member> <member name="M:System.Runtime.CompilerServices.ICriticalNotifyCompletion.UnsafeOnCompleted(System.Action)"> <summary>Schedules the continuation action to be invoked when the instance completes.</summary> <param name="continuation">The action to invoke when the operation completes.</param> <exception cref="T:System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> <remarks>Unlike OnCompleted, UnsafeOnCompleted need not propagate ExecutionContext information.</remarks> </member> <member name="T:System.Runtime.CompilerServices.VoidTaskResult"> <summary>Used with Task(of void)</summary> </member> </members> </doc>
{ "pile_set_name": "Github" }
= ThreadPoolExecutor 源码分析 include::_attributes.adoc[] [cols="9,33,9,38",options="header"] |=== |状态名称 |比特位 |十进制 |描述 |RUNNING |111-00000000000000000000000000000 >|-536870912 |运行中状态,可以接收新的任务和执行任务队列中的任务 |SHUTDOWN |000-00000000000000000000000000000 >|0 |shutdown状态,不再接收新的任务,但是会执行任务队列中的任务 |STOP |001-00000000000000000000000000000 >|536870912 |停止状态,不再接收新的任务,也不会执行任务队列中的任务,中断所有执行中的任务 |TIDYING |010-00000000000000000000000000000 >|1073741824 |整理中状态,所有任务已经终结,工作线程数为0,过渡到此状态的工作线程会调用钩子方法 `terminated()` |TERMINATED |011-00000000000000000000000000000 >|1610612736 |终结状态,钩子方法 `terminated()` 执行完毕 |=== 由于运行状态值存放在高3位,所以可以直接通过十进制值(甚至可以忽略低29位,直接用ctl进行比较,或者使用ctl和线程池状态常量进行比较)来比较和判断线程池的状态:工作线程数为0的前提下:`RUNNING(-536870912)` < `SHUTDOWN(0)` < `STOP(536870912)` < `TIDYING(1073741824)` < `TERMINATED(1610612736)`。 image::images/ThreadPoolExecutor-states.jpeg[] [{java_src_attr}] ---- /** * Executes the given task sometime in the future. The task * may execute in a new thread or in an existing pooled thread. * * If the task cannot be submitted for execution, either because this * executor has been shutdown or because its capacity has been reached, * the task is handled by the current {@link RejectedExecutionHandler}. * * @param command the task to execute * @throws RejectedExecutionException at discretion of * {@code RejectedExecutionHandler}, if the task * cannot be accepted for execution * @throws NullPointerException if {@code command} is null */ public void execute(Runnable command) { if (command == null) throw new NullPointerException(); /* * Proceed in 3 steps: * * 1. If fewer than corePoolSize threads are running, try to * start a new thread with the given command as its first * task. The call to addWorker atomically checks runState and * workerCount, and so prevents false alarms that would add * threads when it shouldn't, by returning false. * * 2. If a task can be successfully queued, then we still need * to double-check whether we should have added a thread * (because existing ones died since last checking) or that * the pool shut down since entry into this method. So we * recheck state and if necessary roll back the enqueuing if * stopped, or start a new thread if there are none. * * 3. If we cannot queue task, then we try to add a new * thread. If it fails, we know we are shut down or saturated * and so reject the task. */ int c = ctl.get(); // 如果当前工作线程数小于核心线程数,则创建新的线程并执行传入的任务 if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)) // 创建核心线程成功则直接返回 return; // 创建核心线程失败,则在其他任务提交时,已经创建了足够多的线程数 // 或者线程池关闭等等,总之线程池状态已经发生变化, // 则更新 ctl 的临时变量 c = ctl.get(); } // 运行到这里说明创建核心线程失败,则当前工作线程已经大于等于 corePoolSize // 判断线程池是否运行并且尝试用非阻塞方法向任务队列中添加任务(失败则返回 false) if (isRunning(c) && workQueue.offer(command)) { int recheck = ctl.get(); // 向任务队列投放任务成功,对线程池状态做二次检查 // 如果线程池状态不是运行中,则从任务队列中移除任务并执行拒绝策略 if (! isRunning(recheck) && remove(command)) // 执行拒绝策略 -- 结束 reject(command); // 走到下面的 else if 分支,则说明 // 0、线程池可能是 RUNNING 状态 // 1、任务移除失败(失败原因可能是任务已经被执行) // 如果当前线程数为0,则创建一个非核心线程并传入任务为 null -- 结束 // 创建的线程不会马上执行任务,而是等待获取任务队列中的任务去执行 // 如果当前线程数不为0,则什么也不做。因为任务已经成功加入队列,总会执行。 else if (workerCountOf(recheck) == 0) addWorker(null, false); } // 执行到这里说明: // 0、线程池中的工作线程总数已经大于等于 corePoolSize // 1、线程池可能不是 RUNNING 状态 // 2、线程池可能是 RUNNING 状态同时任务队列已经满了 // 如果向任务队列投放任务失败,则会尝试创建非核心线程传入任务执行 // 创建非核心线程失败,此时需要拒绝执行任务 else if (!addWorker(command, false)) // 执行拒绝策略 -- 结束 reject(command); } ---- 为什么需要二次检查线程池的运行状态,当前工作线程数量为 `0`,尝试创建一个非核心线程并且传入的任务对象为 `null`?这个可以看API注释: **** 如果一个任务成功加入任务队列,我们依然需要二次检查是否需要添加一个工作线程(因为所有存活的工作线程有可能在最后一次检查之后已经终结)或者执行当前方法的时候线程池是否已经 `shutdown` 了。所以我们需要二次检查线程池的状态,必要时把任务从任务队列中移除或者在没有可用的工作线程的前提下新建一个工作线程。 **** image::images/ThreadPoolExecutor-process.jpeg[] `runWorker()` 方法的核心流程: image::images/ThreadPoolExecutor-runWorker.jpeg[] == 大纲 . 基本使用 . 使用 `Executors` 创建线程池 . 自定义任务,并提交任务 . 获取返回结果 . 线程池的类图结构 . 创建执行线程 . 取出任务执行 . 如何实现 `invokeAny(Collection<? extends Callable<T>> tasks)` ? . 如何实现 `invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)` ? . 如何实现 `invokeAll(Collection<? extends Callable<T>> tasks)` ? . 如何实现 `invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)` ? . 如何判断线程超时?以及超时后如何杀掉线程? . 如何终止任务?温柔终止?或者野蛮终止? . 线程池在jDK5、6、7中有哪些升级变化? . 拒绝策略 == 核心点 . 关键参数 .. `corePoolSize` .. `maximumPoolSize` .. `BlockingQueue` .. `RejectedExecutionHandler` .. `keepAliveTime` .. `threadFactory` . `RejectedExecutionHandler` .. `AbortPolicy` .. `CallerRunsPolicy` .. `DiscardPolicy` .. `DiscardOldestPolicy` 在生产环境,为了避免首次调用超时,可以调用 `executor.prestartAllCoreThreads()` 预创建所有 `core` 线程,避免来一个创一个带来首次调用慢的问题。 == 问题 . 任务添加后,如何执行? . 一个任务执行完成后,如何在同一个线程执行下一个任务? . 在 `corePoolSize` 比 `maximumPoolSize` 小的情况下,如何判定一个线程是否超时?并且如何删除一个线程? . 任务添加后, . 如何返回任务执行的结果? . 这个线程池还有哪些可以改进的地方?比如 Guava 中提供了哪些线程池? . 如何改造成添加任务,如果没有达到 `maxPoolSize` 则先创建线程? === Tomcat 改进 可不可以自己封装一个Queue,在插入时增加以下逻辑呢? * 如果当前有空闲线程等待接客,则把任务加入队列让孩儿们去抢。 * 如果没有空闲的了,总线程数又没到达max,那就返回false,让Executor去创建线程。 * 如果总线程数已达到max,则继续把任务加入队列缓冲一下。 * 如果缓冲队列也满了,抛出拒绝异常。 .https://github.com/apache/tomcat/blob/master/java/org/apache/tomcat/util/threads/TaskQueue.java [{java_src_attr}] ---- public class TaskQueue extends LinkedBlockingQueue<Runnable> { private transient volatile ThreadPoolExecutor parent = null; @Override public boolean offer(Runnable o) { //we can't do any checks if (parent==null) return super.offer(o); //we are maxed out on threads, simply queue the object if (parent.getPoolSize() == parent.getMaximumPoolSize()) return super.offer(o); //we have idle threads, just add it to the queue if (parent.getSubmittedCount()<=(parent.getPoolSize())) return super.offer(o); //if we have less threads than maximum force creation of a new thread if (parent.getPoolSize()<parent.getMaximumPoolSize()) return false; //if we reached here, we need to add it to the queue return super.offer(o); } } ---- 如何判断当前有没有空闲的线程等待接客?Tomcat 则靠扩展 `Executor`,增加一个当前请求数的计数器,在 `execute()` 方法前加1,再重载 `afterExecute()` 方法减1,然后判断当前线程总数是否大于当前请求总数就知道有咩有围观群众。 == 需要注意的点 . 线程池如何初始化? . 任务如何添加? . 任务如何执行? . 任务如何终止? . 遇到异常如何处理? . 线程池队列已满,如何拒绝? . 任务执行过程中出现异常,如何处理?关闭该线程,重启一个吗? . ?? . 任务如何存放? . 任务存放后,如何取出来? . 如何做到不断地一个一个执行下去? . 为什么 `Worker` 继承 `AbstractQueuedSynchronizer` ?AQS起什么作用?是否需要先研究一下? == 收获 . 可以继承 `ThreadPoolExecutor`,实现 `beforeExecute()` 和 `afterExecute()` 等方法,来加入执行时的回调。类似的回调,还有 `terminated()` . 添加任务时, `execute()` 方法的第二种情况,为什么还有再次检查? [{java_src_attr}] ---- include::{sourcedir}/concurrent/ThreadPoolExecutorTest.java[] ---- == 思考题 自己实现一个线程池。 == 参考资料 . http://www.throwable.club/2019/07/15/java-concurrency-thread-pool-executor/[JUC线程池ThreadPoolExecutor源码分析 - Throwable's Blog] . https://www.cnblogs.com/leesf456/p/5585627.html[【JUC】JDK1.8源码分析之ThreadPoolExecutor(一) - leesf - 博客园] . https://mp.weixin.qq.com/s/baYuX8aCwQ9PP6k7TDl2Ww[Java线程池实现原理及其在美团业务中的实践] . http://calvin1978.blogcn.com/articles/java-threadpool.html[Java ThreadPool的正确打开方式 | 江南白衣] . http://calvin1978.blogcn.com/articles/tomcat-threadpool.html[Tomcat线程池,更符合大家想象的可扩展线程池 | 江南白衣] . https://mp.weixin.qq.com/s/YAeneN-x_En55FlC2mVcaA[每天都在用,但你知道 Tomcat 的线程池有多努力吗?] . http://www.throwable.club/2019/07/15/java-concurrency-thread-pool-executor/[JUC线程池ThreadPoolExecutor源码分析 - Throwable's Blog . http://jindong.io/2015/03/30/java-concurrent-package-ThreadPoolExecutor/[Java并发包源码学习之线程池(一)ThreadPoolExecutor源码分析 - Jindong] . http://my.oschina.net/zouqun/blog/407149[ThreadPoolExecutor简介与源码分析 - 邹胜群的个人页面 - 开源中国社区] . http://onlychoice.github.io/blog/2013/09/13/java-concurrent-source-code-reading-2/[Java并发源码分析 - ThreadPoolExecutor - SHOW ME THE CODE] . http://blog.csdn.net/xieyuooo/article/details/8718741[Java线程池架构原理和源码解析(ThreadPoolExecutor) - xieyuooo的专栏 - 博客频道 - CSDN.NET] . http://www.cnblogs.com/skywang12345/p/java_threads_category.html[Java多线程系列目录(共43篇) - 如果天空不死 - 博客园] .. 搞清楚了 `ctl` 的含义,高三位是状态,低29位是线程数 .. 主要属性的含义,主要方法的实现,任务添加后,三种不同的处理方式 .. 线程池状态变换 .. 线程池拒绝策略的实现 .. 带返回值的任务的实现方式,`Callable`,`Future` . http://www.molotang.com/articles/514.html[ThreadPoolExecutor的基本使用 | 三石·道] . http://www.molotang.com/articles/522.html[ThreadPoolExecutor的任务提交、任务处理、线程复用和维护相关源码分析 | 三石·道] . http://www.molotang.com/articles/526.html[ThreadPoolExecutor的生命周期相关源码分析 | 三石·道] . http://www.molotang.com/articles/553.html[ThreadPoolExecutor的任务饱和丢弃策略及源码实现 | 三石·道] . http://ifeve.com/java-threadpool/[聊聊并发(三)Java线程池的分析和使用 | 并发编程网 - ifeve.com] . http://www.infoq.com/cn/articles/executor-framework-thread-pool-task-execution-part-01?utm_campaign=rightbar_v2&utm_source=infoq&utm_medium=articles_link&utm_content=link_text[戏(细)说Executor框架线程池任务执行全过程(上)] . http://www.infoq.com/cn/articles/executor-framework-thread-pool-task-execution-part-02?utm_campaign=rightbar_v2&utm_source=infoq&utm_medium=articles_link&utm_content=link_text[戏(细)说Executor框架线程池任务执行全过程(下)] . http://blog.csdn.net/techq/article/details/6818201[ThreadPoolExecutor 源码分析 - techq’s blog - 博客频道 - CSDN.NET] . http://blog.sina.com.cn/s/blog_753035050100wbtm.html[JAVA线程池(ThreadPoolExecutor)源码分析_journeylin_新浪博客] . http://www.cnblogs.com/rilley/archive/2012/02/07/2341767.html[ThreadPoolExecutor源码分析 - rilley - 博客园]
{ "pile_set_name": "Github" }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * The production QuantifierPrefix :: ? evaluates by returning the two results 0 and 1 * * @path ch15/15.10/15.10.2/15.10.2.7/S15.10.2.7_A5_T9.js * @description Execute /b?b?b?b/.exec("abbbbc") and check results */ __executed = /b?b?b?b/.exec("abbbbc"); __expected = ["bbbb"]; __expected.index = 1; __expected.input = "abbbbc"; //CHECK#1 if (__executed.length !== __expected.length) { $ERROR('#1: __executed = /b?b?b?b/.exec("abbbbc"); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length); } //CHECK#2 if (__executed.index !== __expected.index) { $ERROR('#2: __executed = /b?b?b?b/.exec("abbbbc"); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index); } //CHECK#3 if (__executed.input !== __expected.input) { $ERROR('#3: __executed = /b?b?b?b/.exec("abbbbc"); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input); } //CHECK#4 for(var index=0; index<__expected.length; index++) { if (__executed[index] !== __expected[index]) { $ERROR('#4: __executed = /b?b?b?b/.exec("abbbbc"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]); } }
{ "pile_set_name": "Github" }
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ****************************************************************************** * * Copyright (C) 2003-2016, International Business Machines * Corporation and others. All Rights Reserved. * ****************************************************************************** * file name: ucnv_ext.cpp * encoding: UTF-8 * tab size: 8 (not used) * indentation:4 * * created on: 2003jun13 * created by: Markus W. Scherer * * Conversion extensions */ #include "unicode/utypes.h" #if !UCONFIG_NO_CONVERSION && !UCONFIG_NO_LEGACY_CONVERSION #include "unicode/uset.h" #include "unicode/ustring.h" #include "ucnv_bld.h" #include "ucnv_cnv.h" #include "ucnv_ext.h" #include "cmemory.h" #include "uassert.h" /* to Unicode --------------------------------------------------------------- */ /* * @return lookup value for the byte, if found; else 0 */ static inline uint32_t ucnv_extFindToU(const uint32_t *toUSection, int32_t length, uint8_t byte) { uint32_t word0, word; int32_t i, start, limit; /* check the input byte against the lowest and highest section bytes */ start=(int32_t)UCNV_EXT_TO_U_GET_BYTE(toUSection[0]); limit=(int32_t)UCNV_EXT_TO_U_GET_BYTE(toUSection[length-1]); if(byte<start || limit<byte) { return 0; /* the byte is out of range */ } if(length==((limit-start)+1)) { /* direct access on a linear array */ return UCNV_EXT_TO_U_GET_VALUE(toUSection[byte-start]); /* could be 0 */ } /* word0 is suitable for <=toUSection[] comparison, word for <toUSection[] */ word0=UCNV_EXT_TO_U_MAKE_WORD(byte, 0); /* * Shift byte once instead of each section word and add 0xffffff. * We will compare the shifted/added byte (bbffffff) against * section words which have byte values in the same bit position. * If and only if byte bb < section byte ss then bbffffff<ssvvvvvv * for all v=0..f * so we need not mask off the lower 24 bits of each section word. */ word=word0|UCNV_EXT_TO_U_VALUE_MASK; /* binary search */ start=0; limit=length; for(;;) { i=limit-start; if(i<=1) { break; /* done */ } /* start<limit-1 */ if(i<=4) { /* linear search for the last part */ if(word0<=toUSection[start]) { break; } if(++start<limit && word0<=toUSection[start]) { break; } if(++start<limit && word0<=toUSection[start]) { break; } /* always break at start==limit-1 */ ++start; break; } i=(start+limit)/2; if(word<toUSection[i]) { limit=i; } else { start=i; } } /* did we really find it? */ if(start<limit && byte==UCNV_EXT_TO_U_GET_BYTE(word=toUSection[start])) { return UCNV_EXT_TO_U_GET_VALUE(word); /* never 0 */ } else { return 0; /* not found */ } } /* * TRUE if not an SI/SO stateful converter, * or if the match length fits with the current converter state */ #define UCNV_EXT_TO_U_VERIFY_SISO_MATCH(sisoState, match) \ ((sisoState)<0 || ((sisoState)==0) == (match==1)) /* * this works like ucnv_extMatchFromU() except * - the first character is in pre * - no trie is used * - the returned matchLength is not offset by 2 */ static int32_t ucnv_extMatchToU(const int32_t *cx, int8_t sisoState, const char *pre, int32_t preLength, const char *src, int32_t srcLength, uint32_t *pMatchValue, UBool /*useFallback*/, UBool flush) { const uint32_t *toUTable, *toUSection; uint32_t value, matchValue; int32_t i, j, idx, length, matchLength; uint8_t b; if(cx==NULL || cx[UCNV_EXT_TO_U_LENGTH]<=0) { return 0; /* no extension data, no match */ } /* initialize */ toUTable=UCNV_EXT_ARRAY(cx, UCNV_EXT_TO_U_INDEX, uint32_t); idx=0; matchValue=0; i=j=matchLength=0; if(sisoState==0) { /* SBCS state of an SI/SO stateful converter, look at only exactly 1 byte */ if(preLength>1) { return 0; /* no match of a DBCS sequence in SBCS mode */ } else if(preLength==1) { srcLength=0; } else /* preLength==0 */ { if(srcLength>1) { srcLength=1; } } flush=TRUE; } /* we must not remember fallback matches when not using fallbacks */ /* match input units until there is a full match or the input is consumed */ for(;;) { /* go to the next section */ toUSection=toUTable+idx; /* read first pair of the section */ value=*toUSection++; length=UCNV_EXT_TO_U_GET_BYTE(value); value=UCNV_EXT_TO_U_GET_VALUE(value); if( value!=0 && (UCNV_EXT_TO_U_IS_ROUNDTRIP(value) || TO_U_USE_FALLBACK(useFallback)) && UCNV_EXT_TO_U_VERIFY_SISO_MATCH(sisoState, i+j) ) { /* remember longest match so far */ matchValue=value; matchLength=i+j; } /* match pre[] then src[] */ if(i<preLength) { b=(uint8_t)pre[i++]; } else if(j<srcLength) { b=(uint8_t)src[j++]; } else { /* all input consumed, partial match */ if(flush || (length=(i+j))>UCNV_EXT_MAX_BYTES) { /* * end of the entire input stream, stop with the longest match so far * or: partial match must not be longer than UCNV_EXT_MAX_BYTES * because it must fit into state buffers */ break; } else { /* continue with more input next time */ return -length; } } /* search for the current UChar */ value=ucnv_extFindToU(toUSection, length, b); if(value==0) { /* no match here, stop with the longest match so far */ break; } else { if(UCNV_EXT_TO_U_IS_PARTIAL(value)) { /* partial match, continue */ idx=(int32_t)UCNV_EXT_TO_U_GET_PARTIAL_INDEX(value); } else { if( (UCNV_EXT_TO_U_IS_ROUNDTRIP(value) || TO_U_USE_FALLBACK(useFallback)) && UCNV_EXT_TO_U_VERIFY_SISO_MATCH(sisoState, i+j) ) { /* full match, stop with result */ matchValue=value; matchLength=i+j; } else { /* full match on fallback not taken, stop with the longest match so far */ } break; } } } if(matchLength==0) { /* no match at all */ return 0; } /* return result */ *pMatchValue=UCNV_EXT_TO_U_MASK_ROUNDTRIP(matchValue); return matchLength; } static inline void ucnv_extWriteToU(UConverter *cnv, const int32_t *cx, uint32_t value, UChar **target, const UChar *targetLimit, int32_t **offsets, int32_t srcIndex, UErrorCode *pErrorCode) { /* output the result */ if(UCNV_EXT_TO_U_IS_CODE_POINT(value)) { /* output a single code point */ ucnv_toUWriteCodePoint( cnv, UCNV_EXT_TO_U_GET_CODE_POINT(value), target, targetLimit, offsets, srcIndex, pErrorCode); } else { /* output a string - with correct data we have resultLength>0 */ ucnv_toUWriteUChars( cnv, UCNV_EXT_ARRAY(cx, UCNV_EXT_TO_U_UCHARS_INDEX, UChar)+ UCNV_EXT_TO_U_GET_INDEX(value), UCNV_EXT_TO_U_GET_LENGTH(value), target, targetLimit, offsets, srcIndex, pErrorCode); } } /* * get the SI/SO toU state (state 0 is for SBCS, 1 for DBCS), * or 1 for DBCS-only, * or -1 if the converter is not SI/SO stateful * * Note: For SI/SO stateful converters getting here, * cnv->mode==0 is equivalent to firstLength==1. */ #define UCNV_SISO_STATE(cnv) \ ((cnv)->sharedData->mbcs.outputType==MBCS_OUTPUT_2_SISO ? (int8_t)(cnv)->mode : \ (cnv)->sharedData->mbcs.outputType==MBCS_OUTPUT_DBCS_ONLY ? 1 : -1) /* * target<targetLimit; set error code for overflow */ U_CFUNC UBool ucnv_extInitialMatchToU(UConverter *cnv, const int32_t *cx, int32_t firstLength, const char **src, const char *srcLimit, UChar **target, const UChar *targetLimit, int32_t **offsets, int32_t srcIndex, UBool flush, UErrorCode *pErrorCode) { uint32_t value = 0; /* initialize output-only param to 0 to silence gcc */ int32_t match; /* try to match */ match=ucnv_extMatchToU(cx, (int8_t)UCNV_SISO_STATE(cnv), (const char *)cnv->toUBytes, firstLength, *src, (int32_t)(srcLimit-*src), &value, cnv->useFallback, flush); if(match>0) { /* advance src pointer for the consumed input */ *src+=match-firstLength; /* write result to target */ ucnv_extWriteToU(cnv, cx, value, target, targetLimit, offsets, srcIndex, pErrorCode); return TRUE; } else if(match<0) { /* save state for partial match */ const char *s; int32_t j; /* copy the first code point */ s=(const char *)cnv->toUBytes; cnv->preToUFirstLength=(int8_t)firstLength; for(j=0; j<firstLength; ++j) { cnv->preToU[j]=*s++; } /* now copy the newly consumed input */ s=*src; match=-match; for(; j<match; ++j) { cnv->preToU[j]=*s++; } *src=s; /* same as *src=srcLimit; because we reached the end of input */ cnv->preToULength=(int8_t)match; return TRUE; } else /* match==0 no match */ { return FALSE; } } U_CFUNC UChar32 ucnv_extSimpleMatchToU(const int32_t *cx, const char *source, int32_t length, UBool useFallback) { uint32_t value = 0; /* initialize output-only param to 0 to silence gcc */ int32_t match; if(length<=0) { return 0xffff; } /* try to match */ match=ucnv_extMatchToU(cx, -1, source, length, NULL, 0, &value, useFallback, TRUE); if(match==length) { /* write result for simple, single-character conversion */ if(UCNV_EXT_TO_U_IS_CODE_POINT(value)) { return UCNV_EXT_TO_U_GET_CODE_POINT(value); } } /* * return no match because * - match>0 && value points to string: simple conversion cannot handle multiple code points * - match>0 && match!=length: not all input consumed, forbidden for this function * - match==0: no match found in the first place * - match<0: partial match, not supported for simple conversion (and flush==TRUE) */ return 0xfffe; } /* * continue partial match with new input * never called for simple, single-character conversion */ U_CFUNC void ucnv_extContinueMatchToU(UConverter *cnv, UConverterToUnicodeArgs *pArgs, int32_t srcIndex, UErrorCode *pErrorCode) { uint32_t value = 0; /* initialize output-only param to 0 to silence gcc */ int32_t match, length; match=ucnv_extMatchToU(cnv->sharedData->mbcs.extIndexes, (int8_t)UCNV_SISO_STATE(cnv), cnv->preToU, cnv->preToULength, pArgs->source, (int32_t)(pArgs->sourceLimit-pArgs->source), &value, cnv->useFallback, pArgs->flush); if(match>0) { if(match>=cnv->preToULength) { /* advance src pointer for the consumed input */ pArgs->source+=match-cnv->preToULength; cnv->preToULength=0; } else { /* the match did not use all of preToU[] - keep the rest for replay */ length=cnv->preToULength-match; uprv_memmove(cnv->preToU, cnv->preToU+match, length); cnv->preToULength=(int8_t)-length; } /* write result */ ucnv_extWriteToU(cnv, cnv->sharedData->mbcs.extIndexes, value, &pArgs->target, pArgs->targetLimit, &pArgs->offsets, srcIndex, pErrorCode); } else if(match<0) { /* save state for partial match */ const char *s; int32_t j; /* just _append_ the newly consumed input to preToU[] */ s=pArgs->source; match=-match; for(j=cnv->preToULength; j<match; ++j) { cnv->preToU[j]=*s++; } pArgs->source=s; /* same as *src=srcLimit; because we reached the end of input */ cnv->preToULength=(int8_t)match; } else /* match==0 */ { /* * no match * * We need to split the previous input into two parts: * * 1. The first codepage character is unmappable - that's how we got into * trying the extension data in the first place. * We need to move it from the preToU buffer * to the error buffer, set an error code, * and prepare the rest of the previous input for 2. * * 2. The rest of the previous input must be converted once we * come back from the callback for the first character. * At that time, we have to try again from scratch to convert * these input characters. * The replay will be handled by the ucnv.c conversion code. */ /* move the first codepage character to the error field */ uprv_memcpy(cnv->toUBytes, cnv->preToU, cnv->preToUFirstLength); cnv->toULength=cnv->preToUFirstLength; /* move the rest up inside the buffer */ length=cnv->preToULength-cnv->preToUFirstLength; if(length>0) { uprv_memmove(cnv->preToU, cnv->preToU+cnv->preToUFirstLength, length); } /* mark preToU for replay */ cnv->preToULength=(int8_t)-length; /* set the error code for unassigned */ *pErrorCode=U_INVALID_CHAR_FOUND; } } /* from Unicode ------------------------------------------------------------- */ // Use roundtrips, "good one-way" mappings, and some normal fallbacks. static inline UBool extFromUUseMapping(UBool useFallback, uint32_t value, UChar32 firstCP) { return ((value&UCNV_EXT_FROM_U_STATUS_MASK)!=0 || FROM_U_USE_FALLBACK(useFallback, firstCP)) && (value&UCNV_EXT_FROM_U_RESERVED_MASK)==0; } /* * @return index of the UChar, if found; else <0 */ static inline int32_t ucnv_extFindFromU(const UChar *fromUSection, int32_t length, UChar u) { int32_t i, start, limit; /* binary search */ start=0; limit=length; for(;;) { i=limit-start; if(i<=1) { break; /* done */ } /* start<limit-1 */ if(i<=4) { /* linear search for the last part */ if(u<=fromUSection[start]) { break; } if(++start<limit && u<=fromUSection[start]) { break; } if(++start<limit && u<=fromUSection[start]) { break; } /* always break at start==limit-1 */ ++start; break; } i=(start+limit)/2; if(u<fromUSection[i]) { limit=i; } else { start=i; } } /* did we really find it? */ if(start<limit && u==fromUSection[start]) { return start; } else { return -1; /* not found */ } } /* * @param cx pointer to extension data; if NULL, returns 0 * @param firstCP the first code point before all the other UChars * @param pre UChars that must match; !initialMatch: partial match with them * @param preLength length of pre, >=0 * @param src UChars that can be used to complete a match * @param srcLength length of src, >=0 * @param pMatchValue [out] output result value for the match from the data structure * @param useFallback "use fallback" flag, usually from cnv->useFallback * @param flush TRUE if the end of the input stream is reached * @return >1: matched, return value=total match length (number of input units matched) * 1: matched, no mapping but request for <subchar1> * (only for the first code point) * 0: no match * <0: partial match, return value=negative total match length * (partial matches are never returned for flush==TRUE) * (partial matches are never returned as being longer than UCNV_EXT_MAX_UCHARS) * the matchLength is 2 if only firstCP matched, and >2 if firstCP and * further code units matched */ static int32_t ucnv_extMatchFromU(const int32_t *cx, UChar32 firstCP, const UChar *pre, int32_t preLength, const UChar *src, int32_t srcLength, uint32_t *pMatchValue, UBool useFallback, UBool flush) { const uint16_t *stage12, *stage3; const uint32_t *stage3b; const UChar *fromUTableUChars, *fromUSectionUChars; const uint32_t *fromUTableValues, *fromUSectionValues; uint32_t value, matchValue; int32_t i, j, idx, length, matchLength; UChar c; if(cx==NULL) { return 0; /* no extension data, no match */ } /* trie lookup of firstCP */ idx=firstCP>>10; /* stage 1 index */ if(idx>=cx[UCNV_EXT_FROM_U_STAGE_1_LENGTH]) { return 0; /* the first code point is outside the trie */ } stage12=UCNV_EXT_ARRAY(cx, UCNV_EXT_FROM_U_STAGE_12_INDEX, uint16_t); stage3=UCNV_EXT_ARRAY(cx, UCNV_EXT_FROM_U_STAGE_3_INDEX, uint16_t); idx=UCNV_EXT_FROM_U(stage12, stage3, idx, firstCP); stage3b=UCNV_EXT_ARRAY(cx, UCNV_EXT_FROM_U_STAGE_3B_INDEX, uint32_t); value=stage3b[idx]; if(value==0) { return 0; } /* * Tests for (value&UCNV_EXT_FROM_U_RESERVED_MASK)==0: * Do not interpret values with reserved bits used, for forward compatibility, * and do not even remember intermediate results with reserved bits used. */ if(UCNV_EXT_TO_U_IS_PARTIAL(value)) { /* partial match, enter the loop below */ idx=(int32_t)UCNV_EXT_FROM_U_GET_PARTIAL_INDEX(value); /* initialize */ fromUTableUChars=UCNV_EXT_ARRAY(cx, UCNV_EXT_FROM_U_UCHARS_INDEX, UChar); fromUTableValues=UCNV_EXT_ARRAY(cx, UCNV_EXT_FROM_U_VALUES_INDEX, uint32_t); matchValue=0; i=j=matchLength=0; /* we must not remember fallback matches when not using fallbacks */ /* match input units until there is a full match or the input is consumed */ for(;;) { /* go to the next section */ fromUSectionUChars=fromUTableUChars+idx; fromUSectionValues=fromUTableValues+idx; /* read first pair of the section */ length=*fromUSectionUChars++; value=*fromUSectionValues++; if(value!=0 && extFromUUseMapping(useFallback, value, firstCP)) { /* remember longest match so far */ matchValue=value; matchLength=2+i+j; } /* match pre[] then src[] */ if(i<preLength) { c=pre[i++]; } else if(j<srcLength) { c=src[j++]; } else { /* all input consumed, partial match */ if(flush || (length=(i+j))>UCNV_EXT_MAX_UCHARS) { /* * end of the entire input stream, stop with the longest match so far * or: partial match must not be longer than UCNV_EXT_MAX_UCHARS * because it must fit into state buffers */ break; } else { /* continue with more input next time */ return -(2+length); } } /* search for the current UChar */ idx=ucnv_extFindFromU(fromUSectionUChars, length, c); if(idx<0) { /* no match here, stop with the longest match so far */ break; } else { value=fromUSectionValues[idx]; if(UCNV_EXT_FROM_U_IS_PARTIAL(value)) { /* partial match, continue */ idx=(int32_t)UCNV_EXT_FROM_U_GET_PARTIAL_INDEX(value); } else { if(extFromUUseMapping(useFallback, value, firstCP)) { /* full match, stop with result */ matchValue=value; matchLength=2+i+j; } else { /* full match on fallback not taken, stop with the longest match so far */ } break; } } } if(matchLength==0) { /* no match at all */ return 0; } } else /* result from firstCP trie lookup */ { if(extFromUUseMapping(useFallback, value, firstCP)) { /* full match, stop with result */ matchValue=value; matchLength=2; } else { /* fallback not taken */ return 0; } } /* return result */ if(matchValue==UCNV_EXT_FROM_U_SUBCHAR1) { return 1; /* assert matchLength==2 */ } *pMatchValue=matchValue; return matchLength; } /* * @param value fromUnicode mapping table value; ignores roundtrip and reserved bits */ static inline void ucnv_extWriteFromU(UConverter *cnv, const int32_t *cx, uint32_t value, char **target, const char *targetLimit, int32_t **offsets, int32_t srcIndex, UErrorCode *pErrorCode) { uint8_t buffer[1+UCNV_EXT_MAX_BYTES]; const uint8_t *result; int32_t length, prevLength; length=UCNV_EXT_FROM_U_GET_LENGTH(value); value=(uint32_t)UCNV_EXT_FROM_U_GET_DATA(value); /* output the result */ if(length<=UCNV_EXT_FROM_U_MAX_DIRECT_LENGTH) { /* * Generate a byte array and then write it below. * This is not the fastest possible way, but it should be ok for * extension mappings, and it is much simpler. * Offset and overflow handling are only done once this way. */ uint8_t *p=buffer+1; /* reserve buffer[0] for shiftByte below */ switch(length) { case 3: *p++=(uint8_t)(value>>16); U_FALLTHROUGH; case 2: *p++=(uint8_t)(value>>8); U_FALLTHROUGH; case 1: *p++=(uint8_t)value; U_FALLTHROUGH; default: break; /* will never occur */ } result=buffer+1; } else { result=UCNV_EXT_ARRAY(cx, UCNV_EXT_FROM_U_BYTES_INDEX, uint8_t)+value; } /* with correct data we have length>0 */ if((prevLength=cnv->fromUnicodeStatus)!=0) { /* handle SI/SO stateful output */ uint8_t shiftByte; if(prevLength>1 && length==1) { /* change from double-byte mode to single-byte */ shiftByte=(uint8_t)UCNV_SI; cnv->fromUnicodeStatus=1; } else if(prevLength==1 && length>1) { /* change from single-byte mode to double-byte */ shiftByte=(uint8_t)UCNV_SO; cnv->fromUnicodeStatus=2; } else { shiftByte=0; } if(shiftByte!=0) { /* prepend the shift byte to the result bytes */ buffer[0]=shiftByte; if(result!=buffer+1) { uprv_memcpy(buffer+1, result, length); } result=buffer; ++length; } } ucnv_fromUWriteBytes(cnv, (const char *)result, length, target, targetLimit, offsets, srcIndex, pErrorCode); } /* * target<targetLimit; set error code for overflow */ U_CFUNC UBool ucnv_extInitialMatchFromU(UConverter *cnv, const int32_t *cx, UChar32 cp, const UChar **src, const UChar *srcLimit, char **target, const char *targetLimit, int32_t **offsets, int32_t srcIndex, UBool flush, UErrorCode *pErrorCode) { uint32_t value = 0; /* initialize output-only param to 0 to silence gcc */ int32_t match; /* try to match */ match=ucnv_extMatchFromU(cx, cp, NULL, 0, *src, (int32_t)(srcLimit-*src), &value, cnv->useFallback, flush); /* reject a match if the result is a single byte for DBCS-only */ if( match>=2 && !(UCNV_EXT_FROM_U_GET_LENGTH(value)==1 && cnv->sharedData->mbcs.outputType==MBCS_OUTPUT_DBCS_ONLY) ) { /* advance src pointer for the consumed input */ *src+=match-2; /* remove 2 for the initial code point */ /* write result to target */ ucnv_extWriteFromU(cnv, cx, value, target, targetLimit, offsets, srcIndex, pErrorCode); return TRUE; } else if(match<0) { /* save state for partial match */ const UChar *s; int32_t j; /* copy the first code point */ cnv->preFromUFirstCP=cp; /* now copy the newly consumed input */ s=*src; match=-match-2; /* remove 2 for the initial code point */ for(j=0; j<match; ++j) { cnv->preFromU[j]=*s++; } *src=s; /* same as *src=srcLimit; because we reached the end of input */ cnv->preFromULength=(int8_t)match; return TRUE; } else if(match==1) { /* matched, no mapping but request for <subchar1> */ cnv->useSubChar1=TRUE; return FALSE; } else /* match==0 no match */ { return FALSE; } } /* * Used by ISO 2022 implementation. * @return number of bytes in *pValue; negative number if fallback; 0 for no mapping */ U_CFUNC int32_t ucnv_extSimpleMatchFromU(const int32_t *cx, UChar32 cp, uint32_t *pValue, UBool useFallback) { uint32_t value; int32_t match; /* try to match */ match=ucnv_extMatchFromU(cx, cp, NULL, 0, NULL, 0, &value, useFallback, TRUE); if(match>=2) { /* write result for simple, single-character conversion */ int32_t length; int isRoundtrip; isRoundtrip=UCNV_EXT_FROM_U_IS_ROUNDTRIP(value); length=UCNV_EXT_FROM_U_GET_LENGTH(value); value=(uint32_t)UCNV_EXT_FROM_U_GET_DATA(value); if(length<=UCNV_EXT_FROM_U_MAX_DIRECT_LENGTH) { *pValue=value; return isRoundtrip ? length : -length; #if 0 /* not currently used */ } else if(length==4) { /* de-serialize a 4-byte result */ const uint8_t *result=UCNV_EXT_ARRAY(cx, UCNV_EXT_FROM_U_BYTES_INDEX, uint8_t)+value; *pValue= ((uint32_t)result[0]<<24)| ((uint32_t)result[1]<<16)| ((uint32_t)result[2]<<8)| result[3]; return isRoundtrip ? 4 : -4; #endif } } /* * return no match because * - match>1 && resultLength>4: result too long for simple conversion * - match==1: no match found, <subchar1> preferred * - match==0: no match found in the first place * - match<0: partial match, not supported for simple conversion (and flush==TRUE) */ return 0; } /* * continue partial match with new input, requires cnv->preFromUFirstCP>=0 * never called for simple, single-character conversion */ U_CFUNC void ucnv_extContinueMatchFromU(UConverter *cnv, UConverterFromUnicodeArgs *pArgs, int32_t srcIndex, UErrorCode *pErrorCode) { uint32_t value = 0; /* initialize output-only param to 0 to silence gcc */ int32_t match; match=ucnv_extMatchFromU(cnv->sharedData->mbcs.extIndexes, cnv->preFromUFirstCP, cnv->preFromU, cnv->preFromULength, pArgs->source, (int32_t)(pArgs->sourceLimit-pArgs->source), &value, cnv->useFallback, pArgs->flush); if(match>=2) { match-=2; /* remove 2 for the initial code point */ if(match>=cnv->preFromULength) { /* advance src pointer for the consumed input */ pArgs->source+=match-cnv->preFromULength; cnv->preFromULength=0; } else { /* the match did not use all of preFromU[] - keep the rest for replay */ int32_t length=cnv->preFromULength-match; u_memmove(cnv->preFromU, cnv->preFromU+match, length); cnv->preFromULength=(int8_t)-length; } /* finish the partial match */ cnv->preFromUFirstCP=U_SENTINEL; /* write result */ ucnv_extWriteFromU(cnv, cnv->sharedData->mbcs.extIndexes, value, &pArgs->target, pArgs->targetLimit, &pArgs->offsets, srcIndex, pErrorCode); } else if(match<0) { /* save state for partial match */ const UChar *s; int32_t j; /* just _append_ the newly consumed input to preFromU[] */ s=pArgs->source; match=-match-2; /* remove 2 for the initial code point */ for(j=cnv->preFromULength; j<match; ++j) { U_ASSERT(j>=0); cnv->preFromU[j]=*s++; } pArgs->source=s; /* same as *src=srcLimit; because we reached the end of input */ cnv->preFromULength=(int8_t)match; } else /* match==0 or 1 */ { /* * no match * * We need to split the previous input into two parts: * * 1. The first code point is unmappable - that's how we got into * trying the extension data in the first place. * We need to move it from the preFromU buffer * to the error buffer, set an error code, * and prepare the rest of the previous input for 2. * * 2. The rest of the previous input must be converted once we * come back from the callback for the first code point. * At that time, we have to try again from scratch to convert * these input characters. * The replay will be handled by the ucnv.c conversion code. */ if(match==1) { /* matched, no mapping but request for <subchar1> */ cnv->useSubChar1=TRUE; } /* move the first code point to the error field */ cnv->fromUChar32=cnv->preFromUFirstCP; cnv->preFromUFirstCP=U_SENTINEL; /* mark preFromU for replay */ cnv->preFromULength=-cnv->preFromULength; /* set the error code for unassigned */ *pErrorCode=U_INVALID_CHAR_FOUND; } } static UBool extSetUseMapping(UConverterUnicodeSet which, int32_t minLength, uint32_t value) { if(which==UCNV_ROUNDTRIP_SET) { // Add only code points for which the roundtrip flag is set. // Do not add any fallbacks, even if ucnv_fromUnicode() would use them // (fallbacks from PUA). See the API docs for ucnv_getUnicodeSet(). // // By analogy, also do not add "good one-way" mappings. // // Do not add entries with reserved bits set. if(((value&(UCNV_EXT_FROM_U_ROUNDTRIP_FLAG|UCNV_EXT_FROM_U_RESERVED_MASK))!= UCNV_EXT_FROM_U_ROUNDTRIP_FLAG)) { return FALSE; } } else /* UCNV_ROUNDTRIP_AND_FALLBACK_SET */ { // Do not add entries with reserved bits set. if((value&UCNV_EXT_FROM_U_RESERVED_MASK)!=0) { return FALSE; } } // Do not add <subchar1> entries or other (future?) pseudo-entries // with an output length of 0. return UCNV_EXT_FROM_U_GET_LENGTH(value)>=minLength; } static void ucnv_extGetUnicodeSetString(const UConverterSharedData *sharedData, const int32_t *cx, const USetAdder *sa, UConverterUnicodeSet which, int32_t minLength, UChar32 firstCP, UChar s[UCNV_EXT_MAX_UCHARS], int32_t length, int32_t sectionIndex, UErrorCode *pErrorCode) { const UChar *fromUSectionUChars; const uint32_t *fromUSectionValues; uint32_t value; int32_t i, count; fromUSectionUChars=UCNV_EXT_ARRAY(cx, UCNV_EXT_FROM_U_UCHARS_INDEX, UChar)+sectionIndex; fromUSectionValues=UCNV_EXT_ARRAY(cx, UCNV_EXT_FROM_U_VALUES_INDEX, uint32_t)+sectionIndex; /* read first pair of the section */ count=*fromUSectionUChars++; value=*fromUSectionValues++; if(extSetUseMapping(which, minLength, value)) { if(length==U16_LENGTH(firstCP)) { /* add the initial code point */ sa->add(sa->set, firstCP); } else { /* add the string so far */ sa->addString(sa->set, s, length); } } for(i=0; i<count; ++i) { /* append this code unit and recurse or add the string */ s[length]=fromUSectionUChars[i]; value=fromUSectionValues[i]; if(value==0) { /* no mapping, do nothing */ } else if(UCNV_EXT_FROM_U_IS_PARTIAL(value)) { ucnv_extGetUnicodeSetString( sharedData, cx, sa, which, minLength, firstCP, s, length+1, (int32_t)UCNV_EXT_FROM_U_GET_PARTIAL_INDEX(value), pErrorCode); } else if(extSetUseMapping(which, minLength, value)) { sa->addString(sa->set, s, length+1); } } } U_CFUNC void ucnv_extGetUnicodeSet(const UConverterSharedData *sharedData, const USetAdder *sa, UConverterUnicodeSet which, UConverterSetFilter filter, UErrorCode *pErrorCode) { const int32_t *cx; const uint16_t *stage12, *stage3, *ps2, *ps3; const uint32_t *stage3b; uint32_t value; int32_t st1, stage1Length, st2, st3, minLength; UChar s[UCNV_EXT_MAX_UCHARS]; UChar32 c; int32_t length; cx=sharedData->mbcs.extIndexes; if(cx==NULL) { return; } stage12=UCNV_EXT_ARRAY(cx, UCNV_EXT_FROM_U_STAGE_12_INDEX, uint16_t); stage3=UCNV_EXT_ARRAY(cx, UCNV_EXT_FROM_U_STAGE_3_INDEX, uint16_t); stage3b=UCNV_EXT_ARRAY(cx, UCNV_EXT_FROM_U_STAGE_3B_INDEX, uint32_t); stage1Length=cx[UCNV_EXT_FROM_U_STAGE_1_LENGTH]; /* enumerate the from-Unicode trie table */ c=0; /* keep track of the current code point while enumerating */ if(filter==UCNV_SET_FILTER_2022_CN) { minLength=3; } else if( sharedData->mbcs.outputType==MBCS_OUTPUT_DBCS_ONLY || filter!=UCNV_SET_FILTER_NONE ) { /* DBCS-only, ignore single-byte results */ minLength=2; } else { minLength=1; } /* * the trie enumeration is almost the same as * in MBCSGetUnicodeSet() for MBCS_OUTPUT_1 */ for(st1=0; st1<stage1Length; ++st1) { st2=stage12[st1]; if(st2>stage1Length) { ps2=stage12+st2; for(st2=0; st2<64; ++st2) { if((st3=(int32_t)ps2[st2]<<UCNV_EXT_STAGE_2_LEFT_SHIFT)!=0) { /* read the stage 3 block */ ps3=stage3+st3; do { value=stage3b[*ps3++]; if(value==0) { /* no mapping, do nothing */ } else if(UCNV_EXT_FROM_U_IS_PARTIAL(value)) { // Recurse for partial results. length=0; U16_APPEND_UNSAFE(s, length, c); ucnv_extGetUnicodeSetString( sharedData, cx, sa, which, minLength, c, s, length, (int32_t)UCNV_EXT_FROM_U_GET_PARTIAL_INDEX(value), pErrorCode); } else if(extSetUseMapping(which, minLength, value)) { switch(filter) { case UCNV_SET_FILTER_2022_CN: if(!(UCNV_EXT_FROM_U_GET_LENGTH(value)==3 && UCNV_EXT_FROM_U_GET_DATA(value)<=0x82ffff)) { continue; } break; case UCNV_SET_FILTER_SJIS: if(!(UCNV_EXT_FROM_U_GET_LENGTH(value)==2 && (value=UCNV_EXT_FROM_U_GET_DATA(value))>=0x8140 && value<=0xeffc)) { continue; } break; case UCNV_SET_FILTER_GR94DBCS: if(!(UCNV_EXT_FROM_U_GET_LENGTH(value)==2 && (uint16_t)((value=UCNV_EXT_FROM_U_GET_DATA(value))-0xa1a1)<=(0xfefe - 0xa1a1) && (uint8_t)(value-0xa1)<=(0xfe - 0xa1))) { continue; } break; case UCNV_SET_FILTER_HZ: if(!(UCNV_EXT_FROM_U_GET_LENGTH(value)==2 && (uint16_t)((value=UCNV_EXT_FROM_U_GET_DATA(value))-0xa1a1)<=(0xfdfe - 0xa1a1) && (uint8_t)(value-0xa1)<=(0xfe - 0xa1))) { continue; } break; default: /* * UCNV_SET_FILTER_NONE, * or UCNV_SET_FILTER_DBCS_ONLY which is handled via minLength */ break; } sa->add(sa->set, c); } } while((++c&0xf)!=0); } else { c+=16; /* empty stage 3 block */ } } } else { c+=1024; /* empty stage 2 block */ } } } #endif /* #if !UCONFIG_NO_LEGACY_CONVERSION */
{ "pile_set_name": "Github" }
HDF5 "packedbits.h5" { DATASET "/DS64BITS" { DATATYPE H5T_STD_I64LE DATASPACE SIMPLE { ( 8, 64 ) / ( 8, 64 ) } PACKED_BITS OFFSET=0 LENGTH=16 DATA { (0,0): 65535, 65534, 65532, 65528, 65520, 65504, 65472, 65408, 65280, (0,9): 65024, 64512, 63488, 61440, 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, (0,22): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (0,44): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (1,0): 65534, 65532, 65528, 65520, 65504, 65472, 65408, 65280, 65024, (1,9): 64512, 63488, 61440, 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, 0, 0, (1,23): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (1,45): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (2,0): 65532, 65528, 65520, 65504, 65472, 65408, 65280, 65024, 64512, (2,9): 63488, 61440, 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (2,25): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (2,47): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (3,0): 65528, 65520, 65504, 65472, 65408, 65280, 65024, 64512, 63488, (3,9): 61440, 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (3,26): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (3,48): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (4,0): 65520, 65504, 65472, 65408, 65280, 65024, 64512, 63488, 61440, (4,9): 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (4,27): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (4,49): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (5,0): 65504, 65472, 65408, 65280, 65024, 64512, 63488, 61440, 57344, (5,9): 49152, 32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (5,29): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (5,51): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (6,0): 65472, 65408, 65280, 65024, 64512, 63488, 61440, 57344, 49152, (6,9): 32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (6,30): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (6,52): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (7,0): 65408, 65280, 65024, 64512, 63488, 61440, 57344, 49152, 32768, 0, (7,10): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (7,32): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (7,54): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } PACKED_BITS OFFSET=16 LENGTH=16 DATA { (0,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (0,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65534, (0,18): 65532, 65528, 65520, 65504, 65472, 65408, 65280, 65024, 64512, (0,27): 63488, 61440, 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (0,42): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (1,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (1,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65534, 65532, (1,18): 65528, 65520, 65504, 65472, 65408, 65280, 65024, 64512, 63488, (1,27): 61440, 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (1,44): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (2,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (2,9): 65535, 65535, 65535, 65535, 65535, 65535, 65534, 65532, 65528, (2,18): 65520, 65504, 65472, 65408, 65280, 65024, 64512, 63488, 61440, (2,27): 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (2,45): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (3,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (3,9): 65535, 65535, 65535, 65535, 65535, 65534, 65532, 65528, 65520, (3,18): 65504, 65472, 65408, 65280, 65024, 64512, 63488, 61440, 57344, (3,27): 49152, 32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (3,46): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (4,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (4,9): 65535, 65535, 65535, 65535, 65534, 65532, 65528, 65520, 65504, (4,18): 65472, 65408, 65280, 65024, 64512, 63488, 61440, 57344, 49152, (4,27): 32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (4,48): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (5,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (5,9): 65535, 65535, 65535, 65534, 65532, 65528, 65520, 65504, 65472, (5,18): 65408, 65280, 65024, 64512, 63488, 61440, 57344, 49152, 32768, 0, (5,28): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (5,50): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (6,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (6,9): 65535, 65535, 65534, 65532, 65528, 65520, 65504, 65472, 65408, (6,18): 65280, 65024, 64512, 63488, 61440, 57344, 49152, 32768, 0, 0, 0, (6,29): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (6,51): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (7,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (7,9): 65535, 65534, 65532, 65528, 65520, 65504, 65472, 65408, 65280, (7,18): 65024, 64512, 63488, 61440, 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, (7,31): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (7,53): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } PACKED_BITS OFFSET=32 LENGTH=16 DATA { (0,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (0,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (0,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (0,27): 65535, 65535, 65535, 65535, 65535, 65535, 65534, 65532, 65528, (0,36): 65520, 65504, 65472, 65408, 65280, 65024, 64512, 63488, 61440, (0,45): 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (0,63): 0, (1,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (1,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (1,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (1,27): 65535, 65535, 65535, 65535, 65535, 65534, 65532, 65528, 65520, (1,36): 65504, 65472, 65408, 65280, 65024, 64512, 63488, 61440, 57344, (1,45): 49152, 32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (2,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (2,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (2,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (2,27): 65535, 65535, 65535, 65535, 65534, 65532, 65528, 65520, 65504, (2,36): 65472, 65408, 65280, 65024, 64512, 63488, 61440, 57344, 49152, (2,45): 32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (3,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (3,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (3,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (3,27): 65535, 65535, 65535, 65534, 65532, 65528, 65520, 65504, 65472, (3,36): 65408, 65280, 65024, 64512, 63488, 61440, 57344, 49152, 32768, 0, (3,46): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (4,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (4,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (4,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (4,27): 65535, 65535, 65534, 65532, 65528, 65520, 65504, 65472, 65408, (4,36): 65280, 65024, 64512, 63488, 61440, 57344, 49152, 32768, 0, 0, 0, (4,47): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (5,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (5,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (5,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (5,27): 65535, 65534, 65532, 65528, 65520, 65504, 65472, 65408, 65280, (5,36): 65024, 64512, 63488, 61440, 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, (5,49): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (6,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (6,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (6,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (6,27): 65534, 65532, 65528, 65520, 65504, 65472, 65408, 65280, 65024, (6,36): 64512, 63488, 61440, 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, 0, 0, (6,50): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (7,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (7,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (7,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65534, (7,27): 65532, 65528, 65520, 65504, 65472, 65408, 65280, 65024, 64512, (7,36): 63488, 61440, 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (7,51): 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } PACKED_BITS OFFSET=48 LENGTH=16 DATA { (0,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (0,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (0,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (0,27): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (0,36): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (0,45): 65535, 65535, 65535, 65535, 65534, 65532, 65528, 65520, 65504, (0,54): 65472, 65408, 65280, 65024, 64512, 63488, 61440, 57344, 49152, (0,63): 32768, (1,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (1,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (1,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (1,27): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (1,36): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (1,45): 65535, 65535, 65535, 65534, 65532, 65528, 65520, 65504, 65472, (1,54): 65408, 65280, 65024, 64512, 63488, 61440, 57344, 49152, 32768, 0, (2,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (2,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (2,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (2,27): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (2,36): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (2,45): 65535, 65535, 65534, 65532, 65528, 65520, 65504, 65472, 65408, (2,54): 65280, 65024, 64512, 63488, 61440, 57344, 49152, 32768, 0, 0, (3,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (3,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (3,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (3,27): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (3,36): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (3,45): 65535, 65534, 65532, 65528, 65520, 65504, 65472, 65408, 65280, (3,54): 65024, 64512, 63488, 61440, 57344, 49152, 32768, 0, 0, 0, (4,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (4,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (4,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (4,27): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (4,36): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (4,45): 65534, 65532, 65528, 65520, 65504, 65472, 65408, 65280, 65024, (4,54): 64512, 63488, 61440, 57344, 49152, 32768, 0, 0, 0, 0, (5,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (5,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (5,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (5,27): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (5,36): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65534, (5,45): 65532, 65528, 65520, 65504, 65472, 65408, 65280, 65024, 64512, (5,54): 63488, 61440, 57344, 49152, 32768, 0, 0, 0, 0, 0, (6,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (6,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (6,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (6,27): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (6,36): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65534, 65532, (6,45): 65528, 65520, 65504, 65472, 65408, 65280, 65024, 64512, 63488, (6,54): 61440, 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, (7,0): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (7,9): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (7,18): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (7,27): 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, (7,36): 65535, 65535, 65535, 65535, 65535, 65535, 65534, 65532, 65528, (7,45): 65520, 65504, 65472, 65408, 65280, 65024, 64512, 63488, 61440, (7,54): 57344, 49152, 32768, 0, 0, 0, 0, 0, 0, 0 } } }
{ "pile_set_name": "Github" }
# Browserify example Two steps need to be done for this to work In the project root npm install In this folder ../../node_modules/.bin/browserify main.js -o bundle.js
{ "pile_set_name": "Github" }
package com.tmobile.cso.pacman.datashipper.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * The Class AssetGroupUtil. */ public class AssetGroupUtil { /** The Constant log. */ private static final Logger LOGGER = LoggerFactory.getLogger(AssetGroupUtil.class); private static final String DISTRIBUTION = "distribution"; private static final String SEVERITY = "severity"; private static final String COUNT = "count"; private static final String OUTPUT = "output" ; private static final String TOTAL = "total" ; private static final String COMPLIANT = "compliant"; private static final String NON_COMPLIANT = "noncompliant" ; private static final String DOMAIN = "domain"; private AssetGroupUtil(){ } /** * Fetch asset groups. * * @param asstApiUri * the asst api uri * @return the map * @throws Exception */ @SuppressWarnings("unchecked") public static Map<String, List<String>> fetchAssetGroups(String asstApiUri,String token) throws Exception { String assetGroupJson = HttpUtil.get(asstApiUri + "/list/assetgroup",token); Map<String, Object> assetInfoMap = Util.parseJson(assetGroupJson); Map<String, List<String>> assetGroups = new HashMap<>(); if (!assetInfoMap.isEmpty()) { assetGroups = ((List<Map<String, Object>>) assetInfoMap.get("data")).stream().collect( Collectors.toMap(obj -> obj.get("name").toString(), obj -> (List<String>) obj.get("domains"))); } return assetGroups; } /** * Fetch type counts. * * @param asstApiUri * the asst api uri * @param ag * the ag * @return the list * @throws Exception */ @SuppressWarnings("unchecked") public static List<Map<String, Object>> fetchTypeCounts(String asstApiUri, String ag,String token) throws Exception { String typeCountJson = HttpUtil.get(asstApiUri + "/count?ag=" + ag,token); Map<String, Object> typeCountMap = Util.parseJson(typeCountJson); List<Map<String, Object>> typeCounts = new ArrayList<>(); try { typeCounts = (List<Map<String, Object>>) ((Map<String, Object>) typeCountMap.get("data")).get("assetcount"); } catch (Exception e) { LOGGER.error("Error in fetchTypeCounts",e); throw e; } return typeCounts; } /** * Fetch patching compliance. * * @param api * the api * @param ag * the ag * @return the map * @throws Exception */ public static Map<String, Object> fetchPatchingCompliance(String api, String ag ,String token) throws Exception { Map<String, Object> patchingInfo = new HashMap<>(); try { String responseJson = HttpUtil.get(api + "/patching?ag=" + ag,token); Map<String, Object> vulnMap = Util.parseJson(responseJson); @SuppressWarnings("unchecked") Map<String, Map<String, Object>> data = (Map<String, Map<String, Object>>) vulnMap.get("data"); Map<String, Object> output = data.get(OUTPUT); if (output != null) patchingInfo.putAll(data.get(OUTPUT)); } catch (Exception e) { LOGGER.error("Error in fetchVulnCount",e); throw e; } return patchingInfo; } /** * Fetch vuln distribution. * * @param api * the api * @param ag * the ag * @return the list * @throws Exception */ @SuppressWarnings("unchecked") public static List<Map<String, Object>> fetchVulnDistribution(String api, String ag ,String token) throws Exception { List<Map<String, Object>> vulnInfo = new ArrayList<>(); try { String typeCountJson = HttpUtil.get(api + "/vulnerabilities/distribution?ag=" + ag,token); Map<String, Object> vulnMap = Util.parseJson(typeCountJson); Map<String, List<Map<String, Object>>> data = (Map<String, List<Map<String, Object>>>) vulnMap.get("data"); List<Map<String, Object>> apps = data.get("response"); for (Map<String, Object> app : apps) { String application = app.get("application").toString(); List<Map<String, Object>> envs = (List<Map<String, Object>>) app.get("applicationInfo"); for (Map<String, Object> env : envs) { String environment = env.get("environment").toString(); List<Map<String, Object>> sevinfo = (List<Map<String, Object>>) env.get("severityInfo"); for (Map<String, Object> sev : sevinfo) { Map<String, Object> vuln = new HashMap<>(); vuln.put("tags.Application", application); vuln.put("tags.Environment", environment); vuln.put("severitylevel", sev.get("severitylevel")); vuln.put(SEVERITY, sev.get(SEVERITY)); vuln.put(COUNT, sev.get(COUNT)); vulnInfo.add(vuln); } } } } catch (Exception e) { LOGGER.error("Error in fetchVulnDistribution" , e); throw e; } return vulnInfo; } /** * Fetch compliance info. * * @param apiUrl * the api url * @param ag * the ag * @param domains * the domains * @return the list * @throws Exception */ @SuppressWarnings("unchecked") public static List<Map<String, Object>> fetchComplianceInfo(String apiUrl, String ag, List<String> domains ,String token) throws Exception { List<Map<String, Object>> compInfo = new ArrayList<>(); try { for (String domain : domains) { String typeCountJson = HttpUtil .get(apiUrl + "/overallcompliance?ag=" + ag + "&domain=" + Util.encodeUrl(domain),token); Map<String, Object> complianceMap = Util.parseJson(typeCountJson); Map<String, Map<String, Object>> data = (Map<String, Map<String, Object>>) complianceMap.get("data"); Map<String, Object> complianceStats = data.get(DISTRIBUTION); if (complianceStats != null) { complianceStats.put(DOMAIN, domain); compInfo.add(complianceStats); } } } catch (Exception e) { LOGGER.error("Error in fetchComplianceInfo" , e); throw e; } return compInfo; } /** * Fetch rule compliance info. * * @param compapiuri * the compapiuri * @param ag * the ag * @param domains * the domains * @return the list * @throws Exception */ public static List<Map<String, Object>> fetchRuleComplianceInfo(String compapiuri, String ag, List<String> domains ,String token) throws Exception { List<Map<String, Object>> ruleInfoList = new ArrayList<>(); try { for (String domain : domains) { String ruleCommplianceInfo = HttpUtil.post(compapiuri + "/noncompliancepolicy", "{\"ag\":\"" + ag + "\",\"filter\":{\"domain\":\"" + domain + "\"}}",token,"Bearer"); JsonObject response = new JsonParser().parse(ruleCommplianceInfo).getAsJsonObject(); JsonArray ruleInfoListJson = response.get("data").getAsJsonObject().get("response").getAsJsonArray(); JsonObject ruleinfoJson; Map<String, Object> ruleInfo; for (JsonElement _ruleinfo : ruleInfoListJson) { ruleinfoJson = _ruleinfo.getAsJsonObject(); ruleInfo = new HashMap<>(); ruleInfo.put(DOMAIN, domain); ruleInfo.put("ruleId", ruleinfoJson.get("ruleId").getAsString()); ruleInfo.put("compliance_percent", ruleinfoJson.get("compliance_percent").getAsDouble()); ruleInfo.put(TOTAL, ruleinfoJson.get("assetsScanned").getAsLong()); ruleInfo.put(COMPLIANT, ruleinfoJson.get("passed").getAsLong()); ruleInfo.put(NON_COMPLIANT, ruleinfoJson.get("failed").getAsLong()); ruleInfo.put("contribution_percent", ruleinfoJson.get("contribution_percent").getAsDouble()); ruleInfoList.add(ruleInfo); } } } catch (Exception e) { LOGGER.error("Error retrieving Rule Compliance Info" , e); throw e; } return ruleInfoList; } /** * Fetch vuln summary. * * @param compapiuri * the compapiuri * @param ag * the ag * @return the map * @throws Exception */ public static Map<String, Object> fetchVulnSummary(String compapiuri, String ag ,String token) throws Exception { Map<String, Object> vulnSummary = new HashMap<>(); try { String vulnSummaryResponse = HttpUtil.get(compapiuri + "/vulnerabilites?ag=" + ag,token); JsonObject vulnSummaryJson = new JsonParser().parse(vulnSummaryResponse).getAsJsonObject(); JsonObject vulnJsonObj = vulnSummaryJson.get("data").getAsJsonObject().get(OUTPUT).getAsJsonObject(); long total = vulnJsonObj.get("hosts").getAsLong(); long noncompliant = vulnJsonObj.get("totalVulnerableAssets").getAsLong(); vulnSummary.put(TOTAL, total); vulnSummary.put(NON_COMPLIANT, noncompliant); vulnSummary.put(COMPLIANT, total - noncompliant); } catch (Exception e) { LOGGER.error("Error retrieving vuln sumamary " , e); throw e; } return vulnSummary; } /** * Fetch tagging summary. * * @param compapiuri * the compapiuri * @param ag * the ag * @return the map * @throws Exception */ public static Map<String, Object> fetchTaggingSummary(String compapiuri, String ag ,String token) throws Exception { Map<String, Object> taggingSummary = new HashMap<>(); try { String taggingSummaryResponse = HttpUtil.get(compapiuri + "/tagging?ag=" + ag,token); JsonObject taggingSummaryJson = new JsonParser().parse(taggingSummaryResponse).getAsJsonObject(); JsonObject taggingJsonObj = taggingSummaryJson.get("data").getAsJsonObject().get(OUTPUT) .getAsJsonObject(); long total = taggingJsonObj.get("assets").getAsLong(); long noncompliant = taggingJsonObj.get("untagged").getAsLong(); long compliant = taggingJsonObj.get("tagged").getAsLong(); taggingSummary.put(TOTAL, total); taggingSummary.put(NON_COMPLIANT, noncompliant); taggingSummary.put(COMPLIANT, compliant); } catch (Exception e) { LOGGER.error("Error retrieving tagging sumamary " , e); throw e; } return taggingSummary; } /** * Fetch cert summary. * * @param compapiuri * the compapiuri * @param ag * the ag * @return the map * @throws Exception */ public static Map<String, Object> fetchCertSummary(String compapiuri, String ag ,String token) throws Exception { Map<String, Object> certSummary = new HashMap<>(); try { String certSummaryResponse = HttpUtil.get(compapiuri + "/certificates?ag=" + ag,token); JsonObject certSummaryJson = new JsonParser().parse(certSummaryResponse).getAsJsonObject(); JsonObject certJsonObj = certSummaryJson.get("data").getAsJsonObject().get(OUTPUT).getAsJsonObject(); long total = certJsonObj.get("certificates").getAsLong(); long noncompliant = certJsonObj.get("certificates_expiring").getAsLong(); long compliant = total - noncompliant; certSummary.put(TOTAL, total); certSummary.put(NON_COMPLIANT, noncompliant); certSummary.put(COMPLIANT, compliant); } catch (Exception e) { LOGGER.error("Error retrieving cert sumamary " , e); throw e; } return certSummary; } /** * Fetch issues info. * * @param compapiuri * the compapiuri * @param ag * the ag * @param domains * the domains * @return the list * @throws Exception */ public static List<Map<String, Object>> fetchIssuesInfo(String compapiuri, String ag, List<String> domains ,String token) throws Exception { List<Map<String, Object>> issueInfoList = new ArrayList<>(); Map<String, Object> issuesInfo; try { for (String domain : domains) { String distributionResponse = HttpUtil .get(compapiuri + "/issues/distribution?ag=" + ag + "&domain=" + Util.encodeUrl(domain),token); JsonObject distributionJson = new JsonParser().parse(distributionResponse).getAsJsonObject(); JsonObject distributionObj = distributionJson.get("data").getAsJsonObject().get(DISTRIBUTION) .getAsJsonObject(); issuesInfo = new HashMap<>(); issuesInfo.put(DOMAIN, domain); issuesInfo.put(TOTAL, distributionObj.get("total_issues").getAsLong()); JsonObject distributionSeverity = distributionObj.get("distribution_by_severity").getAsJsonObject(); JsonObject distributionCategory = distributionObj.get("distribution_ruleCategory").getAsJsonObject(); Set<String> severityKeys = distributionSeverity.keySet(); for (String severityKey : severityKeys) { issuesInfo.put(severityKey, distributionSeverity.get(severityKey).getAsLong()); } Set<String> categoryKeys = distributionCategory.keySet(); for (String categoryKey : categoryKeys) { issuesInfo.put(categoryKey, distributionCategory.get(categoryKey).getAsLong()); } issueInfoList.add(issuesInfo); } } catch (Exception e) { LOGGER.error("Error retrieving issues info " , e); throw e; } return issueInfoList; } }
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <DDDefinition xmlns="http://www.cern.ch/cms/DDL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.cern.ch/cms/DDL ../../../DetectorDescription/Schema/DDLSchema.xsd"> <ConstantsSection label="tecpetalb.xml" eval="true"> <Constant name="PetalWidth0" value="25.8*deg"/> <Constant name="PetalWidth1" value="29.9*deg"/> <Constant name="PetalWidth2" value="26.9*deg"/> <Constant name="PetalR1" value="55.50*cm"/> <Constant name="PetalR2" value="75.60*cm"/> <Constant name="ICC35B5shift" value="-4.54*deg"/> </ConstantsSection> <SolidSection label="tecpetalb.xml"> <Tubs name="TECPetal1B" rMin="[tecpetalb:PetalR1]" rMax="[tecpetalb:PetalR2]" dz="[tecpetpar:PetalThick]/2" startPhi="-[tecpetalb:PetalWidth1]/2" deltaPhi="[tecpetalb:PetalWidth1]"/> <Tubs name="TECPetal2B" rMin="[tecpetalb:PetalR2]" rMax="[tecpetpar:PetalRmax]" dz="[tecpetpar:PetalThick]/2" startPhi="-[tecpetalb:PetalWidth2]/2" deltaPhi="[tecpetalb:PetalWidth2]"/> <Tubs name="TECICC1B1" rMin="391.89*mm" rMax="449.56*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-2.17643*deg" deltaPhi="4.35286*deg"/> <Tubs name="TECICC1B2" rMin="449.56*mm" rMax="493.23*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-5.83087*deg" deltaPhi="11.6617*deg"/> <Tubs name="TECICC1B3" rMin="493.23*mm" rMax="586.67*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-2.17298*deg" deltaPhi="4.34596*deg"/> <Tubs name="TECICC35B1" rMin="586.67*mm" rMax="657.37*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-2.10147*deg" deltaPhi="4.20295*deg"/> <Tubs name="TECICC35B2" rMin="657.37*mm" rMax="690.87*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-12.3423*deg" deltaPhi="24.6847*deg"/> <Tubs name="TECICC35B3" rMin="690.87*mm" rMax="915.67*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-2.89888*deg" deltaPhi="5.79776*deg"/> <Tubs name="TECICC35B4" rMin="915.67*mm" rMax="971.8*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-7.10953*deg" deltaPhi="14.2191*deg"/> <Tubs name="TECICC35B5" rMin="971.8*mm" rMax="1085.91*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-3.62561*deg+[ICC35B5shift]" deltaPhi="7.25122*deg"/> <Tubs name="TECICC0LB1" rMin="356.18*mm" rMax="390.57*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-9.12831*deg" deltaPhi="18.2566*deg"/> <Tubs name="TECICC0LB2" rMin="390.57*mm" rMax="432.42*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-2.24672*deg" deltaPhi="4.49345*deg"/> <Tubs name="TECICC2B1" rMin="542.92*mm" rMax="585.28*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-6.44875*deg" deltaPhi="12.8975*deg"/> <Tubs name="TECICC2B2" rMin="585.28*mm" rMax="637.44*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-1.65027*deg" deltaPhi="3.30054*deg"/> <Tubs name="TECICC46B1" rMin="764.83*mm" rMax="814.65*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-1.45104*deg" deltaPhi="2.90208*deg"/> <Tubs name="TECICC46B2" rMin="814.65*mm" rMax="872.36*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-12.1736*deg" deltaPhi="24.3473*deg"/> <Tubs name="TECICC46B3" rMin="872.36*mm" rMax="933.02*mm" dz="[tecpetpar:ICCThick]/2" startPhi="-2.12357*deg" deltaPhi="4.24715*deg"/> </SolidSection> <LogicalPartSection label="tecpetalb.xml"> <LogicalPart name="TECICC1B1" category="unspecified"> <rSolid name="tecpetalb:TECICC1B1"/> <rMaterial name="tecmaterial:TEC_ICC1B"/> </LogicalPart> <LogicalPart name="TECICC1B2" category="unspecified"> <rSolid name="tecpetalb:TECICC1B2"/> <rMaterial name="tecmaterial:TEC_ICC1B"/> </LogicalPart> <LogicalPart name="TECICC1B3" category="unspecified"> <rSolid name="tecpetalb:TECICC1B3"/> <rMaterial name="tecmaterial:TEC_ICC1B"/> </LogicalPart> <LogicalPart name="TECICC35B1" category="unspecified"> <rSolid name="tecpetalb:TECICC35B1"/> <rMaterial name="tecmaterial:TEC_ICC35B"/> </LogicalPart> <LogicalPart name="TECICC35B2" category="unspecified"> <rSolid name="tecpetalb:TECICC35B2"/> <rMaterial name="tecmaterial:TEC_ICC35B"/> </LogicalPart> <LogicalPart name="TECICC35B3" category="unspecified"> <rSolid name="tecpetalb:TECICC35B3"/> <rMaterial name="tecmaterial:TEC_ICC35B"/> </LogicalPart> <LogicalPart name="TECICC35B4" category="unspecified"> <rSolid name="tecpetalb:TECICC35B4"/> <rMaterial name="tecmaterial:TEC_ICC35B"/> </LogicalPart> <LogicalPart name="TECICC35B5" category="unspecified"> <rSolid name="tecpetalb:TECICC35B5"/> <rMaterial name="tecmaterial:TEC_ICC35B"/> </LogicalPart> <LogicalPart name="TECICC0LB1" category="unspecified"> <rSolid name="tecpetalb:TECICC0LB1"/> <rMaterial name="tecmaterial:TEC_ICC0LB"/> </LogicalPart> <LogicalPart name="TECICC0LB2" category="unspecified"> <rSolid name="tecpetalb:TECICC0LB2"/> <rMaterial name="tecmaterial:TEC_ICC0LB"/> </LogicalPart> <LogicalPart name="TECICC2B1" category="unspecified"> <rSolid name="tecpetalb:TECICC2B1"/> <rMaterial name="tecmaterial:TEC_ICC2B"/> </LogicalPart> <LogicalPart name="TECICC2B2" category="unspecified"> <rSolid name="tecpetalb:TECICC2B2"/> <rMaterial name="tecmaterial:TEC_ICC2B"/> </LogicalPart> <LogicalPart name="TECICC46B1" category="unspecified"> <rSolid name="tecpetalb:TECICC46B1"/> <rMaterial name="tecmaterial:TEC_ICC46B"/> </LogicalPart> <LogicalPart name="TECICC46B2" category="unspecified"> <rSolid name="tecpetalb:TECICC46B2"/> <rMaterial name="tecmaterial:TEC_ICC46B"/> </LogicalPart> <LogicalPart name="TECICC46B3" category="unspecified"> <rSolid name="tecpetalb:TECICC46B3"/> <rMaterial name="tecmaterial:TEC_ICC46B"/> </LogicalPart> </LogicalPartSection> </DDDefinition>
{ "pile_set_name": "Github" }
/* * This file is part of KubeSphere Console. * Copyright (C) 2019 The KubeSphere Console Authors. * * KubeSphere Console 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. * * KubeSphere Console 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 KubeSphere Console. If not, see <https://www.gnu.org/licenses/>. */ import React, { Component } from 'react' import { Panel, Text } from 'components/Base' import { createCenterWindowOpt } from 'utils/dom' import styles from './index.scss' export default class Tools extends Component { getWindowOpts() { return createCenterWindowOpt({ width: 1200, height: 800, scrollbars: 1, resizable: 1, }) } handleTool = e => { window.open( e.currentTarget.dataset.url, e.currentTarget.dataset.title, this.getWindowOpts() ) } render() { const { cluster } = this.props return ( <Panel title={t('Tools')}> <div className={styles.level}> <div className="margin-r12" data-title="KubeCtl" data-url={`/clusters/${cluster}/kubectl`} onClick={this.handleTool} > <Text icon="terminal" title="Kubectl" description={t('KUBECTL_DESC')} /> </div> <div data-title="KubeConfig" data-url={`/clusters/${cluster}/kubeConfig`} onClick={this.handleTool} > <Text icon="data" title="KubeConfig" description={t('KUBECONFIG_DESC')} /> </div> </div> </Panel> ) } }
{ "pile_set_name": "Github" }
## 0.9.0 * Drop support for Scala 2.11 * Upgrade to Scala 2.12.10. Remove `Prop_TempHack`. * Add support for Scala 2.13.1 * Add to `Gen`: `def batches[A](as: Vector[A], partitionSize: Range.Inclusive, keepRemainder: Boolean = true): Gen[Vector[Vector[A]]]` * Remove deprecated code in `Gen`. * Upgrade dependencies ## 0.9.1 * New Gen methods for Scala 2.13 only: * `Gen#to(Factory)` - eg. `Gen.int.to(List)` * `Gen#to1(Factory)` - eg. `Gen.int.to1(List)` * `Gen#arraySeq` - eg. `Gen.int.arraySeq` & `Gen.int.arraySeq(0 to 4)` * `Gen#arraySeq1` - eg. `Gen.int.arraySeq1` & `Gen.int.arraySeq1(1 to 4)` ## 0.9.2 * Cross-publish for Scala.JS 1.0
{ "pile_set_name": "Github" }
set hive.fetch.task.conversion=more; DESCRIBE FUNCTION size; DESCRIBE FUNCTION EXTENDED size; EXPLAIN FROM src_thrift SELECT size(src_thrift.lint), size(src_thrift.lintstring), size(src_thrift.mstringstring), size(null) WHERE src_thrift.lint IS NOT NULL AND NOT (src_thrift.mstringstring IS NULL) LIMIT 1; FROM src_thrift SELECT size(src_thrift.lint), size(src_thrift.lintstring), size(src_thrift.mstringstring), size(null) WHERE src_thrift.lint IS NOT NULL AND NOT (src_thrift.mstringstring IS NULL) LIMIT 1;
{ "pile_set_name": "Github" }
// This file is originating from https://github.com/google/jsonapi/ // To this file the license conditions of LICENSE apply. package jsonapi import ( "fmt" "time" "github.com/shopspring/decimal" ) type BadModel struct { ID int `jsonapi:"primary"` } type ModelBadTypes struct { ID string `jsonapi:"primary,badtypes"` StringField string `jsonapi:"attr,string_field"` FloatField float64 `jsonapi:"attr,float_field"` TimeField time.Time `jsonapi:"attr,time_field"` TimePtrField *time.Time `jsonapi:"attr,time_ptr_field"` } type WithPointer struct { ID *uint64 `jsonapi:"primary,with-pointers"` Name *string `jsonapi:"attr,name"` IsActive *bool `jsonapi:"attr,is-active"` IntVal *int `jsonapi:"attr,int-val"` FloatVal *float32 `jsonapi:"attr,float-val"` } type Timestamp struct { ID int `jsonapi:"primary,timestamps"` Time time.Time `jsonapi:"attr,timestamp,iso8601"` Next *time.Time `jsonapi:"attr,next,iso8601"` } type Car struct { ID *string `jsonapi:"primary,cars"` Make *string `jsonapi:"attr,make,omitempty"` Model *string `jsonapi:"attr,model,omitempty"` Year *uint `jsonapi:"attr,year,omitempty"` } type Post struct { Blog ID uint64 `jsonapi:"primary,posts"` BlogID int `jsonapi:"attr,blog_id"` ClientID string `jsonapi:"client-id"` Title string `jsonapi:"attr,title"` Body string `jsonapi:"attr,body"` Comments []*Comment `jsonapi:"relation,comments"` LatestComment *Comment `jsonapi:"relation,latest_comment"` } type Comment struct { ID int `jsonapi:"primary,comments"` ClientID string `jsonapi:"client-id"` PostID int `jsonapi:"attr,post_id"` Body string `jsonapi:"attr,body"` } type Book struct { ID uint64 `jsonapi:"primary,books"` Author string `jsonapi:"attr,author"` ISBN string `jsonapi:"attr,isbn"` Title string `jsonapi:"attr,title,omitempty"` Description *string `jsonapi:"attr,description"` Pages *uint `jsonapi:"attr,pages,omitempty"` PublishedAt time.Time Tags []string `jsonapi:"attr,tags"` Decimal1 decimal.Decimal `jsonapi:"attr,dec1,omitempty"` Decimal2 decimal.Decimal `jsonapi:"attr,dec2,omitempty"` Decimal3 decimal.Decimal `jsonapi:"attr,dec3,omitempty"` } type Blog struct { ID int `jsonapi:"primary,blogs"` ClientID string `jsonapi:"client-id"` Title string `jsonapi:"attr,title"` Posts []*Post `jsonapi:"relation,posts"` CurrentPost *Post `jsonapi:"relation,current_post"` CurrentPostID int `jsonapi:"attr,current_post_id"` CreatedAt time.Time `jsonapi:"attr,created_at"` ViewCount int `jsonapi:"attr,view_count"` } func (b *Blog) JSONAPILinks() *Links { return &Links{ "self": fmt.Sprintf("https://example.com/api/blogs/%d", b.ID), "comments": Link{ Href: fmt.Sprintf("https://example.com/api/blogs/%d/comments", b.ID), Meta: Meta{ "counts": map[string]uint{ "likes": 4, "comments": 20, }, }, }, } } func (b *Blog) JSONAPIRelationshipLinks(relation string) *Links { if relation == "posts" { return &Links{ "related": Link{ Href: fmt.Sprintf("https://example.com/api/blogs/%d/posts", b.ID), Meta: Meta{ "count": len(b.Posts), }, }, } } if relation == "current_post" { return &Links{ "self": fmt.Sprintf("https://example.com/api/posts/%s", "3"), "related": Link{ Href: fmt.Sprintf("https://example.com/api/blogs/%d/current_post", b.ID), }, } } return nil } func (b *Blog) JSONAPIMeta() *Meta { return &Meta{ "detail": "extra details regarding the blog", } } func (b *Blog) JSONAPIRelationshipMeta(relation string) *Meta { if relation == "posts" { return &Meta{ "this": map[string]interface{}{ "can": map[string]interface{}{ "go": []interface{}{ "as", "deep", map[string]interface{}{ "as": "required", }, }, }, }, } } if relation == "current_post" { return &Meta{ "detail": "extra current_post detail", } } return nil } type BadComment struct { ID uint64 `jsonapi:"primary,bad-comment"` Body string `jsonapi:"attr,body"` } func (bc *BadComment) JSONAPILinks() *Links { return &Links{ "self": []string{"invalid", "should error"}, } } type Company struct { ID string `jsonapi:"primary,companies"` Name string `jsonapi:"attr,name"` Boss Employee `jsonapi:"attr,boss"` Teams []Team `jsonapi:"attr,teams"` FoundedAt time.Time `jsonapi:"attr,founded-at,iso8601"` } type Team struct { Name string `jsonapi:"attr,name"` Leader *Employee `jsonapi:"attr,leader"` Members []Employee `jsonapi:"attr,members"` } type Employee struct { Firstname string `jsonapi:"attr,firstname"` Surname string `jsonapi:"attr,surname"` Age int `jsonapi:"attr,age"` HiredAt *time.Time `jsonapi:"attr,hired-at,iso8601"` } type CustomIntType int type CustomFloatType float64 type CustomStringType string type CustomAttributeTypes struct { ID string `jsonapi:"primary,customtypes"` Int CustomIntType `jsonapi:"attr,int"` IntPtr *CustomIntType `jsonapi:"attr,intptr"` IntPtrNull *CustomIntType `jsonapi:"attr,intptrnull"` Float CustomFloatType `jsonapi:"attr,float"` String CustomStringType `jsonapi:"attr,string"` }
{ "pile_set_name": "Github" }
% % This contains viturally all of the data files % in "Analysis of Variance, Design, and Regression: % Applied Statistical Methods" by Ronald Christensen % (1996, Chapman and Hall). The individual files % correspond with tables in the book in a self % explanitory manner (presuming you have the book to % look at). There are three files that correspond % to data in exercises or examples. % % The author retains no rights to these data. % % Comments should be directed to: % Ronald Christensen % Dept. of Math and Statistics % University of New Mexico % Albq., NM 87131 % e-mail: [email protected] % % More information about the book and alternative % access to the data can be obtained from % the web at: www.math.unm.edu/~fletcher % % % File: ../data/christensen/tab4-12.dat % % Note: attribute names were generated automatically since there was no % information in the data itself. % % % Information about the dataset % CLASSTYPE: numeric % CLASSINDEX: none specific % @relation christensen-tab4-12 @attribute col_1 INTEGER @attribute col_2 INTEGER @attribute col_3 INTEGER @data 1,18,7 2,9,11 3,7,11 4,6,4 5,10,8 6,7,12 7,13,5 8,1,11
{ "pile_set_name": "Github" }
/* * Copyright 2020 Free Software Foundation, Inc. * * This file is part of GNU Radio * * SPDX-License-Identifier: GPL-3.0-or-later * */ /***********************************************************************************/ /* This file is automatically generated using bindtool and can be manually edited */ /* The following lines can be configured to regenerate this file during cmake */ /* If manual edits are made, the following tags should be modified accordingly. */ /* BINDTOOL_GEN_AUTOMATIC(0) */ /* BINDTOOL_USE_PYGCCXML(0) */ /* BINDTOOL_HEADER_FILE(tagged_stream_multiply_length.h) */ /* BINDTOOL_HEADER_FILE_HASH(d35538f07d2fbd15d2b08a39de2090b3) */ /***********************************************************************************/ #include <pybind11/complex.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> namespace py = pybind11; #include <gnuradio/blocks/tagged_stream_multiply_length.h> // pydoc.h is automatically generated in the build directory #include <tagged_stream_multiply_length_pydoc.h> void bind_tagged_stream_multiply_length(py::module& m) { using tagged_stream_multiply_length = ::gr::blocks::tagged_stream_multiply_length; py::class_<tagged_stream_multiply_length, gr::block, gr::basic_block, std::shared_ptr<tagged_stream_multiply_length>>( m, "tagged_stream_multiply_length", D(tagged_stream_multiply_length)) .def(py::init(&tagged_stream_multiply_length::make), py::arg("itemsize"), py::arg("lengthtagname"), py::arg("scalar"), D(tagged_stream_multiply_length, make)) .def("set_scalar", &tagged_stream_multiply_length::set_scalar, py::arg("scalar"), D(tagged_stream_multiply_length, set_scalar)) ; }
{ "pile_set_name": "Github" }
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FenixEdu Academic is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.ui.struts.action.resourceAllocationManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.action.DynaActionForm; import org.apache.struts.util.LabelValueBean; import org.fenixedu.academic.domain.ShiftType; import org.fenixedu.academic.domain.exceptions.DomainException; import org.fenixedu.academic.dto.InfoCurricularYear; import org.fenixedu.academic.dto.InfoExecutionCourse; import org.fenixedu.academic.dto.InfoExecutionDegree; import org.fenixedu.academic.dto.InfoShift; import org.fenixedu.academic.dto.InfoShiftEditor; import org.fenixedu.academic.dto.resourceAllocationManager.ContextSelectionBean; import org.fenixedu.academic.service.services.exceptions.FenixServiceException; import org.fenixedu.academic.service.services.exceptions.FenixServiceMultipleException; import org.fenixedu.academic.service.services.resourceAllocationManager.CriarTurno; import org.fenixedu.academic.service.services.resourceAllocationManager.DeleteShift; import org.fenixedu.academic.service.services.resourceAllocationManager.DeleteShifts; import org.fenixedu.academic.service.services.resourceAllocationManager.ReadShiftsByExecutionPeriodAndExecutionDegreeAndCurricularYear; import org.fenixedu.academic.ui.struts.action.exceptions.ExistingActionException; import org.fenixedu.academic.ui.struts.action.resourceAllocationManager.base.FenixExecutionDegreeAndCurricularYearContextDispatchAction; import org.fenixedu.academic.ui.struts.action.resourceAllocationManager.utils.PresentationConstants; import org.fenixedu.academic.ui.struts.action.resourceAllocationManager.utils.RequestUtils; import org.fenixedu.academic.ui.struts.action.utils.ContextUtils; import org.fenixedu.academic.ui.struts.config.FenixErrorExceptionHandler; import org.fenixedu.academic.util.Bundle; import org.fenixedu.bennu.core.i18n.BundleUtil; import org.fenixedu.bennu.struts.annotations.ExceptionHandling; import org.fenixedu.bennu.struts.annotations.Exceptions; import org.fenixedu.bennu.struts.annotations.Forward; import org.fenixedu.bennu.struts.annotations.Forwards; import org.fenixedu.bennu.struts.annotations.Mapping; /** * @author Luis Cruz &amp; Sara Ribeiro * */ @Mapping(path = "/manageShifts", module = "resourceAllocationManager", input = "/manageShifts.do?method=listShifts", formBean = "createShiftForm", functionality = ExecutionPeriodDA.class) @Forwards({ @Forward(name = "ShowShiftList", path = "/resourceAllocationManager/manageShifts_bd.jsp"), @Forward(name = "EditShift", path = "/resourceAllocationManager/manageShift.do?method=prepareEditShift") }) @Exceptions(@ExceptionHandling(handler = FenixErrorExceptionHandler.class, type = ExistingActionException.class, key = "resources.Action.exceptions.ExistingActionException", scope = "request")) public class ManageShiftsDA extends FenixExecutionDegreeAndCurricularYearContextDispatchAction { @Mapping(path = "/deleteShifts", module = "resourceAllocationManager", input = "/manageShifts.do?method=listShifts&page=0", formBean = "selectMultipleItemsForm", functionality = ExecutionPeriodDA.class) public static class DeleteShiftsDA extends ManageShiftsDA { private String getQueryParam(HttpServletRequest request, String name) { return Stream.of(name, (String) request.getAttribute(name)).collect(Collectors.joining("=")); } private ActionForward redirectToShiftsList(HttpServletRequest request) { String url = Stream.of("/manageShifts.do?method=listShifts&page=0", getQueryParam(request, PresentationConstants.ACADEMIC_INTERVAL), getQueryParam(request, PresentationConstants.CURRICULAR_YEAR_OID), getQueryParam(request, PresentationConstants.EXECUTION_DEGREE_OID)).collect(Collectors.joining("&")); return redirect(url, request); } public ActionForward deleteShift(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ContextUtils.setShiftContext(request); InfoShift infoShiftToDelete = (InfoShift) request.getAttribute(PresentationConstants.SHIFT); try { DeleteShift.run(infoShiftToDelete); } catch (FenixServiceException exception) { ActionErrors actionErrors = new ActionErrors(); if (exception.getMessage() != null && exception.getMessage().length() > 0) { actionErrors.add("errors.deleteshift", new ActionError(exception.getMessage(), exception.getArgs())); } else { actionErrors.add("errors.deleteshift", new ActionError("error.deleteShift")); } saveErrors(request, actionErrors); return mapping.getInputForward(); } catch (DomainException exception) { ActionMessages actionMessages = new ActionMessages(); actionMessages.add("errors.deleteshift", new ActionMessage(exception.getLocalizedMessage(), false)); saveErrors(request, actionMessages); return mapping.getInputForward(); } return redirectToShiftsList(request); } public ActionForward deleteShifts(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaActionForm deleteShiftsForm = (DynaActionForm) form; String[] selectedShifts = (String[]) deleteShiftsForm.get("selectedItems"); if (selectedShifts.length == 0) { ActionErrors actionErrors = new ActionErrors(); actionErrors.add("errors.shifts.notSelected", new ActionError("errors.shifts.notSelected")); saveErrors(request, actionErrors); return mapping.getInputForward(); } final List<String> shiftOIDs = new ArrayList<String>(); for (String selectedShift : selectedShifts) { shiftOIDs.add(selectedShift); } try { DeleteShifts.run(shiftOIDs); } catch (FenixServiceMultipleException e) { final ActionMessages actionMessages = new ActionMessages(); for (final DomainException domainException : e.getExceptionList()) { actionMessages.add(Integer.toString(domainException.hashCode()), new ActionMessage(domainException.getLocalizedMessage(), false)); } saveErrors(request, actionMessages); return mapping.getInputForward(); } return redirectToShiftsList(request); } } public ActionForward listShifts(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { readAndSetInfoToManageShifts(request); return mapping.findForward("ShowShiftList"); } public ActionForward listExecutionCourseCourseLoads(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { readAndSetInfoToManageShifts(request); DynaActionForm createShiftForm = (DynaActionForm) form; InfoExecutionCourse infoExecutionCourse = RequestUtils.getExecutionCourseBySigla(request, (String) createShiftForm.get("courseInitials")); if (infoExecutionCourse != null) { final List<LabelValueBean> tiposAula = new ArrayList<LabelValueBean>(); for (final ShiftType shiftType : infoExecutionCourse.getExecutionCourse().getShiftTypes()) { tiposAula .add(new LabelValueBean(BundleUtil.getString(Bundle.ENUMERATION, shiftType.getName()), shiftType.name())); } request.setAttribute("tiposAula", tiposAula); } return mapping.findForward("ShowShiftList"); } public ActionForward createShift(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaActionForm createShiftForm = (DynaActionForm) form; InfoShiftEditor infoShift = new InfoShiftEditor(); infoShift.setAvailabilityFinal(new Integer(0)); InfoExecutionCourse infoExecutionCourse = RequestUtils.getExecutionCourseBySigla(request, (String) createShiftForm.get("courseInitials")); infoShift.setInfoDisciplinaExecucao(infoExecutionCourse); infoShift.setInfoLessons(null); infoShift.setLotacao((Integer) createShiftForm.get("lotacao")); infoShift.setNome((String) createShiftForm.get("nome")); String[] selectedShiftTypes = (String[]) createShiftForm.get("shiftTiposAula"); if (selectedShiftTypes.length == 0) { ActionErrors actionErrors = new ActionErrors(); actionErrors.add("errors.shift.types.notSelected", new ActionError("errors.shift.types.notSelected")); saveErrors(request, actionErrors); return mapping.getInputForward(); } final List<ShiftType> shiftTypes = new ArrayList<ShiftType>(); for (String selectedShiftType : selectedShiftTypes) { shiftTypes.add(ShiftType.valueOf(selectedShiftType.toString())); } infoShift.setTipos(shiftTypes); // try { final InfoShift newInfoShift = CriarTurno.run(infoShift); request.setAttribute(PresentationConstants.SHIFT, newInfoShift); // } catch (ExistingServiceException ex) { // throw new ExistingActionException("O Shift", ex); // } request.setAttribute(PresentationConstants.EXECUTION_COURSE, infoExecutionCourse); return mapping.findForward("EditShift"); } private void readAndSetInfoToManageShifts(HttpServletRequest request) throws FenixServiceException, Exception { ContextSelectionBean context = (ContextSelectionBean) request.getAttribute(PresentationConstants.CONTEXT_SELECTION_BEAN); List<InfoShift> infoShifts = ReadShiftsByExecutionPeriodAndExecutionDegreeAndCurricularYear.run(context.getAcademicInterval(), new InfoExecutionDegree(context.getExecutionDegree()), new InfoCurricularYear(context.getCurricularYear())); Collections.sort(infoShifts, InfoShift.SHIFT_COMPARATOR_BY_TYPE_AND_ORDERED_LESSONS); if (infoShifts != null && !infoShifts.isEmpty()) { request.setAttribute(PresentationConstants.SHIFTS, infoShifts); } ManageShiftDA.getExecutionCourses(request); } }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_31) on Sun Jan 06 11:49:20 CST 2013 --> <TITLE> O-Index </TITLE> <META NAME="date" CONTENT="2013-01-06"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="O-Index"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="index-13.html"><B>PREV LETTER</B></A>&nbsp; &nbsp;<A HREF="index-15.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-14.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-14.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">K</A> <A HREF="index-11.html">L</A> <A HREF="index-12.html">M</A> <A HREF="index-13.html">N</A> <A HREF="index-14.html">O</A> <A HREF="index-15.html">P</A> <A HREF="index-16.html">Q</A> <A HREF="index-17.html">R</A> <A HREF="index-18.html">S</A> <A HREF="index-19.html">T</A> <A HREF="index-20.html">U</A> <A HREF="index-21.html">V</A> <A HREF="index-22.html">W</A> <A HREF="index-23.html">X</A> <HR> <A NAME="_O_"><!-- --></A><H2> <B>O</B></H2> <DL> <DT><A HREF="../com/intel/cosbench/driver/util/ObjectPicker.html" title="class in com.intel.cosbench.driver.util"><B>ObjectPicker</B></A> - Class in <A HREF="../com/intel/cosbench/driver/util/package-summary.html">com.intel.cosbench.driver.util</A><DD>This class encapsulates logic to pick up objects.<DT><A HREF="../com/intel/cosbench/driver/util/ObjectPicker.html#ObjectPicker()"><B>ObjectPicker()</B></A> - Constructor for class com.intel.cosbench.driver.util.<A HREF="../com/intel/cosbench/driver/util/ObjectPicker.html" title="class in com.intel.cosbench.driver.util">ObjectPicker</A> <DD>&nbsp; <DT><A HREF="../com/intel/cosbench/driver/util/ObjectScanner.html" title="class in com.intel.cosbench.driver.util"><B>ObjectScanner</B></A> - Class in <A HREF="../com/intel/cosbench/driver/util/package-summary.html">com.intel.cosbench.driver.util</A><DD>This class encapsulates logic to scan object ranges.<DT><A HREF="../com/intel/cosbench/driver/util/ObjectScanner.html#ObjectScanner()"><B>ObjectScanner()</B></A> - Constructor for class com.intel.cosbench.driver.util.<A HREF="../com/intel/cosbench/driver/util/ObjectScanner.html" title="class in com.intel.cosbench.driver.util">ObjectScanner</A> <DD>&nbsp; <DT><A HREF="../com/intel/cosbench/driver/operator/OperationListener.html#onOperationCompleted(com.intel.cosbench.bench.Result)"><B>onOperationCompleted(Result)</B></A> - Method in interface com.intel.cosbench.driver.operator.<A HREF="../com/intel/cosbench/driver/operator/OperationListener.html" title="interface in com.intel.cosbench.driver.operator">OperationListener</A> <DD>&nbsp; <DT><A HREF="../com/intel/cosbench/driver/operator/OperationListener.html#onSampleCreated(com.intel.cosbench.bench.Sample)"><B>onSampleCreated(Sample)</B></A> - Method in interface com.intel.cosbench.driver.operator.<A HREF="../com/intel/cosbench/driver/operator/OperationListener.html" title="interface in com.intel.cosbench.driver.operator">OperationListener</A> <DD>&nbsp; <DT><A HREF="../com/intel/cosbench/driver/operator/Disposer.html#OP_TYPE"><B>OP_TYPE</B></A> - Static variable in class com.intel.cosbench.driver.operator.<A HREF="../com/intel/cosbench/driver/operator/Disposer.html" title="class in com.intel.cosbench.driver.operator">Disposer</A> <DD>&nbsp; <DT><A HREF="../com/intel/cosbench/driver/operator/Initializer.html#OP_TYPE"><B>OP_TYPE</B></A> - Static variable in class com.intel.cosbench.driver.operator.<A HREF="../com/intel/cosbench/driver/operator/Initializer.html" title="class in com.intel.cosbench.driver.operator">Initializer</A> <DD>&nbsp; <DT><A HREF="../com/intel/cosbench/driver/operator/Operator.html#operate(com.intel.cosbench.driver.operator.Session)"><B>operate(Session)</B></A> - Method in interface com.intel.cosbench.driver.operator.<A HREF="../com/intel/cosbench/driver/operator/Operator.html" title="interface in com.intel.cosbench.driver.operator">Operator</A> <DD>&nbsp; <DT><A HREF="../com/intel/cosbench/config/Operation.html" title="class in com.intel.cosbench.config"><B>Operation</B></A> - Class in <A HREF="../com/intel/cosbench/config/package-summary.html">com.intel.cosbench.config</A><DD>The model class mapping to "operation" in configuration xml with following form: <operation type="type" ratio="ratio" division="division" config="config" /><DT><A HREF="../com/intel/cosbench/config/Operation.html#Operation()"><B>Operation()</B></A> - Constructor for class com.intel.cosbench.config.<A HREF="../com/intel/cosbench/config/Operation.html" title="class in com.intel.cosbench.config">Operation</A> <DD>&nbsp; <DT><A HREF="../com/intel/cosbench/config/Operation.html#Operation(java.lang.String)"><B>Operation(String)</B></A> - Constructor for class com.intel.cosbench.config.<A HREF="../com/intel/cosbench/config/Operation.html" title="class in com.intel.cosbench.config">Operation</A> <DD>&nbsp; <DT><A HREF="../com/intel/cosbench/driver/operator/OperationListener.html" title="interface in com.intel.cosbench.driver.operator"><B>OperationListener</B></A> - Interface in <A HREF="../com/intel/cosbench/driver/operator/package-summary.html">com.intel.cosbench.driver.operator</A><DD>&nbsp;<DT><A HREF="../com/intel/cosbench/driver/util/OperationPicker.html" title="class in com.intel.cosbench.driver.util"><B>OperationPicker</B></A> - Class in <A HREF="../com/intel/cosbench/driver/util/package-summary.html">com.intel.cosbench.driver.util</A><DD>This class encapsulates logic to pick up operations.<DT><A HREF="../com/intel/cosbench/driver/util/OperationPicker.html#OperationPicker()"><B>OperationPicker()</B></A> - Constructor for class com.intel.cosbench.driver.util.<A HREF="../com/intel/cosbench/driver/util/OperationPicker.html" title="class in com.intel.cosbench.driver.util">OperationPicker</A> <DD>&nbsp; <DT><A HREF="../com/intel/cosbench/driver/operator/Operator.html" title="interface in com.intel.cosbench.driver.operator"><B>Operator</B></A> - Interface in <A HREF="../com/intel/cosbench/driver/operator/package-summary.html">com.intel.cosbench.driver.operator</A><DD>&nbsp;<DT><A HREF="../com/intel/cosbench/driver/model/OperatorContext.html" title="class in com.intel.cosbench.driver.model"><B>OperatorContext</B></A> - Class in <A HREF="../com/intel/cosbench/driver/model/package-summary.html">com.intel.cosbench.driver.model</A><DD>This class encapsulates operator related information.<DT><A HREF="../com/intel/cosbench/driver/model/OperatorContext.html#OperatorContext()"><B>OperatorContext()</B></A> - Constructor for class com.intel.cosbench.driver.model.<A HREF="../com/intel/cosbench/driver/model/OperatorContext.html" title="class in com.intel.cosbench.driver.model">OperatorContext</A> <DD>&nbsp; <DT><A HREF="../com/intel/cosbench/driver/model/OperatorRegistry.html" title="class in com.intel.cosbench.driver.model"><B>OperatorRegistry</B></A> - Class in <A HREF="../com/intel/cosbench/driver/model/package-summary.html">com.intel.cosbench.driver.model</A><DD>&nbsp;<DT><A HREF="../com/intel/cosbench/driver/model/OperatorRegistry.html#OperatorRegistry()"><B>OperatorRegistry()</B></A> - Constructor for class com.intel.cosbench.driver.model.<A HREF="../com/intel/cosbench/driver/model/OperatorRegistry.html" title="class in com.intel.cosbench.driver.model">OperatorRegistry</A> <DD>&nbsp; <DT><A HREF="../com/intel/cosbench/driver/operator/Operators.html" title="class in com.intel.cosbench.driver.operator"><B>Operators</B></A> - Class in <A HREF="../com/intel/cosbench/driver/operator/package-summary.html">com.intel.cosbench.driver.operator</A><DD>&nbsp;<DT><A HREF="../com/intel/cosbench/driver/operator/Operators.html#Operators()"><B>Operators()</B></A> - Constructor for class com.intel.cosbench.driver.operator.<A HREF="../com/intel/cosbench/driver/operator/Operators.html" title="class in com.intel.cosbench.driver.operator">Operators</A> <DD>&nbsp; </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="index-13.html"><B>PREV LETTER</B></A>&nbsp; &nbsp;<A HREF="index-15.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-14.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-14.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">K</A> <A HREF="index-11.html">L</A> <A HREF="index-12.html">M</A> <A HREF="index-13.html">N</A> <A HREF="index-14.html">O</A> <A HREF="index-15.html">P</A> <A HREF="index-16.html">Q</A> <A HREF="index-17.html">R</A> <A HREF="index-18.html">S</A> <A HREF="index-19.html">T</A> <A HREF="index-20.html">U</A> <A HREF="index-21.html">V</A> <A HREF="index-22.html">W</A> <A HREF="index-23.html">X</A> <HR> </BODY> </HTML>
{ "pile_set_name": "Github" }
from rubicon.java import android_events from toga.handlers import wrapped_handler from .libs.activity import IPythonApp, MainActivity from .window import Window # `MainWindow` is defined here in `app.py`, not `window.py`, to mollify the test suite. class MainWindow(Window): pass class TogaApp(IPythonApp): def __init__(self, app): super().__init__() self._interface = app MainActivity.setPythonApp(self) print('Python app launched & stored in Android Activity class') def onCreate(self): print("Toga app: onCreate") def onStart(self): print("Toga app: onStart") def onResume(self): print("Toga app: onResume") def onPause(self): print("Toga app: onPause") def onStop(self): print("Toga app: onStop") def onDestroy(self): print("Toga app: onDestroy") def onRestart(self): print("Toga app: onRestart") @property def native(self): # We access `MainActivity.singletonThis` freshly each time, rather than # storing a reference in `__init__()`, because it's not safe to use the # same reference over time because `rubicon-java` creates a JNI local # reference. return MainActivity.singletonThis class App: def __init__(self, interface): self.interface = interface self.interface._impl = self self._listener = None self.loop = android_events.AndroidEventLoop() @property def native(self): return self._listener.native if self._listener else None def create(self): # The `_listener` listens for activity event callbacks. For simplicity, # the app's `.native` is the listener's native Java class. self._listener = TogaApp(self) # Call user code to populate the main window self.interface.startup() def open_document(self, fileURL): print("Can't open document %s (yet)" % fileURL) def main_loop(self): # In order to support user asyncio code, start the Python/Android cooperative event loop. self.loop.run_forever_cooperatively() # On Android, Toga UI integrates automatically into the main Android event loop by virtue # of the Android Activity system. self.create() def set_main_window(self, window): pass def show_about_dialog(self): self.interface.factory.not_implemented("App.show_about_dialog()") def exit(self): pass def set_on_exit(self, value): pass def add_background_task(self, handler): self.loop.call_soon(wrapped_handler(self, handler), self)
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); namespace GrumPHP\Locator; use GrumPHP\Configuration\GuessedPaths; use GrumPHP\Exception\RuntimeException; use GrumPHP\Util\ComposerFile; use GrumPHP\Util\Filesystem; class GuessedPathsLocator { /** * @var Filesystem */ private $filesystem; /** * @var GitWorkingDirLocator */ private $gitWorkingDirLocator; /** * @var GitRepositoryDirLocator */ private $gitRepositoryDirLocator; public function __construct( Filesystem $filesystem, GitWorkingDirLocator $gitWorkingDirLocator, GitRepositoryDirLocator $gitRepositoryDirLocator ) { $this->filesystem = $filesystem; $this->gitWorkingDirLocator = $gitWorkingDirLocator; $this->gitRepositoryDirLocator = $gitRepositoryDirLocator; } public function locate(?string $cliConfigFile): GuessedPaths { $workingDir = getcwd(); $cliConfigFile = $this->makeOptionalPathAbsolute($workingDir, $cliConfigFile); $cliConfigPath = $cliConfigFile ? dirname($cliConfigFile) : null; $projectDirEnv = $this->makeOptionalPathAbsolute($workingDir, (string) ($_SERVER['GRUMPHP_PROJECT_DIR'] ?? '')); $gitWorkingDir = $this->filesystem->makePathAbsolute( (string) ($_SERVER['GRUMPHP_GIT_WORKING_DIR'] ?? $this->safelyLocateGitWorkingDir($workingDir)), $workingDir ); $gitRepositoryDir = $this->filesystem->makePathAbsolute( (string) ($_SERVER['GRUMPHP_GIT_REPOSITORY_DIR'] ?? $this->gitRepositoryDirLocator->locate( $this->filesystem->buildPath($gitWorkingDir, '.git') )), $workingDir ); $composerFilePathname = $this->filesystem->guessFile( array_filter([ $this->makeOptionalPathAbsolute($workingDir, (string) ($_SERVER['GRUMPHP_COMPOSER_DIR'] ?? '')), $cliConfigPath, $projectDirEnv, $workingDir, $gitWorkingDir ]), [ 'composer.json' ] ); $composerFilePath = dirname($composerFilePathname); $composerFile = new ComposerFile( $composerFilePathname, $this->filesystem->exists($composerFilePathname) ? json_decode($this->filesystem->readFromFileInfo(new \SplFileInfo($composerFilePathname)), true) : [] ); $binDir = $this->filesystem->guessPath(array_filter([ $this->makeOptionalPathAbsolute($workingDir, (string) ($_SERVER['GRUMPHP_BIN_DIR'] ?? '')), $this->makeOptionalPathAbsolute( $composerFilePath, $this->ensureOptionalArgumentWithValidSlashes($composerFile->getBinDir()) ) ])); $composerConfigDefaultPath = $this->makeOptionalPathAbsolute( $composerFilePath, $this->ensureOptionalArgumentWithValidSlashes($composerFile->getConfigDefaultPath()) ); $projectDir = $this->filesystem->guessPath([ $projectDirEnv, $this->makeOptionalPathAbsolute( $composerFilePath, $this->ensureOptionalArgumentWithValidSlashes($composerFile->getProjectPath()) ), $workingDir ]); $defaultConfigFile = $this->filesystem->guessFile( array_filter([ $cliConfigFile, $cliConfigPath, $composerConfigDefaultPath, $projectDir, $workingDir, $gitWorkingDir, ]), [ 'grumphp.yml', 'grumphp.yaml', 'grumphp.yml.dist', 'grumphp.yaml.dist', ] ); return new GuessedPaths( $gitWorkingDir, $gitRepositoryDir, $workingDir, $projectDir, $binDir, $composerFile, $defaultConfigFile ); } private function makeOptionalPathAbsolute(string $baseDir, ?string $path): ?string { if (!$path) { return null; } return $this->filesystem->makePathAbsolute($path, $baseDir); } private function ensureOptionalArgumentWithValidSlashes(?string $path): ?string { if (!$path) { return null; } return $this->filesystem->ensureValidSlashes($path); } /** * The git locator fails when no git dir can be found. * However : that might degrade the user experience when just running the info commands on the cli tool. * Gitonomy will detect invalid git dirs anyways. So it is ok to fall back to e.g. the current working dir. */ private function safelyLocateGitWorkingDir(string $fallbackDir): string { try { return $this->gitWorkingDirLocator->locate(); } catch (RuntimeException $e) { return $fallbackDir; } } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>IDEDidComputeMac32BitWarning</key> <true/> </dict> </plist>
{ "pile_set_name": "Github" }
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "ConstantTrend", cycle_length = 7, transform = "BoxCox", sigma = 0.0, exog_count = 20, ar_order = 12);
{ "pile_set_name": "Github" }
package sarama type SaslHandshakeResponse struct { Err KError EnabledMechanisms []string } func (r *SaslHandshakeResponse) encode(pe packetEncoder) error { pe.putInt16(int16(r.Err)) return pe.putStringArray(r.EnabledMechanisms) } func (r *SaslHandshakeResponse) decode(pd packetDecoder, version int16) error { kerr, err := pd.getInt16() if err != nil { return err } r.Err = KError(kerr) if r.EnabledMechanisms, err = pd.getStringArray(); err != nil { return err } return nil } func (r *SaslHandshakeResponse) key() int16 { return 17 } func (r *SaslHandshakeResponse) version() int16 { return 0 } func (r *SaslHandshakeResponse) headerVersion() int16 { return 0 } func (r *SaslHandshakeResponse) requiredVersion() KafkaVersion { return V0_10_0_0 }
{ "pile_set_name": "Github" }
<?xml version="1.1" encoding="UTF-8" standalone="no"?> <!-- #%L kylo-service-app %% Copyright (C) 2017 ThinkBig Analytics %% 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. #L% --> <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd"> <changeSet author="sr186054" id="kylo-0.8.3-ADD_LAST_ACTIVITY-column"> <validCheckSum>7:e81d9013304ff56950150bdb4a485a1a</validCheckSum> <validCheckSum>7:c4c6cf970d6a8215bb6dc5ad8cde9c7b</validCheckSum> <addColumn tableName="NIFI_FEED_STATS"> <column name="LAST_ACTIVITY_TIMESTAMP" type="BIGINT"/> </addColumn> </changeSet> </databaseChangeLog>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.fly.tour.me"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" android:name="debug.MeApplication"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <activity android:name=".NewsTypeAddActivity" android:label="新闻类型设置" android:theme="@style/AppTheme.BlackBackBar" /> <activity android:name=".NewsTypeListActivity" android:label="新闻类型列表" android:theme="@style/AppTheme.BackBar"/> </application> </manifest>
{ "pile_set_name": "Github" }
package SecurityReplicationTest import spock.lang.Specification import groovy.json.JsonSlurper class SecurityReplicationTest extends Specification { def 'update extract diff patch test'() { setup: def baseurl = 'http://localhost:8088/artifactory/api/plugins/execute' def auth = "Basic ${'admin:password'.bytes.encodeBase64()}" def conn = new URL("http://localhost:8088/artifactory/api/system/version").openConnection() conn.requestMethod = 'GET' conn.setRequestProperty('Authorization', auth) assert conn.responseCode == 200 def version = new JsonSlurper().parse(conn.inputStream).version.split('\\.') conn.disconnect() def major = version[0] as int def minor = version[1] as int def vtest = (major > 5 || (major == 5 && minor >= 6)) ? '-56' : 'old' vtest = (major > 5 || (major == 5 && minor >= 10)) ? '' : vtest conn = new URL("$baseurl/testSecurityDump").openConnection() conn.requestMethod = 'GET' conn.setRequestProperty('Authorization', auth) assert conn.responseCode == 200 def original = conn.inputStream.text, file = null, snapshot = null conn.disconnect() when: conn = new URL("$baseurl/testDBUpdate").openConnection() conn.requestMethod = 'POST' conn.doOutput = true conn.setRequestProperty('Authorization', auth) conn.setRequestProperty('Content-Type', 'application/json') file = new File("./src/test/groovy/SecurityReplicationTest/sec1${vtest}.json") conn.outputStream << file.text assert conn.responseCode == 200 conn.disconnect() conn = new URL("$baseurl/testSecurityDump").openConnection() conn.requestMethod = 'GET' conn.setRequestProperty('Authorization', auth) assert conn.responseCode == 200 snapshot = conn.inputStream.text conn.disconnect() then: file.text == snapshot when: conn = new URL("$baseurl/testDBUpdate").openConnection() conn.requestMethod = 'POST' conn.doOutput = true conn.setRequestProperty('Authorization', auth) conn.setRequestProperty('Content-Type', 'application/json') file = new File("./src/test/groovy/SecurityReplicationTest/sec2${vtest}.json") conn.outputStream << file.text assert conn.responseCode == 200 conn.disconnect() conn = new URL("$baseurl/testSecurityDump").openConnection() conn.requestMethod = 'GET' conn.setRequestProperty('Authorization', auth) assert conn.responseCode == 200 snapshot = conn.inputStream.text conn.disconnect() then: file.text == snapshot cleanup: conn = new URL("$baseurl/testDBUpdate").openConnection() conn.requestMethod = 'POST' conn.doOutput = true conn.setRequestProperty('Authorization', auth) conn.setRequestProperty('Content-Type', 'application/json') conn.outputStream << original assert conn.responseCode == 200 conn.disconnect() } }
{ "pile_set_name": "Github" }
#!/bin/sh java -jar ../dist/SocketTest.jar c:10.0.0.1:5555
{ "pile_set_name": "Github" }
use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub enum Request { Get { key: String }, Set { key: String, value: String }, Remove { key: String }, } #[derive(Debug, Serialize, Deserialize)] pub enum Response { Get(Option<String>), Set, Remove, Err(String), }
{ "pile_set_name": "Github" }
## GLOBAL ## - id: "global.home" translation: "Beginpagina" - id: "global.categories" translation: "Categorieem" - id: "global.category" translation: "Categorie" - id: "global.tags" translation: "Tags" - id: "global.tag" translation: "Tag" - id: "global.archives" translation: "Archieven" - id: "global.search" translation: "Zoeken" - id: "global.about" translation: "Over" - id: "global.author_picture" translation: "Foto van auteur" - id: "global.share_on" translation: "Delen op %s" - id: "global.mail" translation: "Mail" - id: "global.rss" translation: "RSS" - id: "global.search_category" translation: "Zoek op categorie" - id: "global.search_tag" translation: "Zoek op tag" - id: "global.search_date" translation: "Zoek op datum (YYYY/MM/DD)" ## GLOBAL.POST_FOUND ## - id: "global.posts_found.zero" translation: "Geen posts gevonden" - id: "global.posts_found.one" translation: "1 post gevonden" - id: "global.posts_found.other" translation: "{n} posts gevonden" ## GLOBAL.CATEGORIES_FOUND ## - id: "global.categories_found.zero" translation: "geen categorie gevonden" - id: "global.categories_found.one" translation: "1 categorie gevonden" - id: "global.categories_found.other" translation: "{n} categorieen gevonden" ## GLOBAL.TAGS_FOUND ## - id: "global.tags_found.zero" translation: "geen tags gevonden" - id: "global.tags_found.one" translation: "1 tag gevonden" - id: "global.tags_found.other" translation: "{n} tags gevonden" ## PAGINATION ## - id: "pagination.page" translation: "pagina {{ .Paginator.PageNumber }}" - id: "pagination.of" translation: "van {{ .Paginator.TotalPages }}" - id: "pagination.newer_posts" translation: "NIEUWERE POSTS" - id: "pagination.older_posts" translation: "OUDERE POSTS" - id: "pagination.previous" translation: "VORIGE" - id: "pagination.next" translation: "VOLGENDE" ## POST ## - id: "post.no_title" translation: "Geen titel" - id: "post.categorized_in" translation: "in" - id: "post.tagged_in" translation: "GETAGGED IN" - id: "post.toc" translation: "Inhoudsopgave" - id: "post.read_more" translation: "Lees verder" - id: "post.go_to_website" translation: "Ga naar website" - id: "post.comment_and_share" translation: "Reageer en deel" ## FOOTER ## - id: "footer.all_rights_reserved" translation: "Alle rechten voorbehouden" ## DATE ## - id: "date.month.january" translation: "Januari" - id: "date.month.february" translation: "Februari" - id: "date.month.march" translation: "Maart" - id: "date.month.april" translation: "April" - id: "date.month.may" translation: "Mei" - id: "date.month.june" translation: "Juni" - id: "date.month.july" translation: "Juli" - id: "date.month.august" translation: "Augustus" - id: "date.month.september" translation: "September" - id: "date.month.october" translation: "Oktober" - id: "date.month.november" translation: "November" - id: "date.month.december" translation: "December"
{ "pile_set_name": "Github" }
--- a/util/Assert.c +++ b/util/Assert.c @@ -19,10 +19,6 @@ #include <stdlib.h> #include <stdarg.h> -#ifdef __GLIBC__ -# include <execinfo.h> -#endif - Gcc_PRINTF(1, 2) void Assert_failure(const char* format, ...) { @@ -33,21 +29,6 @@ va_start(args, format); vfprintf(stderr, format, args); fflush(stderr); - -#ifdef __GLIBC__ - void *array[20]; - size_t size = backtrace(array, 20); - char **strings = backtrace_symbols(array, size); - - fprintf(stderr, "Backtrace (%zd frames):\n", size); - for (size_t i = 0; i < size; i++) - { - fprintf(stderr, " %s\n", strings[i]); - } - fflush(stderr); - free(strings); - -#endif abort(); va_end(args); }
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright (c) 2008, 2020 Andrew Gvozdev 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/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Andrew Gvozdev (Quoin Inc.) - Initial implementation * Sergei Kovalchuk (NXP) - Switch dependency from com.ibm.icu to java.text *******************************************************************************/ package org.eclipse.cdt.make.internal.ui.dnd; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.eclipse.cdt.make.core.IMakeTarget; import org.eclipse.cdt.make.internal.ui.MakeUIPlugin; import org.eclipse.core.resources.IContainer; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.widgets.Shell; /** * {@code TextTransferDropTargetListener} handles dropping of selected text to * Make Target View. Each line of miltiline text passed is treated as separate * make target command. {@link TextTransfer} is used as the transfer agent. * * @see AbstractContainerAreaDropAdapter * @see org.eclipse.swt.dnd.DropTargetListener */ public class TextTransferDropTargetListener extends AbstractContainerAreaDropAdapter { Viewer fViewer; /** * Constructor setting a viewer such as TreeViewer to pull selection from later on. * @param viewer - the viewer providing shell for UI. */ public TextTransferDropTargetListener(Viewer viewer) { fViewer = viewer; } /** * @return the {@link Transfer} type that this listener can accept a * drop operation for. */ @Override public Transfer getTransfer() { return TextTransfer.getInstance(); } /** * Initial drag operation. Only {@link DND#DROP_COPY} is supported for * dropping text to Make Target View, same as for {@code dragOverOperation}. * * @param operation - incoming operation. * @return changed operation. */ @Override public int dragEnterOperation(int operation) { return dragOverOperation(operation, null, null); } /** * Operation of dragging over a drop target. Only {@link DND#DROP_COPY} is * supported for dropping text to Make Target View. * * @param operation - incoming operation. * @return changed operation. */ @Override public int dragOverOperation(int operation, IContainer dropContainer, Object dropTarget) { // This class is intended only for drag/drop between eclipse instances, // so DND_COPY always set and we don't bother checking if the target is the source if (operation != DND.DROP_NONE) { return DND.DROP_COPY; } return operation; } /** * Implementation of the actual drop of {@code dropObject} to {@code dropContainer}. * * @param dropObject - object to drop. * @param dropContainer - container where to drop the object. * @param operation - drop operation. */ @Override public void dropToContainer(Object dropObject, IContainer dropContainer, int operation) { if (dropObject instanceof String && ((String) dropObject).length() > 0 && dropContainer != null) { createMultilineTargetsUI((String) dropObject, dropContainer, operation, fViewer.getControl().getShell()); } } /** * Convert multiline text to array of {@code IMakeTarget}s. Each line is * interpreted as one separate make command. * * @param multilineText - input text. * @param container - container where the targets will belong. * @return resulting array of {@code IMakeTarget}s. */ private static IMakeTarget[] prepareMakeTargetsFromString(String multilineText, IContainer container) { if (container != null) { String[] lines = multilineText.split("[\n\r]"); //$NON-NLS-1$ List<IMakeTarget> makeTargets = new ArrayList<>(lines.length); for (String command : lines) { command = command.trim(); if (command.length() > 0) { String name = command; String buildCommand = command; String buildTarget = null; String defaultBuildCommand = MakeTargetDndUtil.getProjectBuildCommand(container.getProject()); if (command.startsWith(defaultBuildCommand + " ")) { //$NON-NLS-1$ buildCommand = defaultBuildCommand; buildTarget = command.substring(defaultBuildCommand.length() + 1).trim(); name = buildTarget; } try { makeTargets.add(MakeTargetDndUtil.createMakeTarget(name, buildTarget, buildCommand, container)); } catch (CoreException e) { // Ignore failed targets MakeUIPlugin.log(e); } } } return makeTargets.toArray(new IMakeTarget[makeTargets.size()]); } return null; } /** * Combined operation of creating make targets in Make Target View from * multiline text. The method will ask a confirmation if user tries to drop * more then 1 target to prevent easily made mistake of unintended copying * of old contents of the clipboard. * * @param multilineText - input make target commands in textual form. * @param dropContainer - container where add the targets. * @param operation - operation such as copying or moving. Must be a * {@link org.eclipse.swt.dnd.DND} operation. * @param shell - a shell to display progress of operation to user. * * @see DND#DROP_NONE * @see DND#DROP_COPY * @see DND#DROP_MOVE * @see DND#DROP_LINK */ public static void createMultilineTargetsUI(String multilineText, IContainer dropContainer, int operation, Shell shell) { IMakeTarget[] makeTargets = prepareMakeTargetsFromString(multilineText, dropContainer); boolean confirmed = true; if (makeTargets.length > 1) { String title = MakeUIPlugin.getResourceString("MakeTargetDnD.title.createFromTextConfirm"); //$NON-NLS-1$ String question = MessageFormat.format( MakeUIPlugin.getResourceString("MakeTargetDnD.message.createFromTextConfirm"), //$NON-NLS-1$ new Object[] { Integer.valueOf(makeTargets.length) }); String topTargets = ""; //$NON-NLS-1$ for (int i = 0; i < makeTargets.length; i++) { // limit dimensions of the confirm dialog final int HEIGHT_LIMIT = 20; final int LENGTH_LIMIT = 200; if (i > HEIGHT_LIMIT) { topTargets = topTargets + "..."; //$NON-NLS-1$ break; } String name = makeTargets[i].getName(); if (name.length() > LENGTH_LIMIT) { name = name.substring(0, LENGTH_LIMIT - 3) + "..."; //$NON-NLS-1$ } topTargets = topTargets + name + "\n"; //$NON-NLS-1$ } confirmed = MessageDialog.openConfirm(shell, title, question + topTargets); } if (confirmed) { MakeTargetDndUtil.copyTargets(makeTargets, dropContainer, operation, shell); } } }
{ "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 v1alpha1 is alpha objects from meta that will be introduced. package v1alpha1 import ( "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" ) // TODO: Table does not generate to protobuf because of the interface{} - fix protobuf // generation to support a meta type that can accept any valid JSON. // Table is a tabular representation of a set of API resources. The server transforms the // object into a set of preferred columns for quickly reviewing the objects. // +protobuf=false // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type Table struct { v1.TypeMeta `json:",inline"` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds // +optional v1.ListMeta `json:"metadata,omitempty"` // columnDefinitions describes each column in the returned items array. The number of cells per row // will always match the number of column definitions. ColumnDefinitions []TableColumnDefinition `json:"columnDefinitions"` // rows is the list of items in the table. Rows []TableRow `json:"rows"` } // TableColumnDefinition contains information about a column returned in the Table. // +protobuf=false type TableColumnDefinition struct { // name is a human readable name for the column. Name string `json:"name"` // type is an OpenAPI type definition for this column. // See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for more. Type string `json:"type"` // format is an optional OpenAPI type definition for this column. The 'name' format is applied // to the primary identifier column to assist in clients identifying column is the resource name. // See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for more. Format string `json:"format"` // description is a human readable description of this column. Description string `json:"description"` // priority is an integer defining the relative importance of this column compared to others. Lower // numbers are considered higher priority. Columns that may be omitted in limited space scenarios // should be given a higher priority. Priority int32 `json:"priority"` } // TableRow is an individual row in a table. // +protobuf=false type TableRow struct { // cells will be as wide as headers and may contain strings, numbers, booleans, simple maps, or lists, or // null. See the type field of the column definition for a more detailed description. Cells []interface{} `json:"cells"` // conditions describe additional status of a row that are relevant for a human user. // +optional Conditions []TableRowCondition `json:"conditions,omitempty"` // This field contains the requested additional information about each object based on the includeObject // policy when requesting the Table. If "None", this field is empty, if "Object" this will be the // default serialization of the object for the current API version, and if "Metadata" (the default) will // contain the object metadata. Check the returned kind and apiVersion of the object before parsing. // +optional Object runtime.RawExtension `json:"object,omitempty"` } // TableRowCondition allows a row to be marked with additional information. // +protobuf=false type TableRowCondition struct { // Type of row condition. Type RowConditionType `json:"type"` // Status of the condition, one of True, False, Unknown. Status ConditionStatus `json:"status"` // (brief) machine readable reason for the condition's last transition. // +optional Reason string `json:"reason,omitempty"` // Human readable message indicating details about last transition. // +optional Message string `json:"message,omitempty"` } type RowConditionType string // These are valid conditions of a row. This list is not exhaustive and new conditions may be // inculded by other resources. const ( // RowCompleted means the underlying resource has reached completion and may be given less // visual priority than other resources. RowCompleted RowConditionType = "Completed" ) type ConditionStatus string // These are valid condition statuses. "ConditionTrue" means a resource is in the condition. // "ConditionFalse" means a resource is not in the condition. "ConditionUnknown" means kubernetes // can't decide if a resource is in the condition or not. In the future, we could add other // intermediate conditions, e.g. ConditionDegraded. const ( ConditionTrue ConditionStatus = "True" ConditionFalse ConditionStatus = "False" ConditionUnknown ConditionStatus = "Unknown" ) // IncludeObjectPolicy controls which portion of the object is returned with a Table. type IncludeObjectPolicy string const ( // IncludeNone returns no object. IncludeNone IncludeObjectPolicy = "None" // IncludeMetadata serializes the object containing only its metadata field. IncludeMetadata IncludeObjectPolicy = "Metadata" // IncludeObject contains the full object. IncludeObject IncludeObjectPolicy = "Object" ) // TableOptions are used when a Table is requested by the caller. // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type TableOptions struct { v1.TypeMeta `json:",inline"` // includeObject decides whether to include each object along with its columnar information. // Specifying "None" will return no object, specifying "Object" will return the full object contents, and // specifying "Metadata" (the default) will return the object's metadata in the PartialObjectMetadata kind // in version v1alpha1 of the meta.k8s.io API group. IncludeObject IncludeObjectPolicy `json:"includeObject,omitempty" protobuf:"bytes,1,opt,name=includeObject,casttype=IncludeObjectPolicy"` } // PartialObjectMetadata is a generic representation of any object with ObjectMeta. It allows clients // to get access to a particular ObjectMeta schema without knowing the details of the version. // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type PartialObjectMetadata struct { v1.TypeMeta `json:",inline"` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata // +optional v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` } // PartialObjectMetadataList contains a list of objects containing only their metadata // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type PartialObjectMetadataList struct { v1.TypeMeta `json:",inline"` // items contains each of the included items. Items []*PartialObjectMetadata `json:"items" protobuf:"bytes,1,rep,name=items"` }
{ "pile_set_name": "Github" }
.. SPDX-License-Identifier: GPL-2.0+ HiFive Unleashed ================ FU540-C000 RISC-V SoC --------------------- The FU540-C000 is the world’s first 4+1 64-bit RISC-V SoC from SiFive. The HiFive Unleashed development platform is based on FU540-C000 and capable of running Linux. Mainline support ---------------- The support for following drivers are already enabled: 1. SiFive UART Driver. 2. SiFive PRCI Driver for clock. 3. Cadence MACB ethernet driver for networking support. 4. SiFive SPI Driver. 5. MMC SPI Driver for MMC/SD support. TODO: 1. U-Boot expects the serial console device entry to be present under /chosen DT node. Without a serial console U-Boot will panic. Example: .. code-block:: none chosen { stdout-path = "/soc/serial@10010000:115200"; }; Building -------- 1. Add the RISC-V toolchain to your PATH. 2. Setup ARCH & cross compilation enviornment variable: .. code-block:: none export ARCH=riscv export CROSS_COMPILE=<riscv64 toolchain prefix> 3. make sifive_fu540_defconfig 4. make Flashing -------- The current U-Boot port is supported in S-mode only and loaded from DRAM. A prior stage M-mode firmware/bootloader (e.g OpenSBI) is required to boot the u-boot.bin in S-mode and provide M-mode runtime services. Currently, the u-boot.bin is used as a payload of the OpenSBI FW_PAYLOAD firmware. We need to compile OpenSBI with below command: .. code-block:: none make PLATFORM=sifive/fu540 FW_PAYLOAD_PATH=<path to u-boot-dtb.bin> More detailed description of steps required to build FW_PAYLOAD firmware is beyond the scope of this document. Please refer OpenSBI documenation. (Note: OpenSBI git repo is at https://github.com/riscv/opensbi.git) Once the prior stage firmware/bootloader binary is generated, it should be copied to the first partition of the sdcard. .. code-block:: none sudo dd if=<prior_stage_firmware_binary> of=/dev/disk2s1 bs=1024 Booting ------- Once you plugin the sdcard and power up, you should see the U-Boot prompt. Sample boot log from HiFive Unleashed board ------------------------------------------- .. code-block:: none U-Boot 2019.07-00024-g350ff02f5b (Jul 22 2019 - 11:45:02 +0530) CPU: rv64imafdc Model: SiFive HiFive Unleashed A00 DRAM: 8 GiB MMC: spi@10050000:mmc@0: 0 In: serial@10010000 Out: serial@10010000 Err: serial@10010000 Net: eth0: ethernet@10090000 Hit any key to stop autoboot: 0 => version U-Boot 2019.07-00024-g350ff02f5b (Jul 22 2019 - 11:45:02 +0530) riscv64-linux-gcc.br_real (Buildroot 2018.11-rc2-00003-ga0787e9) 8.2.0 GNU ld (GNU Binutils) 2.31.1 => mmc info Device: spi@10050000:mmc@0 Manufacturer ID: 3 OEM: 5344 Name: SU08G Bus Speed: 20000000 Mode: SD Legacy Rd Block Len: 512 SD version 2.0 High Capacity: Yes Capacity: 7.4 GiB Bus Width: 1-bit Erase Group Size: 512 Bytes => mmc part Partition Map for MMC device 0 -- Partition Type: EFI Part Start LBA End LBA Name Attributes Type GUID Partition GUID 1 0x00000800 0x000107ff "bootloader" attrs: 0x0000000000000000 type: 2e54b353-1271-4842-806f-e436d6af6985 guid: 393bbd36-7111-491c-9869-ce24008f6403 2 0x00040800 0x00ecdfde "" attrs: 0x0000000000000000 type: 0fc63daf-8483-4772-8e79-3d69d8477de4 guid: 7fc9a949-5480-48c7-b623-04923080757f Now you can configure your networking, tftp server and use tftp boot method to load uImage. .. code-block:: none => setenv ipaddr 10.206.7.133 => setenv netmask 255.255.252.0 => setenv serverip 10.206.4.143 => setenv gateway 10.206.4.1 => tftpboot ${kernel_addr_r} /sifive/fu540/Image ethernet@10090000: PHY present at 0 ethernet@10090000: Starting autonegotiation... ethernet@10090000: Autonegotiation complete ethernet@10090000: link up, 1000Mbps full-duplex (lpa: 0x3c00) Using ethernet@10090000 device TFTP from server 10.206.4.143; our IP address is 10.206.7.133 Filename '/sifive/fu540/Image'. Load address: 0x84000000 Loading: ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ########################################## 1.2 MiB/s done Bytes transferred = 8867100 (874d1c hex) => tftpboot ${ramdisk_addr_r} /sifive/fu540/uRamdisk ethernet@10090000: PHY present at 0 ethernet@10090000: Starting autonegotiation... ethernet@10090000: Autonegotiation complete ethernet@10090000: link up, 1000Mbps full-duplex (lpa: 0x3c00) Using ethernet@10090000 device TFTP from server 10.206.4.143; our IP address is 10.206.7.133 Filename '/sifive/fu540/uRamdisk'. Load address: 0x88300000 Loading: ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ############## 418.9 KiB/s done Bytes transferred = 2398272 (249840 hex) => tftpboot ${fdt_addr_r} /sifive/fu540/hifive-unleashed-a00.dtb ethernet@10090000: PHY present at 0 ethernet@10090000: Starting autonegotiation... ethernet@10090000: Autonegotiation complete ethernet@10090000: link up, 1000Mbps full-duplex (lpa: 0x7c00) Using ethernet@10090000 device TFTP from server 10.206.4.143; our IP address is 10.206.7.133 Filename '/sifive/fu540/hifive-unleashed-a00.dtb'. Load address: 0x88000000 Loading: ## 1000 Bytes/s done Bytes transferred = 5614 (15ee hex) => setenv bootargs "root=/dev/ram rw console=ttySIF0 ip=dhcp earlycon=sbi" => booti ${kernel_addr_r} ${ramdisk_addr_r} ${fdt_addr_r} ## Loading init Ramdisk from Legacy Image at 88300000 ... Image Name: Linux RootFS Image Type: RISC-V Linux RAMDisk Image (uncompressed) Data Size: 2398208 Bytes = 2.3 MiB Load Address: 00000000 Entry Point: 00000000 Verifying Checksum ... OK ## Flattened Device Tree blob at 88000000 Booting using the fdt blob at 0x88000000 Using Device Tree in place at 0000000088000000, end 00000000880045ed Starting kernel ... [ 0.000000] OF: fdt: Ignoring memory range 0x80000000 - 0x80200000 [ 0.000000] Linux version 5.3.0-rc1-00003-g460ac558152f (anup@anup-lab-machine) (gcc version 8.2.0 (Buildroot 2018.11-rc2-00003-ga0787e9)) #6 SMP Mon Jul 22 10:01:01 IST 2019 [ 0.000000] earlycon: sbi0 at I/O port 0x0 (options '') [ 0.000000] printk: bootconsole [sbi0] enabled [ 0.000000] Initial ramdisk at: 0x(____ptrval____) (2398208 bytes) [ 0.000000] Zone ranges: [ 0.000000] DMA32 [mem 0x0000000080200000-0x00000000ffffffff] [ 0.000000] Normal [mem 0x0000000100000000-0x000000027fffffff] [ 0.000000] Movable zone start for each node [ 0.000000] Early memory node ranges [ 0.000000] node 0: [mem 0x0000000080200000-0x000000027fffffff] [ 0.000000] Initmem setup node 0 [mem 0x0000000080200000-0x000000027fffffff] [ 0.000000] software IO TLB: mapped [mem 0xfbfff000-0xfffff000] (64MB) [ 0.000000] CPU with hartid=0 is not available [ 0.000000] CPU with hartid=0 is not available [ 0.000000] elf_hwcap is 0x112d [ 0.000000] percpu: Embedded 18 pages/cpu s34584 r8192 d30952 u73728 [ 0.000000] Built 1 zonelists, mobility grouping on. Total pages: 2067975 [ 0.000000] Kernel command line: root=/dev/ram rw console=ttySIF0 ip=dhcp earlycon=sbi [ 0.000000] Dentry cache hash table entries: 1048576 (order: 11, 8388608 bytes, linear) [ 0.000000] Inode-cache hash table entries: 524288 (order: 10, 4194304 bytes, linear) [ 0.000000] Sorting __ex_table... [ 0.000000] mem auto-init: stack:off, heap alloc:off, heap free:off [ 0.000000] Memory: 8182308K/8386560K available (5916K kernel code, 368K rwdata, 1840K rodata, 213K init, 304K bss, 204252K reserved, 0K cma-reserved) [ 0.000000] SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=4, Nodes=1 [ 0.000000] rcu: Hierarchical RCU implementation. [ 0.000000] rcu: RCU restricting CPUs from NR_CPUS=8 to nr_cpu_ids=4. [ 0.000000] rcu: RCU calculated value of scheduler-enlistment delay is 25 jiffies. [ 0.000000] rcu: Adjusting geometry for rcu_fanout_leaf=16, nr_cpu_ids=4 [ 0.000000] NR_IRQS: 0, nr_irqs: 0, preallocated irqs: 0 [ 0.000000] plic: mapped 53 interrupts with 4 handlers for 9 contexts. [ 0.000000] riscv_timer_init_dt: Registering clocksource cpuid [0] hartid [1] [ 0.000000] clocksource: riscv_clocksource: mask: 0xffffffffffffffff max_cycles: 0x1d854df40, max_idle_ns: 3526361616960 ns [ 0.000006] sched_clock: 64 bits at 1000kHz, resolution 1000ns, wraps every 2199023255500ns [ 0.008559] Console: colour dummy device 80x25 [ 0.012989] Calibrating delay loop (skipped), value calculated using timer frequency.. 2.00 BogoMIPS (lpj=4000) [ 0.023104] pid_max: default: 32768 minimum: 301 [ 0.028273] Mount-cache hash table entries: 16384 (order: 5, 131072 bytes, linear) [ 0.035765] Mountpoint-cache hash table entries: 16384 (order: 5, 131072 bytes, linear) [ 0.045307] rcu: Hierarchical SRCU implementation. [ 0.049875] smp: Bringing up secondary CPUs ... [ 0.055729] smp: Brought up 1 node, 4 CPUs [ 0.060599] devtmpfs: initialized [ 0.064819] random: get_random_u32 called from bucket_table_alloc.isra.10+0x4e/0x160 with crng_init=0 [ 0.073720] clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 7645041785100000 ns [ 0.083176] futex hash table entries: 1024 (order: 4, 65536 bytes, linear) [ 0.090721] NET: Registered protocol family 16 [ 0.106319] vgaarb: loaded [ 0.108670] SCSI subsystem initialized [ 0.112515] usbcore: registered new interface driver usbfs [ 0.117758] usbcore: registered new interface driver hub [ 0.123167] usbcore: registered new device driver usb [ 0.128905] clocksource: Switched to clocksource riscv_clocksource [ 0.141239] NET: Registered protocol family 2 [ 0.145506] tcp_listen_portaddr_hash hash table entries: 4096 (order: 4, 65536 bytes, linear) [ 0.153754] TCP established hash table entries: 65536 (order: 7, 524288 bytes, linear) [ 0.163466] TCP bind hash table entries: 65536 (order: 8, 1048576 bytes, linear) [ 0.173468] TCP: Hash tables configured (established 65536 bind 65536) [ 0.179739] UDP hash table entries: 4096 (order: 5, 131072 bytes, linear) [ 0.186627] UDP-Lite hash table entries: 4096 (order: 5, 131072 bytes, linear) [ 0.194117] NET: Registered protocol family 1 [ 0.198417] RPC: Registered named UNIX socket transport module. [ 0.203887] RPC: Registered udp transport module. [ 0.208664] RPC: Registered tcp transport module. [ 0.213429] RPC: Registered tcp NFSv4.1 backchannel transport module. [ 0.219944] PCI: CLS 0 bytes, default 64 [ 0.224170] Unpacking initramfs... [ 0.262347] Freeing initrd memory: 2336K [ 0.266531] workingset: timestamp_bits=62 max_order=21 bucket_order=0 [ 0.280406] NFS: Registering the id_resolver key type [ 0.284798] Key type id_resolver registered [ 0.289048] Key type id_legacy registered [ 0.293114] nfs4filelayout_init: NFSv4 File Layout Driver Registering... [ 0.300262] NET: Registered protocol family 38 [ 0.304432] Block layer SCSI generic (bsg) driver version 0.4 loaded (major 254) [ 0.311862] io scheduler mq-deadline registered [ 0.316461] io scheduler kyber registered [ 0.356421] Serial: 8250/16550 driver, 4 ports, IRQ sharing disabled [ 0.363004] 10010000.serial: ttySIF0 at MMIO 0x10010000 (irq = 4, base_baud = 0) is a SiFive UART v0 [ 0.371468] printk: console [ttySIF0] enabled [ 0.371468] printk: console [ttySIF0] enabled [ 0.380223] printk: bootconsole [sbi0] disabled [ 0.380223] printk: bootconsole [sbi0] disabled [ 0.389589] 10011000.serial: ttySIF1 at MMIO 0x10011000 (irq = 1, base_baud = 0) is a SiFive UART v0 [ 0.398680] [drm] radeon kernel modesetting enabled. [ 0.412395] loop: module loaded [ 0.415214] sifive_spi 10040000.spi: mapped; irq=3, cs=1 [ 0.420628] sifive_spi 10050000.spi: mapped; irq=5, cs=1 [ 0.425897] libphy: Fixed MDIO Bus: probed [ 0.429964] macb 10090000.ethernet: Registered clk switch 'sifive-gemgxl-mgmt' [ 0.436743] macb: GEM doesn't support hardware ptp. [ 0.441621] libphy: MACB_mii_bus: probed [ 0.601316] Microsemi VSC8541 SyncE 10090000.ethernet-ffffffff:00: attached PHY driver [Microsemi VSC8541 SyncE] (mii_bus:phy_addr=10090000.ethernet-ffffffff:00, irq=POLL) [ 0.615857] macb 10090000.ethernet eth0: Cadence GEM rev 0x10070109 at 0x10090000 irq 6 (70:b3:d5:92:f2:f3) [ 0.625634] e1000e: Intel(R) PRO/1000 Network Driver - 3.2.6-k [ 0.631381] e1000e: Copyright(c) 1999 - 2015 Intel Corporation. [ 0.637382] ehci_hcd: USB 2.0 'Enhanced' Host Controller (EHCI) Driver [ 0.643799] ehci-pci: EHCI PCI platform driver [ 0.648261] ehci-platform: EHCI generic platform driver [ 0.653497] ohci_hcd: USB 1.1 'Open' Host Controller (OHCI) Driver [ 0.659599] ohci-pci: OHCI PCI platform driver [ 0.664055] ohci-platform: OHCI generic platform driver [ 0.669448] usbcore: registered new interface driver uas [ 0.674575] usbcore: registered new interface driver usb-storage [ 0.680642] mousedev: PS/2 mouse device common for all mice [ 0.709493] mmc_spi spi1.0: SD/MMC host mmc0, no DMA, no WP, no poweroff, cd polling [ 0.716615] usbcore: registered new interface driver usbhid [ 0.722023] usbhid: USB HID core driver [ 0.726738] NET: Registered protocol family 10 [ 0.731359] Segment Routing with IPv6 [ 0.734332] sit: IPv6, IPv4 and MPLS over IPv4 tunneling driver [ 0.740687] NET: Registered protocol family 17 [ 0.744660] Key type dns_resolver registered [ 0.806775] mmc0: host does not support reading read-only switch, assuming write-enable [ 0.814020] mmc0: new SDHC card on SPI [ 0.820137] mmcblk0: mmc0:0000 SU08G 7.40 GiB [ 0.850220] mmcblk0: p1 p2 [ 3.821524] macb 10090000.ethernet eth0: link up (1000/Full) [ 3.828938] IPv6: ADDRCONF(NETDEV_CHANGE): eth0: link becomes ready [ 3.848919] Sending DHCP requests .., OK [ 6.252076] IP-Config: Got DHCP answer from 10.206.4.1, my address is 10.206.7.133 [ 6.259624] IP-Config: Complete: [ 6.262831] device=eth0, hwaddr=70:b3:d5:92:f2:f3, ipaddr=10.206.7.133, mask=255.255.252.0, gw=10.206.4.1 [ 6.272809] host=dhcp-10-206-7-133, domain=sdcorp.global.sandisk.com, nis-domain=(none) [ 6.281228] bootserver=10.206.126.11, rootserver=10.206.126.11, rootpath= [ 6.281232] nameserver0=10.86.1.1, nameserver1=10.86.2.1 [ 6.294179] ntpserver0=10.86.1.1, ntpserver1=10.86.2.1 [ 6.301026] Freeing unused kernel memory: 212K [ 6.304683] This architecture does not have kernel memory protection. [ 6.311121] Run /init as init process _ _ | ||_| | | _ ____ _ _ _ _ | || | _ \| | | |\ \/ / | || | | | | |_| |/ \ |_||_|_| |_|\____|\_/\_/ Busybox Rootfs Please press Enter to activate this console. / #
{ "pile_set_name": "Github" }
'use strict'; const os = require('os'); const _ = require('lodash'); const isDocker = require('is-docker'); const { machineIdSync } = require('node-machine-id'); const fetch = require('node-fetch'); const ciEnv = require('ci-info'); const ee = require('../../utils/ee'); const defaultQueryOpts = { timeout: 1000, headers: { 'Content-Type': 'application/json' }, }; const ANALYTICS_URI = 'https://analytics.strapi.io'; /** * Create a send function for event with all the necessary metadatas * @param {Object} strapi strapi app * @returns {Function} (event, payload) -> Promise{boolean} */ module.exports = strapi => { const uuid = strapi.config.uuid; const deviceId = machineIdSync(); const isEE = strapi.EE === true && ee.isEE === true; const anonymous_metadata = { environment: strapi.config.environment, os: os.type(), osPlatform: os.platform(), osRelease: os.release(), nodeVersion: process.version, docker: process.env.DOCKER || isDocker(), isCI: ciEnv.isCI, version: strapi.config.info.strapi, strapiVersion: strapi.config.info.strapi, projectType: isEE ? 'Enterprise' : 'Community', }; return async (event, payload = {}, opts = {}) => { const reqParams = { method: 'POST', body: JSON.stringify({ event, uuid, deviceId, properties: { ...payload, ...anonymous_metadata, }, }), ..._.merge({}, defaultQueryOpts, opts), }; try { const res = await fetch(`${ANALYTICS_URI}/track`, reqParams); return res.ok; } catch (err) { return false; } }; };
{ "pile_set_name": "Github" }
// Copyright 2017 The Go 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 cryptobyte contains types that help with parsing and constructing // length-prefixed, binary messages, including ASN.1 DER. (The asn1 subpackage // contains useful ASN.1 constants.) // // The String type is for parsing. It wraps a []byte slice and provides helper // functions for consuming structures, value by value. // // The Builder type is for constructing messages. It providers helper functions // for appending values and also for appending length-prefixed submessages – // without having to worry about calculating the length prefix ahead of time. // // See the documentation and examples for the Builder and String types to get // started. package cryptobyte // import "golang.org/x/crypto/cryptobyte" // String represents a string of bytes. It provides methods for parsing // fixed-length and length-prefixed values from it. type String []byte // read advances a String by n bytes and returns them. If less than n bytes // remain, it returns nil. func (s *String) read(n int) []byte { if len(*s) < n || n < 0 { return nil } v := (*s)[:n] *s = (*s)[n:] return v } // Skip advances the String by n byte and reports whether it was successful. func (s *String) Skip(n int) bool { return s.read(n) != nil } // ReadUint8 decodes an 8-bit value into out and advances over it. // It reports whether the read was successful. func (s *String) ReadUint8(out *uint8) bool { v := s.read(1) if v == nil { return false } *out = uint8(v[0]) return true } // ReadUint16 decodes a big-endian, 16-bit value into out and advances over it. // It reports whether the read was successful. func (s *String) ReadUint16(out *uint16) bool { v := s.read(2) if v == nil { return false } *out = uint16(v[0])<<8 | uint16(v[1]) return true } // ReadUint24 decodes a big-endian, 24-bit value into out and advances over it. // It reports whether the read was successful. func (s *String) ReadUint24(out *uint32) bool { v := s.read(3) if v == nil { return false } *out = uint32(v[0])<<16 | uint32(v[1])<<8 | uint32(v[2]) return true } // ReadUint32 decodes a big-endian, 32-bit value into out and advances over it. // It reports whether the read was successful. func (s *String) ReadUint32(out *uint32) bool { v := s.read(4) if v == nil { return false } *out = uint32(v[0])<<24 | uint32(v[1])<<16 | uint32(v[2])<<8 | uint32(v[3]) return true } func (s *String) readUnsigned(out *uint32, length int) bool { v := s.read(length) if v == nil { return false } var result uint32 for i := 0; i < length; i++ { result <<= 8 result |= uint32(v[i]) } *out = result return true } func (s *String) readLengthPrefixed(lenLen int, outChild *String) bool { lenBytes := s.read(lenLen) if lenBytes == nil { return false } var length uint32 for _, b := range lenBytes { length = length << 8 length = length | uint32(b) } v := s.read(int(length)) if v == nil { return false } *outChild = v return true } // ReadUint8LengthPrefixed reads the content of an 8-bit length-prefixed value // into out and advances over it. It reports whether the read was successful. func (s *String) ReadUint8LengthPrefixed(out *String) bool { return s.readLengthPrefixed(1, out) } // ReadUint16LengthPrefixed reads the content of a big-endian, 16-bit // length-prefixed value into out and advances over it. It reports whether the // read was successful. func (s *String) ReadUint16LengthPrefixed(out *String) bool { return s.readLengthPrefixed(2, out) } // ReadUint24LengthPrefixed reads the content of a big-endian, 24-bit // length-prefixed value into out and advances over it. It reports whether // the read was successful. func (s *String) ReadUint24LengthPrefixed(out *String) bool { return s.readLengthPrefixed(3, out) } // ReadBytes reads n bytes into out and advances over them. It reports // whether the read was successful. func (s *String) ReadBytes(out *[]byte, n int) bool { v := s.read(n) if v == nil { return false } *out = v return true } // CopyBytes copies len(out) bytes into out and advances over them. It reports // whether the copy operation was successful func (s *String) CopyBytes(out []byte) bool { n := len(out) v := s.read(n) if v == nil { return false } return copy(out, v) == n } // Empty reports whether the string does not contain any bytes. func (s String) Empty() bool { return len(s) == 0 }
{ "pile_set_name": "Github" }
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build linux // +build mips mipsle package unix import ( "syscall" "unsafe" ) func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) //sys Dup2(oldfd int, newfd int) (err error) //sysnb EpollCreate(size int) (fd int, err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64 //sysnb Getegid() (egid int) //sysnb Geteuid() (euid int) //sysnb Getgid() (gid int) //sysnb Getuid() (uid int) //sys Lchown(path string, uid int, gid int) (err error) //sys Listen(s int, n int) (err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64 //sys Setfsgid(gid int) (err error) //sys Setfsuid(uid int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sys Shutdown(fd int, how int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64 //sys Ustat(dev int, ubuf *Ustat_t) (err error) //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) //sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) //sysnb setgroups(n int, list *_Gid_t) (err error) //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) //sysnb socket(domain int, typ int, proto int) (fd int, err error) //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) //sysnb InotifyInit() (fd int, err error) //sys Ioperm(from int, num int, on int) (err error) //sys Iopl(level int) (err error) //sys futimesat(dirfd int, path string, times *[2]Timeval) (err error) //sysnb Gettimeofday(tv *Timeval) (err error) //sysnb Time(t *Time_t) (tt Time_t, err error) //sys Utime(path string, buf *Utimbuf) (err error) //sys utimes(path string, times *[2]Timeval) (err error) //sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 //sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 //sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 //sys Pause() (err error) func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) if e != 0 { err = errnoErr(e) } return } func Statfs(path string, buf *Statfs_t) (err error) { p, err := BytePtrFromString(path) if err != nil { return err } _, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(p)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) if e != 0 { err = errnoErr(e) } return } func Seek(fd int, offset int64, whence int) (off int64, err error) { _, _, e := Syscall6(SYS__LLSEEK, uintptr(fd), uintptr(offset>>32), uintptr(offset), uintptr(unsafe.Pointer(&off)), uintptr(whence), 0) if e != 0 { err = errnoErr(e) } return } func setTimespec(sec, nsec int64) Timespec { return Timespec{Sec: int32(sec), Nsec: int32(nsec)} } func setTimeval(sec, usec int64) Timeval { return Timeval{Sec: int32(sec), Usec: int32(usec)} } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, flags) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sysnb pipe() (p1 int, p2 int, err error) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } p[0], p[1], err = pipe() return } //sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { page := uintptr(offset / 4096) if offset != int64(page)*4096 { return 0, EINVAL } return mmap2(addr, length, prot, flags, fd, page) } const rlimInf32 = ^uint32(0) const rlimInf64 = ^uint64(0) type rlimit32 struct { Cur uint32 Max uint32 } //sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_GETRLIMIT func Getrlimit(resource int, rlim *Rlimit) (err error) { err = prlimit(0, resource, nil, rlim) if err != ENOSYS { return err } rl := rlimit32{} err = getrlimit(resource, &rl) if err != nil { return } if rl.Cur == rlimInf32 { rlim.Cur = rlimInf64 } else { rlim.Cur = uint64(rl.Cur) } if rl.Max == rlimInf32 { rlim.Max = rlimInf64 } else { rlim.Max = uint64(rl.Max) } return } //sysnb setrlimit(resource int, rlim *rlimit32) (err error) = SYS_SETRLIMIT func Setrlimit(resource int, rlim *Rlimit) (err error) { err = prlimit(0, resource, rlim, nil) if err != ENOSYS { return err } rl := rlimit32{} if rlim.Cur == rlimInf64 { rl.Cur = rlimInf32 } else if rlim.Cur < uint64(rlimInf32) { rl.Cur = uint32(rlim.Cur) } else { return EINVAL } if rlim.Max == rlimInf64 { rl.Max = rlimInf32 } else if rlim.Max < uint64(rlimInf32) { rl.Max = uint32(rlim.Max) } else { return EINVAL } return setrlimit(resource, &rl) } func (r *PtraceRegs) PC() uint64 { return r.Epc } func (r *PtraceRegs) SetPC(pc uint64) { r.Epc = pc } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } //sys poll(fds *PollFd, nfds int, timeout int) (n int, err error) func Poll(fds []PollFd, timeout int) (n int, err error) { if len(fds) == 0 { return poll(nil, 0, timeout) } return poll(&fds[0], len(fds), timeout) }
{ "pile_set_name": "Github" }
create table t1 as select cast(key as int) key, value from src where key <= 10; select * from t1 sort by key; create table t2 as select cast(2*key as int) key, value from t1; select * from t2 sort by key; create table t3 as select * from (select * from t1 union all select * from t2) b; select * from t3 sort by key, value; create table t4 (key int, value string); select * from t4; explain select * from t1 a left semi join t2 b on a.key=b.key sort by a.key, a.value; select * from t1 a left semi join t2 b on a.key=b.key sort by a.key, a.value; explain select * from t2 a left semi join t1 b on b.key=a.key sort by a.key, a.value; select * from t2 a left semi join t1 b on b.key=a.key sort by a.key, a.value; explain select * from t1 a left semi join t4 b on b.key=a.key sort by a.key, a.value; select * from t1 a left semi join t4 b on b.key=a.key sort by a.key, a.value; explain select a.value from t1 a left semi join t3 b on (b.key = a.key and b.key < '15') sort by a.value; select a.value from t1 a left semi join t3 b on (b.key = a.key and b.key < '15') sort by a.value; explain select * from t1 a left semi join t2 b on a.key = b.key and b.value < "val_10" sort by a.key, a.value; select * from t1 a left semi join t2 b on a.key = b.key and b.value < "val_10" sort by a.key, a.value; explain select a.value from t1 a left semi join (select key from t3 where key > 5) b on a.key = b.key sort by a.value; select a.value from t1 a left semi join (select key from t3 where key > 5) b on a.key = b.key sort by a.value; explain select a.value from t1 a left semi join (select key , value from t2 where key > 5) b on a.key = b.key and b.value <= 'val_20' sort by a.value ; select a.value from t1 a left semi join (select key , value from t2 where key > 5) b on a.key = b.key and b.value <= 'val_20' sort by a.value ; explain select * from t2 a left semi join (select key , value from t1 where key > 2) b on a.key = b.key sort by a.key, a.value; select * from t2 a left semi join (select key , value from t1 where key > 2) b on a.key = b.key sort by a.key, a.value; explain select /*+ mapjoin(b) */ a.key from t3 a left semi join t1 b on a.key = b.key sort by a.key; select /*+ mapjoin(b) */ a.key from t3 a left semi join t1 b on a.key = b.key sort by a.key; explain select * from t1 a left semi join t2 b on a.key = 2*b.key sort by a.key, a.value; select * from t1 a left semi join t2 b on a.key = 2*b.key sort by a.key, a.value; explain select * from t1 a join t2 b on a.key = b.key left semi join t3 c on b.key = c.key sort by a.key, a.value; select * from t1 a join t2 b on a.key = b.key left semi join t3 c on b.key = c.key sort by a.key, a.value; explain select * from t3 a left semi join t1 b on a.key = b.key and a.value=b.value sort by a.key, a.value; select * from t3 a left semi join t1 b on a.key = b.key and a.value=b.value sort by a.key, a.value; explain select /*+ mapjoin(b, c) */ a.key from t3 a left semi join t1 b on a.key = b.key left semi join t2 c on a.key = c.key sort by a.key; select /*+ mapjoin(b, c) */ a.key from t3 a left semi join t1 b on a.key = b.key left semi join t2 c on a.key = c.key sort by a.key; explain select a.key from t3 a left outer join t1 b on a.key = b.key left semi join t2 c on b.key = c.key sort by a.key; select a.key from t3 a left outer join t1 b on a.key = b.key left semi join t2 c on b.key = c.key sort by a.key; explain select a.key from t1 a right outer join t3 b on a.key = b.key left semi join t2 c on b.key = c.key sort by a.key; select a.key from t1 a right outer join t3 b on a.key = b.key left semi join t2 c on b.key = c.key sort by a.key; explain select a.key from t1 a full outer join t3 b on a.key = b.key left semi join t2 c on b.key = c.key sort by a.key; select a.key from t1 a full outer join t3 b on a.key = b.key left semi join t2 c on b.key = c.key sort by a.key; explain select a.key from t3 a left semi join t2 b on a.key = b.key left outer join t1 c on a.key = c.key sort by a.key; select a.key from t3 a left semi join t2 b on a.key = b.key left outer join t1 c on a.key = c.key sort by a.key; explain select a.key from t3 a left semi join t2 b on a.key = b.key right outer join t1 c on a.key = c.key sort by a.key; select a.key from t3 a left semi join t2 b on a.key = b.key right outer join t1 c on a.key = c.key sort by a.key; explain select a.key from t3 a left semi join t1 b on a.key = b.key full outer join t2 c on a.key = c.key sort by a.key; select a.key from t3 a left semi join t1 b on a.key = b.key full outer join t2 c on a.key = c.key sort by a.key; explain select a.key from t3 a left semi join t2 b on a.key = b.key left outer join t1 c on a.value = c.value sort by a.key; select a.key from t3 a left semi join t2 b on a.key = b.key left outer join t1 c on a.value = c.value sort by a.key; explain select a.key from t3 a left semi join t2 b on a.value = b.value where a.key > 100; select a.key from t3 a left semi join t2 b on a.value = b.value where a.key > 100;
{ "pile_set_name": "Github" }
--- !tapi-tbd-v2 archs: [ armv7, armv7s, arm64, arm64e ] platform: ios flags: [ flat_namespace, not_app_extension_safe ] install-name: /System/Library/PrivateFrameworks/OSAnalytics.framework/OSAnalytics current-version: 1 compatibility-version: 1 objc-constraint: retain_release exports: - archs: [ armv7, armv7s, arm64, arm64e ] symbols: [ _OSAnalyticsVersionNumber, _OSAnalyticsVersionString, _OTALoggingBaseDirectory, _XPCClientHasEntitlement, _kDomainKey, _kKeyKey, _kPreferenceDomainDataAnalysis, _kRemovalKey, _kSamplingKey, _kUserKey, _kValueKey, _killDescription, _legacyCertArr, _osa_scanDir, _processName ] objc-classes: [ _OSAAppleErrorReport, _OSAEphemeralLog, _OSAHttpSubmitter, _OSAJetsamReport, _OSALog, _OSAProxyConfiguration, _OSAStreamDeflater, _OSASubmitter, _OSASystemConfiguration, _OSATasking, _OSAXPCServices, _PCCEndpoint, _PCCGroupJob, _PCCIDSEndpoint, _PCCJob, _PCCProxiedDevice, _PCCProxyingDevice, _PCCRequest ] objc-ivars: [ _OSAAppleErrorReport._capture_time, _OSAAppleErrorReport._incidentID, _OSAAppleErrorReport._logType, _OSAAppleErrorReport._logWritingOptions, _OSAAppleErrorReport._logfile, _OSAAppleErrorReport._notes, _OSAEphemeralLog._content, _OSAHttpSubmitter._connection, _OSAHttpSubmitter._last_thoughput_check, _OSAHttpSubmitter._payload, _OSAHttpSubmitter._response, _OSAHttpSubmitter._submissionSem, _OSAHttpSubmitter._submissionURL, _OSAHttpSubmitter._submitOkFlag, _OSAHttpSubmitter._thoughput_warnings, _OSAJetsamReport._event_code, _OSAJetsamReport._event_reason, _OSAJetsamReport._isSuspendedOnlyJetsam, _OSAJetsamReport._killedActiveApps, _OSAJetsamReport._killed_or_suspended_count, _OSAJetsamReport._largestActiveApp, _OSAJetsamReport._largestProcess, _OSAJetsamReport._snapshot, _OSAJetsamReport._wiredBytes, _OSALog._bugType, _OSALog._deleteOnRetire, _OSALog._filepath, _OSALog._metaData, _OSALog._preserveFiles, _OSALog._stream, _OSAProxyConfiguration._automatedContextURL, _OSAProxyConfiguration._automatedDeviceGroup, _OSAProxyConfiguration._awdReporterKey, _OSAProxyConfiguration._buildVersion, _OSAProxyConfiguration._crashReporterKey, _OSAProxyConfiguration._currentTaskingIDByRouting, _OSAProxyConfiguration._experimentGroup, _OSAProxyConfiguration._identifier, _OSAProxyConfiguration._internalKey, _OSAProxyConfiguration._logPath, _OSAProxyConfiguration._modelCode, _OSAProxyConfiguration._osTrain, _OSAProxyConfiguration._productBuildString, _OSAProxyConfiguration._productName, _OSAProxyConfiguration._productNameVersionBuildString, _OSAProxyConfiguration._productReleaseString, _OSAProxyConfiguration._productVersion, _OSAProxyConfiguration._releaseType, _OSAProxyConfiguration._seedGroup, _OSAProxyConfiguration._serialNumber, _OSAProxyConfiguration._systemId, _OSAProxyConfiguration._targetAudience, _OSAProxyConfiguration._uiCountryCode, _OSAStreamDeflater._capViolation, _OSAStreamDeflater._in, _OSAStreamDeflater._out, _OSAStreamDeflater._strm, _OSASubmitter._allowUnsignedBlobs, _OSASubmitter._connectionType, _OSASubmitter._internalWhitelist, _OSASubmitter._jobCount, _OSASubmitter._jobs, _OSASubmitter._responseCode, _OSASubmitter._responseData, _OSASubmitter._responseHeaders, _OSASubmitter._results, _OSASubmitter._submissionCap, _OSASubmitter._summary, _OSASubmitter._taskings, _OSASubmitter._writeArchives, _OSASystemConfiguration._appleInternal, _OSASystemConfiguration._logBlacklist, _OSASystemConfiguration._logConfig, _OSASystemConfiguration._multiUserMode, _OSASystemConfiguration._pairedWatchOS, _OSAXPCServices._listenerConnection, _OSAXPCServices._txn, _OSAXPCServices._txnTimer, _PCCEndpoint._delegate, _PCCEndpoint._deviceIds, _PCCEndpoint._fileTimeout, _PCCGroupJob._consecutive_error_count, _PCCGroupJob._content, _PCCGroupJob._error_count, _PCCGroupJob._log_sets, _PCCGroupJob._rejected_count, _PCCGroupJob._success_count, _PCCGroupJob._total_count, _PCCIDSEndpoint._homeDeviceService, _PCCIDSEndpoint._pairedWatchService, _PCCIDSEndpoint._serviceByDevice, _PCCJob._errObj, _PCCJob._jid, _PCCJob._lastTouch, _PCCJob._metadata, _PCCJob._options, _PCCJob._package, _PCCJob._target, _PCCProxiedDevice._endpoint, _PCCProxiedDevice._expiryTimer, _PCCProxiedDevice._groupXferJob, _PCCProxiedDevice._jobByTracker, _PCCProxiedDevice._jobTimeout, _PCCProxiedDevice._job_queue, _PCCProxiedDevice._txn, _PCCProxiedDevice.expire_count, _PCCProxiedDevice.file_count, _PCCProxiedDevice.job_count, _PCCProxiedDevice.msg_count, _PCCProxiedDevice.up_count, _PCCProxyingDevice._endpoint, _PCCProxyingDevice._expiryTimer, _PCCProxyingDevice._lastTouch, _PCCProxyingDevice._reqById, _PCCProxyingDevice._reqByTracker, _PCCProxyingDevice._requestTimeout, _PCCProxyingDevice._request_queue, _PCCProxyingDevice._sync_proxy_queue, _PCCProxyingDevice._txn, _PCCProxyingDevice.expire_count, _PCCProxyingDevice.file_count, _PCCProxyingDevice.msg_count, _PCCProxyingDevice.request_count, _PCCProxyingDevice.up_count, _PCCRequest._callback, _PCCRequest._jid, _PCCRequest._options, _PCCRequest._type ] ...
{ "pile_set_name": "Github" }
<?php include('loklak.php'); $baseURL = 'http://localhost:9000'; $l = new Loklak($baseURL); $values = $l->settings(); $settingsResponse = json_decode($values); $settingsResponse = $settingsResponse->body; $settingsResponse = json_decode($settingsResponse, true); var_dump($settingsResponse); ?>
{ "pile_set_name": "Github" }
// run // Copyright 2009 The Go 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 main func panic1(s string) bool { panic(s); } func main() { x := false && panic1("first") && panic1("second"); x = x == true && panic1("first") && panic1("second"); } /* ; 6.out second panic PC=0x250f98 main·panic1+0x36 /Users/rsc/goX/test/bugs/bug142.go:6 main·panic1(0xae30, 0x0) main·main+0x23 /Users/rsc/goX/test/bugs/bug142.go:10 main·main() mainstart+0xf /Users/rsc/goX/src/runtime/amd64/asm.s:53 mainstart() sys·Goexit /Users/rsc/goX/src/runtime/proc.c:124 sys·Goexit() ; */
{ "pile_set_name": "Github" }
// Copyright 2018 The Flutter Architecture Sample Authors. All rights reserved. // Use of this source code is governed by the MIT license that can be found // in the LICENSE file. import 'package:fire_redux_sample/models/models.dart'; import 'package:fire_redux_sample/reducers/loading_reducer.dart'; import 'package:fire_redux_sample/reducers/tabs_reducer.dart'; import 'package:fire_redux_sample/reducers/todos_reducer.dart'; import 'package:fire_redux_sample/reducers/visibility_reducer.dart'; // We create the State reducer by combining many smaller reducers into one! AppState appReducer(AppState state, action) { return AppState( isLoading: loadingReducer(state.isLoading, action), todos: todosReducer(state.todos, action), activeFilter: visibilityReducer(state.activeFilter, action), activeTab: tabsReducer(state.activeTab, action), ); }
{ "pile_set_name": "Github" }
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 This module defines interface types and binders -} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} -- FlexibleInstances for Binary (DefMethSpec IfaceType) {-# LANGUAGE BangPatterns #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE LambdaCase #-} #if !MIN_VERSION_GLASGOW_HASKELL(8,10,0,0) {-# OPTIONS_GHC -Wno-overlapping-patterns -Wno-incomplete-patterns #-} -- N.B. This can be dropped once GHC 8.8 can be dropped as a -- bootstrap compiler. #endif module GHC.Iface.Type ( IfExtName, IfLclName, IfaceType(..), IfacePredType, IfaceKind, IfaceCoercion(..), IfaceMCoercion(..), IfaceUnivCoProv(..), IfaceMult, IfaceTyCon(..), IfaceTyConInfo(..), IfaceTyConSort(..), IfaceTyLit(..), IfaceAppArgs(..), IfaceContext, IfaceBndr(..), IfaceOneShot(..), IfaceLamBndr, IfaceTvBndr, IfaceIdBndr, IfaceTyConBinder, IfaceForAllSpecBndr, IfaceForAllBndr, ArgFlag(..), AnonArgFlag(..), ShowForAllFlag(..), mkIfaceForAllTvBndr, mkIfaceTyConKind, ifaceForAllSpecToBndrs, ifaceForAllSpecToBndr, ifForAllBndrVar, ifForAllBndrName, ifaceBndrName, ifTyConBinderVar, ifTyConBinderName, -- Equality testing isIfaceLiftedTypeKind, -- Conversion from IfaceAppArgs to IfaceTypes/ArgFlags appArgsIfaceTypes, appArgsIfaceTypesArgFlags, -- Printing SuppressBndrSig(..), UseBndrParens(..), PrintExplicitKinds(..), pprIfaceType, pprParendIfaceType, pprPrecIfaceType, pprIfaceContext, pprIfaceContextArr, pprIfaceIdBndr, pprIfaceLamBndr, pprIfaceTvBndr, pprIfaceTyConBinders, pprIfaceBndrs, pprIfaceAppArgs, pprParendIfaceAppArgs, pprIfaceForAllPart, pprIfaceForAllPartMust, pprIfaceForAll, pprIfaceSigmaType, pprIfaceTyLit, pprIfaceCoercion, pprParendIfaceCoercion, splitIfaceSigmaTy, pprIfaceTypeApp, pprUserIfaceForAll, pprIfaceCoTcApp, pprTyTcApp, pprIfacePrefixApp, ppr_fun_arrow, isIfaceTauType, suppressIfaceInvisibles, stripIfaceInvisVars, stripInvisArgs, mkIfaceTySubst, substIfaceTyVar, substIfaceAppArgs, inDomIfaceTySubst, many_ty ) where #include "HsVersions.h" import GHC.Prelude import {-# SOURCE #-} GHC.Builtin.Types ( coercibleTyCon, heqTyCon , liftedRepDataConTyCon, tupleTyConName , manyDataConTyCon, oneDataConTyCon ) import {-# SOURCE #-} GHC.Core.Type ( isRuntimeRepTy, isMultiplicityTy ) import GHC.Core.TyCon hiding ( pprPromotionQuote ) import GHC.Core.Coercion.Axiom import GHC.Types.Var import GHC.Builtin.Names import GHC.Types.Name import GHC.Types.Basic import GHC.Utils.Binary import GHC.Utils.Outputable import GHC.Data.FastString import GHC.Utils.Misc import GHC.Utils.Panic import Data.Maybe( isJust ) import qualified Data.Semigroup as Semi import Control.DeepSeq {- ************************************************************************ * * Local (nested) binders * * ************************************************************************ -} type IfLclName = FastString -- A local name in iface syntax type IfExtName = Name -- An External or WiredIn Name can appear in Iface syntax -- (However Internal or System Names never should) data IfaceBndr -- Local (non-top-level) binders = IfaceIdBndr {-# UNPACK #-} !IfaceIdBndr | IfaceTvBndr {-# UNPACK #-} !IfaceTvBndr type IfaceIdBndr = (IfaceType, IfLclName, IfaceType) type IfaceTvBndr = (IfLclName, IfaceKind) ifaceTvBndrName :: IfaceTvBndr -> IfLclName ifaceTvBndrName (n,_) = n ifaceIdBndrName :: IfaceIdBndr -> IfLclName ifaceIdBndrName (_,n,_) = n ifaceBndrName :: IfaceBndr -> IfLclName ifaceBndrName (IfaceTvBndr bndr) = ifaceTvBndrName bndr ifaceBndrName (IfaceIdBndr bndr) = ifaceIdBndrName bndr ifaceBndrType :: IfaceBndr -> IfaceType ifaceBndrType (IfaceIdBndr (_, _, t)) = t ifaceBndrType (IfaceTvBndr (_, t)) = t type IfaceLamBndr = (IfaceBndr, IfaceOneShot) data IfaceOneShot -- See Note [Preserve OneShotInfo] in "GHC.Core.Tidy" = IfaceNoOneShot -- and Note [The oneShot function] in "GHC.Types.Id.Make" | IfaceOneShot instance Outputable IfaceOneShot where ppr IfaceNoOneShot = text "NoOneShotInfo" ppr IfaceOneShot = text "OneShot" {- %************************************************************************ %* * IfaceType %* * %************************************************************************ -} ------------------------------- type IfaceKind = IfaceType -- | A kind of universal type, used for types and kinds. -- -- Any time a 'Type' is pretty-printed, it is first converted to an 'IfaceType' -- before being printed. See Note [Pretty printing via Iface syntax] in "GHC.Core.Ppr.TyThing" data IfaceType = IfaceFreeTyVar TyVar -- See Note [Free tyvars in IfaceType] | IfaceTyVar IfLclName -- Type/coercion variable only, not tycon | IfaceLitTy IfaceTyLit | IfaceAppTy IfaceType IfaceAppArgs -- See Note [Suppressing invisible arguments] for -- an explanation of why the second field isn't -- IfaceType, analogous to AppTy. | IfaceFunTy AnonArgFlag IfaceMult IfaceType IfaceType | IfaceForAllTy IfaceForAllBndr IfaceType | IfaceTyConApp IfaceTyCon IfaceAppArgs -- Not necessarily saturated -- Includes newtypes, synonyms, tuples | IfaceCastTy IfaceType IfaceCoercion | IfaceCoercionTy IfaceCoercion | IfaceTupleTy -- Saturated tuples (unsaturated ones use IfaceTyConApp) TupleSort -- What sort of tuple? PromotionFlag -- A bit like IfaceTyCon IfaceAppArgs -- arity = length args -- For promoted data cons, the kind args are omitted -- Why have this? Only for efficiency: IfaceTupleTy can omit the -- type arguments, as they can be recreated when deserializing. -- In an experiment, removing IfaceTupleTy resulted in a 0.75% regression -- in interface file size (in GHC's boot libraries). -- See !3987. type IfaceMult = IfaceType type IfacePredType = IfaceType type IfaceContext = [IfacePredType] data IfaceTyLit = IfaceNumTyLit Integer | IfaceStrTyLit FastString deriving (Eq) type IfaceTyConBinder = VarBndr IfaceBndr TyConBndrVis type IfaceForAllBndr = VarBndr IfaceBndr ArgFlag type IfaceForAllSpecBndr = VarBndr IfaceBndr Specificity -- | Make an 'IfaceForAllBndr' from an 'IfaceTvBndr'. mkIfaceForAllTvBndr :: ArgFlag -> IfaceTvBndr -> IfaceForAllBndr mkIfaceForAllTvBndr vis var = Bndr (IfaceTvBndr var) vis -- | Build the 'tyConKind' from the binders and the result kind. -- Keep in sync with 'mkTyConKind' in "GHC.Core.TyCon". mkIfaceTyConKind :: [IfaceTyConBinder] -> IfaceKind -> IfaceKind mkIfaceTyConKind bndrs res_kind = foldr mk res_kind bndrs where mk :: IfaceTyConBinder -> IfaceKind -> IfaceKind mk (Bndr tv (AnonTCB af)) k = IfaceFunTy af many_ty (ifaceBndrType tv) k mk (Bndr tv (NamedTCB vis)) k = IfaceForAllTy (Bndr tv vis) k ifaceForAllSpecToBndrs :: [IfaceForAllSpecBndr] -> [IfaceForAllBndr] ifaceForAllSpecToBndrs = map ifaceForAllSpecToBndr ifaceForAllSpecToBndr :: IfaceForAllSpecBndr -> IfaceForAllBndr ifaceForAllSpecToBndr (Bndr tv spec) = Bndr tv (Invisible spec) -- | Stores the arguments in a type application as a list. -- See @Note [Suppressing invisible arguments]@. data IfaceAppArgs = IA_Nil | IA_Arg IfaceType -- The type argument ArgFlag -- The argument's visibility. We store this here so -- that we can: -- -- 1. Avoid pretty-printing invisible (i.e., specified -- or inferred) arguments when -- -fprint-explicit-kinds isn't enabled, or -- 2. When -fprint-explicit-kinds *is*, enabled, print -- specified arguments in @(...) and inferred -- arguments in @{...}. IfaceAppArgs -- The rest of the arguments instance Semi.Semigroup IfaceAppArgs where IA_Nil <> xs = xs IA_Arg ty argf rest <> xs = IA_Arg ty argf (rest Semi.<> xs) instance Monoid IfaceAppArgs where mempty = IA_Nil mappend = (Semi.<>) -- Encodes type constructors, kind constructors, -- coercion constructors, the lot. -- We have to tag them in order to pretty print them -- properly. data IfaceTyCon = IfaceTyCon { ifaceTyConName :: IfExtName , ifaceTyConInfo :: IfaceTyConInfo } deriving (Eq) -- | The various types of TyCons which have special, built-in syntax. data IfaceTyConSort = IfaceNormalTyCon -- ^ a regular tycon | IfaceTupleTyCon !Arity !TupleSort -- ^ e.g. @(a, b, c)@ or @(#a, b, c#)@. -- The arity is the tuple width, not the tycon arity -- (which is twice the width in the case of unboxed -- tuples). | IfaceSumTyCon !Arity -- ^ e.g. @(a | b | c)@ | IfaceEqualityTyCon -- ^ A heterogeneous equality TyCon -- (i.e. eqPrimTyCon, eqReprPrimTyCon, heqTyCon) -- that is actually being applied to two types -- of the same kind. This affects pretty-printing -- only: see Note [Equality predicates in IfaceType] deriving (Eq) instance Outputable IfaceTyConSort where ppr IfaceNormalTyCon = text "normal" ppr (IfaceTupleTyCon n sort) = ppr sort <> colon <> ppr n ppr (IfaceSumTyCon n) = text "sum:" <> ppr n ppr IfaceEqualityTyCon = text "equality" {- Note [Free tyvars in IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Nowadays (since Nov 16, 2016) we pretty-print a Type by converting to an IfaceType and pretty printing that. This eliminates a lot of pretty-print duplication, and it matches what we do with pretty- printing TyThings. See Note [Pretty printing via Iface syntax] in GHC.Core.Ppr.TyThing. It works fine for closed types, but when printing debug traces (e.g. when using -ddump-tc-trace) we print a lot of /open/ types. These types are full of TcTyVars, and it's absolutely crucial to print them in their full glory, with their unique, TcTyVarDetails etc. So we simply embed a TyVar in IfaceType with the IfaceFreeTyVar constructor. Note that: * We never expect to serialise an IfaceFreeTyVar into an interface file, nor to deserialise one. IfaceFreeTyVar is used only in the "convert to IfaceType and then pretty-print" pipeline. We do the same for covars, naturally. Note [Equality predicates in IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GHC has several varieties of type equality (see Note [The equality types story] in GHC.Builtin.Types.Prim for details). In an effort to avoid confusing users, we suppress the differences during pretty printing unless certain flags are enabled. Here is how each equality predicate* is printed in homogeneous and heterogeneous contexts, depending on which combination of the -fprint-explicit-kinds and -fprint-equality-relations flags is used: -------------------------------------------------------------------------------------------- | Predicate | Neither flag | -fprint-explicit-kinds | |-------------------------------|----------------------------|-----------------------------| | a ~ b (homogeneous) | a ~ b | (a :: Type) ~ (b :: Type) | | a ~~ b, homogeneously | a ~ b | (a :: Type) ~ (b :: Type) | | a ~~ b, heterogeneously | a ~~ c | (a :: Type) ~~ (c :: k) | | a ~# b, homogeneously | a ~ b | (a :: Type) ~ (b :: Type) | | a ~# b, heterogeneously | a ~~ c | (a :: Type) ~~ (c :: k) | | Coercible a b (homogeneous) | Coercible a b | Coercible @Type a b | | a ~R# b, homogeneously | Coercible a b | Coercible @Type a b | | a ~R# b, heterogeneously | a ~R# b | (a :: Type) ~R# (c :: k) | |-------------------------------|----------------------------|-----------------------------| | Predicate | -fprint-equality-relations | Both flags | |-------------------------------|----------------------------|-----------------------------| | a ~ b (homogeneous) | a ~ b | (a :: Type) ~ (b :: Type) | | a ~~ b, homogeneously | a ~~ b | (a :: Type) ~~ (b :: Type) | | a ~~ b, heterogeneously | a ~~ c | (a :: Type) ~~ (c :: k) | | a ~# b, homogeneously | a ~# b | (a :: Type) ~# (b :: Type) | | a ~# b, heterogeneously | a ~# c | (a :: Type) ~# (c :: k) | | Coercible a b (homogeneous) | Coercible a b | Coercible @Type a b | | a ~R# b, homogeneously | a ~R# b | (a :: Type) ~R# (b :: Type) | | a ~R# b, heterogeneously | a ~R# b | (a :: Type) ~R# (c :: k) | -------------------------------------------------------------------------------------------- (* There is no heterogeneous, representational, lifted equality counterpart to (~~). There could be, but there seems to be no use for it.) This table adheres to the following rules: A. With -fprint-equality-relations, print the true equality relation. B. Without -fprint-equality-relations: i. If the equality is representational and homogeneous, use Coercible. ii. Otherwise, if the equality is representational, use ~R#. iii. If the equality is nominal and homogeneous, use ~. iv. Otherwise, if the equality is nominal, use ~~. C. With -fprint-explicit-kinds, print kinds on both sides of an infix operator, as above; or print the kind with Coercible. D. Without -fprint-explicit-kinds, don't print kinds. A hetero-kinded equality is used homogeneously when it is applied to two identical kinds. Unfortunately, determining this from an IfaceType isn't possible since we can't see through type synonyms. Consequently, we need to record whether this particular application is homogeneous in IfaceTyConSort for the purposes of pretty-printing. See Note [The equality types story] in GHC.Builtin.Types.Prim. -} data IfaceTyConInfo -- Used to guide pretty-printing -- and to disambiguate D from 'D (they share a name) = IfaceTyConInfo { ifaceTyConIsPromoted :: PromotionFlag , ifaceTyConSort :: IfaceTyConSort } deriving (Eq) data IfaceMCoercion = IfaceMRefl | IfaceMCo IfaceCoercion data IfaceCoercion = IfaceReflCo IfaceType | IfaceGReflCo Role IfaceType (IfaceMCoercion) | IfaceFunCo Role IfaceCoercion IfaceCoercion IfaceCoercion | IfaceTyConAppCo Role IfaceTyCon [IfaceCoercion] | IfaceAppCo IfaceCoercion IfaceCoercion | IfaceForAllCo IfaceBndr IfaceCoercion IfaceCoercion | IfaceCoVarCo IfLclName | IfaceAxiomInstCo IfExtName BranchIndex [IfaceCoercion] | IfaceAxiomRuleCo IfLclName [IfaceCoercion] -- There are only a fixed number of CoAxiomRules, so it suffices -- to use an IfaceLclName to distinguish them. -- See Note [Adding built-in type families] in GHC.Builtin.Types.Literals | IfaceUnivCo IfaceUnivCoProv Role IfaceType IfaceType | IfaceSymCo IfaceCoercion | IfaceTransCo IfaceCoercion IfaceCoercion | IfaceNthCo Int IfaceCoercion | IfaceLRCo LeftOrRight IfaceCoercion | IfaceInstCo IfaceCoercion IfaceCoercion | IfaceKindCo IfaceCoercion | IfaceSubCo IfaceCoercion | IfaceFreeCoVar CoVar -- See Note [Free tyvars in IfaceType] | IfaceHoleCo CoVar -- ^ See Note [Holes in IfaceCoercion] data IfaceUnivCoProv = IfacePhantomProv IfaceCoercion | IfaceProofIrrelProv IfaceCoercion | IfacePluginProv String {- Note [Holes in IfaceCoercion] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When typechecking fails the typechecker will produce a HoleCo to stand in place of the unproven assertion. While we generally don't want to let these unproven assertions leak into interface files, we still need to be able to pretty-print them as we use IfaceType's pretty-printer to render Types. For this reason IfaceCoercion has a IfaceHoleCo constructor; however, we fails when asked to serialize to a IfaceHoleCo to ensure that they don't end up in an interface file. %************************************************************************ %* * Functions over IFaceTypes * * ************************************************************************ -} ifaceTyConHasKey :: IfaceTyCon -> Unique -> Bool ifaceTyConHasKey tc key = ifaceTyConName tc `hasKey` key isIfaceLiftedTypeKind :: IfaceKind -> Bool isIfaceLiftedTypeKind (IfaceTyConApp tc IA_Nil) = isLiftedTypeKindTyConName (ifaceTyConName tc) isIfaceLiftedTypeKind (IfaceTyConApp tc (IA_Arg (IfaceTyConApp ptr_rep_lifted IA_Nil) Required IA_Nil)) = tc `ifaceTyConHasKey` tYPETyConKey && ptr_rep_lifted `ifaceTyConHasKey` liftedRepDataConKey isIfaceLiftedTypeKind _ = False splitIfaceSigmaTy :: IfaceType -> ([IfaceForAllBndr], [IfacePredType], IfaceType) -- Mainly for printing purposes -- -- Here we split nested IfaceSigmaTy properly. -- -- @ -- forall t. T t => forall m a b. M m => (a -> m b) -> t a -> m (t b) -- @ -- -- If you called @splitIfaceSigmaTy@ on this type: -- -- @ -- ([t, m, a, b], [T t, M m], (a -> m b) -> t a -> m (t b)) -- @ splitIfaceSigmaTy ty = case (bndrs, theta) of ([], []) -> (bndrs, theta, tau) _ -> let (bndrs', theta', tau') = splitIfaceSigmaTy tau in (bndrs ++ bndrs', theta ++ theta', tau') where (bndrs, rho) = split_foralls ty (theta, tau) = split_rho rho split_foralls (IfaceForAllTy bndr ty) | isInvisibleArgFlag (binderArgFlag bndr) = case split_foralls ty of { (bndrs, rho) -> (bndr:bndrs, rho) } split_foralls rho = ([], rho) split_rho (IfaceFunTy InvisArg _ ty1 ty2) = case split_rho ty2 of { (ps, tau) -> (ty1:ps, tau) } split_rho tau = ([], tau) splitIfaceReqForallTy :: IfaceType -> ([IfaceForAllBndr], IfaceType) splitIfaceReqForallTy (IfaceForAllTy bndr ty) | isVisibleArgFlag (binderArgFlag bndr) = case splitIfaceReqForallTy ty of { (bndrs, rho) -> (bndr:bndrs, rho) } splitIfaceReqForallTy rho = ([], rho) suppressIfaceInvisibles :: PrintExplicitKinds -> [IfaceTyConBinder] -> [a] -> [a] suppressIfaceInvisibles (PrintExplicitKinds True) _tys xs = xs suppressIfaceInvisibles (PrintExplicitKinds False) tys xs = suppress tys xs where suppress _ [] = [] suppress [] a = a suppress (k:ks) (x:xs) | isInvisibleTyConBinder k = suppress ks xs | otherwise = x : suppress ks xs stripIfaceInvisVars :: PrintExplicitKinds -> [IfaceTyConBinder] -> [IfaceTyConBinder] stripIfaceInvisVars (PrintExplicitKinds True) tyvars = tyvars stripIfaceInvisVars (PrintExplicitKinds False) tyvars = filterOut isInvisibleTyConBinder tyvars -- | Extract an 'IfaceBndr' from an 'IfaceForAllBndr'. ifForAllBndrVar :: IfaceForAllBndr -> IfaceBndr ifForAllBndrVar = binderVar -- | Extract the variable name from an 'IfaceForAllBndr'. ifForAllBndrName :: IfaceForAllBndr -> IfLclName ifForAllBndrName fab = ifaceBndrName (ifForAllBndrVar fab) -- | Extract an 'IfaceBndr' from an 'IfaceTyConBinder'. ifTyConBinderVar :: IfaceTyConBinder -> IfaceBndr ifTyConBinderVar = binderVar -- | Extract the variable name from an 'IfaceTyConBinder'. ifTyConBinderName :: IfaceTyConBinder -> IfLclName ifTyConBinderName tcb = ifaceBndrName (ifTyConBinderVar tcb) ifTypeIsVarFree :: IfaceType -> Bool -- Returns True if the type definitely has no variables at all -- Just used to control pretty printing ifTypeIsVarFree ty = go ty where go (IfaceTyVar {}) = False go (IfaceFreeTyVar {}) = False go (IfaceAppTy fun args) = go fun && go_args args go (IfaceFunTy _ w arg res) = go w && go arg && go res go (IfaceForAllTy {}) = False go (IfaceTyConApp _ args) = go_args args go (IfaceTupleTy _ _ args) = go_args args go (IfaceLitTy _) = True go (IfaceCastTy {}) = False -- Safe go (IfaceCoercionTy {}) = False -- Safe go_args IA_Nil = True go_args (IA_Arg arg _ args) = go arg && go_args args {- Note [Substitution on IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Substitutions on IfaceType are done only during pretty-printing to construct the result type of a GADT, and does not deal with binders (eg IfaceForAll), so it doesn't need fancy capture stuff. -} type IfaceTySubst = FastStringEnv IfaceType -- Note [Substitution on IfaceType] mkIfaceTySubst :: [(IfLclName,IfaceType)] -> IfaceTySubst -- See Note [Substitution on IfaceType] mkIfaceTySubst eq_spec = mkFsEnv eq_spec inDomIfaceTySubst :: IfaceTySubst -> IfaceTvBndr -> Bool -- See Note [Substitution on IfaceType] inDomIfaceTySubst subst (fs, _) = isJust (lookupFsEnv subst fs) substIfaceType :: IfaceTySubst -> IfaceType -> IfaceType -- See Note [Substitution on IfaceType] substIfaceType env ty = go ty where go (IfaceFreeTyVar tv) = IfaceFreeTyVar tv go (IfaceTyVar tv) = substIfaceTyVar env tv go (IfaceAppTy t ts) = IfaceAppTy (go t) (substIfaceAppArgs env ts) go (IfaceFunTy af w t1 t2) = IfaceFunTy af (go w) (go t1) (go t2) go ty@(IfaceLitTy {}) = ty go (IfaceTyConApp tc tys) = IfaceTyConApp tc (substIfaceAppArgs env tys) go (IfaceTupleTy s i tys) = IfaceTupleTy s i (substIfaceAppArgs env tys) go (IfaceForAllTy {}) = pprPanic "substIfaceType" (ppr ty) go (IfaceCastTy ty co) = IfaceCastTy (go ty) (go_co co) go (IfaceCoercionTy co) = IfaceCoercionTy (go_co co) go_mco IfaceMRefl = IfaceMRefl go_mco (IfaceMCo co) = IfaceMCo $ go_co co go_co (IfaceReflCo ty) = IfaceReflCo (go ty) go_co (IfaceGReflCo r ty mco) = IfaceGReflCo r (go ty) (go_mco mco) go_co (IfaceFunCo r w c1 c2) = IfaceFunCo r (go_co w) (go_co c1) (go_co c2) go_co (IfaceTyConAppCo r tc cos) = IfaceTyConAppCo r tc (go_cos cos) go_co (IfaceAppCo c1 c2) = IfaceAppCo (go_co c1) (go_co c2) go_co (IfaceForAllCo {}) = pprPanic "substIfaceCoercion" (ppr ty) go_co (IfaceFreeCoVar cv) = IfaceFreeCoVar cv go_co (IfaceCoVarCo cv) = IfaceCoVarCo cv go_co (IfaceHoleCo cv) = IfaceHoleCo cv go_co (IfaceAxiomInstCo a i cos) = IfaceAxiomInstCo a i (go_cos cos) go_co (IfaceUnivCo prov r t1 t2) = IfaceUnivCo (go_prov prov) r (go t1) (go t2) go_co (IfaceSymCo co) = IfaceSymCo (go_co co) go_co (IfaceTransCo co1 co2) = IfaceTransCo (go_co co1) (go_co co2) go_co (IfaceNthCo n co) = IfaceNthCo n (go_co co) go_co (IfaceLRCo lr co) = IfaceLRCo lr (go_co co) go_co (IfaceInstCo c1 c2) = IfaceInstCo (go_co c1) (go_co c2) go_co (IfaceKindCo co) = IfaceKindCo (go_co co) go_co (IfaceSubCo co) = IfaceSubCo (go_co co) go_co (IfaceAxiomRuleCo n cos) = IfaceAxiomRuleCo n (go_cos cos) go_cos = map go_co go_prov (IfacePhantomProv co) = IfacePhantomProv (go_co co) go_prov (IfaceProofIrrelProv co) = IfaceProofIrrelProv (go_co co) go_prov (IfacePluginProv str) = IfacePluginProv str substIfaceAppArgs :: IfaceTySubst -> IfaceAppArgs -> IfaceAppArgs substIfaceAppArgs env args = go args where go IA_Nil = IA_Nil go (IA_Arg ty arg tys) = IA_Arg (substIfaceType env ty) arg (go tys) substIfaceTyVar :: IfaceTySubst -> IfLclName -> IfaceType substIfaceTyVar env tv | Just ty <- lookupFsEnv env tv = ty | otherwise = IfaceTyVar tv {- ************************************************************************ * * Functions over IfaceAppArgs * * ************************************************************************ -} stripInvisArgs :: PrintExplicitKinds -> IfaceAppArgs -> IfaceAppArgs stripInvisArgs (PrintExplicitKinds True) tys = tys stripInvisArgs (PrintExplicitKinds False) tys = suppress_invis tys where suppress_invis c = case c of IA_Nil -> IA_Nil IA_Arg t argf ts | isVisibleArgFlag argf -> IA_Arg t argf $ suppress_invis ts -- Keep recursing through the remainder of the arguments, as it's -- possible that there are remaining invisible ones. -- See the "In type declarations" section of Note [VarBndrs, -- TyCoVarBinders, TyConBinders, and visibility] in GHC.Core.TyCo.Rep. | otherwise -> suppress_invis ts appArgsIfaceTypes :: IfaceAppArgs -> [IfaceType] appArgsIfaceTypes IA_Nil = [] appArgsIfaceTypes (IA_Arg t _ ts) = t : appArgsIfaceTypes ts appArgsIfaceTypesArgFlags :: IfaceAppArgs -> [(IfaceType, ArgFlag)] appArgsIfaceTypesArgFlags IA_Nil = [] appArgsIfaceTypesArgFlags (IA_Arg t a ts) = (t, a) : appArgsIfaceTypesArgFlags ts ifaceVisAppArgsLength :: IfaceAppArgs -> Int ifaceVisAppArgsLength = go 0 where go !n IA_Nil = n go n (IA_Arg _ argf rest) | isVisibleArgFlag argf = go (n+1) rest | otherwise = go n rest {- Note [Suppressing invisible arguments] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use the IfaceAppArgs data type to specify which of the arguments to a type should be displayed when pretty-printing, under the control of -fprint-explicit-kinds. See also Type.filterOutInvisibleTypes. For example, given T :: forall k. (k->*) -> k -> * -- Ordinary kind polymorphism 'Just :: forall k. k -> 'Maybe k -- Promoted we want T * Tree Int prints as T Tree Int 'Just * prints as Just * For type constructors (IfaceTyConApp), IfaceAppArgs is a quite natural fit, since the corresponding Core constructor: data Type = ... | TyConApp TyCon [Type] Already puts all of its arguments into a list. So when converting a Type to an IfaceType (see toIfaceAppArgsX in GHC.Core.ToIface), we simply use the kind of the TyCon (which is cached) to guide the process of converting the argument Types into an IfaceAppArgs list. We also want this behavior for IfaceAppTy, since given: data Proxy (a :: k) f :: forall (t :: forall a. a -> Type). Proxy Type (t Bool True) We want to print the return type as `Proxy (t True)` without the use of -fprint-explicit-kinds (#15330). Accomplishing this is trickier than in the tycon case, because the corresponding Core constructor for IfaceAppTy: data Type = ... | AppTy Type Type Only stores one argument at a time. Therefore, when converting an AppTy to an IfaceAppTy (in toIfaceTypeX in GHC.CoreToIface), we: 1. Flatten the chain of AppTys down as much as possible 2. Use typeKind to determine the function Type's kind 3. Use this kind to guide the process of converting the argument Types into an IfaceAppArgs list. By flattening the arguments like this, we obtain two benefits: (a) We can reuse the same machinery to pretty-print IfaceTyConApp arguments as we do IfaceTyApp arguments, which means that we only need to implement the logic to filter out invisible arguments once. (b) Unlike for tycons, finding the kind of a type in general (through typeKind) is not a constant-time operation, so by flattening the arguments first, we decrease the number of times we have to call typeKind. Note [Pretty-printing invisible arguments] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Note [Suppressing invisible arguments] is all about how to avoid printing invisible arguments when the -fprint-explicit-kinds flag is disables. Well, what about when it's enabled? Then we can and should print invisible kind arguments, and this Note explains how we do it. As two running examples, consider the following code: {-# LANGUAGE PolyKinds #-} data T1 a data T2 (a :: k) When displaying these types (with -fprint-explicit-kinds on), we could just do the following: T1 k a T2 k a That certainly gets the job done. But it lacks a crucial piece of information: is the `k` argument inferred or specified? To communicate this, we use visible kind application syntax to distinguish the two cases: T1 @{k} a T2 @k a Here, @{k} indicates that `k` is an inferred argument, and @k indicates that `k` is a specified argument. (See Note [VarBndrs, TyCoVarBinders, TyConBinders, and visibility] in GHC.Core.TyCo.Rep for a lengthier explanation on what "inferred" and "specified" mean.) ************************************************************************ * * Pretty-printing * * ************************************************************************ -} if_print_coercions :: SDoc -- ^ if printing coercions -> SDoc -- ^ otherwise -> SDoc if_print_coercions yes no = sdocOption sdocPrintExplicitCoercions $ \print_co -> getPprStyle $ \style -> getPprDebug $ \debug -> if print_co || dumpStyle style || debug then yes else no pprIfaceInfixApp :: PprPrec -> SDoc -> SDoc -> SDoc -> SDoc pprIfaceInfixApp ctxt_prec pp_tc pp_ty1 pp_ty2 = maybeParen ctxt_prec opPrec $ sep [pp_ty1, pp_tc <+> pp_ty2] pprIfacePrefixApp :: PprPrec -> SDoc -> [SDoc] -> SDoc pprIfacePrefixApp ctxt_prec pp_fun pp_tys | null pp_tys = pp_fun | otherwise = maybeParen ctxt_prec appPrec $ hang pp_fun 2 (sep pp_tys) isIfaceTauType :: IfaceType -> Bool isIfaceTauType (IfaceForAllTy _ _) = False isIfaceTauType (IfaceFunTy InvisArg _ _ _) = False isIfaceTauType _ = True -- ----------------------------- Printing binders ------------------------------------ instance Outputable IfaceBndr where ppr (IfaceIdBndr bndr) = pprIfaceIdBndr bndr ppr (IfaceTvBndr bndr) = char '@' <> pprIfaceTvBndr bndr (SuppressBndrSig False) (UseBndrParens False) pprIfaceBndrs :: [IfaceBndr] -> SDoc pprIfaceBndrs bs = sep (map ppr bs) pprIfaceLamBndr :: IfaceLamBndr -> SDoc pprIfaceLamBndr (b, IfaceNoOneShot) = ppr b pprIfaceLamBndr (b, IfaceOneShot) = ppr b <> text "[OneShot]" pprIfaceIdBndr :: IfaceIdBndr -> SDoc pprIfaceIdBndr (w, name, ty) = parens (ppr name <> brackets (ppr w) <+> dcolon <+> ppr ty) {- Note [Suppressing binder signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When printing the binders in a 'forall', we want to keep the kind annotations: forall (a :: k). blah ^^^^ good On the other hand, when we print the binders of a data declaration in :info, the kind information would be redundant due to the standalone kind signature: type F :: Symbol -> Type type F (s :: Symbol) = blah ^^^^^^^^^ redundant Here we'd like to omit the kind annotation: type F :: Symbol -> Type type F s = blah Note [Printing type abbreviations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Normally, we pretty-print `TYPE 'LiftedRep` as `Type` (or `*`) and `FUN 'Many` as `(->)`. This way, error messages don't refer to levity polymorphism or linearity if it is not necessary. However, when printing the definition of Type or (->) with :info, this would give confusing output: `type (->) = (->)` (#18594). Solution: detect when we are in :info and disable displaying the synonym with the SDoc option sdocPrintTypeAbbreviations. If there will be a need, in the future we could expose it as a flag -fprint-type-abbreviations or even two separate flags controlling TYPE 'LiftedRep and FUN 'Many. -} -- | Do we want to suppress kind annotations on binders? -- See Note [Suppressing binder signatures] newtype SuppressBndrSig = SuppressBndrSig Bool newtype UseBndrParens = UseBndrParens Bool newtype PrintExplicitKinds = PrintExplicitKinds Bool pprIfaceTvBndr :: IfaceTvBndr -> SuppressBndrSig -> UseBndrParens -> SDoc pprIfaceTvBndr (tv, ki) (SuppressBndrSig suppress_sig) (UseBndrParens use_parens) | suppress_sig = ppr tv | isIfaceLiftedTypeKind ki = ppr tv | otherwise = maybe_parens (ppr tv <+> dcolon <+> ppr ki) where maybe_parens | use_parens = parens | otherwise = id pprIfaceTyConBinders :: SuppressBndrSig -> [IfaceTyConBinder] -> SDoc pprIfaceTyConBinders suppress_sig = sep . map go where go :: IfaceTyConBinder -> SDoc go (Bndr (IfaceIdBndr bndr) _) = pprIfaceIdBndr bndr go (Bndr (IfaceTvBndr bndr) vis) = -- See Note [Pretty-printing invisible arguments] case vis of AnonTCB VisArg -> ppr_bndr (UseBndrParens True) AnonTCB InvisArg -> char '@' <> braces (ppr_bndr (UseBndrParens False)) -- The above case is rare. (See Note [AnonTCB InvisArg] in GHC.Core.TyCon.) -- Should we print these differently? NamedTCB Required -> ppr_bndr (UseBndrParens True) -- See Note [Explicit Case Statement for Specificity] NamedTCB (Invisible spec) -> case spec of SpecifiedSpec -> char '@' <> ppr_bndr (UseBndrParens True) InferredSpec -> char '@' <> braces (ppr_bndr (UseBndrParens False)) where ppr_bndr = pprIfaceTvBndr bndr suppress_sig instance Binary IfaceBndr where put_ bh (IfaceIdBndr aa) = do putByte bh 0 put_ bh aa put_ bh (IfaceTvBndr ab) = do putByte bh 1 put_ bh ab get bh = do h <- getByte bh case h of 0 -> do aa <- get bh return (IfaceIdBndr aa) _ -> do ab <- get bh return (IfaceTvBndr ab) instance Binary IfaceOneShot where put_ bh IfaceNoOneShot = do putByte bh 0 put_ bh IfaceOneShot = do putByte bh 1 get bh = do h <- getByte bh case h of 0 -> do return IfaceNoOneShot _ -> do return IfaceOneShot -- ----------------------------- Printing IfaceType ------------------------------------ --------------------------------- instance Outputable IfaceType where ppr ty = pprIfaceType ty pprIfaceType, pprParendIfaceType :: IfaceType -> SDoc pprIfaceType = pprPrecIfaceType topPrec pprParendIfaceType = pprPrecIfaceType appPrec pprPrecIfaceType :: PprPrec -> IfaceType -> SDoc -- We still need `hideNonStandardTypes`, since the `pprPrecIfaceType` may be -- called from other places, besides `:type` and `:info`. pprPrecIfaceType prec ty = hideNonStandardTypes (ppr_ty prec) ty ppr_fun_arrow :: IfaceMult -> SDoc ppr_fun_arrow w | (IfaceTyConApp tc _) <- w , tc `ifaceTyConHasKey` (getUnique manyDataConTyCon) = arrow | (IfaceTyConApp tc _) <- w , tc `ifaceTyConHasKey` (getUnique oneDataConTyCon) = lollipop | otherwise = mulArrow (pprIfaceType w) ppr_sigma :: PprPrec -> IfaceType -> SDoc ppr_sigma ctxt_prec ty = maybeParen ctxt_prec funPrec (pprIfaceSigmaType ShowForAllMust ty) ppr_ty :: PprPrec -> IfaceType -> SDoc ppr_ty ctxt_prec ty@(IfaceForAllTy {}) = ppr_sigma ctxt_prec ty ppr_ty ctxt_prec ty@(IfaceFunTy InvisArg _ _ _) = ppr_sigma ctxt_prec ty ppr_ty _ (IfaceFreeTyVar tyvar) = ppr tyvar -- This is the main reason for IfaceFreeTyVar! ppr_ty _ (IfaceTyVar tyvar) = ppr tyvar -- See Note [TcTyVars in IfaceType] ppr_ty ctxt_prec (IfaceTyConApp tc tys) = pprTyTcApp ctxt_prec tc tys ppr_ty ctxt_prec (IfaceTupleTy i p tys) = pprTuple ctxt_prec i p tys ppr_ty _ (IfaceLitTy n) = pprIfaceTyLit n -- Function types ppr_ty ctxt_prec (IfaceFunTy _ w ty1 ty2) -- Should be VisArg = -- We don't want to lose synonyms, so we mustn't use splitFunTys here. maybeParen ctxt_prec funPrec $ sep [ppr_ty funPrec ty1, sep (ppr_fun_tail w ty2)] where ppr_fun_tail wthis (IfaceFunTy VisArg wnext ty1 ty2) = (ppr_fun_arrow wthis <+> ppr_ty funPrec ty1) : ppr_fun_tail wnext ty2 ppr_fun_tail wthis other_ty = [ppr_fun_arrow wthis <+> pprIfaceType other_ty] ppr_ty ctxt_prec (IfaceAppTy t ts) = if_print_coercions ppr_app_ty ppr_app_ty_no_casts where ppr_app_ty = sdocOption sdocPrintExplicitKinds $ \print_kinds -> let tys_wo_kinds = appArgsIfaceTypesArgFlags $ stripInvisArgs (PrintExplicitKinds print_kinds) ts in pprIfacePrefixApp ctxt_prec (ppr_ty funPrec t) (map (ppr_app_arg appPrec) tys_wo_kinds) -- Strip any casts from the head of the application ppr_app_ty_no_casts = case t of IfaceCastTy head _ -> ppr_ty ctxt_prec (mk_app_tys head ts) _ -> ppr_app_ty mk_app_tys :: IfaceType -> IfaceAppArgs -> IfaceType mk_app_tys (IfaceTyConApp tc tys1) tys2 = IfaceTyConApp tc (tys1 `mappend` tys2) mk_app_tys t1 tys2 = IfaceAppTy t1 tys2 ppr_ty ctxt_prec (IfaceCastTy ty co) = if_print_coercions (parens (ppr_ty topPrec ty <+> text "|>" <+> ppr co)) (ppr_ty ctxt_prec ty) ppr_ty ctxt_prec (IfaceCoercionTy co) = if_print_coercions (ppr_co ctxt_prec co) (text "<>") {- Note [Defaulting RuntimeRep variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RuntimeRep variables are considered by many (most?) users to be little more than syntactic noise. When the notion was introduced there was a significant and understandable push-back from those with pedagogy in mind, which argued that RuntimeRep variables would throw a wrench into nearly any teach approach since they appear in even the lowly ($) function's type, ($) :: forall (w :: RuntimeRep) a (b :: TYPE w). (a -> b) -> a -> b which is significantly less readable than its non RuntimeRep-polymorphic type of ($) :: (a -> b) -> a -> b Moreover, unboxed types don't appear all that often in run-of-the-mill Haskell programs, so it makes little sense to make all users pay this syntactic overhead. For this reason it was decided that we would hide RuntimeRep variables for now (see #11549). We do this by defaulting all type variables of kind RuntimeRep to LiftedRep. Likewise, we default all Multiplicity variables to Many. This is done in a pass right before pretty-printing (defaultNonStandardVars, controlled by -fprint-explicit-runtime-reps and -XLinearTypes) This applies to /quantified/ variables like 'w' above. What about variables that are /free/ in the type being printed, which certainly happens in error messages. Suppose (#16074) we are reporting a mismatch between two skolems (a :: RuntimeRep) ~ (b :: RuntimeRep) We certainly don't want to say "Can't match LiftedRep ~ LiftedRep"! But if we are printing the type (forall (a :: Type r). blah we do want to turn that (free) r into LiftedRep, so it prints as (forall a. blah) Conclusion: keep track of whether we are in the kind of a binder; only if so, convert free RuntimeRep variables to LiftedRep. -} -- | Default 'RuntimeRep' variables to 'LiftedRep', and 'Multiplicity' -- variables to 'Many'. For example: -- -- @ -- ($) :: forall (r :: GHC.Types.RuntimeRep) a (b :: TYPE r). -- (a -> b) -> a -> b -- Just :: forall (k :: Multiplicity) a. a # k -> Maybe a -- @ -- -- turns in to, -- -- @ ($) :: forall a (b :: *). (a -> b) -> a -> b @ -- @ Just :: forall a . a -> Maybe a @ -- -- We do this to prevent RuntimeRep and Multiplicity variables from -- incurring a significant syntactic overhead in otherwise simple -- type signatures (e.g. ($)). See Note [Defaulting RuntimeRep variables] -- and #11549 for further discussion. defaultNonStandardVars :: Bool -> Bool -> IfaceType -> IfaceType defaultNonStandardVars do_runtimereps do_multiplicities ty = go False emptyFsEnv ty where go :: Bool -- True <=> Inside the kind of a binder -> FastStringEnv IfaceType -- Set of enclosing forall-ed RuntimeRep/Multiplicity variables -> IfaceType -> IfaceType go ink subs (IfaceForAllTy (Bndr (IfaceTvBndr (var, var_kind)) argf) ty) | isInvisibleArgFlag argf -- Don't default *visible* quantification -- or we get the mess in #13963 , Just substituted_ty <- check_substitution var_kind = let subs' = extendFsEnv subs var substituted_ty -- Record that we should replace it with LiftedRep, -- and recurse, discarding the forall in go ink subs' ty go ink subs (IfaceForAllTy bndr ty) = IfaceForAllTy (go_ifacebndr subs bndr) (go ink subs ty) go _ subs ty@(IfaceTyVar tv) = case lookupFsEnv subs tv of Just s -> s Nothing -> ty go in_kind _ ty@(IfaceFreeTyVar tv) -- See Note [Defaulting RuntimeRep variables], about free vars | in_kind && do_runtimereps && GHC.Core.Type.isRuntimeRepTy (tyVarKind tv) = liftedRep_ty | do_multiplicities && GHC.Core.Type.isMultiplicityTy (tyVarKind tv) = many_ty | otherwise = ty go ink subs (IfaceTyConApp tc tc_args) = IfaceTyConApp tc (go_args ink subs tc_args) go ink subs (IfaceTupleTy sort is_prom tc_args) = IfaceTupleTy sort is_prom (go_args ink subs tc_args) go ink subs (IfaceFunTy af w arg res) = IfaceFunTy af (go ink subs w) (go ink subs arg) (go ink subs res) go ink subs (IfaceAppTy t ts) = IfaceAppTy (go ink subs t) (go_args ink subs ts) go ink subs (IfaceCastTy x co) = IfaceCastTy (go ink subs x) co go _ _ ty@(IfaceLitTy {}) = ty go _ _ ty@(IfaceCoercionTy {}) = ty go_ifacebndr :: FastStringEnv IfaceType -> IfaceForAllBndr -> IfaceForAllBndr go_ifacebndr subs (Bndr (IfaceIdBndr (w, n, t)) argf) = Bndr (IfaceIdBndr (w, n, go True subs t)) argf go_ifacebndr subs (Bndr (IfaceTvBndr (n, t)) argf) = Bndr (IfaceTvBndr (n, go True subs t)) argf go_args :: Bool -> FastStringEnv IfaceType -> IfaceAppArgs -> IfaceAppArgs go_args _ _ IA_Nil = IA_Nil go_args ink subs (IA_Arg ty argf args) = IA_Arg (go ink subs ty) argf (go_args ink subs args) check_substitution :: IfaceType -> Maybe IfaceType check_substitution (IfaceTyConApp tc _) | do_runtimereps, tc `ifaceTyConHasKey` runtimeRepTyConKey = Just liftedRep_ty | do_multiplicities, tc `ifaceTyConHasKey` multiplicityTyConKey = Just many_ty check_substitution _ = Nothing liftedRep_ty :: IfaceType liftedRep_ty = IfaceTyConApp (IfaceTyCon dc_name (IfaceTyConInfo IsPromoted IfaceNormalTyCon)) IA_Nil where dc_name = getName liftedRepDataConTyCon many_ty :: IfaceType many_ty = IfaceTyConApp (IfaceTyCon dc_name (IfaceTyConInfo IsPromoted IfaceNormalTyCon)) IA_Nil where dc_name = getName manyDataConTyCon hideNonStandardTypes :: (IfaceType -> SDoc) -> IfaceType -> SDoc hideNonStandardTypes f ty = sdocOption sdocPrintExplicitRuntimeReps $ \printExplicitRuntimeReps -> sdocOption sdocLinearTypes $ \linearTypes -> getPprStyle $ \sty -> let do_runtimerep = not printExplicitRuntimeReps do_multiplicity = not linearTypes in if userStyle sty then f (defaultNonStandardVars do_runtimerep do_multiplicity ty) else f ty instance Outputable IfaceAppArgs where ppr tca = pprIfaceAppArgs tca pprIfaceAppArgs, pprParendIfaceAppArgs :: IfaceAppArgs -> SDoc pprIfaceAppArgs = ppr_app_args topPrec pprParendIfaceAppArgs = ppr_app_args appPrec ppr_app_args :: PprPrec -> IfaceAppArgs -> SDoc ppr_app_args ctx_prec = go where go :: IfaceAppArgs -> SDoc go IA_Nil = empty go (IA_Arg t argf ts) = ppr_app_arg ctx_prec (t, argf) <+> go ts -- See Note [Pretty-printing invisible arguments] ppr_app_arg :: PprPrec -> (IfaceType, ArgFlag) -> SDoc ppr_app_arg ctx_prec (t, argf) = sdocOption sdocPrintExplicitKinds $ \print_kinds -> case argf of Required -> ppr_ty ctx_prec t Specified | print_kinds -> char '@' <> ppr_ty appPrec t Inferred | print_kinds -> char '@' <> braces (ppr_ty topPrec t) _ -> empty ------------------- pprIfaceForAllPart :: [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc pprIfaceForAllPart tvs ctxt sdoc = ppr_iface_forall_part ShowForAllWhen tvs ctxt sdoc -- | Like 'pprIfaceForAllPart', but always uses an explicit @forall@. pprIfaceForAllPartMust :: [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc pprIfaceForAllPartMust tvs ctxt sdoc = ppr_iface_forall_part ShowForAllMust tvs ctxt sdoc pprIfaceForAllCoPart :: [(IfLclName, IfaceCoercion)] -> SDoc -> SDoc pprIfaceForAllCoPart tvs sdoc = sep [ pprIfaceForAllCo tvs, sdoc ] ppr_iface_forall_part :: ShowForAllFlag -> [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc ppr_iface_forall_part show_forall tvs ctxt sdoc = sep [ case show_forall of ShowForAllMust -> pprIfaceForAll tvs ShowForAllWhen -> pprUserIfaceForAll tvs , pprIfaceContextArr ctxt , sdoc] -- | Render the "forall ... ." or "forall ... ->" bit of a type. pprIfaceForAll :: [IfaceForAllBndr] -> SDoc pprIfaceForAll [] = empty pprIfaceForAll bndrs@(Bndr _ vis : _) = sep [ add_separator (forAllLit <+> fsep docs) , pprIfaceForAll bndrs' ] where (bndrs', docs) = ppr_itv_bndrs bndrs vis add_separator stuff = case vis of Required -> stuff <+> arrow _inv -> stuff <> dot -- | Render the ... in @(forall ... .)@ or @(forall ... ->)@. -- Returns both the list of not-yet-rendered binders and the doc. -- No anonymous binders here! ppr_itv_bndrs :: [IfaceForAllBndr] -> ArgFlag -- ^ visibility of the first binder in the list -> ([IfaceForAllBndr], [SDoc]) ppr_itv_bndrs all_bndrs@(bndr@(Bndr _ vis) : bndrs) vis1 | vis `sameVis` vis1 = let (bndrs', doc) = ppr_itv_bndrs bndrs vis1 in (bndrs', pprIfaceForAllBndr bndr : doc) | otherwise = (all_bndrs, []) ppr_itv_bndrs [] _ = ([], []) pprIfaceForAllCo :: [(IfLclName, IfaceCoercion)] -> SDoc pprIfaceForAllCo [] = empty pprIfaceForAllCo tvs = text "forall" <+> pprIfaceForAllCoBndrs tvs <> dot pprIfaceForAllCoBndrs :: [(IfLclName, IfaceCoercion)] -> SDoc pprIfaceForAllCoBndrs bndrs = hsep $ map pprIfaceForAllCoBndr bndrs pprIfaceForAllBndr :: IfaceForAllBndr -> SDoc pprIfaceForAllBndr bndr = case bndr of Bndr (IfaceTvBndr tv) Inferred -> braces $ pprIfaceTvBndr tv suppress_sig (UseBndrParens False) Bndr (IfaceTvBndr tv) _ -> pprIfaceTvBndr tv suppress_sig (UseBndrParens True) Bndr (IfaceIdBndr idv) _ -> pprIfaceIdBndr idv where -- See Note [Suppressing binder signatures] suppress_sig = SuppressBndrSig False pprIfaceForAllCoBndr :: (IfLclName, IfaceCoercion) -> SDoc pprIfaceForAllCoBndr (tv, kind_co) = parens (ppr tv <+> dcolon <+> pprIfaceCoercion kind_co) -- | Show forall flag -- -- Unconditionally show the forall quantifier with ('ShowForAllMust') -- or when ('ShowForAllWhen') the names used are free in the binder -- or when compiling with -fprint-explicit-foralls. data ShowForAllFlag = ShowForAllMust | ShowForAllWhen pprIfaceSigmaType :: ShowForAllFlag -> IfaceType -> SDoc pprIfaceSigmaType show_forall ty = hideNonStandardTypes ppr_fn ty where ppr_fn iface_ty = let (invis_tvs, theta, tau) = splitIfaceSigmaTy iface_ty (req_tvs, tau') = splitIfaceReqForallTy tau -- splitIfaceSigmaTy is recursive, so it will gather the binders after -- the theta, i.e. forall a. theta => forall b. tau -- will give you ([a,b], theta, tau). -- -- This isn't right when it comes to visible forall (see -- testsuite/tests/polykinds/T18522-ppr), -- so we split off required binders separately, -- using splitIfaceReqForallTy. -- -- An alternative solution would be to make splitIfaceSigmaTy -- non-recursive (see #18458). -- Then it could handle both invisible and required binders, and -- splitIfaceReqForallTy wouldn't be necessary here. in ppr_iface_forall_part show_forall invis_tvs theta $ sep [pprIfaceForAll req_tvs, ppr tau'] pprUserIfaceForAll :: [IfaceForAllBndr] -> SDoc pprUserIfaceForAll tvs = sdocOption sdocPrintExplicitForalls $ \print_foralls -> -- See Note [When to print foralls] in this module. ppWhen (any tv_has_kind_var tvs || any tv_is_required tvs || print_foralls) $ pprIfaceForAll tvs where tv_has_kind_var (Bndr (IfaceTvBndr (_,kind)) _) = not (ifTypeIsVarFree kind) tv_has_kind_var _ = False tv_is_required = isVisibleArgFlag . binderArgFlag {- Note [When to print foralls] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We opt to explicitly pretty-print `forall`s if any of the following criteria are met: 1. -fprint-explicit-foralls is on. 2. A bound type variable has a polymorphic kind. E.g., forall k (a::k). Proxy a -> Proxy a Since a's kind mentions a variable k, we print the foralls. 3. A bound type variable is a visible argument (#14238). Suppose we are printing the kind of: T :: forall k -> k -> Type The "forall k ->" notation means that this kind argument is required. That is, it must be supplied at uses of T. E.g., f :: T (Type->Type) Monad -> Int So we print an explicit "T :: forall k -> k -> Type", because omitting it and printing "T :: k -> Type" would be utterly misleading. See Note [VarBndrs, TyCoVarBinders, TyConBinders, and visibility] in GHC.Core.TyCo.Rep. N.B. Until now (Aug 2018) we didn't check anything for coercion variables. Note [Printing foralls in type family instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use the same criteria as in Note [When to print foralls] to determine whether a type family instance should be pretty-printed with an explicit `forall`. Example: type family Foo (a :: k) :: k where Foo Maybe = [] Foo (a :: Type) = Int Foo a = a Without -fprint-explicit-foralls enabled, this will be pretty-printed as: type family Foo (a :: k) :: k where Foo Maybe = [] Foo a = Int forall k (a :: k). Foo a = a Note that only the third equation has an explicit forall, since it has a type variable with a non-Type kind. (If -fprint-explicit-foralls were enabled, then the second equation would be preceded with `forall a.`.) There is one tricky point in the implementation: what visibility do we give the type variables in a type family instance? Type family instances only store type *variables*, not type variable *binders*, and only the latter has visibility information. We opt to default the visibility of each of these type variables to Specified because users can't ever instantiate these variables manually, so the choice of visibility is only relevant to pretty-printing. (This is why the `k` in `forall k (a :: k). ...` above is printed the way it is, even though it wasn't written explicitly in the original source code.) We adopt the same strategy for data family instances. Example: data family DF (a :: k) data instance DF '[a, b] = DFList That data family instance is pretty-printed as: data instance forall j (a :: j) (b :: j). DF '[a, b] = DFList This is despite that the representation tycon for this data instance (call it $DF:List) actually has different visibilities for its binders. However, the visibilities of these binders are utterly irrelevant to the programmer, who cares only about the specificity of variables in `DF`'s type, not $DF:List's type. Therefore, we opt to pretty-print all variables in data family instances as Specified. Note [Printing promoted type constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this GHCi session (#14343) > _ :: Proxy '[ 'True ] error: Found hole: _ :: Proxy '['True] This would be bad, because the '[' looks like a character literal. Solution: in type-level lists and tuples, add a leading space if the first type is itself promoted. See pprSpaceIfPromotedTyCon. -} ------------------- -- | Prefix a space if the given 'IfaceType' is a promoted 'TyCon'. -- See Note [Printing promoted type constructors] pprSpaceIfPromotedTyCon :: IfaceType -> SDoc -> SDoc pprSpaceIfPromotedTyCon (IfaceTyConApp tyCon _) = case ifaceTyConIsPromoted (ifaceTyConInfo tyCon) of IsPromoted -> (space <>) _ -> id pprSpaceIfPromotedTyCon _ = id -- See equivalent function in "GHC.Core.TyCo.Rep" pprIfaceTyList :: PprPrec -> IfaceType -> IfaceType -> SDoc -- Given a type-level list (t1 ': t2), see if we can print -- it in list notation [t1, ...]. -- Precondition: Opt_PrintExplicitKinds is off pprIfaceTyList ctxt_prec ty1 ty2 = case gather ty2 of (arg_tys, Nothing) -> char '\'' <> brackets (pprSpaceIfPromotedTyCon ty1 (fsep (punctuate comma (map (ppr_ty topPrec) (ty1:arg_tys))))) (arg_tys, Just tl) -> maybeParen ctxt_prec funPrec $ hang (ppr_ty funPrec ty1) 2 (fsep [ colon <+> ppr_ty funPrec ty | ty <- arg_tys ++ [tl]]) where gather :: IfaceType -> ([IfaceType], Maybe IfaceType) -- (gather ty) = (tys, Nothing) means ty is a list [t1, .., tn] -- = (tys, Just tl) means ty is of form t1:t2:...tn:tl gather (IfaceTyConApp tc tys) | tc `ifaceTyConHasKey` consDataConKey , IA_Arg _ argf (IA_Arg ty1 Required (IA_Arg ty2 Required IA_Nil)) <- tys , isInvisibleArgFlag argf , (args, tl) <- gather ty2 = (ty1:args, tl) | tc `ifaceTyConHasKey` nilDataConKey = ([], Nothing) gather ty = ([], Just ty) pprIfaceTypeApp :: PprPrec -> IfaceTyCon -> IfaceAppArgs -> SDoc pprIfaceTypeApp prec tc args = pprTyTcApp prec tc args pprTyTcApp :: PprPrec -> IfaceTyCon -> IfaceAppArgs -> SDoc pprTyTcApp ctxt_prec tc tys = sdocOption sdocPrintExplicitKinds $ \print_kinds -> sdocOption sdocPrintTypeAbbreviations $ \print_type_abbreviations -> getPprDebug $ \debug -> if | ifaceTyConName tc `hasKey` ipClassKey , IA_Arg (IfaceLitTy (IfaceStrTyLit n)) Required (IA_Arg ty Required IA_Nil) <- tys -> maybeParen ctxt_prec funPrec $ char '?' <> ftext n <> text "::" <> ppr_ty topPrec ty | IfaceTupleTyCon arity sort <- ifaceTyConSort info , not debug , arity == ifaceVisAppArgsLength tys -> pprTuple ctxt_prec sort (ifaceTyConIsPromoted info) tys | IfaceSumTyCon arity <- ifaceTyConSort info -> pprSum arity (ifaceTyConIsPromoted info) tys | tc `ifaceTyConHasKey` consDataConKey , False <- print_kinds , IA_Arg _ argf (IA_Arg ty1 Required (IA_Arg ty2 Required IA_Nil)) <- tys , isInvisibleArgFlag argf -> pprIfaceTyList ctxt_prec ty1 ty2 | tc `ifaceTyConHasKey` tYPETyConKey , IA_Arg (IfaceTyConApp rep IA_Nil) Required IA_Nil <- tys , rep `ifaceTyConHasKey` liftedRepDataConKey , print_type_abbreviations -- See Note [Printing type abbreviations] -> ppr_kind_type ctxt_prec | tc `ifaceTyConHasKey` funTyConKey , IA_Arg (IfaceTyConApp rep IA_Nil) Required args <- tys , rep `ifaceTyConHasKey` manyDataConKey , print_type_abbreviations -- See Note [Printing type abbreviations] -> pprIfacePrefixApp ctxt_prec (parens arrow) (map (ppr_ty appPrec) $ appArgsIfaceTypes $ stripInvisArgs (PrintExplicitKinds print_kinds) args) | tc `ifaceTyConHasKey` errorMessageTypeErrorFamKey , not debug -- Suppress detail unless you _really_ want to see -> text "(TypeError ...)" | Just doc <- ppr_equality ctxt_prec tc (appArgsIfaceTypes tys) -> doc | otherwise -> ppr_iface_tc_app ppr_app_arg ctxt_prec tc $ appArgsIfaceTypesArgFlags $ stripInvisArgs (PrintExplicitKinds print_kinds) tys where info = ifaceTyConInfo tc ppr_kind_type :: PprPrec -> SDoc ppr_kind_type ctxt_prec = sdocOption sdocStarIsType $ \case False -> text "Type" True -> maybeParen ctxt_prec starPrec $ unicodeSyntax (char '★') (char '*') -- | Pretty-print a type-level equality. -- Returns (Just doc) if the argument is a /saturated/ application -- of eqTyCon (~) -- eqPrimTyCon (~#) -- eqReprPrimTyCon (~R#) -- heqTyCon (~~) -- -- See Note [Equality predicates in IfaceType] -- and Note [The equality types story] in GHC.Builtin.Types.Prim ppr_equality :: PprPrec -> IfaceTyCon -> [IfaceType] -> Maybe SDoc ppr_equality ctxt_prec tc args | hetero_eq_tc , [k1, k2, t1, t2] <- args = Just $ print_equality (k1, k2, t1, t2) | hom_eq_tc , [k, t1, t2] <- args = Just $ print_equality (k, k, t1, t2) | otherwise = Nothing where homogeneous = tc_name `hasKey` eqTyConKey -- (~) || hetero_tc_used_homogeneously where hetero_tc_used_homogeneously = case ifaceTyConSort $ ifaceTyConInfo tc of IfaceEqualityTyCon -> True _other -> False -- True <=> a heterogeneous equality whose arguments -- are (in this case) of the same kind tc_name = ifaceTyConName tc pp = ppr_ty hom_eq_tc = tc_name `hasKey` eqTyConKey -- (~) hetero_eq_tc = tc_name `hasKey` eqPrimTyConKey -- (~#) || tc_name `hasKey` eqReprPrimTyConKey -- (~R#) || tc_name `hasKey` heqTyConKey -- (~~) nominal_eq_tc = tc_name `hasKey` heqTyConKey -- (~~) || tc_name `hasKey` eqPrimTyConKey -- (~#) print_equality args = sdocOption sdocPrintExplicitKinds $ \print_kinds -> sdocOption sdocPrintEqualityRelations $ \print_eqs -> getPprStyle $ \style -> getPprDebug $ \debug -> print_equality' args print_kinds (print_eqs || dumpStyle style || debug) print_equality' (ki1, ki2, ty1, ty2) print_kinds print_eqs | -- If -fprint-equality-relations is on, just print the original TyCon print_eqs = ppr_infix_eq (ppr tc) | -- Homogeneous use of heterogeneous equality (ty1 ~~ ty2) -- or unlifted equality (ty1 ~# ty2) nominal_eq_tc, homogeneous = ppr_infix_eq (text "~") | -- Heterogeneous use of unlifted equality (ty1 ~# ty2) not homogeneous = ppr_infix_eq (ppr heqTyCon) | -- Homogeneous use of representational unlifted equality (ty1 ~R# ty2) tc_name `hasKey` eqReprPrimTyConKey, homogeneous = let ki | print_kinds = [pp appPrec ki1] | otherwise = [] in pprIfacePrefixApp ctxt_prec (ppr coercibleTyCon) (ki ++ [pp appPrec ty1, pp appPrec ty2]) -- The other cases work as you'd expect | otherwise = ppr_infix_eq (ppr tc) where ppr_infix_eq :: SDoc -> SDoc ppr_infix_eq eq_op = pprIfaceInfixApp ctxt_prec eq_op (pp_ty_ki ty1 ki1) (pp_ty_ki ty2 ki2) where pp_ty_ki ty ki | print_kinds = parens (pp topPrec ty <+> dcolon <+> pp opPrec ki) | otherwise = pp opPrec ty pprIfaceCoTcApp :: PprPrec -> IfaceTyCon -> [IfaceCoercion] -> SDoc pprIfaceCoTcApp ctxt_prec tc tys = ppr_iface_tc_app (\prec (co, _) -> ppr_co prec co) ctxt_prec tc (map (, Required) tys) -- We are trying to re-use ppr_iface_tc_app here, which requires its -- arguments to be accompanied by visibilities. But visibility is -- irrelevant when printing coercions, so just default everything to -- Required. -- | Pretty-prints an application of a type constructor to some arguments -- (whose visibilities are known). This is polymorphic (over @a@) since we use -- this function to pretty-print two different things: -- -- 1. Types (from `pprTyTcApp'`) -- -- 2. Coercions (from 'pprIfaceCoTcApp') ppr_iface_tc_app :: (PprPrec -> (a, ArgFlag) -> SDoc) -> PprPrec -> IfaceTyCon -> [(a, ArgFlag)] -> SDoc ppr_iface_tc_app pp _ tc [ty] | tc `ifaceTyConHasKey` listTyConKey = pprPromotionQuote tc <> brackets (pp topPrec ty) ppr_iface_tc_app pp ctxt_prec tc tys | tc `ifaceTyConHasKey` liftedTypeKindTyConKey = ppr_kind_type ctxt_prec | not (isSymOcc (nameOccName (ifaceTyConName tc))) = pprIfacePrefixApp ctxt_prec (ppr tc) (map (pp appPrec) tys) | [ ty1@(_, Required) , ty2@(_, Required) ] <- tys -- Infix, two visible arguments (we know nothing of precedence though). -- Don't apply this special case if one of the arguments is invisible, -- lest we print something like (@LiftedRep -> @LiftedRep) (#15941). = pprIfaceInfixApp ctxt_prec (ppr tc) (pp opPrec ty1) (pp opPrec ty2) | otherwise = pprIfacePrefixApp ctxt_prec (parens (ppr tc)) (map (pp appPrec) tys) pprSum :: Arity -> PromotionFlag -> IfaceAppArgs -> SDoc pprSum _arity is_promoted args = -- drop the RuntimeRep vars. -- See Note [Unboxed tuple RuntimeRep vars] in GHC.Core.TyCon let tys = appArgsIfaceTypes args args' = drop (length tys `div` 2) tys in pprPromotionQuoteI is_promoted <> sumParens (pprWithBars (ppr_ty topPrec) args') pprTuple :: PprPrec -> TupleSort -> PromotionFlag -> IfaceAppArgs -> SDoc pprTuple ctxt_prec sort promoted args = case promoted of IsPromoted -> let tys = appArgsIfaceTypes args args' = drop (length tys `div` 2) tys spaceIfPromoted = case args' of arg0:_ -> pprSpaceIfPromotedTyCon arg0 _ -> id in ppr_tuple_app args' $ pprPromotionQuoteI IsPromoted <> tupleParens sort (spaceIfPromoted (pprWithCommas pprIfaceType args')) NotPromoted | ConstraintTuple <- sort , IA_Nil <- args -> maybeParen ctxt_prec sigPrec $ text "() :: Constraint" | otherwise -> -- drop the RuntimeRep vars. -- See Note [Unboxed tuple RuntimeRep vars] in GHC.Core.TyCon let tys = appArgsIfaceTypes args args' = case sort of UnboxedTuple -> drop (length tys `div` 2) tys _ -> tys in ppr_tuple_app args' $ pprPromotionQuoteI promoted <> tupleParens sort (pprWithCommas pprIfaceType args') where ppr_tuple_app :: [IfaceType] -> SDoc -> SDoc ppr_tuple_app args_wo_runtime_reps ppr_args_w_parens -- Special-case unary boxed tuples so that they are pretty-printed as -- `Solo x`, not `(x)` | [_] <- args_wo_runtime_reps , BoxedTuple <- sort = let unit_tc_info = IfaceTyConInfo promoted IfaceNormalTyCon unit_tc = IfaceTyCon (tupleTyConName sort 1) unit_tc_info in pprPrecIfaceType ctxt_prec $ IfaceTyConApp unit_tc args | otherwise = ppr_args_w_parens pprIfaceTyLit :: IfaceTyLit -> SDoc pprIfaceTyLit (IfaceNumTyLit n) = integer n pprIfaceTyLit (IfaceStrTyLit n) = text (show n) pprIfaceCoercion, pprParendIfaceCoercion :: IfaceCoercion -> SDoc pprIfaceCoercion = ppr_co topPrec pprParendIfaceCoercion = ppr_co appPrec ppr_co :: PprPrec -> IfaceCoercion -> SDoc ppr_co _ (IfaceReflCo ty) = angleBrackets (ppr ty) <> ppr_role Nominal ppr_co _ (IfaceGReflCo r ty IfaceMRefl) = angleBrackets (ppr ty) <> ppr_role r ppr_co ctxt_prec (IfaceGReflCo r ty (IfaceMCo co)) = ppr_special_co ctxt_prec (text "GRefl" <+> ppr r <+> pprParendIfaceType ty) [co] ppr_co ctxt_prec (IfaceFunCo r cow co1 co2) = maybeParen ctxt_prec funPrec $ sep (ppr_co funPrec co1 : ppr_fun_tail cow co2) where ppr_fun_tail cow' (IfaceFunCo r cow co1 co2) = (coercionArrow cow' <> ppr_role r <+> ppr_co funPrec co1) : ppr_fun_tail cow co2 ppr_fun_tail cow' other_co = [coercionArrow cow' <> ppr_role r <+> pprIfaceCoercion other_co] coercionArrow w = mulArrow (ppr_co topPrec w) ppr_co _ (IfaceTyConAppCo r tc cos) = parens (pprIfaceCoTcApp topPrec tc cos) <> ppr_role r ppr_co ctxt_prec (IfaceAppCo co1 co2) = maybeParen ctxt_prec appPrec $ ppr_co funPrec co1 <+> pprParendIfaceCoercion co2 ppr_co ctxt_prec co@(IfaceForAllCo {}) = maybeParen ctxt_prec funPrec $ pprIfaceForAllCoPart tvs (pprIfaceCoercion inner_co) where (tvs, inner_co) = split_co co split_co (IfaceForAllCo (IfaceTvBndr (name, _)) kind_co co') = let (tvs, co'') = split_co co' in ((name,kind_co):tvs,co'') split_co (IfaceForAllCo (IfaceIdBndr (_, name, _)) kind_co co') = let (tvs, co'') = split_co co' in ((name,kind_co):tvs,co'') split_co co' = ([], co') -- Why these three? See Note [TcTyVars in IfaceType] ppr_co _ (IfaceFreeCoVar covar) = ppr covar ppr_co _ (IfaceCoVarCo covar) = ppr covar ppr_co _ (IfaceHoleCo covar) = braces (ppr covar) ppr_co _ (IfaceUnivCo prov role ty1 ty2) = text "Univ" <> (parens $ sep [ ppr role <+> pprIfaceUnivCoProv prov , dcolon <+> ppr ty1 <> comma <+> ppr ty2 ]) ppr_co ctxt_prec (IfaceInstCo co ty) = maybeParen ctxt_prec appPrec $ text "Inst" <+> pprParendIfaceCoercion co <+> pprParendIfaceCoercion ty ppr_co ctxt_prec (IfaceAxiomRuleCo tc cos) = maybeParen ctxt_prec appPrec $ ppr tc <+> parens (interpp'SP cos) ppr_co ctxt_prec (IfaceAxiomInstCo n i cos) = ppr_special_co ctxt_prec (ppr n <> brackets (ppr i)) cos ppr_co ctxt_prec (IfaceSymCo co) = ppr_special_co ctxt_prec (text "Sym") [co] ppr_co ctxt_prec (IfaceTransCo co1 co2) = maybeParen ctxt_prec opPrec $ ppr_co opPrec co1 <+> semi <+> ppr_co opPrec co2 ppr_co ctxt_prec (IfaceNthCo d co) = ppr_special_co ctxt_prec (text "Nth:" <> int d) [co] ppr_co ctxt_prec (IfaceLRCo lr co) = ppr_special_co ctxt_prec (ppr lr) [co] ppr_co ctxt_prec (IfaceSubCo co) = ppr_special_co ctxt_prec (text "Sub") [co] ppr_co ctxt_prec (IfaceKindCo co) = ppr_special_co ctxt_prec (text "Kind") [co] ppr_special_co :: PprPrec -> SDoc -> [IfaceCoercion] -> SDoc ppr_special_co ctxt_prec doc cos = maybeParen ctxt_prec appPrec (sep [doc, nest 4 (sep (map pprParendIfaceCoercion cos))]) ppr_role :: Role -> SDoc ppr_role r = underscore <> pp_role where pp_role = case r of Nominal -> char 'N' Representational -> char 'R' Phantom -> char 'P' ------------------ pprIfaceUnivCoProv :: IfaceUnivCoProv -> SDoc pprIfaceUnivCoProv (IfacePhantomProv co) = text "phantom" <+> pprParendIfaceCoercion co pprIfaceUnivCoProv (IfaceProofIrrelProv co) = text "irrel" <+> pprParendIfaceCoercion co pprIfaceUnivCoProv (IfacePluginProv s) = text "plugin" <+> doubleQuotes (text s) ------------------- instance Outputable IfaceTyCon where ppr tc = pprPromotionQuote tc <> ppr (ifaceTyConName tc) instance Outputable IfaceTyConInfo where ppr (IfaceTyConInfo { ifaceTyConIsPromoted = prom , ifaceTyConSort = sort }) = angleBrackets $ ppr prom <> comma <+> ppr sort pprPromotionQuote :: IfaceTyCon -> SDoc pprPromotionQuote tc = pprPromotionQuoteI $ ifaceTyConIsPromoted $ ifaceTyConInfo tc pprPromotionQuoteI :: PromotionFlag -> SDoc pprPromotionQuoteI NotPromoted = empty pprPromotionQuoteI IsPromoted = char '\'' instance Outputable IfaceCoercion where ppr = pprIfaceCoercion instance Binary IfaceTyCon where put_ bh (IfaceTyCon n i) = put_ bh n >> put_ bh i get bh = do n <- get bh i <- get bh return (IfaceTyCon n i) instance Binary IfaceTyConSort where put_ bh IfaceNormalTyCon = putByte bh 0 put_ bh (IfaceTupleTyCon arity sort) = putByte bh 1 >> put_ bh arity >> put_ bh sort put_ bh (IfaceSumTyCon arity) = putByte bh 2 >> put_ bh arity put_ bh IfaceEqualityTyCon = putByte bh 3 get bh = do n <- getByte bh case n of 0 -> return IfaceNormalTyCon 1 -> IfaceTupleTyCon <$> get bh <*> get bh 2 -> IfaceSumTyCon <$> get bh _ -> return IfaceEqualityTyCon instance Binary IfaceTyConInfo where put_ bh (IfaceTyConInfo i s) = put_ bh i >> put_ bh s get bh = IfaceTyConInfo <$> get bh <*> get bh instance Outputable IfaceTyLit where ppr = pprIfaceTyLit instance Binary IfaceTyLit where put_ bh (IfaceNumTyLit n) = putByte bh 1 >> put_ bh n put_ bh (IfaceStrTyLit n) = putByte bh 2 >> put_ bh n get bh = do tag <- getByte bh case tag of 1 -> do { n <- get bh ; return (IfaceNumTyLit n) } 2 -> do { n <- get bh ; return (IfaceStrTyLit n) } _ -> panic ("get IfaceTyLit " ++ show tag) instance Binary IfaceAppArgs where put_ bh tk = case tk of IA_Arg t a ts -> putByte bh 0 >> put_ bh t >> put_ bh a >> put_ bh ts IA_Nil -> putByte bh 1 get bh = do c <- getByte bh case c of 0 -> do t <- get bh a <- get bh ts <- get bh return $! IA_Arg t a ts 1 -> return IA_Nil _ -> panic ("get IfaceAppArgs " ++ show c) ------------------- -- Some notes about printing contexts -- -- In the event that we are printing a singleton context (e.g. @Eq a@) we can -- omit parentheses. However, we must take care to set the precedence correctly -- to opPrec, since something like @a :~: b@ must be parenthesized (see -- #9658). -- -- When printing a larger context we use 'fsep' instead of 'sep' so that -- the context doesn't get displayed as a giant column. Rather than, -- instance (Eq a, -- Eq b, -- Eq c, -- Eq d, -- Eq e, -- Eq f, -- Eq g, -- Eq h, -- Eq i, -- Eq j, -- Eq k, -- Eq l) => -- Eq (a, b, c, d, e, f, g, h, i, j, k, l) -- -- we want -- -- instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, -- Eq j, Eq k, Eq l) => -- Eq (a, b, c, d, e, f, g, h, i, j, k, l) -- | Prints "(C a, D b) =>", including the arrow. -- Used when we want to print a context in a type, so we -- use 'funPrec' to decide whether to parenthesise a singleton -- predicate; e.g. Num a => a -> a pprIfaceContextArr :: [IfacePredType] -> SDoc pprIfaceContextArr [] = empty pprIfaceContextArr [pred] = ppr_ty funPrec pred <+> darrow pprIfaceContextArr preds = ppr_parend_preds preds <+> darrow -- | Prints a context or @()@ if empty -- You give it the context precedence pprIfaceContext :: PprPrec -> [IfacePredType] -> SDoc pprIfaceContext _ [] = text "()" pprIfaceContext prec [pred] = ppr_ty prec pred pprIfaceContext _ preds = ppr_parend_preds preds ppr_parend_preds :: [IfacePredType] -> SDoc ppr_parend_preds preds = parens (fsep (punctuate comma (map ppr preds))) instance Binary IfaceType where put_ _ (IfaceFreeTyVar tv) = pprPanic "Can't serialise IfaceFreeTyVar" (ppr tv) put_ bh (IfaceForAllTy aa ab) = do putByte bh 0 put_ bh aa put_ bh ab put_ bh (IfaceTyVar ad) = do putByte bh 1 put_ bh ad put_ bh (IfaceAppTy ae af) = do putByte bh 2 put_ bh ae put_ bh af put_ bh (IfaceFunTy af aw ag ah) = do putByte bh 3 put_ bh af put_ bh aw put_ bh ag put_ bh ah put_ bh (IfaceTyConApp tc tys) = do { putByte bh 5; put_ bh tc; put_ bh tys } put_ bh (IfaceCastTy a b) = do { putByte bh 6; put_ bh a; put_ bh b } put_ bh (IfaceCoercionTy a) = do { putByte bh 7; put_ bh a } put_ bh (IfaceTupleTy s i tys) = do { putByte bh 8; put_ bh s; put_ bh i; put_ bh tys } put_ bh (IfaceLitTy n) = do { putByte bh 9; put_ bh n } get bh = do h <- getByte bh case h of 0 -> do aa <- get bh ab <- get bh return (IfaceForAllTy aa ab) 1 -> do ad <- get bh return (IfaceTyVar ad) 2 -> do ae <- get bh af <- get bh return (IfaceAppTy ae af) 3 -> do af <- get bh aw <- get bh ag <- get bh ah <- get bh return (IfaceFunTy af aw ag ah) 5 -> do { tc <- get bh; tys <- get bh ; return (IfaceTyConApp tc tys) } 6 -> do { a <- get bh; b <- get bh ; return (IfaceCastTy a b) } 7 -> do { a <- get bh ; return (IfaceCoercionTy a) } 8 -> do { s <- get bh; i <- get bh; tys <- get bh ; return (IfaceTupleTy s i tys) } _ -> do n <- get bh return (IfaceLitTy n) instance Binary IfaceMCoercion where put_ bh IfaceMRefl = do putByte bh 1 put_ bh (IfaceMCo co) = do putByte bh 2 put_ bh co get bh = do tag <- getByte bh case tag of 1 -> return IfaceMRefl 2 -> do a <- get bh return $ IfaceMCo a _ -> panic ("get IfaceMCoercion " ++ show tag) instance Binary IfaceCoercion where put_ bh (IfaceReflCo a) = do putByte bh 1 put_ bh a put_ bh (IfaceGReflCo a b c) = do putByte bh 2 put_ bh a put_ bh b put_ bh c put_ bh (IfaceFunCo a w b c) = do putByte bh 3 put_ bh a put_ bh w put_ bh b put_ bh c put_ bh (IfaceTyConAppCo a b c) = do putByte bh 4 put_ bh a put_ bh b put_ bh c put_ bh (IfaceAppCo a b) = do putByte bh 5 put_ bh a put_ bh b put_ bh (IfaceForAllCo a b c) = do putByte bh 6 put_ bh a put_ bh b put_ bh c put_ bh (IfaceCoVarCo a) = do putByte bh 7 put_ bh a put_ bh (IfaceAxiomInstCo a b c) = do putByte bh 8 put_ bh a put_ bh b put_ bh c put_ bh (IfaceUnivCo a b c d) = do putByte bh 9 put_ bh a put_ bh b put_ bh c put_ bh d put_ bh (IfaceSymCo a) = do putByte bh 10 put_ bh a put_ bh (IfaceTransCo a b) = do putByte bh 11 put_ bh a put_ bh b put_ bh (IfaceNthCo a b) = do putByte bh 12 put_ bh a put_ bh b put_ bh (IfaceLRCo a b) = do putByte bh 13 put_ bh a put_ bh b put_ bh (IfaceInstCo a b) = do putByte bh 14 put_ bh a put_ bh b put_ bh (IfaceKindCo a) = do putByte bh 15 put_ bh a put_ bh (IfaceSubCo a) = do putByte bh 16 put_ bh a put_ bh (IfaceAxiomRuleCo a b) = do putByte bh 17 put_ bh a put_ bh b put_ _ (IfaceFreeCoVar cv) = pprPanic "Can't serialise IfaceFreeCoVar" (ppr cv) put_ _ (IfaceHoleCo cv) = pprPanic "Can't serialise IfaceHoleCo" (ppr cv) -- See Note [Holes in IfaceCoercion] get bh = do tag <- getByte bh case tag of 1 -> do a <- get bh return $ IfaceReflCo a 2 -> do a <- get bh b <- get bh c <- get bh return $ IfaceGReflCo a b c 3 -> do a <- get bh w <- get bh b <- get bh c <- get bh return $ IfaceFunCo a w b c 4 -> do a <- get bh b <- get bh c <- get bh return $ IfaceTyConAppCo a b c 5 -> do a <- get bh b <- get bh return $ IfaceAppCo a b 6 -> do a <- get bh b <- get bh c <- get bh return $ IfaceForAllCo a b c 7 -> do a <- get bh return $ IfaceCoVarCo a 8 -> do a <- get bh b <- get bh c <- get bh return $ IfaceAxiomInstCo a b c 9 -> do a <- get bh b <- get bh c <- get bh d <- get bh return $ IfaceUnivCo a b c d 10-> do a <- get bh return $ IfaceSymCo a 11-> do a <- get bh b <- get bh return $ IfaceTransCo a b 12-> do a <- get bh b <- get bh return $ IfaceNthCo a b 13-> do a <- get bh b <- get bh return $ IfaceLRCo a b 14-> do a <- get bh b <- get bh return $ IfaceInstCo a b 15-> do a <- get bh return $ IfaceKindCo a 16-> do a <- get bh return $ IfaceSubCo a 17-> do a <- get bh b <- get bh return $ IfaceAxiomRuleCo a b _ -> panic ("get IfaceCoercion " ++ show tag) instance Binary IfaceUnivCoProv where put_ bh (IfacePhantomProv a) = do putByte bh 1 put_ bh a put_ bh (IfaceProofIrrelProv a) = do putByte bh 2 put_ bh a put_ bh (IfacePluginProv a) = do putByte bh 3 put_ bh a get bh = do tag <- getByte bh case tag of 1 -> do a <- get bh return $ IfacePhantomProv a 2 -> do a <- get bh return $ IfaceProofIrrelProv a 3 -> do a <- get bh return $ IfacePluginProv a _ -> panic ("get IfaceUnivCoProv " ++ show tag) instance Binary (DefMethSpec IfaceType) where put_ bh VanillaDM = putByte bh 0 put_ bh (GenericDM t) = putByte bh 1 >> put_ bh t get bh = do h <- getByte bh case h of 0 -> return VanillaDM _ -> do { t <- get bh; return (GenericDM t) } instance NFData IfaceType where rnf = \case IfaceFreeTyVar f1 -> f1 `seq` () IfaceTyVar f1 -> rnf f1 IfaceLitTy f1 -> rnf f1 IfaceAppTy f1 f2 -> rnf f1 `seq` rnf f2 IfaceFunTy f1 f2 f3 f4 -> f1 `seq` rnf f2 `seq` rnf f3 `seq` rnf f4 IfaceForAllTy f1 f2 -> f1 `seq` rnf f2 IfaceTyConApp f1 f2 -> rnf f1 `seq` rnf f2 IfaceCastTy f1 f2 -> rnf f1 `seq` rnf f2 IfaceCoercionTy f1 -> rnf f1 IfaceTupleTy f1 f2 f3 -> f1 `seq` f2 `seq` rnf f3 instance NFData IfaceTyLit where rnf = \case IfaceNumTyLit f1 -> rnf f1 IfaceStrTyLit f1 -> rnf f1 instance NFData IfaceCoercion where rnf = \case IfaceReflCo f1 -> rnf f1 IfaceGReflCo f1 f2 f3 -> f1 `seq` rnf f2 `seq` rnf f3 IfaceFunCo f1 f2 f3 f4 -> f1 `seq` rnf f2 `seq` rnf f3 `seq` rnf f4 IfaceTyConAppCo f1 f2 f3 -> f1 `seq` rnf f2 `seq` rnf f3 IfaceAppCo f1 f2 -> rnf f1 `seq` rnf f2 IfaceForAllCo f1 f2 f3 -> rnf f1 `seq` rnf f2 `seq` rnf f3 IfaceCoVarCo f1 -> rnf f1 IfaceAxiomInstCo f1 f2 f3 -> rnf f1 `seq` rnf f2 `seq` rnf f3 IfaceAxiomRuleCo f1 f2 -> rnf f1 `seq` rnf f2 IfaceUnivCo f1 f2 f3 f4 -> rnf f1 `seq` f2 `seq` rnf f3 `seq` rnf f4 IfaceSymCo f1 -> rnf f1 IfaceTransCo f1 f2 -> rnf f1 `seq` rnf f2 IfaceNthCo f1 f2 -> rnf f1 `seq` rnf f2 IfaceLRCo f1 f2 -> f1 `seq` rnf f2 IfaceInstCo f1 f2 -> rnf f1 `seq` rnf f2 IfaceKindCo f1 -> rnf f1 IfaceSubCo f1 -> rnf f1 IfaceFreeCoVar f1 -> f1 `seq` () IfaceHoleCo f1 -> f1 `seq` () instance NFData IfaceUnivCoProv where rnf x = seq x () instance NFData IfaceMCoercion where rnf x = seq x () instance NFData IfaceOneShot where rnf x = seq x () instance NFData IfaceTyConSort where rnf = \case IfaceNormalTyCon -> () IfaceTupleTyCon arity sort -> rnf arity `seq` sort `seq` () IfaceSumTyCon arity -> rnf arity IfaceEqualityTyCon -> () instance NFData IfaceTyConInfo where rnf (IfaceTyConInfo f s) = f `seq` rnf s instance NFData IfaceTyCon where rnf (IfaceTyCon nm info) = rnf nm `seq` rnf info instance NFData IfaceBndr where rnf = \case IfaceIdBndr id_bndr -> rnf id_bndr IfaceTvBndr tv_bndr -> rnf tv_bndr instance NFData IfaceAppArgs where rnf = \case IA_Nil -> () IA_Arg f1 f2 f3 -> rnf f1 `seq` f2 `seq` rnf f3
{ "pile_set_name": "Github" }
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ #ifndef __com_sun_star_form_FormButtonType_idl__ #define __com_sun_star_form_FormButtonType_idl__ module com { module sun { module star { module form { /** specifies the action to execute when a button is pressed. @see com::sun::star::form::component::CommandButton */ published enum FormButtonType { /** requires the button to act like a common push button, means no special action is triggered. */ PUSH, /** When the button is clicked, it performs a submit on its containing form. */ SUBMIT, /** When the button is clicked, it performs a reset on its containing form. */ RESET, /** When the button is clicked, a URL set for the button is opened. @see com::sun::star::form::component::CommandButton::TargetURL @see com::sun::star::form::component::CommandButton::TargetFrame */ URL }; }; }; }; }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
{ "pile_set_name": "Github" }
-- Copyright 2004-2020 H2 Group. Multiple-Licensed under the MPL 2.0, -- and the EPL 1.0 (https://h2database.com/html/license.html). -- Initial Developer: H2 Group -- SELECT QUOTE_IDENT(NULL); >> null SELECT QUOTE_IDENT(''); >> "" SELECT QUOTE_IDENT('a'); >> "a" SELECT QUOTE_IDENT('"a""A"'); >> """a""""A"""
{ "pile_set_name": "Github" }
#!/usr/bin/env python """ pcolormesh uses a QuadMesh, a faster generalization of pcolor, but with some restrictions. This demo illustrates a bug in quadmesh with masked data. """ import numpy as np from matplotlib.pyplot import figure, show, savefig from matplotlib import cm, colors from numpy import ma n = 12 x = np.linspace(-1.5, 1.5, n) y = np.linspace(-1.5, 1.5, n*2) X, Y = np.meshgrid(x, y) Qx = np.cos(Y) - np.cos(X) Qz = np.sin(Y) + np.sin(X) Qx = (Qx + 1.1) Z = np.sqrt(X**2 + Y**2)/5 Z = (Z - Z.min()) / (Z.max() - Z.min()) # The color array can include masked values: Zm = ma.masked_where(np.fabs(Qz) < 0.5*np.amax(Qz), Z) fig = figure() ax = fig.add_subplot(121) ax.set_axis_bgcolor("#bdb76b") ax.pcolormesh(Qx, Qz, Z, shading='gouraud') ax.set_title('Without masked values') ax = fig.add_subplot(122) ax.set_axis_bgcolor("#bdb76b") # You can control the color of the masked region: #cmap = cm.jet #cmap.set_bad('r', 1.0) #ax.pcolormesh(Qx,Qz,Zm, cmap=cmap) # Or use the default, which is transparent: col = ax.pcolormesh(Qx, Qz, Zm, shading='gouraud') ax.set_title('With masked values') show()
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Text; namespace Surging.Tools.Cli.Internal.Messages { public class HttpResultMessage<T> : HttpResultMessage { /// <summary> /// 数据集 /// </summary> public T Entity { get; set; } /// <summary> /// 生成自定义服务数据集 /// </summary> /// <param name="successd">状态值(true:成功 false:失败)</param> /// <param name="message">返回到客户端的消息</param> /// <param name="entity">返回到客户端的数据集</param> /// <returns>返回信息结果集</returns> public static HttpResultMessage<T> Create(bool successd, string message, T entity) { return new HttpResultMessage<T>() { IsSucceed = successd, Message = message, Entity = entity }; } /// <summary> /// 生成自定义服务数据集 /// </summary> /// <param name="successd">状态值(true:成功 false:失败)</param> /// <param name="entity">返回到客户端的数据集</param> /// <returns>返回信息结果集</returns> public static HttpResultMessage<T> Create(bool successd, T entity) { return new HttpResultMessage<T>() { IsSucceed = successd, Entity = entity }; } } public class HttpResultMessage { /// <summary> /// 生成错误信息 /// </summary> /// <param name="message">返回客户端的消息</param> /// <returns>返回服务数据集</returns> public static HttpResultMessage Error(string message) { return new HttpResultMessage() { Message = message, IsSucceed = false }; } /// <summary> /// 生成服务器数据集 /// </summary> /// <param name="success">状态值(true:成功 false:失败)</param> /// <param name="successMessage">返回客户端的消息</param> /// <param name="errorMessage">错误信息</param> /// <returns>返回服务数据集</returns> public static HttpResultMessage Create(bool success, string successMessage = "", string errorMessage = "") { return new HttpResultMessage() { Message = success ? successMessage : errorMessage, IsSucceed = success }; } /// <summary> /// 构造服务数据集 /// </summary> public HttpResultMessage() { IsSucceed = false; Message = string.Empty; } /// <summary> /// 状态值 /// </summary> public bool IsSucceed { get; set; } /// <summary> ///返回客户端的消息 /// </summary> public string Message { get; set; } /// <summary> /// 状态码 /// </summary> public int StatusCode { get; set; } } }
{ "pile_set_name": "Github" }
{ "name": "helloemit", "version": "0.0.5", "description": "This is the Hello World of Accord Protocol Templates with Emit.", "accordproject": { "template": "clause", "cicero": "^0.21.0" } }
{ "pile_set_name": "Github" }
<!-- This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> <!ENTITY connectionsDialog.title "Configuración da conexión"> <!ENTITY proxyTitle.label "Configurar proxy para acceder á Internet"> <!ENTITY noProxyTypeRadio.label "Sen proxy"> <!ENTITY noProxyTypeRadio.accesskey "y"> <!ENTITY systemTypeRadio.label "Usar a configuración do proxy do sistema"> <!ENTITY systemTypeRadio.accesskey "U"> <!ENTITY WPADTypeRadio.label "Detectar automaticamente a configuración do proxy para esta rede"> <!ENTITY WPADTypeRadio.accesskey "g"> <!ENTITY manualTypeRadio.label "Configuración manual do proxy:"> <!ENTITY manualTypeRadio.accesskey "m"> <!ENTITY autoTypeRadio.label "URL da configuración automática do proxy:"> <!ENTITY autoTypeRadio.accesskey "a"> <!ENTITY reload.label "Recargar"> <!ENTITY reload.accesskey "e"> <!ENTITY ftp.label "Proxy FTP:"> <!ENTITY ftp.accesskey "F"> <!ENTITY http.label "Proxy HTTP:"> <!ENTITY http.accesskey "H"> <!ENTITY ssl.label "Proxy SSL:"> <!ENTITY ssl.accesskey "L"> <!ENTITY socks.label "Servidor SOCKS:"> <!ENTITY socks.accesskey "C"> <!ENTITY socks4.label "SOCKS v4"> <!ENTITY socks4.accesskey "K"> <!ENTITY socks5.label "SOCKS v5"> <!ENTITY socks5.accesskey "v"> <!ENTITY socksRemoteDNS.accesskey "d"> <!ENTITY port.label "Porto:"> <!ENTITY HTTPport.accesskey "P"> <!ENTITY SSLport.accesskey "o"> <!ENTITY FTPport.accesskey "r"> <!ENTITY SOCKSport.accesskey "t"> <!ENTITY noproxy.label "Sen proxy para:"> <!ENTITY noproxy.accesskey "n"> <!ENTITY noproxyExplain.label "Exemplo: .mozilla.org, .net.nz, 192.168.1.0/24"> <!ENTITY shareproxy.label "Usar este servidor proxy para todos os protocolos"> <!ENTITY shareproxy.accesskey "s"> <!ENTITY autologinproxy.label "Non preguntar autenticación se o contrasinal está gardado"> <!ENTITY autologinproxy.accesskey "i"> <!ENTITY autologinproxy.tooltip "Esta opción autentícao silenciosamente cos proxy cando gardou as credenciais para eles. Preguntaráselle cando falle a autenticación. "> <!ENTITY socksRemoteDNS.label2 "Proxy DNS when using SOCKS v5"> <!ENTITY window.macWidth2 "44em"> <!ENTITY window.width2 "49em">
{ "pile_set_name": "Github" }
using System.Collections.Generic; using System.Threading.Tasks; using ReactiveUI; using CodeHub.Core.Services; using System.Reactive; using System; using Octokit; using System.Reactive.Linq; using Splat; using CodeHub.Core.Messages; namespace CodeHub.Core.ViewModels.Gists { public class CurrentUserGistsViewModel : GistsViewModel { private readonly IDisposable _addToken; public CurrentUserGistsViewModel(string username, IMessageService messageService = null) : base(ApiUrls.UsersGists(username)) { messageService = messageService ?? Locator.Current.GetService<IMessageService>(); _addToken = messageService.Listen<GistAddMessage>(msg => Gists.Insert(0, msg.Gist)); } } public class GistsViewModel : ReactiveObject { private readonly IApplicationService _applicationService; private readonly IAlertDialogService _dialogService; private readonly ReactiveList<Gist> _internalItems = new ReactiveList<Gist>(resetChangeThreshold: double.MaxValue); public ReactiveCommand<Unit, bool> LoadCommand { get; } public ReactiveCommand<Unit, bool> LoadMoreCommand { get; } public IReadOnlyReactiveList<GistItemViewModel> Items { get; private set; } protected ReactiveList<Gist> Gists => _internalItems; public ReactiveCommand<GistItemViewModel, GistItemViewModel> ItemSelected { get; } private ObservableAsPropertyHelper<bool> _hasMore; public bool HasMore => _hasMore.Value; private Uri _nextPage; private Uri NextPage { get { return _nextPage; } set { this.RaiseAndSetIfChanged(ref _nextPage, value); } } private string _searchText; public string SearchText { get { return _searchText; } set { this.RaiseAndSetIfChanged(ref _searchText, value); } } private readonly ObservableAsPropertyHelper<bool> _isEmpty; public bool IsEmpty => _isEmpty.Value; public static GistsViewModel CreatePublicGistsViewModel() => new GistsViewModel(ApiUrls.PublicGists()); public static GistsViewModel CreateStarredGistsViewModel() => new GistsViewModel(ApiUrls.StarredGists()); public static GistsViewModel CreateUserGistsViewModel(string username) => new GistsViewModel(ApiUrls.UsersGists(username)); public GistsViewModel( Uri uri, IApplicationService applicationService = null, IAlertDialogService dialogService = null) { _applicationService = applicationService ?? Locator.Current.GetService<IApplicationService>(); _dialogService = dialogService ?? Locator.Current.GetService<IAlertDialogService>(); NextPage = uri; var showDescription = _applicationService.Account.ShowRepositoryDescriptionInList; ItemSelected = ReactiveCommand.Create<GistItemViewModel, GistItemViewModel>(x => x); var gistItems = _internalItems.CreateDerivedCollection( x => new GistItemViewModel(x, GoToItem)); var searchUpdated = this.WhenAnyValue(x => x.SearchText) .Throttle(TimeSpan.FromMilliseconds(400), RxApp.MainThreadScheduler); Items = gistItems.CreateDerivedCollection( x => x, x => x.Title.ContainsKeyword(SearchText) || x.Description.ContainsKeyword(SearchText), signalReset: searchUpdated); LoadCommand = ReactiveCommand.CreateFromTask(async t => { _internalItems.Clear(); var parameters = new Dictionary<string, string> { ["per_page"] = 100.ToString() }; var items = await RetrieveItems(uri, parameters); _internalItems.AddRange(items); return items.Count > 0; }); var canLoadMore = this.WhenAnyValue(x => x.NextPage).Select(x => x != null); LoadMoreCommand = ReactiveCommand.CreateFromTask(async _ => { var items = await RetrieveItems(NextPage); _internalItems.AddRange(items); return items.Count > 0; }, canLoadMore); LoadCommand.Select(_ => _internalItems.Count == 0) .ToProperty(this, x => x.IsEmpty, out _isEmpty, true); LoadCommand.ThrownExceptions.Subscribe(LoadingError); LoadMoreCommand.ThrownExceptions.Subscribe(LoadingError); _hasMore = this.WhenAnyValue(x => x.NextPage) .Select(x => x != null) .ToProperty(this, x => x.HasMore); } private void LoadingError(Exception err) { _dialogService.Alert("Error Loading", err.Message).ToBackground(); } private void GoToItem(GistItemViewModel item) { ItemSelected.ExecuteNow(item); } private async Task<IReadOnlyList<Gist>> RetrieveItems( Uri repositoriesUri, IDictionary<string, string> parameters = null) { try { var connection = _applicationService.GitHubClient.Connection; var ret = await connection.Get<IReadOnlyList<Gist>>(repositoriesUri, parameters, "application/json"); NextPage = ret.HttpResponse.ApiInfo.Links.ContainsKey("next") ? ret.HttpResponse.ApiInfo.Links["next"] : null; return ret.Body; } catch { NextPage = null; throw; } } } }
{ "pile_set_name": "Github" }
div { margin: 0.6em 0 1.8em; }
{ "pile_set_name": "Github" }
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/logging/type/http_request.proto package ltype import ( fmt "fmt" proto "github.com/golang/protobuf/proto" duration "github.com/golang/protobuf/ptypes/duration" _ "google.golang.org/genproto/googleapis/api/annotations" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // A common proto for logging HTTP requests. Only contains semantics // defined by the HTTP specification. Product-specific logging // information MUST be defined in a separate message. type HttpRequest struct { // The request method. Examples: `"GET"`, `"HEAD"`, `"PUT"`, `"POST"`. RequestMethod string `protobuf:"bytes,1,opt,name=request_method,json=requestMethod,proto3" json:"request_method,omitempty"` // The scheme (http, https), the host name, the path and the query // portion of the URL that was requested. // Example: `"http://example.com/some/info?color=red"`. RequestUrl string `protobuf:"bytes,2,opt,name=request_url,json=requestUrl,proto3" json:"request_url,omitempty"` // The size of the HTTP request message in bytes, including the request // headers and the request body. RequestSize int64 `protobuf:"varint,3,opt,name=request_size,json=requestSize,proto3" json:"request_size,omitempty"` // The response code indicating the status of response. // Examples: 200, 404. Status int32 `protobuf:"varint,4,opt,name=status,proto3" json:"status,omitempty"` // The size of the HTTP response message sent back to the client, in bytes, // including the response headers and the response body. ResponseSize int64 `protobuf:"varint,5,opt,name=response_size,json=responseSize,proto3" json:"response_size,omitempty"` // The user agent sent by the client. Example: // `"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET CLR 1.0.3705)"`. UserAgent string `protobuf:"bytes,6,opt,name=user_agent,json=userAgent,proto3" json:"user_agent,omitempty"` // The IP address (IPv4 or IPv6) of the client that issued the HTTP // request. Examples: `"192.168.1.1"`, `"FE80::0202:B3FF:FE1E:8329"`. RemoteIp string `protobuf:"bytes,7,opt,name=remote_ip,json=remoteIp,proto3" json:"remote_ip,omitempty"` // The IP address (IPv4 or IPv6) of the origin server that the request was // sent to. ServerIp string `protobuf:"bytes,13,opt,name=server_ip,json=serverIp,proto3" json:"server_ip,omitempty"` // The referer URL of the request, as defined in // [HTTP/1.1 Header Field Definitions](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). Referer string `protobuf:"bytes,8,opt,name=referer,proto3" json:"referer,omitempty"` // The request processing latency on the server, from the time the request was // received until the response was sent. Latency *duration.Duration `protobuf:"bytes,14,opt,name=latency,proto3" json:"latency,omitempty"` // Whether or not a cache lookup was attempted. CacheLookup bool `protobuf:"varint,11,opt,name=cache_lookup,json=cacheLookup,proto3" json:"cache_lookup,omitempty"` // Whether or not an entity was served from cache // (with or without validation). CacheHit bool `protobuf:"varint,9,opt,name=cache_hit,json=cacheHit,proto3" json:"cache_hit,omitempty"` // Whether or not the response was validated with the origin server before // being served from cache. This field is only meaningful if `cache_hit` is // True. CacheValidatedWithOriginServer bool `protobuf:"varint,10,opt,name=cache_validated_with_origin_server,json=cacheValidatedWithOriginServer,proto3" json:"cache_validated_with_origin_server,omitempty"` // The number of HTTP response bytes inserted into cache. Set only when a // cache fill was attempted. CacheFillBytes int64 `protobuf:"varint,12,opt,name=cache_fill_bytes,json=cacheFillBytes,proto3" json:"cache_fill_bytes,omitempty"` // Protocol used for the request. Examples: "HTTP/1.1", "HTTP/2", "websocket" Protocol string `protobuf:"bytes,15,opt,name=protocol,proto3" json:"protocol,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *HttpRequest) Reset() { *m = HttpRequest{} } func (m *HttpRequest) String() string { return proto.CompactTextString(m) } func (*HttpRequest) ProtoMessage() {} func (*HttpRequest) Descriptor() ([]byte, []int) { return fileDescriptor_ea45f4ec7ed7b641, []int{0} } func (m *HttpRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_HttpRequest.Unmarshal(m, b) } func (m *HttpRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_HttpRequest.Marshal(b, m, deterministic) } func (m *HttpRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_HttpRequest.Merge(m, src) } func (m *HttpRequest) XXX_Size() int { return xxx_messageInfo_HttpRequest.Size(m) } func (m *HttpRequest) XXX_DiscardUnknown() { xxx_messageInfo_HttpRequest.DiscardUnknown(m) } var xxx_messageInfo_HttpRequest proto.InternalMessageInfo func (m *HttpRequest) GetRequestMethod() string { if m != nil { return m.RequestMethod } return "" } func (m *HttpRequest) GetRequestUrl() string { if m != nil { return m.RequestUrl } return "" } func (m *HttpRequest) GetRequestSize() int64 { if m != nil { return m.RequestSize } return 0 } func (m *HttpRequest) GetStatus() int32 { if m != nil { return m.Status } return 0 } func (m *HttpRequest) GetResponseSize() int64 { if m != nil { return m.ResponseSize } return 0 } func (m *HttpRequest) GetUserAgent() string { if m != nil { return m.UserAgent } return "" } func (m *HttpRequest) GetRemoteIp() string { if m != nil { return m.RemoteIp } return "" } func (m *HttpRequest) GetServerIp() string { if m != nil { return m.ServerIp } return "" } func (m *HttpRequest) GetReferer() string { if m != nil { return m.Referer } return "" } func (m *HttpRequest) GetLatency() *duration.Duration { if m != nil { return m.Latency } return nil } func (m *HttpRequest) GetCacheLookup() bool { if m != nil { return m.CacheLookup } return false } func (m *HttpRequest) GetCacheHit() bool { if m != nil { return m.CacheHit } return false } func (m *HttpRequest) GetCacheValidatedWithOriginServer() bool { if m != nil { return m.CacheValidatedWithOriginServer } return false } func (m *HttpRequest) GetCacheFillBytes() int64 { if m != nil { return m.CacheFillBytes } return 0 } func (m *HttpRequest) GetProtocol() string { if m != nil { return m.Protocol } return "" } func init() { proto.RegisterType((*HttpRequest)(nil), "google.logging.type.HttpRequest") } func init() { proto.RegisterFile("google/logging/type/http_request.proto", fileDescriptor_ea45f4ec7ed7b641) } var fileDescriptor_ea45f4ec7ed7b641 = []byte{ // 511 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x92, 0x5b, 0x6b, 0x14, 0x31, 0x18, 0x86, 0x99, 0x1e, 0xf6, 0x90, 0x3d, 0x58, 0x22, 0x68, 0xba, 0x6a, 0x5d, 0x2b, 0xca, 0x5c, 0xcd, 0x80, 0xbd, 0x11, 0xbc, 0x72, 0x15, 0x6d, 0xa5, 0x62, 0x99, 0x7a, 0x00, 0x59, 0x18, 0x66, 0x77, 0xbf, 0x9d, 0x09, 0x66, 0x27, 0x31, 0xc9, 0x54, 0xb6, 0x7f, 0xc6, 0x7b, 0x6f, 0xfc, 0x1f, 0xfe, 0x2a, 0xc9, 0x97, 0x0c, 0x28, 0xf4, 0x66, 0x21, 0xef, 0xf3, 0xbc, 0x49, 0xf6, 0x9b, 0x90, 0xa7, 0xa5, 0x94, 0xa5, 0x80, 0x54, 0xc8, 0xb2, 0xe4, 0x75, 0x99, 0xda, 0xad, 0x82, 0xb4, 0xb2, 0x56, 0xe5, 0x1a, 0xbe, 0x37, 0x60, 0x6c, 0xa2, 0xb4, 0xb4, 0x92, 0xde, 0xf6, 0x5e, 0x12, 0xbc, 0xc4, 0x79, 0x93, 0xfb, 0xa1, 0x5c, 0x28, 0x9e, 0x16, 0x75, 0x2d, 0x6d, 0x61, 0xb9, 0xac, 0x8d, 0xaf, 0x4c, 0x8e, 0x02, 0xc5, 0xd5, 0xa2, 0x59, 0xa7, 0xab, 0x46, 0xa3, 0xe0, 0xf9, 0xf1, 0xef, 0x3d, 0x32, 0x38, 0xb5, 0x56, 0x65, 0xfe, 0x20, 0xfa, 0x84, 0x8c, 0xc3, 0x99, 0xf9, 0x06, 0x6c, 0x25, 0x57, 0x2c, 0x9a, 0x46, 0x71, 0x3f, 0x1b, 0x85, 0xf4, 0x3d, 0x86, 0xf4, 0x21, 0x19, 0xb4, 0x5a, 0xa3, 0x05, 0xdb, 0x41, 0x87, 0x84, 0xe8, 0x93, 0x16, 0xf4, 0x11, 0x19, 0xb6, 0x82, 0xe1, 0xd7, 0xc0, 0x76, 0xa7, 0x51, 0xbc, 0x9b, 0xb5, 0xa5, 0x4b, 0x7e, 0x0d, 0xf4, 0x0e, 0xe9, 0x18, 0x5b, 0xd8, 0xc6, 0xb0, 0xbd, 0x69, 0x14, 0xef, 0x67, 0x61, 0x45, 0x1f, 0x93, 0x91, 0x06, 0xa3, 0x64, 0x6d, 0xc0, 0x77, 0xf7, 0xb1, 0x3b, 0x6c, 0x43, 0x2c, 0x3f, 0x20, 0xa4, 0x31, 0xa0, 0xf3, 0xa2, 0x84, 0xda, 0xb2, 0x0e, 0x9e, 0xdf, 0x77, 0xc9, 0x4b, 0x17, 0xd0, 0x7b, 0xa4, 0xaf, 0x61, 0x23, 0x2d, 0xe4, 0x5c, 0xb1, 0x2e, 0xd2, 0x9e, 0x0f, 0xce, 0x94, 0x83, 0x06, 0xf4, 0x15, 0x68, 0x07, 0x47, 0x1e, 0xfa, 0xe0, 0x4c, 0x51, 0x46, 0xba, 0x1a, 0xd6, 0xa0, 0x41, 0xb3, 0x1e, 0xa2, 0x76, 0x49, 0x4f, 0x48, 0x57, 0x14, 0x16, 0xea, 0xe5, 0x96, 0x8d, 0xa7, 0x51, 0x3c, 0x78, 0x76, 0x98, 0x84, 0xef, 0xd1, 0x0e, 0x37, 0x79, 0x1d, 0x86, 0x9b, 0xb5, 0xa6, 0x9b, 0xc3, 0xb2, 0x58, 0x56, 0x90, 0x0b, 0x29, 0xbf, 0x35, 0x8a, 0x0d, 0xa6, 0x51, 0xdc, 0xcb, 0x06, 0x98, 0x9d, 0x63, 0xe4, 0xae, 0xe3, 0x95, 0x8a, 0x5b, 0xd6, 0x47, 0xde, 0xc3, 0xe0, 0x94, 0x5b, 0xfa, 0x8e, 0x1c, 0x7b, 0x78, 0x55, 0x08, 0xbe, 0x2a, 0x2c, 0xac, 0xf2, 0x1f, 0xdc, 0x56, 0xb9, 0xd4, 0xbc, 0xe4, 0x75, 0xee, 0xaf, 0xcd, 0x08, 0xb6, 0x8e, 0xd0, 0xfc, 0xdc, 0x8a, 0x5f, 0xb8, 0xad, 0x3e, 0xa0, 0x76, 0x89, 0x16, 0x8d, 0xc9, 0x81, 0xdf, 0x6b, 0xcd, 0x85, 0xc8, 0x17, 0x5b, 0x0b, 0x86, 0x0d, 0x71, 0xb6, 0x63, 0xcc, 0xdf, 0x70, 0x21, 0x66, 0x2e, 0xa5, 0x13, 0xd2, 0xc3, 0xff, 0xb4, 0x94, 0x82, 0xdd, 0xf2, 0x03, 0x6a, 0xd7, 0xb3, 0x9f, 0x11, 0xb9, 0xbb, 0x94, 0x9b, 0xe4, 0x86, 0xb7, 0x38, 0x3b, 0xf8, 0xe7, 0x29, 0x5d, 0xb8, 0xc2, 0x45, 0xf4, 0xf5, 0x79, 0x10, 0x4b, 0x29, 0x8a, 0xba, 0x4c, 0xa4, 0x2e, 0xd3, 0x12, 0x6a, 0xdc, 0x2e, 0xf5, 0xa8, 0x50, 0xdc, 0xfc, 0xf7, 0xf6, 0x5f, 0x08, 0xf7, 0xfb, 0x6b, 0xe7, 0xf0, 0xad, 0xaf, 0xbe, 0x12, 0xb2, 0x59, 0x25, 0xe7, 0xe1, 0xa4, 0x8f, 0x5b, 0x05, 0x7f, 0x5a, 0x36, 0x47, 0x36, 0x0f, 0x6c, 0xee, 0xd8, 0xa2, 0x83, 0x9b, 0x9f, 0xfc, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x7d, 0xa3, 0x36, 0xbb, 0x57, 0x03, 0x00, 0x00, }
{ "pile_set_name": "Github" }
require(['jquery','lzo1x', 'lzo-lvar', 'lzo-decomp', 'bluebird'], function ($,lzo1x_mod, lzo_lvar_mod, lzo_decomp, Promise) { // Value of undefined. var UNDEFINED = void 0; /** * Wrap value as a resolved promise. */ function resolve(value) { return Promise.resolve(value); } /** * Wrap value as a rejected promise. */ function reject(reason) { return Promise.reject(reason); } /** * For sliceThen(..).exec(proc, ..), mark what proc function returns is multiple values * to be used by further Promise#spread(..) call. */ function spreadus() { var args = Array.prototype.slice.apply(arguments); args._spreadus_ = true; return args; } function sliceThen(file, offset, len) { var p = new Promise(function(_resolve) { var reader = new FileReader(); reader.onload = function() { _resolve(reader.result); } // console.log('slice: ', offset, ' + ', len); if (arguments.length === 3 ) { reader.readAsArrayBuffer(file.slice(offset, offset + len)); // It's an asynchronous call! } else { reader.readAsArrayBuffer(file); } }); /** * Call proc with specified arguments prepending with sliced file/blob data (ArrayBuffer) been read. * @param first argument is a function to be executed * @param other optional arguments to be passed to function following auto supplied input ArrayBuffer * @return a promise object which can be chained with further process through spread() method */ p.exec = function(proc /*, args... */) { var args = Array.prototype.slice.call(arguments, 1); return p.then(function(data) { args.unshift(data); var ret = proc.apply(null, args); return resolve(ret !== UNDEFINED && ret._spreadus_ ? ret : [ret]); }); }; return p; } var COUNT = 20; function compress(input) { console.log('start to compress...') var t = performance.now(); var state = {inputBuffer: new Uint8Array(input)}; switch (lzo1x.compress(state)) { case 0: console.log('compression speed(Mb/s): ', 1000 * input.byteLength / (performance.now() - t) / 1024 /1024); return spreadus(input, state.outputBuffer); default: throw "Failed to compress"; } } function t1(origin, comp) { //* var t = performance.now(); for (var i = 0; i < COUNT; i++) { var state = {inputBuffer: comp}; lzo1x.decompress(state); } t = (performance.now() - t) * 1024 * 1024 / 1000 / COUNT; console.log('t1 speed(Mb/s): ', comp.byteLength / t); console.log('t1 speed(Mb/s): ', origin.byteLength / t); console.log(origin.byteLength, comp.byteLength, state.outputBuffer.length); //*/ return spreadus(origin, comp); } function t2(origin, comp) { var t = performance.now(); for (var i = 0; i < COUNT; i++) { var state = {inputBuffer: comp}; lzo1x_lvar.decompress(state); } t = (performance.now() - t) * 1024 * 1024 / 1000 / COUNT; console.log('t2 speed(Mb/s): ', comp.byteLength / t); console.log('t2 speed(Mb/s): ', origin.byteLength / t); console.log(origin.byteLength, comp.byteLength, state.outputBuffer.length); return spreadus(origin, comp); } function t3(origin, comp) { //* // var flex = lzo_decomp.createFlexBuffer(origin.byteLength, 4096 * 32); var options = {blockSize: 4096 * 32}; var t = performance.now(); for (var i = 0; i < COUNT; i++) { var state = {inputBuffer: comp}; var decomp = lzo_decomp.decompress(comp, options); } t = (performance.now() - t) * 1024 * 1024 / 1000 / COUNT; console.log('t3 speed(Mb/s): ', comp.byteLength / t); console.log('t3 speed(Mb/s): ', origin.byteLength / t); console.log(origin.byteLength, comp.byteLength, decomp.length); //*/ return spreadus(origin, comp); } $(function() { $('#fileset').on('change', function(e) { var fileList = $(e.target).prop('files'); console.log(fileList); for (var i = 0; i < fileList.length; i++) { var f = fileList[i]; sliceThen(f) .exec(compress) .spread(function(input, output) { console.log(input.byteLength + ' -> ' + output.length); return spreadus(input, output); }) /*/ .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) .spread(t1) .spread(t3) //*/ .spread(t1) .spread(t3) ; } }); }); });
{ "pile_set_name": "Github" }
/* * This is the header file for the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. * * Changed so as no longer to depend on Colin Plumb's `usual.h' * header definitions * - Ian Jackson <[email protected]>. * Still in the public domain. */ #ifndef MD5_UTILS_H_ #define MD5_UTILS_H_ #ifdef __cplusplus extern "C" { #endif #define md5byte unsigned char #define UWORD32 unsigned int typedef struct MD5Context MD5Context; struct MD5Context { UWORD32 buf[4]; UWORD32 bytes[2]; UWORD32 in[16]; }; void MD5Init(struct MD5Context *context); void MD5Update(struct MD5Context *context, md5byte const *buf, unsigned len); void MD5Final(unsigned char digest[16], struct MD5Context *context); void MD5Transform(UWORD32 buf[4], UWORD32 const in[16]); #ifdef __cplusplus } // extern "C" #endif #endif // MD5_UTILS_H_
{ "pile_set_name": "Github" }
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/about'
{ "pile_set_name": "Github" }
// Boost.Assign library // // Copyright Thorsten Ottosen 2003-2004. Use, modification and // distribution is subject to 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) // // For more information, see http://www.boost.org/libs/assign/ // #ifndef BOOST_ASSIGN_STD_SET_HPP #define BOOST_ASSIGN_STD_SET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include <boost/assign/list_inserter.hpp> #include <boost/config.hpp> #include <set> namespace boost { namespace assign { template< class K, class C, class A, class K2 > inline list_inserter< assign_detail::call_insert< std::set<K,C,A> >, K > operator+=( std::set<K,C,A>& c, K2 k ) { return insert( c )( k ); } template< class K, class C, class A, class K2 > inline list_inserter< assign_detail::call_insert< std::multiset<K,C,A> >, K > operator+=( std::multiset<K,C,A>& c, K2 k ) { return insert( c )( k ); } } } #endif
{ "pile_set_name": "Github" }
[android-components](../../../index.md) / [mozilla.components.concept.engine](../../index.md) / [HitResult](../index.md) / [EMAIL](index.md) / [&lt;init&gt;](./-init-.md) # &lt;init&gt; `EMAIL(src: `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`)` The type used if the URI is prepended with 'mailto:'.
{ "pile_set_name": "Github" }
/* * Copyright 2015-2016 RonCoo(http://www.roncoo.com) Group. * * 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.roncoo.adminlte.service; import java.util.List; import com.roncoo.adminlte.bean.entity.RcEmailAccountInfo; import com.roncoo.adminlte.bean.vo.Result; import com.roncoo.adminlte.util.base.Page; /** * 邮件账号服务功能 * * @author LYQ */ public interface EmailAccountInfoService { /** * 分页查询 * * @param page * @param example * @return */ Result<Page<RcEmailAccountInfo>> listForPage(int pageCurrent, int pageSize,String premise,String datePremise); /** * 根据id查询 * * @param id * @return */ Result<RcEmailAccountInfo> query(Long id); /** * 添加 * * @param info */ Result<RcEmailAccountInfo> save(RcEmailAccountInfo info); /** * 根据id删除 * * @param id */ Result<RcEmailAccountInfo> delete(Long id); /** * 更新 * * @param info * @return */ Result<RcEmailAccountInfo> update(RcEmailAccountInfo info); /** * @return */ Result<List<RcEmailAccountInfo>> list(); }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <Scheme LastUpgradeVersion = "0460" version = "1.3"> <BuildAction parallelizeBuildables = "YES" buildImplicitDependencies = "YES"> <BuildActionEntries> <BuildActionEntry buildForTesting = "YES" buildForRunning = "YES" buildForProfiling = "YES" buildForArchiving = "YES" buildForAnalyzing = "YES"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "1D09EE3417B12E7F005E521C" BuildableName = "OpenWeatherMapAPI-OSX.app" BlueprintName = "OpenWeatherMapAPI-OSX" ReferencedContainer = "container:OpenWeatherMapAPI.xcodeproj"> </BuildableReference> </BuildActionEntry> </BuildActionEntries> </BuildAction> <TestAction selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv = "YES" buildConfiguration = "Debug"> <Testables> </Testables> <MacroExpansion> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "1D09EE3417B12E7F005E521C" BuildableName = "OpenWeatherMapAPI-OSX.app" BlueprintName = "OpenWeatherMapAPI-OSX" ReferencedContainer = "container:OpenWeatherMapAPI.xcodeproj"> </BuildableReference> </MacroExpansion> </TestAction> <LaunchAction selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" launchStyle = "0" useCustomWorkingDirectory = "NO" buildConfiguration = "Debug" ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" allowLocationSimulation = "YES"> <BuildableProductRunnable> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "1D09EE3417B12E7F005E521C" BuildableName = "OpenWeatherMapAPI-OSX.app" BlueprintName = "OpenWeatherMapAPI-OSX" ReferencedContainer = "container:OpenWeatherMapAPI.xcodeproj"> </BuildableReference> </BuildableProductRunnable> <AdditionalOptions> </AdditionalOptions> </LaunchAction> <ProfileAction shouldUseLaunchSchemeArgsEnv = "YES" savedToolIdentifier = "" useCustomWorkingDirectory = "NO" buildConfiguration = "Release" debugDocumentVersioning = "YES"> <BuildableProductRunnable> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "1D09EE3417B12E7F005E521C" BuildableName = "OpenWeatherMapAPI-OSX.app" BlueprintName = "OpenWeatherMapAPI-OSX" ReferencedContainer = "container:OpenWeatherMapAPI.xcodeproj"> </BuildableReference> </BuildableProductRunnable> </ProfileAction> <AnalyzeAction buildConfiguration = "Debug"> </AnalyzeAction> <ArchiveAction buildConfiguration = "Release" revealArchiveInOrganizer = "YES"> </ArchiveAction> </Scheme>
{ "pile_set_name": "Github" }
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2019, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. ---------------------------------------------------------------------- */ /** @file Defines the helper data structures for importing 3DS files. http://www.jalix.org/ressources/graphics/3DS/_unofficials/3ds-unofficial.txt */ #ifndef AI_SMOOTHINGGROUPS_H_INC #define AI_SMOOTHINGGROUPS_H_INC #include <assimp/vector3.h> #include <stdint.h> #include <vector> // --------------------------------------------------------------------------- /** Helper structure representing a face with smoothing groups assigned */ struct FaceWithSmoothingGroup { FaceWithSmoothingGroup() AI_NO_EXCEPT : mIndices() , iSmoothGroup(0) { // in debug builds set all indices to a common magic value #ifdef ASSIMP_BUILD_DEBUG this->mIndices[0] = 0xffffffff; this->mIndices[1] = 0xffffffff; this->mIndices[2] = 0xffffffff; #endif } //! Indices. .3ds is using uint16. However, after //! an unique vertex set has been generated, //! individual index values might exceed 2^16 uint32_t mIndices[3]; //! specifies to which smoothing group the face belongs to uint32_t iSmoothGroup; }; // --------------------------------------------------------------------------- /** Helper structure representing a mesh whose faces have smoothing groups assigned. This allows us to reuse the code for normal computations from smoothings groups for several loaders (3DS, ASE). All of them use face structures which inherit from #FaceWithSmoothingGroup, but as they add extra members and need to be copied by value we need to use a template here. */ template <class T> struct MeshWithSmoothingGroups { //! Vertex positions std::vector<aiVector3D> mPositions; //! Face lists std::vector<T> mFaces; //! List of normal vectors std::vector<aiVector3D> mNormals; }; // --------------------------------------------------------------------------- /** Computes normal vectors for the mesh */ template <class T> void ComputeNormalsWithSmoothingsGroups(MeshWithSmoothingGroups<T>& sMesh); // include implementations #include "SmoothingGroups.inl" #endif // !! AI_SMOOTHINGGROUPS_H_INC
{ "pile_set_name": "Github" }
function [currentSol, allObjValues, allSolutions] = optimizeCbModelNLP(model, varargin) % Optimizes constraint-based model using a non-linear objective % % USAGE: % % [currentSol, allObjValues, allSolutions] = optimizeCbModelNLP(model, varargin) % % INPUT: % model: COBRA model structure % % Optional inputs are parameter/value pairs % % OPTIONAL INPUT: % objFunction: Name of the non-linear matlab function to be optimized (the % corresponding m-file must be in the current matlab path) % The function receives two arguments, the current flux % vector, and the `NLPProblem` structure. % initFunction: Name of the matlab function used to generate random initial % starting points. The function will be supplied with two % arguments: the model and a cell array of input arguments % (specified in the initArgs parameter) % osenseStr: Optimization direction ('max' or 'min'), this will % override any mention in the model. % nOpt: Number of independent optimization runs performed % objArgs: Cell array of arguments that are supplied to the % objective function as `objArguments` in the NLPProblem % structure (i.e. the second element, will have a field % `objArguments`.) % initArgs: Cell array of arguments to the 'initFunction', will be % provided as second input Argument to the `initFunction` % solveroptions: A Struct with options for the solver used. This is % specific to the solver in question, but the fields should % relate to options accepted by the solver. % % OUTPUTS: % currentSol: Solution structure % allObjValues: Array of objective value of each iteration % allSolutions: Array of flux distribution of each iteration % % .. Authors: % - Markus Herrgard 8/24/07 % - Modified for new options in solveCobraNLP by Daniel Zielinski 3/19/10 % - Changed the function to use parameter/value pairs, Thomas Pfau 07/22/17 global CBT_NLP_SOLVER defaultosenseStr = 'max'; if isfield(model,'osenseStr') defaultosenseStr = model.osenseStr; end defaultObjFunction = 'NLPobjPerFlux'; defaultInitFunction = 'randomObjFBASol'; p = inputParser; addRequired(p,'model',@isstruct) addParamValue(p,'objFunction',defaultObjFunction,@ischar) addParamValue(p,'initFunction',defaultInitFunction,@ischar) addParamValue(p,'osenseStr',defaultosenseStr,@(x) strcmp(x,'min') | strcmp(x,'max')); addParamValue(p,'nOpt',100,@(x) rem(x,1) == 0); addParamValue(p,'objArgs',{},@iscell) addParamValue(p,'initArgs',[],@iscell) addParamValue(p,'solverOptions',[],@isstruct) parse(p,model,varargin{:}); [osenseStr,objFunction,initFunction,nOpt,objArgs,initArgs,solverOptions] = ... deal( p.Results.osenseStr,p.Results.objFunction,p.Results.initFunction, ... p.Results.nOpt,p.Results.objArgs,p.Results.initArgs, p.Results.solverOptions); %To assure, that we don't have any complications, we replace the model %osenseStr during the processing. model.osenseStr = osenseStr; if strcmp(osenseStr,'max') osense = -1; else osense = 1; end %Set some defaults for fmincon: if isnumeric(solverOptions) if strcmp(CBT_NLP_SOLVER,'matlab') if verLessThan('matlab','9') solverOptions = struct('TolFun',1e-20); else solverOptions = struct('FunctionTolerance', 1e-20,'OptimalityTolerance',1e-20); end else solverOptions = struct(); end end %Set default values, if they are not set. if ~isfield(solverOptions,'iterationLimit') solverOptions.iterationLimit = 100000; end if ~isfield(solverOptions,'printLevel') solverOptions.printLevel = 3; %3 prints every iteration. 1 does a summary. 0 = silent. end %The same as above for the objective Function if strcmp(initFunction,defaultInitFunction) && isnumeric(initArgs) solOpt = optimizeCbModel(model,osenseStr); %Minimum fraction of the objective function to select start points from %is 50% of the maximal objective initArgs = {osenseStr,0.5, 0.5 * solOpt.f}; else if isnumeric(initArgs) initArgs = {}; end end [nMets,nRxns] = size(model.S); NLPproblem = buildLPproblemFromModel(model); NLPproblem.objFunction = objFunction; NLPproblem.objArguments = objArgs; % Current best solution currentSol.f = osense*inf; allObjValues = zeros(nOpt,1); allSolutions = zeros(nRxns,nOpt); NLPproblem.user.model = model; %pass the model into the problem for access by the nonlinear objective function for i = 1:nOpt x0 = feval(initFunction,model,initArgs); NLPproblem.x0 = x0; %x0 now a cell within the NLP problem structure solNLP = solveCobraNLP(NLPproblem,solverOptions); %New function call %solNLP = solveCobraNLP(NLPproblem,[],objArgs); Old Code fprintf('%d\t%f\n',i,osense*solNLP.obj); allObjValues(i) = osense*solNLP.obj; allSolutions(:,i) = solNLP.full; if osense*solNLP.obj > currentSol.f currentSol.f = osense*solNLP.obj; currentSol.x = solNLP.full; currentSol.stat = solNLP.stat; end end
{ "pile_set_name": "Github" }
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.ide.util; import com.intellij.ide.util.treeView.smartTree.NodeProvider; import com.intellij.ide.util.treeView.smartTree.TreeElement; import com.intellij.openapi.actionSystem.Shortcut; import com.intellij.openapi.util.NlsContexts; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; /** * @author Konstantin Bulenkov */ public interface FileStructureNodeProvider<T extends TreeElement> extends NodeProvider<T> { @NotNull @NlsContexts.Checkbox String getCheckBoxText(); Shortcut @NotNull [] getShortcut(); }
{ "pile_set_name": "Github" }
From dba08e4e0dee6dfbb30ed30ffcf36f12646dfa4e Mon Sep 17 00:00:00 2001 From: Antonio Gomes <[email protected]> Date: Sat, 11 Jun 2016 10:30:30 -0400 Subject: [PATCH] Adapt DesktopFactoryOzone to respect --ozone-platform parameter. Patch removes SetInstance method from DesktopFactoryOzone and as well as ::GetNativeTheme implementation. The former is not necessary given that DesktopFactoryOzone::GetInstance instantiate the proper DesktopFactoryOzone now, either according to --ozone-platform={platform_name} or to a default platform name. --- .../widget/desktop_aura/desktop_factory_ozone.cc | 20 ++++++++++++++------ ui/views/widget/desktop_aura/desktop_factory_ozone.h | 3 --- .../desktop_aura/desktop_window_tree_host_ozone.cc | 5 ----- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/ui/views/widget/desktop_aura/desktop_factory_ozone.cc b/ui/views/widget/desktop_aura/desktop_factory_ozone.cc index e0a4489..d39aecd 100644 --- a/ui/views/widget/desktop_aura/desktop_factory_ozone.cc +++ b/ui/views/widget/desktop_aura/desktop_factory_ozone.cc @@ -5,25 +5,33 @@ #include "ui/views/widget/desktop_aura/desktop_factory_ozone.h" #include "base/logging.h" +#include "ui/ozone/platform_object.h" namespace views { // static -DesktopFactoryOzone* DesktopFactoryOzone::impl_ = NULL; +DesktopFactoryOzone* DesktopFactoryOzone::impl_ = nullptr; DesktopFactoryOzone::DesktopFactoryOzone() { + DCHECK(!impl_) << "There should only be a single DesktopFactoryOzone."; + impl_ = this; } DesktopFactoryOzone::~DesktopFactoryOzone() { + DCHECK_EQ(impl_, this); + impl_ = nullptr; } DesktopFactoryOzone* DesktopFactoryOzone::GetInstance() { - CHECK(impl_) << "DesktopFactoryOzone accessed before constructed"; + if (!impl_) { + scoped_ptr<DesktopFactoryOzone> factory = + ui::PlatformObject<DesktopFactoryOzone>::Create(); + + // TODO(tonikitoo): Currently need to leak this object. + DesktopFactoryOzone* leaky = factory.release(); + DCHECK_EQ(impl_, leaky); + } return impl_; } -void DesktopFactoryOzone::SetInstance(DesktopFactoryOzone* impl) { - impl_ = impl; -} - } // namespace views diff --git a/ui/views/widget/desktop_aura/desktop_factory_ozone.h b/ui/views/widget/desktop_aura/desktop_factory_ozone.h index 2af191b..8e45864 100644 --- a/ui/views/widget/desktop_aura/desktop_factory_ozone.h +++ b/ui/views/widget/desktop_aura/desktop_factory_ozone.h @@ -28,9 +28,6 @@ class VIEWS_EXPORT DesktopFactoryOzone { // Returns the instance. static DesktopFactoryOzone* GetInstance(); - // Sets the implementation delegate. Ownership is retained by the caller. - static void SetInstance(DesktopFactoryOzone* impl); - // Delegates implementation of DesktopWindowTreeHost::Create externally to // Ozone implementation. virtual DesktopWindowTreeHost* CreateWindowTreeHost( diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_ozone.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_ozone.cc index e67af41..a83f53d 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_ozone.cc +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_ozone.cc @@ -18,9 +18,4 @@ DesktopWindowTreeHost* DesktopWindowTreeHost::Create( desktop_native_widget_aura); } -// static -ui::NativeTheme* DesktopWindowTreeHost::GetNativeTheme(aura::Window* window) { - return ui::NativeThemeAura::instance(); -} - } // namespace views -- 2.7.4
{ "pile_set_name": "Github" }
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #include "unittest.h" #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/filereadstream.h" #include "rapidjson/encodedstream.h" #include "rapidjson/stringbuffer.h" #include <sstream> #include <algorithm> #ifdef __clang__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(c++98-compat) RAPIDJSON_DIAG_OFF(missing-variable-declarations) #endif using namespace rapidjson; template <typename DocumentType> void ParseCheck(DocumentType& doc) { typedef typename DocumentType::ValueType ValueType; EXPECT_FALSE(doc.HasParseError()); if (doc.HasParseError()) printf("Error: %d at %zu\n", static_cast<int>(doc.GetParseError()), doc.GetErrorOffset()); EXPECT_TRUE(static_cast<ParseResult>(doc)); EXPECT_TRUE(doc.IsObject()); EXPECT_TRUE(doc.HasMember("hello")); const ValueType& hello = doc["hello"]; EXPECT_TRUE(hello.IsString()); EXPECT_STREQ("world", hello.GetString()); EXPECT_TRUE(doc.HasMember("t")); const ValueType& t = doc["t"]; EXPECT_TRUE(t.IsTrue()); EXPECT_TRUE(doc.HasMember("f")); const ValueType& f = doc["f"]; EXPECT_TRUE(f.IsFalse()); EXPECT_TRUE(doc.HasMember("n")); const ValueType& n = doc["n"]; EXPECT_TRUE(n.IsNull()); EXPECT_TRUE(doc.HasMember("i")); const ValueType& i = doc["i"]; EXPECT_TRUE(i.IsNumber()); EXPECT_EQ(123, i.GetInt()); EXPECT_TRUE(doc.HasMember("pi")); const ValueType& pi = doc["pi"]; EXPECT_TRUE(pi.IsNumber()); EXPECT_DOUBLE_EQ(3.1416, pi.GetDouble()); EXPECT_TRUE(doc.HasMember("a")); const ValueType& a = doc["a"]; EXPECT_TRUE(a.IsArray()); EXPECT_EQ(4u, a.Size()); for (SizeType j = 0; j < 4; j++) EXPECT_EQ(j + 1, a[j].GetUint()); } template <typename Allocator, typename StackAllocator> void ParseTest() { typedef GenericDocument<UTF8<>, Allocator, StackAllocator> DocumentType; DocumentType doc; const char* json = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "; doc.Parse(json); ParseCheck(doc); doc.SetNull(); StringStream s(json); doc.template ParseStream<0>(s); ParseCheck(doc); doc.SetNull(); char *buffer = strdup(json); doc.ParseInsitu(buffer); ParseCheck(doc); free(buffer); // Parse(const Ch*, size_t) size_t length = strlen(json); buffer = reinterpret_cast<char*>(malloc(length * 2)); memcpy(buffer, json, length); memset(buffer + length, 'X', length); #if RAPIDJSON_HAS_STDSTRING std::string s2(buffer, length); // backup buffer #endif doc.SetNull(); doc.Parse(buffer, length); free(buffer); ParseCheck(doc); #if RAPIDJSON_HAS_STDSTRING // Parse(std::string) doc.SetNull(); doc.Parse(s2); ParseCheck(doc); #endif } TEST(Document, Parse) { ParseTest<MemoryPoolAllocator<>, CrtAllocator>(); ParseTest<MemoryPoolAllocator<>, MemoryPoolAllocator<> >(); ParseTest<CrtAllocator, MemoryPoolAllocator<> >(); ParseTest<CrtAllocator, CrtAllocator>(); } TEST(Document, UnchangedOnParseError) { Document doc; doc.SetArray().PushBack(0, doc.GetAllocator()); ParseResult err = doc.Parse("{]"); EXPECT_TRUE(doc.HasParseError()); EXPECT_EQ(err.Code(), doc.GetParseError()); EXPECT_EQ(err.Offset(), doc.GetErrorOffset()); EXPECT_TRUE(doc.IsArray()); EXPECT_EQ(doc.Size(), 1u); err = doc.Parse("{}"); EXPECT_FALSE(doc.HasParseError()); EXPECT_FALSE(err.IsError()); EXPECT_EQ(err.Code(), doc.GetParseError()); EXPECT_EQ(err.Offset(), doc.GetErrorOffset()); EXPECT_TRUE(doc.IsObject()); EXPECT_EQ(doc.MemberCount(), 0u); } static FILE* OpenEncodedFile(const char* filename) { const char *paths[] = { "encodings", "bin/encodings", "../bin/encodings", "../../bin/encodings", "../../../bin/encodings" }; char buffer[1024]; for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) { sprintf(buffer, "%s/%s", paths[i], filename); FILE *fp = fopen(buffer, "rb"); if (fp) return fp; } return 0; } TEST(Document, Parse_Encoding) { const char* json = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "; typedef GenericDocument<UTF16<> > DocumentType; DocumentType doc; // Parse<unsigned, SourceEncoding>(const SourceEncoding::Ch*) // doc.Parse<kParseDefaultFlags, UTF8<> >(json); // EXPECT_FALSE(doc.HasParseError()); // EXPECT_EQ(0, StrCmp(doc[L"hello"].GetString(), L"world")); // Parse<unsigned, SourceEncoding>(const SourceEncoding::Ch*, size_t) size_t length = strlen(json); char* buffer = reinterpret_cast<char*>(malloc(length * 2)); memcpy(buffer, json, length); memset(buffer + length, 'X', length); #if RAPIDJSON_HAS_STDSTRING std::string s2(buffer, length); // backup buffer #endif doc.SetNull(); doc.Parse<kParseDefaultFlags, UTF8<> >(buffer, length); free(buffer); EXPECT_FALSE(doc.HasParseError()); if (doc.HasParseError()) printf("Error: %d at %zu\n", static_cast<int>(doc.GetParseError()), doc.GetErrorOffset()); EXPECT_EQ(0, StrCmp(doc[L"hello"].GetString(), L"world")); #if RAPIDJSON_HAS_STDSTRING // Parse<unsigned, SourceEncoding>(std::string) doc.SetNull(); #if defined(_MSC_VER) && _MSC_VER < 1800 doc.Parse<kParseDefaultFlags, UTF8<> >(s2.c_str()); // VS2010 or below cannot handle templated function overloading. Use const char* instead. #else doc.Parse<kParseDefaultFlags, UTF8<> >(s2); #endif EXPECT_FALSE(doc.HasParseError()); EXPECT_EQ(0, StrCmp(doc[L"hello"].GetString(), L"world")); #endif } TEST(Document, ParseStream_EncodedInputStream) { // UTF8 -> UTF16 FILE* fp = OpenEncodedFile("utf8.json"); char buffer[256]; FileReadStream bis(fp, buffer, sizeof(buffer)); EncodedInputStream<UTF8<>, FileReadStream> eis(bis); GenericDocument<UTF16<> > d; d.ParseStream<0, UTF8<> >(eis); EXPECT_FALSE(d.HasParseError()); fclose(fp); wchar_t expected[] = L"I can eat glass and it doesn't hurt me."; GenericValue<UTF16<> >& v = d[L"en"]; EXPECT_TRUE(v.IsString()); EXPECT_EQ(sizeof(expected) / sizeof(wchar_t) - 1, v.GetStringLength()); EXPECT_EQ(0, StrCmp(expected, v.GetString())); // UTF16 -> UTF8 in memory StringBuffer bos; typedef EncodedOutputStream<UTF8<>, StringBuffer> OutputStream; OutputStream eos(bos, false); // Not writing BOM { Writer<OutputStream, UTF16<>, UTF8<> > writer(eos); d.Accept(writer); } // Condense the original file and compare. fp = OpenEncodedFile("utf8.json"); FileReadStream is(fp, buffer, sizeof(buffer)); Reader reader; StringBuffer bos2; Writer<StringBuffer> writer2(bos2); reader.Parse(is, writer2); fclose(fp); EXPECT_EQ(bos.GetSize(), bos2.GetSize()); EXPECT_EQ(0, memcmp(bos.GetString(), bos2.GetString(), bos2.GetSize())); } TEST(Document, ParseStream_AutoUTFInputStream) { // Any -> UTF8 FILE* fp = OpenEncodedFile("utf32be.json"); char buffer[256]; FileReadStream bis(fp, buffer, sizeof(buffer)); AutoUTFInputStream<unsigned, FileReadStream> eis(bis); Document d; d.ParseStream<0, AutoUTF<unsigned> >(eis); EXPECT_FALSE(d.HasParseError()); fclose(fp); char expected[] = "I can eat glass and it doesn't hurt me."; Value& v = d["en"]; EXPECT_TRUE(v.IsString()); EXPECT_EQ(sizeof(expected) - 1, v.GetStringLength()); EXPECT_EQ(0, StrCmp(expected, v.GetString())); // UTF8 -> UTF8 in memory StringBuffer bos; Writer<StringBuffer> writer(bos); d.Accept(writer); // Condense the original file and compare. fp = OpenEncodedFile("utf8.json"); FileReadStream is(fp, buffer, sizeof(buffer)); Reader reader; StringBuffer bos2; Writer<StringBuffer> writer2(bos2); reader.Parse(is, writer2); fclose(fp); EXPECT_EQ(bos.GetSize(), bos2.GetSize()); EXPECT_EQ(0, memcmp(bos.GetString(), bos2.GetString(), bos2.GetSize())); } TEST(Document, Swap) { Document d1; Document::AllocatorType& a = d1.GetAllocator(); d1.SetArray().PushBack(1, a).PushBack(2, a); Value o; o.SetObject().AddMember("a", 1, a); // Swap between Document and Value // d1.Swap(o); // doesn't compile o.Swap(d1); EXPECT_TRUE(d1.IsObject()); EXPECT_TRUE(o.IsArray()); // Swap between Document and Document Document d2; d2.SetArray().PushBack(3, a); d1.Swap(d2); EXPECT_TRUE(d1.IsArray()); EXPECT_TRUE(d2.IsObject()); EXPECT_EQ(&d2.GetAllocator(), &a); // reset value Value().Swap(d1); EXPECT_TRUE(d1.IsNull()); // reset document, including allocator Document().Swap(d2); EXPECT_TRUE(d2.IsNull()); EXPECT_NE(&d2.GetAllocator(), &a); // testing std::swap compatibility d1.SetBool(true); using std::swap; swap(d1, d2); EXPECT_TRUE(d1.IsNull()); EXPECT_TRUE(d2.IsTrue()); swap(o, d2); EXPECT_TRUE(o.IsTrue()); EXPECT_TRUE(d2.IsArray()); } // This should be slow due to assignment in inner-loop. struct OutputStringStream : public std::ostringstream { typedef char Ch; virtual ~OutputStringStream(); void Put(char c) { put(c); } void Flush() {} }; OutputStringStream::~OutputStringStream() {} TEST(Document, AcceptWriter) { Document doc; doc.Parse(" { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "); OutputStringStream os; Writer<OutputStringStream> writer(os); doc.Accept(writer); EXPECT_EQ("{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3,4]}", os.str()); } TEST(Document, UserBuffer) { typedef GenericDocument<UTF8<>, MemoryPoolAllocator<>, MemoryPoolAllocator<> > DocumentType; char valueBuffer[4096]; char parseBuffer[1024]; MemoryPoolAllocator<> valueAllocator(valueBuffer, sizeof(valueBuffer)); MemoryPoolAllocator<> parseAllocator(parseBuffer, sizeof(parseBuffer)); DocumentType doc(&valueAllocator, sizeof(parseBuffer) / 2, &parseAllocator); doc.Parse(" { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "); EXPECT_FALSE(doc.HasParseError()); EXPECT_LE(valueAllocator.Size(), sizeof(valueBuffer)); EXPECT_LE(parseAllocator.Size(), sizeof(parseBuffer)); // Cover MemoryPoolAllocator::Capacity() EXPECT_LE(valueAllocator.Size(), valueAllocator.Capacity()); EXPECT_LE(parseAllocator.Size(), parseAllocator.Capacity()); } // Issue 226: Value of string type should not point to NULL TEST(Document, AssertAcceptInvalidNameType) { Document doc; doc.SetObject(); doc.AddMember("a", 0, doc.GetAllocator()); doc.FindMember("a")->name.SetNull(); // Change name to non-string type. OutputStringStream os; Writer<OutputStringStream> writer(os); ASSERT_THROW(doc.Accept(writer), AssertException); } // Issue 44: SetStringRaw doesn't work with wchar_t TEST(Document, UTF16_Document) { GenericDocument< UTF16<> > json; json.Parse<kParseValidateEncodingFlag>(L"[{\"created_at\":\"Wed Oct 30 17:13:20 +0000 2012\"}]"); ASSERT_TRUE(json.IsArray()); GenericValue< UTF16<> >& v = json[0]; ASSERT_TRUE(v.IsObject()); GenericValue< UTF16<> >& s = v[L"created_at"]; ASSERT_TRUE(s.IsString()); EXPECT_EQ(0, memcmp(L"Wed Oct 30 17:13:20 +0000 2012", s.GetString(), (s.GetStringLength() + 1) * sizeof(wchar_t))); } #if RAPIDJSON_HAS_CXX11_RVALUE_REFS #if 0 // Many old compiler does not support these. Turn it off temporaily. #include <type_traits> TEST(Document, Traits) { static_assert(std::is_constructible<Document>::value, ""); static_assert(std::is_default_constructible<Document>::value, ""); #ifndef _MSC_VER static_assert(!std::is_copy_constructible<Document>::value, ""); #endif static_assert(std::is_move_constructible<Document>::value, ""); static_assert(!std::is_nothrow_constructible<Document>::value, ""); static_assert(!std::is_nothrow_default_constructible<Document>::value, ""); #ifndef _MSC_VER static_assert(!std::is_nothrow_copy_constructible<Document>::value, ""); static_assert(std::is_nothrow_move_constructible<Document>::value, ""); #endif static_assert(std::is_assignable<Document,Document>::value, ""); #ifndef _MSC_VER static_assert(!std::is_copy_assignable<Document>::value, ""); #endif static_assert(std::is_move_assignable<Document>::value, ""); #ifndef _MSC_VER static_assert(std::is_nothrow_assignable<Document, Document>::value, ""); #endif static_assert(!std::is_nothrow_copy_assignable<Document>::value, ""); #ifndef _MSC_VER static_assert(std::is_nothrow_move_assignable<Document>::value, ""); #endif static_assert( std::is_destructible<Document>::value, ""); #ifndef _MSC_VER static_assert(std::is_nothrow_destructible<Document>::value, ""); #endif } #endif template <typename Allocator> struct DocumentMove: public ::testing::Test { }; typedef ::testing::Types< CrtAllocator, MemoryPoolAllocator<> > MoveAllocatorTypes; TYPED_TEST_CASE(DocumentMove, MoveAllocatorTypes); TYPED_TEST(DocumentMove, MoveConstructor) { typedef TypeParam Allocator; typedef GenericDocument<UTF8<>, Allocator> D; Allocator allocator; D a(&allocator); a.Parse("[\"one\", \"two\", \"three\"]"); EXPECT_FALSE(a.HasParseError()); EXPECT_TRUE(a.IsArray()); EXPECT_EQ(3u, a.Size()); EXPECT_EQ(&a.GetAllocator(), &allocator); // Document b(a); // does not compile (!is_copy_constructible) D b(std::move(a)); EXPECT_TRUE(a.IsNull()); EXPECT_TRUE(b.IsArray()); EXPECT_EQ(3u, b.Size()); EXPECT_THROW(a.GetAllocator(), AssertException); EXPECT_EQ(&b.GetAllocator(), &allocator); b.Parse("{\"Foo\": \"Bar\", \"Baz\": 42}"); EXPECT_FALSE(b.HasParseError()); EXPECT_TRUE(b.IsObject()); EXPECT_EQ(2u, b.MemberCount()); // Document c = a; // does not compile (!is_copy_constructible) D c = std::move(b); EXPECT_TRUE(b.IsNull()); EXPECT_TRUE(c.IsObject()); EXPECT_EQ(2u, c.MemberCount()); EXPECT_THROW(b.GetAllocator(), AssertException); EXPECT_EQ(&c.GetAllocator(), &allocator); } TYPED_TEST(DocumentMove, MoveConstructorParseError) { typedef TypeParam Allocator; typedef GenericDocument<UTF8<>, Allocator> D; ParseResult noError; D a; a.Parse("{ 4 = 4]"); ParseResult error(a.GetParseError(), a.GetErrorOffset()); EXPECT_TRUE(a.HasParseError()); EXPECT_NE(error.Code(), noError.Code()); EXPECT_NE(error.Offset(), noError.Offset()); D b(std::move(a)); EXPECT_FALSE(a.HasParseError()); EXPECT_TRUE(b.HasParseError()); EXPECT_EQ(a.GetParseError(), noError.Code()); EXPECT_EQ(b.GetParseError(), error.Code()); EXPECT_EQ(a.GetErrorOffset(), noError.Offset()); EXPECT_EQ(b.GetErrorOffset(), error.Offset()); D c(std::move(b)); EXPECT_FALSE(b.HasParseError()); EXPECT_TRUE(c.HasParseError()); EXPECT_EQ(b.GetParseError(), noError.Code()); EXPECT_EQ(c.GetParseError(), error.Code()); EXPECT_EQ(b.GetErrorOffset(), noError.Offset()); EXPECT_EQ(c.GetErrorOffset(), error.Offset()); } // This test does not properly use parsing, just for testing. // It must call ClearStack() explicitly to prevent memory leak. // But here we cannot as ClearStack() is private. #if 0 TYPED_TEST(DocumentMove, MoveConstructorStack) { typedef TypeParam Allocator; typedef UTF8<> Encoding; typedef GenericDocument<Encoding, Allocator> Document; Document a; size_t defaultCapacity = a.GetStackCapacity(); // Trick Document into getting GetStackCapacity() to return non-zero typedef GenericReader<Encoding, Encoding, Allocator> Reader; Reader reader(&a.GetAllocator()); GenericStringStream<Encoding> is("[\"one\", \"two\", \"three\"]"); reader.template Parse<kParseDefaultFlags>(is, a); size_t capacity = a.GetStackCapacity(); EXPECT_GT(capacity, 0u); Document b(std::move(a)); EXPECT_EQ(a.GetStackCapacity(), defaultCapacity); EXPECT_EQ(b.GetStackCapacity(), capacity); Document c = std::move(b); EXPECT_EQ(b.GetStackCapacity(), defaultCapacity); EXPECT_EQ(c.GetStackCapacity(), capacity); } #endif TYPED_TEST(DocumentMove, MoveAssignment) { typedef TypeParam Allocator; typedef GenericDocument<UTF8<>, Allocator> D; Allocator allocator; D a(&allocator); a.Parse("[\"one\", \"two\", \"three\"]"); EXPECT_FALSE(a.HasParseError()); EXPECT_TRUE(a.IsArray()); EXPECT_EQ(3u, a.Size()); EXPECT_EQ(&a.GetAllocator(), &allocator); // Document b; b = a; // does not compile (!is_copy_assignable) D b; b = std::move(a); EXPECT_TRUE(a.IsNull()); EXPECT_TRUE(b.IsArray()); EXPECT_EQ(3u, b.Size()); EXPECT_THROW(a.GetAllocator(), AssertException); EXPECT_EQ(&b.GetAllocator(), &allocator); b.Parse("{\"Foo\": \"Bar\", \"Baz\": 42}"); EXPECT_FALSE(b.HasParseError()); EXPECT_TRUE(b.IsObject()); EXPECT_EQ(2u, b.MemberCount()); // Document c; c = a; // does not compile (see static_assert) D c; c = std::move(b); EXPECT_TRUE(b.IsNull()); EXPECT_TRUE(c.IsObject()); EXPECT_EQ(2u, c.MemberCount()); EXPECT_THROW(b.GetAllocator(), AssertException); EXPECT_EQ(&c.GetAllocator(), &allocator); } TYPED_TEST(DocumentMove, MoveAssignmentParseError) { typedef TypeParam Allocator; typedef GenericDocument<UTF8<>, Allocator> D; ParseResult noError; D a; a.Parse("{ 4 = 4]"); ParseResult error(a.GetParseError(), a.GetErrorOffset()); EXPECT_TRUE(a.HasParseError()); EXPECT_NE(error.Code(), noError.Code()); EXPECT_NE(error.Offset(), noError.Offset()); D b; b = std::move(a); EXPECT_FALSE(a.HasParseError()); EXPECT_TRUE(b.HasParseError()); EXPECT_EQ(a.GetParseError(), noError.Code()); EXPECT_EQ(b.GetParseError(), error.Code()); EXPECT_EQ(a.GetErrorOffset(), noError.Offset()); EXPECT_EQ(b.GetErrorOffset(), error.Offset()); D c; c = std::move(b); EXPECT_FALSE(b.HasParseError()); EXPECT_TRUE(c.HasParseError()); EXPECT_EQ(b.GetParseError(), noError.Code()); EXPECT_EQ(c.GetParseError(), error.Code()); EXPECT_EQ(b.GetErrorOffset(), noError.Offset()); EXPECT_EQ(c.GetErrorOffset(), error.Offset()); } // This test does not properly use parsing, just for testing. // It must call ClearStack() explicitly to prevent memory leak. // But here we cannot as ClearStack() is private. #if 0 TYPED_TEST(DocumentMove, MoveAssignmentStack) { typedef TypeParam Allocator; typedef UTF8<> Encoding; typedef GenericDocument<Encoding, Allocator> D; D a; size_t defaultCapacity = a.GetStackCapacity(); // Trick Document into getting GetStackCapacity() to return non-zero typedef GenericReader<Encoding, Encoding, Allocator> Reader; Reader reader(&a.GetAllocator()); GenericStringStream<Encoding> is("[\"one\", \"two\", \"three\"]"); reader.template Parse<kParseDefaultFlags>(is, a); size_t capacity = a.GetStackCapacity(); EXPECT_GT(capacity, 0u); D b; b = std::move(a); EXPECT_EQ(a.GetStackCapacity(), defaultCapacity); EXPECT_EQ(b.GetStackCapacity(), capacity); D c; c = std::move(b); EXPECT_EQ(b.GetStackCapacity(), defaultCapacity); EXPECT_EQ(c.GetStackCapacity(), capacity); } #endif #endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS // Issue 22: Memory corruption via operator= // Fixed by making unimplemented assignment operator private. //TEST(Document, Assignment) { // Document d1; // Document d2; // d1 = d2; //} #ifdef __clang__ RAPIDJSON_DIAG_POP #endif
{ "pile_set_name": "Github" }
include $(MAGPIE_ROOT)/build/make_opt/Makefile.h # # Sub-system source main path # # !!Customize!! #export LAYERNAME = rom export SSNAME = cmnos # # Sub-system source main path # export SSMPATH = $(PRJ_ROOT)/$(TARGET)/$(SSNAME) # # Sub-system object search path for GNU tool chain # # !!Customize!! #export SSOBJPATH = $(PRJ_ROOT)/$(TARGET)/$(SSNAME)/obj # # Sub-system/module list at this layer # # !!Customize!! DIRS = allocram clock eeprom intr mem misc printf rompatch string tasklet timer wdt uart sflash #DIRS = allocram # # Archive for this package # # !!Customize!! export L_TARGET = $(LIB_PATH)/libcmnos.a # # Targets # all: # for i in $(SUBDIRS) ; do $(MAKE) -C $$i -f Makefile.ss all || exit $?; done for i in $(DIRS) ; do $(MAKE) -C $$i all || exit $? ; done # ar -rcs $(L_TARGET) `find . -name "*.o"` dep: for i in $(DIRS) ; do $(MAKE) -C $$i dep || exit $? ; done clean: for i in $(DIRS) ; do $(MAKE) -C $$i clean; done init: for i in $(DIRS) ; do $(MAKE) -C $$i init; done
{ "pile_set_name": "Github" }
/* * Copyright (C) 2015 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. */ #ifndef MediaPlaybackTargetPicker_h #define MediaPlaybackTargetPicker_h #if ENABLE(WIRELESS_PLAYBACK_TARGET) #include <wtf/Ref.h> #include <wtf/RunLoop.h> namespace WebCore { class FloatRect; class MediaPlaybackTarget; class MediaPlaybackTargetPicker { public: class Client { protected: virtual ~Client() = default; public: virtual void setPlaybackTarget(Ref<MediaPlaybackTarget>&&) = 0; virtual void externalOutputDeviceAvailableDidChange(bool) = 0; void invalidate(); }; virtual ~MediaPlaybackTargetPicker(); virtual void showPlaybackTargetPicker(const FloatRect&, bool checkActiveRoute, bool useDarkAppearance); virtual void startingMonitoringPlaybackTargets(); virtual void stopMonitoringPlaybackTargets(); virtual void invalidatePlaybackTargets(); void availableDevicesDidChange() { addPendingAction(OutputDeviceAvailabilityChanged); } void currentDeviceDidChange() { addPendingAction(CurrentDeviceDidChange); } protected: explicit MediaPlaybackTargetPicker(Client&); enum ActionType { OutputDeviceAvailabilityChanged = 1 << 0, CurrentDeviceDidChange = 1 << 1, }; typedef unsigned PendingActionFlags; void addPendingAction(PendingActionFlags); void pendingActionTimerFired(); Client* client() const { return m_client; } void setClient(Client* client) { m_client = client; } private: virtual bool externalOutputDeviceAvailable() = 0; virtual Ref<MediaPlaybackTarget> playbackTarget() = 0; PendingActionFlags m_pendingActionFlags { 0 }; Client* m_client; RunLoop::Timer<MediaPlaybackTargetPicker> m_pendingActionTimer; }; } // namespace WebCore #endif // ENABLE(WIRELESS_PLAYBACK_TARGET) #endif // MediaPlaybackTargetPicker_h
{ "pile_set_name": "Github" }
owner = SOV controller = SOV add_core = SOV infra = 3 naval_base = 1
{ "pile_set_name": "Github" }
///////////////////////////////////////////////////////////////////////////// // Name: pyTextures.h // Purpose: // Author: Julio Jerez // Modified by: // Created: 22/05/2010 08:02:08 // RCS-ID: // Copyright: Copyright (c) <2010> <Newton Game Dynamics> // License: // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely ///////////////////////////////////////////////////////////////////////////// #pragma once #include "pyTypes.h" #include "pyBaseNodeInfo.h" class pyScene; class dTextureNodeInfo; class pyTexture: public pyBaseNodeInfo<dTextureNodeInfo> { public: pyTexture(pyScene* scene, void* textureNode); ~pyTexture(void); int GetId(); const char* GetImageName(); };
{ "pile_set_name": "Github" }
require 'tzinfo/timezone_definition' module TZInfo module Definitions module Europe module Skopje include TimezoneDefinition linked_timezone 'Europe/Skopje', 'Europe/Belgrade' end end end end
{ "pile_set_name": "Github" }
/** * Welsh translation for bootstrap-datepicker * S. Morris <[email protected]> */ ;(function($){ $.fn.datepicker.dates['cy'] = { days: ["Sul", "Llun", "Mawrth", "Mercher", "Iau", "Gwener", "Sadwrn", "Sul"], daysShort: ["Sul", "Llu", "Maw", "Mer", "Iau", "Gwe", "Sad", "Sul"], daysMin: ["Su", "Ll", "Ma", "Me", "Ia", "Gwe", "Sa", "Su"], months: ["Ionawr", "Chewfror", "Mawrth", "Ebrill", "Mai", "Mehefin", "Gorfennaf", "Awst", "Medi", "Hydref", "Tachwedd", "Rhagfyr"], monthsShort: ["Ion", "Chw", "Maw", "Ebr", "Mai", "Meh", "Gor", "Aws", "Med", "Hyd", "Tach", "Rha"], today: "Heddiw" }; }(jQuery));
{ "pile_set_name": "Github" }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "render/ssao.h" #include "render/shader.h" #include "render/framebuffer.h" #include "render/defaults.h" #include "util/ini.h" extern ex_ini_t *conf; extern GLuint gposition, gnormal; extern GLuint fbo_vao; vec3 ssao_samples[SSAO_NUM_SAMPLES]; vec3 ssao_noise[16]; // ssao geometry pass GLuint ssao_noise_texture, ssao_fbo, ssao_color_buffer; GLuint ssao_shader; GLuint sample_loc = 0, projection_loc = 0, view_loc = 0, screensize_loc = 0; GLuint gposition_loc = 0, gnormal_loc = 0, noise_loc = 0; // ssao blur pass GLuint ssao_blur_fbo, ssao_color_blur_buffer; GLuint ssao_blur_shader; GLuint ssao_blur_loc = 0; void ssao_init() { srand(time(NULL)); // generate kernel sample hemispheres for (int i=0; i<SSAO_NUM_SAMPLES; i++) { float r1 = (float)rand()/(float)(RAND_MAX/1.0); float r2 = (float)rand()/(float)(RAND_MAX/1.0); float r3 = (float)rand()/(float)(RAND_MAX/1.0); float r4 = (float)rand()/(float)(RAND_MAX/1.0); vec3 sample = {r1 * 2.0 - 1.0, r2 * 2.0 - 1.0, r3}; vec3_norm(sample, sample); sample[0] *= r4; sample[1] *= r4; sample[2] *= r4; // scale samples to be closer to the center float scale = (float)i / (float)SSAO_NUM_SAMPLES; scale = lerp(0.1f, 1.0f, scale * scale); sample[0] *= scale; sample[1] *= scale; sample[2] *= scale; memcpy(ssao_samples[i], sample, sizeof(vec3)); } // generate kernel noise for (int i=0; i<16; i++) { float r1 = (float)rand()/(float)(RAND_MAX/1.0); float r2 = (float)rand()/(float)(RAND_MAX/1.0); vec3 noise = {r1 * 2.0 - 1.0, r2 * 2.0 - 1.0, 0.0f}; memcpy(ssao_noise[i], noise, sizeof(vec3)); } // generate a texture to hold the noise values glGenTextures(1, &ssao_noise_texture); glBindTexture(GL_TEXTURE_2D, ssao_noise_texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, 4, 4, 0, GL_RGB, GL_FLOAT, &ssao_noise[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // generate the ssao framebuffer glGenFramebuffers(1, &ssao_fbo); glBindFramebuffer(GL_FRAMEBUFFER, ssao_fbo); int width = (int)ex_ini_get_float(conf, "graphics", "window_width"); int height = (int)ex_ini_get_float(conf, "graphics", "window_height"); // generate color buffer glGenTextures(1, &ssao_color_buffer); glBindTexture(GL_TEXTURE_2D, ssao_color_buffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width, height, 0, GL_RGB, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ssao_color_buffer, 0); // test framebuffer if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) printf("Error! SSAO Framebuffer is not complete\n"); glBindFramebuffer(GL_FRAMEBUFFER, 0); // generate the ssao blur framebuffer glGenFramebuffers(1, &ssao_blur_fbo); glBindFramebuffer(GL_FRAMEBUFFER, ssao_blur_fbo); // generate ssao blur color buffer glGenTextures(1, &ssao_color_blur_buffer); glBindTexture(GL_TEXTURE_2D, ssao_color_blur_buffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width, height, 0, GL_RGB, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ssao_color_blur_buffer, 0); // test blur framebuffer if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) printf("Error! SSAO Blur Framebuffer is not complete\n"); glBindFramebuffer(GL_FRAMEBUFFER, 0); // load and init the shaders ssao_shader = ex_shader("ssao.glsl"); ssao_blur_shader = ex_shader("ssao.glsl"); } void ssao_render(mat4x4 projection, mat4x4 view) { glBindFramebuffer(GL_FRAMEBUFFER, ssao_fbo); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(ssao_shader); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, gposition); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, gnormal); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, ssao_noise_texture); if (!sample_loc) sample_loc = ex_uniform(ssao_shader, "u_samples"); if (!projection_loc) projection_loc = ex_uniform(ssao_shader, "u_projection"); if (!view_loc) view_loc = ex_uniform(ssao_shader, "u_view"); if (!screensize_loc) screensize_loc = ex_uniform(ssao_shader, "u_screensize"); if (!gposition_loc) gposition_loc = ex_uniform(ssao_shader, "u_gposition"); if (!gnormal_loc) gnormal_loc = ex_uniform(ssao_shader, "u_gnormal"); if (!noise_loc) noise_loc = ex_uniform(ssao_shader, "u_noise"); int width = (int)ex_ini_get_float(conf, "graphics", "window_width"); int height = (int)ex_ini_get_float(conf, "graphics", "window_height"); vec2 screensize = {width, height}; glUniform2fv(screensize_loc, 1, (float*)&screensize[0]); glUniform3fv(sample_loc, SSAO_NUM_SAMPLES, (float*)&ssao_samples[0]); glUniformMatrix4fv(projection_loc, 1, GL_FALSE, (float*)&projection[0]); glUniformMatrix4fv(view_loc, 1, GL_FALSE, (float*)&view[0]); glUniform1i(gposition_loc, 0); glUniform1i(gnormal_loc, 1); glUniform1i(noise_loc, 2); // render screen quad glBindVertexArray(fbo_vao); glDrawArrays(GL_TRIANGLES, 0, 6); // do blur pass glBindFramebuffer(GL_FRAMEBUFFER, ssao_blur_fbo); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(ssao_blur_shader); // send the ssao color texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, ssao_color_buffer); if (!ssao_blur_loc) ssao_blur_loc = ex_uniform(ssao_blur_shader, "u_ssao"); glUniform1i(ssao_blur_loc, 0); glBindVertexArray(fbo_vao); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void ssao_bind_texture(GLuint shader) { glActiveTexture(GL_TEXTURE3); glUniform1i(ex_uniform(shader, "u_ssao"), 3); glBindTexture(GL_TEXTURE_2D, ssao_color_blur_buffer); } void ssao_bind_default(GLuint shader) { glActiveTexture(GL_TEXTURE3); glUniform1i(ex_uniform(shader, "u_ssao"), 3); glBindTexture(GL_TEXTURE_2D, default_texture_ssao); }
{ "pile_set_name": "Github" }
// RUN: %clang_cc1 -fsyntax-only -verify %s int& r1; // expected-error{{declaration of reference variable 'r1' requires an initializer}} extern int& r2;
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace IDDQuickstart452 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); PlotLines(null, null); } private Random rand = new Random(0); private double[] RandomWalk(int points = 5, double start = 100, double mult = 50) { // return an array of difting random numbers double[] values = new double[points]; values[0] = start; for (int i = 1; i < points; i++) values[i] = values[i - 1] + (rand.NextDouble() - .5) * mult; return values; } private double[] Consecutive(int points, double offset = 0, double stepSize = 1) { // return an array of ascending numbers starting at 1 double[] values = new double[points]; for (int i = 0; i < points; i++) values[i] = i * stepSize + 1 + offset; return values; } private void PlotBar(object sender, RoutedEventArgs e) { // generate some random Y data int pointCount = 5; double[] xs1 = Consecutive(pointCount, offset: 0); double[] xs2 = Consecutive(pointCount, offset: .4); double[] ys1 = RandomWalk(pointCount); double[] ys2 = RandomWalk(pointCount); // create the series and describe their styling var bar1 = new InteractiveDataDisplay.WPF.BarGraph() { Color = Brushes.Blue, Description = "Group A", BarsWidth = .35, }; var bar2 = new InteractiveDataDisplay.WPF.BarGraph() { Color = Brushes.Red, Description = "Group B", BarsWidth = .35, }; // load data into each series bar1.PlotBars(xs1, ys1); bar2.PlotBars(xs2, ys2); // add the series to the grid myGrid.Children.Clear(); myGrid.Children.Add(bar1); myGrid.Children.Add(bar2); // customize styling myChart.Title = $"Bar Graph"; myChart.BottomTitle = $"Horizontal Axis Label"; myChart.LeftTitle = $"Vertical Axis Label"; myChart.IsAutoFitEnabled = false; myChart.LegendVisibility = Visibility.Visible; // set axis limits manually myChart.PlotOriginX = .5; myChart.PlotWidth = 5.5; myChart.PlotOriginY = 0; myChart.PlotHeight = 200; } private void PlotScatter(object sender, RoutedEventArgs e) { // generate some random X and Y data int pointCount = 500; double[] xs1 = RandomWalk(pointCount); double[] ys1 = RandomWalk(pointCount); double[] xs2 = RandomWalk(pointCount); double[] ys2 = RandomWalk(pointCount); double[] sizes = Consecutive(pointCount, 10, 0); // create the lines and describe their styling var line1 = new InteractiveDataDisplay.WPF.CircleMarkerGraph() { Color = new SolidColorBrush(Colors.Blue), Description = "Group A", StrokeThickness = 1 }; var line2 = new InteractiveDataDisplay.WPF.CircleMarkerGraph() { Color = new SolidColorBrush(Colors.Red), Description = "Group B", StrokeThickness = 1 }; // load data into the lines line1.PlotSize(xs1, ys1, sizes); line2.PlotSize(xs2, ys2, sizes); // add lines into the grid myGrid.Children.Clear(); myGrid.Children.Add(line1); myGrid.Children.Add(line2); // customize styling myChart.Title = $"Line Plot ({pointCount:n0} points each)"; myChart.BottomTitle = $"Horizontal Axis Label"; myChart.LeftTitle = $"Vertical Axis Label"; myChart.IsAutoFitEnabled = true; myChart.LegendVisibility = Visibility.Hidden; } private void PlotLines(object sender, RoutedEventArgs e) { int pointCount = 10_000; double[] xs = Consecutive(pointCount); double[] ys1 = RandomWalk(pointCount); double[] ys2 = RandomWalk(pointCount); // create the lines and describe their styling var line1 = new InteractiveDataDisplay.WPF.LineGraph { Stroke = new SolidColorBrush(Colors.Blue), Description = "Line A", StrokeThickness = 2 }; var line2 = new InteractiveDataDisplay.WPF.LineGraph { Stroke = new SolidColorBrush(Colors.Red), Description = "Line B", StrokeThickness = 2 }; // load data into the lines line1.Plot(xs, ys1); line2.Plot(xs, ys2); // add lines into the grid myGrid.Children.Clear(); myGrid.Children.Add(line1); myGrid.Children.Add(line2); // customize styling myChart.Title = $"Line Plot ({pointCount:n0} points each)"; myChart.BottomTitle = $"Horizontal Axis Label"; myChart.LeftTitle = $"Vertical Axis Label"; myChart.IsAutoFitEnabled = true; myChart.LegendVisibility = Visibility.Visible; } } }
{ "pile_set_name": "Github" }
1 1 1 7 7 1 9 9 1 14 14 1 18 18 1 23 3 2 27 7 2 29 9 2 33 13 2
{ "pile_set_name": "Github" }
/* * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands. * See the copyright notice in the ACK home directory, in the file "Copyright". * * Author: Ceriel J.H. Jacobs */ /* M A I N P R O G R A M */ /* stripped down version from the one in the Modula-2 compiler */ /* $Id$ */ #include <string.h> #include <alloc.h> #include "input.h" #include "f_info.h" #include "idf.h" #include "LLlex.h" #include "Lpars.h" #include "tokenname.h" int state; /* either IMPLEMENTATION or PROGRAM */ char *ProgName; char **DEFPATH; int nDEF, mDEF; struct file_list *CurrentArg; extern int err_occurred; extern int Roption; char * basename(s) char *s; { static char buf[256]; char *p = strrchr(s, '.'); if (p != 0) *p = 0; strcpy(buf, s); if (p != 0) *p = '.'; return buf; } char * getwdir(fn) register char *fn; { register char *p; p = strrchr(fn, '/'); while (p && *(p + 1) == '\0') { /* remove trailing /'s */ *p = '\0'; p = strrchr(fn, '/'); } if (p) { register char **d = DEFPATH; *p = '\0'; while (*d && strcmp(*d, fn) != 0) d++; if (*d) { *p = '/'; return *d; } fn = Salloc(fn, (unsigned) (p - &fn[0] + 1)); *p = '/'; return fn; } return "."; } static struct file_list *arglist; #ifndef M2COMPILER #define M2COMPILER "m2" #endif char *mflags = ""; char *compiler = M2COMPILER; char *suff = "o"; char *llibs = 0; main(argc, argv) register char **argv; { extern struct tokenname tkidf[]; extern char *getwdir(); int i; ProgName = *argv++; DEFPATH = (char **) Malloc(10 * sizeof(char *)); DEFPATH[1] = 0; mDEF = 10; nDEF = 2; while (--argc > 0) { if (**argv == '-') DoOption((*argv++) + 1); else { Add(&arglist, *argv, getwdir(*argv), 1); argv++; } } init_idf(); reserve(tkidf); print("IFLAGS ="); for (i = 1; i < nDEF; i++) { if (DEFPATH[i]) print(" -I%s", DEFPATH[i]); } print("\nM2FLAGS = %s\nMOD = %s\nSUFFIX = %s\nLIBS = %s\n", mflags, compiler, suff, llibs ? llibs : ""); init_lib(); ProcessArgs(); find_dependencies(); print_dep(); programs(); exit(err_occurred); } struct file_list * new_file_list() { static struct file_list *p; register struct file_list *f; static int cnt; if (--cnt < 0) { p = (struct file_list *)Malloc(50*sizeof(struct file_list)); cnt = 49; } f = p++; f->a_filename = 0; f->a_dir = 0; f->a_next = 0; f->a_idf = 0; f->a_notfound = 0; return f; } Add(parglist, f, d, copy) char *f, *d; struct file_list **parglist; { register struct file_list *a, *b = 0; if (f == 0) return; f_walk(*parglist, a) { if (strcmp(f_filename(a), f) == 0) break; b = a; } if (a) return 0; a = new_file_list(); if (copy) { a->a_filename = Salloc(f, (unsigned) (strlen(f)+1)); } else { a->a_filename = f; } a->a_dir = d; if (! b) *parglist = a; else b->a_next = a; return 1; } int openfile(a) register struct file_list *a; { char *fn; if (!f_notfound(a) && ! InsertFile(f_filename(a), DEFPATH, &fn)) { a->a_notfound = 1; Gerror("Could not find %s", f_filename(a)); return 0; } FileName = fn; LineNumber = 1; a->a_dir = WorkingDir = getwdir(FileName); return 1; } ProcessArgs() { register struct file_list *a; f_walk(arglist, a) { register char *p = strrchr(f_filename(a), '.'); CurrentArg = a; DEFPATH[0] = f_dir(a); if ( p && strcmp(p, ".def") == 0) { ForeignFlag = 0; if (! openfile(a)) { continue; } DefModule(); } else if (p && strcmp(p, ".mod") == 0) { if (! openfile(a)) { *p = 0; /* ??? */ continue; } CompUnit(); } else fatal("No Modula-2 file: %s", f_filename(a)); } } void No_Mem() { fatal("out of memory"); } AddToList(name, ext) char *name, *ext; { /* Try to find a file with basename "name" and extension ".def", in the directories mentioned in "DEFPATH". */ char buf[15]; char *strncpy(); if (strcmp(name, "SYSTEM") != 0 && ! is_library_dir(WorkingDir)) { strncpy(buf, name, 10); buf[10] = '\0'; /* maximum length */ strcat(buf, ext); Add(&arglist, buf, WorkingDir, 1); return 1; } return 0; } find_dependencies() { register struct file_list *arg; print("\nall:\t"); f_walk(arglist, arg) { char *fn = f_filename(arg); char *dotspot = strrchr(fn, '.'); if (dotspot && strcmp(dotspot, ".mod") == 0) { register struct idf *id = f_idf(arg); if (! f_notfound(arg) && id) { if (id->id_type == PROGRAM) { *dotspot = 0; print("%s ", fn); *dotspot = '.'; } file_dep(id); } } } print("\n\n"); print("objects:\t"); f_walk(arglist, arg) { char *fn = f_filename(arg); char *dotspot = strrchr(fn, '.'); if (dotspot && strcmp(dotspot, ".mod") == 0) { register struct idf *id = f_idf(arg); if (! f_notfound(arg) && id) { if (id->id_type == PROGRAM) { *dotspot = 0; print("%s_o_files ", fn); *dotspot = '.'; } } } } print("\n\n\n"); } file_dep(id) register struct idf *id; { register struct lnk *m; if (id->id_ddependson || id->id_mdependson) return; if (id->id_def) Add(&(id->id_mdependson), id->id_def, id->id_dir, 0); for (m = id->id_defimports; m; m = m->lnk_next) { register struct idf *iid = m->lnk_imp; Add(&(id->id_mdependson), iid->id_def, iid->id_dir, 0); if (Add(&(id->id_ddependson), iid->id_def, iid->id_dir, 0)) { register struct file_list *p; file_dep(iid); f_walk(iid->id_ddependson, p) { Add(&(id->id_ddependson), f_filename(p), f_dir(p), 0); Add(&(id->id_mdependson), f_filename(p), f_dir(p), 0); } } } for (m = id->id_modimports; m; m = m->lnk_next) { register struct idf *iid = m->lnk_imp; if (Add(&(id->id_mdependson), iid->id_def, iid->id_dir, 0)) { register struct file_list *p; file_dep(iid); f_walk(iid->id_ddependson, p) { Add(&(id->id_mdependson), f_filename(p), f_dir(p), 0); } } } } char * object(arg) register struct file_list *arg; { static char buf[512]; char *dotp = strrchr(f_filename(arg), '.'); buf[0] = 0; /* if (strcmp(f_dir(arg), ".") != 0) { strcpy(buf, f_dir(arg)); strcat(buf, "/"); } */ if (dotp) *dotp = 0; strcat(buf, f_filename(arg)); if (dotp) *dotp = '.'; strcat(buf, ".$(SUFFIX)"); return buf; } pr_arg(a) register struct file_list *a; { char *f = f_filename(a); char *d = f_dir(a); if (strcmp(d, ".") == 0 || *f == '/' || *f == '.') { print(f); } else print("%s/%s", d, f); } print_dep() { register struct file_list *arg; f_walk(arglist, arg) { char *dotspot = strrchr(f_filename(arg), '.'); if (dotspot && strcmp(dotspot, ".mod") == 0) { register struct idf *id = f_idf(arg); if (! f_notfound(arg) && id) { char *obj = object(arg); register struct file_list *a; print("%s: \\\n\t", obj); pr_arg(arg); f_walk(id->id_mdependson, a) { if (*(f_filename(a))) /* ??? */ { print(" \\\n\t"); pr_arg(a); } } print("\n\t$(MOD) -c $(M2FLAGS) $(IFLAGS) "); pr_arg(arg); print("\n"); } } } } prog_dep(id, a) register struct idf *id; struct file_list *a; { register struct lnk *m; register struct file_list *p; id->id_mdependson = 0; id->id_def = 0; if (id->id_type == PROGRAM) { Add(&(id->id_mdependson), f_filename(a), f_dir(a), 0); } else { if (strlen(id->id_text) >= 10) id->id_text[10] = 0; Add(&(id->id_mdependson), id->id_text, id->id_dir, 0); } for (m = id->id_modimports; m; m = m->lnk_next) { register struct idf *iid = m->lnk_imp; if (Add(&(id->id_mdependson), iid->id_text, iid->id_dir, 0)) { if (iid->id_def) prog_dep(iid); f_walk(iid->id_mdependson, p) { Add(&(id->id_mdependson), f_filename(p), f_dir(p), 0); } } } } module_in_arglist(n) char *n; { register struct file_list *a; f_walk(arglist, a) { char *dotp = strrchr(f_filename(a), '.'); if (dotp && strcmp(dotp, ".mod") == 0 && ! f_notfound(a)) { *dotp = 0; if (strcmp(f_filename(a), n) == 0) { *dotp = '.'; return 1; } *dotp = '.'; } } return 0; } pr_prog_dep(id, a) register struct idf *id; struct file_list *a; { register struct file_list *p; print("\nOBS_%s =", id->id_text); f_walk(id->id_mdependson, p) { if (module_in_arglist(f_filename(p)) || ! f_dir(p)) { print(" \\\n\t%s", object(p)); } } print("\n\nOBS2_%s =", id->id_text); f_walk(id->id_mdependson, p) { if (module_in_arglist(f_filename(p)) || ! f_dir(p)) { /* nothing */ } else if (! is_library_dir(f_dir(p))) { print(" \\\n\t%s/%s", f_dir(p), object(p)); } } print("\n\n"); print("%s_o_files:\t$(OBS_%s)\n\n", basename(f_filename(a)), id->id_text); print("%s:\t$(OBS_%s) $(OBS2_%s)\n", basename(f_filename(a)), id->id_text, id->id_text); print("\t$(MOD) -o %s $(M2FLAGS) $(OBS_%s) $(OBS2_%s) $(LIBS)\n", basename(f_filename(a)), id->id_text, id->id_text); } programs() { register struct file_list *a; f_walk(arglist, a) { char *dotspot = strrchr(f_filename(a), '.'); if (dotspot && strcmp(dotspot, ".mod") == 0) { register struct idf *id = f_idf(a); if (! f_notfound(a) && id && id->id_type == PROGRAM) { prog_dep(id, a); /* *dotspot = 0; */ pr_prog_dep(id, a); /* *dotspot = '.'; */ } } } }
{ "pile_set_name": "Github" }
# # Copyright (C) 2018-2020 Intel Corporation # # SPDX-License-Identifier: MIT # set(RUNTIME_SRCS_CL_DEVICE ${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt ${CMAKE_CURRENT_SOURCE_DIR}/cl_device.cpp ${CMAKE_CURRENT_SOURCE_DIR}/cl_device.h ${CMAKE_CURRENT_SOURCE_DIR}/cl_device_caps.cpp ${CMAKE_CURRENT_SOURCE_DIR}/cl_device_get_cap.inl ${CMAKE_CURRENT_SOURCE_DIR}/cl_device_info.cpp ${CMAKE_CURRENT_SOURCE_DIR}/cl_device_info.h ${CMAKE_CURRENT_SOURCE_DIR}/cl_device_info_map.h ${CMAKE_CURRENT_SOURCE_DIR}/cl_device_vector.h ) target_sources(${NEO_STATIC_LIB_NAME} PRIVATE ${RUNTIME_SRCS_CL_DEVICE}) set_property(GLOBAL PROPERTY RUNTIME_SRCS_CL_DEVICE ${RUNTIME_SRCS_CL_DEVICE}) add_subdirectories()
{ "pile_set_name": "Github" }
package types // import "github.com/docker/docker/api/types" import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/network" ) // configs holds structs used for internal communication between the // frontend (such as an http server) and the backend (such as the // docker daemon). // ContainerCreateConfig is the parameter set to ContainerCreate() type ContainerCreateConfig struct { Name string Config *container.Config HostConfig *container.HostConfig NetworkingConfig *network.NetworkingConfig AdjustCPUShares bool } // ContainerRmConfig holds arguments for the container remove // operation. This struct is used to tell the backend what operations // to perform. type ContainerRmConfig struct { ForceRemove, RemoveVolume, RemoveLink bool } // ExecConfig is a small subset of the Config struct that holds the configuration // for the exec feature of docker. type ExecConfig struct { User string // User that will run the command Privileged bool // Is the container in privileged mode Tty bool // Attach standard streams to a tty. AttachStdin bool // Attach the standard input, makes possible user interaction AttachStderr bool // Attach the standard error AttachStdout bool // Attach the standard output Detach bool // Execute in detach mode DetachKeys string // Escape keys for detach Env []string // Environment variables WorkingDir string // Working directory Cmd []string // Execution commands and args } // PluginRmConfig holds arguments for plugin remove. type PluginRmConfig struct { ForceRemove bool } // PluginEnableConfig holds arguments for plugin enable type PluginEnableConfig struct { Timeout int } // PluginDisableConfig holds arguments for plugin disable. type PluginDisableConfig struct { ForceDisable bool } // NetworkListConfig stores the options available for listing networks type NetworkListConfig struct { // TODO(@cpuguy83): naming is hard, this is pulled from what was being used in the router before moving here Detailed bool Verbose bool }
{ "pile_set_name": "Github" }
Universidad de Antofagasta
{ "pile_set_name": "Github" }
/* * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ /* * This source code is provided to illustrate the usage of a given feature * or technique and has been deliberately simplified. Additional steps * required for a production-quality application, such as security checks, * input validation and proper error handling, might not be present in * this sample code. */ package com.sun.tools.debug.gui; import java.io.File; import java.util.Hashtable; import java.util.Enumeration; import javax.swing.filechooser.*; //### Renamed from 'ExampleFileFilter.java' provided with Swing demos. /** * A convenience implementation of FileFilter that filters out * all files except for those type extensions that it knows about. * * Extensions are of the type ".foo", which is typically found on * Windows and Unix boxes, but not on Macinthosh. Case is ignored. * * Example - create a new filter that filerts out all files * but gif and jpg image files: * * JFileChooser chooser = new JFileChooser(); * ExampleFileFilter filter = new ExampleFileFilter( * new String{"gif", "jpg"}, "JPEG & GIF Images") * chooser.addChoosableFileFilter(filter); * chooser.showOpenDialog(this); * * @author Jeff Dinkins */ public class JDBFileFilter extends FileFilter { private static String TYPE_UNKNOWN = "Type Unknown"; private static String HIDDEN_FILE = "Hidden File"; private Hashtable<String, JDBFileFilter> filters = null; private String description = null; private String fullDescription = null; private boolean useExtensionsInDescription = true; /** * Creates a file filter. If no filters are added, then all * files are accepted. * * @see #addExtension */ public JDBFileFilter() { this.filters = new Hashtable<String, JDBFileFilter>(); } /** * Creates a file filter that accepts files with the given extension. * Example: new JDBFileFilter("jpg"); * * @see #addExtension */ public JDBFileFilter(String extension) { this(extension,null); } /** * Creates a file filter that accepts the given file type. * Example: new JDBFileFilter("jpg", "JPEG Image Images"); * * Note that the "." before the extension is not needed. If * provided, it will be ignored. * * @see #addExtension */ public JDBFileFilter(String extension, String description) { this(); if(extension!=null) { addExtension(extension); } if(description!=null) { setDescription(description); } } /** * Creates a file filter from the given string array. * Example: new JDBFileFilter(String {"gif", "jpg"}); * * Note that the "." before the extension is not needed adn * will be ignored. * * @see #addExtension */ public JDBFileFilter(String[] filters) { this(filters, null); } /** * Creates a file filter from the given string array and description. * Example: new JDBFileFilter(String {"gif", "jpg"}, "Gif and JPG Images"); * * Note that the "." before the extension is not needed and will be ignored. * * @see #addExtension */ public JDBFileFilter(String[] filters, String description) { this(); for (String filter : filters) { // add filters one by one addExtension(filter); } if(description!=null) { setDescription(description); } } /** * Return true if this file should be shown in the directory pane, * false if it shouldn't. * * Files that begin with "." are ignored. * * @see #getExtension * @see FileFilter#accepts */ @Override public boolean accept(File f) { if(f != null) { if(f.isDirectory()) { return true; } String extension = getExtension(f); if(extension != null && filters.get(getExtension(f)) != null) { return true; }; } return false; } /** * Return the extension portion of the file's name . * * @see #getExtension * @see FileFilter#accept */ public String getExtension(File f) { if(f != null) { String filename = f.getName(); int i = filename.lastIndexOf('.'); if(i>0 && i<filename.length()-1) { return filename.substring(i+1).toLowerCase(); }; } return null; } /** * Adds a filetype "dot" extension to filter against. * * For example: the following code will create a filter that filters * out all files except those that end in ".jpg" and ".tif": * * JDBFileFilter filter = new JDBFileFilter(); * filter.addExtension("jpg"); * filter.addExtension("tif"); * * Note that the "." before the extension is not needed and will be ignored. */ public void addExtension(String extension) { if(filters == null) { filters = new Hashtable<String, JDBFileFilter>(5); } filters.put(extension.toLowerCase(), this); fullDescription = null; } /** * Returns the human readable description of this filter. For * example: "JPEG and GIF Image Files (*.jpg, *.gif)" * * @see setDescription * @see setExtensionListInDescription * @see isExtensionListInDescription * @see FileFilter#getDescription */ @Override public String getDescription() { if(fullDescription == null) { if(description == null || isExtensionListInDescription()) { fullDescription = description==null ? "(" : description + " ("; // build the description from the extension list Enumeration<String> extensions = filters.keys(); if(extensions != null) { fullDescription += "." + extensions.nextElement(); while (extensions.hasMoreElements()) { fullDescription += ", " + extensions.nextElement(); } } fullDescription += ")"; } else { fullDescription = description; } } return fullDescription; } /** * Sets the human readable description of this filter. For * example: filter.setDescription("Gif and JPG Images"); * * @see setDescription * @see setExtensionListInDescription * @see isExtensionListInDescription */ public void setDescription(String description) { this.description = description; fullDescription = null; } /** * Determines whether the extension list (.jpg, .gif, etc) should * show up in the human readable description. * * Only relevent if a description was provided in the constructor * or using setDescription(); * * @see getDescription * @see setDescription * @see isExtensionListInDescription */ public void setExtensionListInDescription(boolean b) { useExtensionsInDescription = b; fullDescription = null; } /** * Returns whether the extension list (.jpg, .gif, etc) should * show up in the human readable description. * * Only relevent if a description was provided in the constructor * or using setDescription(); * * @see getDescription * @see setDescription * @see setExtensionListInDescription */ public boolean isExtensionListInDescription() { return useExtensionsInDescription; } }
{ "pile_set_name": "Github" }
#include "ProductionCode2.h" char* ThisFunctionHasNotBeenTested(int Poor, char* LittleFunction) { (void)Poor; (void)LittleFunction; //Since There Are No Tests Yet, This Function Could Be Empty For All We Know. // Which isn't terribly useful... but at least we put in a TEST_IGNORE so we won't forget return (char*)0; }
{ "pile_set_name": "Github" }
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.identity.impl.ldap; import java.util.HashSet; import static org.camunda.bpm.engine.authorization.Authorization.AUTH_TYPE_GRANT; import static org.camunda.bpm.engine.authorization.Permissions.READ; import static org.camunda.bpm.engine.authorization.Resources.GROUP; import java.util.List; import java.util.Set; import org.camunda.bpm.engine.authorization.Authorization; import org.camunda.bpm.engine.authorization.Permission; import org.camunda.bpm.engine.authorization.Resource; import org.camunda.bpm.engine.identity.Group; import static org.camunda.bpm.identity.impl.ldap.LdapTestUtilities.checkPagingResults; import static org.camunda.bpm.identity.impl.ldap.LdapTestUtilities.testGroupPaging; /** * @author Daniel Meyer * */ public class LdapGroupQueryTest extends LdapIdentityProviderTest { public void testQueryNoFilter() { List<Group> groupList = identityService.createGroupQuery().list(); assertEquals(6, groupList.size()); } public void testFilterByGroupId() { Group group = identityService.createGroupQuery().groupId("management").singleResult(); assertNotNull(group); // validate result assertEquals("management", group.getId()); assertEquals("management", group.getName()); group = identityService.createGroupQuery().groupId("whatever").singleResult(); assertNull(group); } public void testFilterByGroupIdIn() { List<Group> groups = identityService.createGroupQuery() .groupIdIn("external", "management") .list(); assertEquals(2, groups.size()); for (Group group : groups) { if (!group.getId().equals("external") && !group.getId().equals("management")) { fail(); } } } public void testFilterByGroupName() { Group group = identityService.createGroupQuery().groupName("management").singleResult(); assertNotNull(group); // validate result assertEquals("management", group.getId()); assertEquals("management", group.getName()); group = identityService.createGroupQuery().groupName("whatever").singleResult(); assertNull(group); } public void testFilterByGroupNameLike() { Group group = identityService.createGroupQuery().groupNameLike("manage*").singleResult(); assertNotNull(group); // validate result assertEquals("management", group.getId()); assertEquals("management", group.getName()); group = identityService.createGroupQuery().groupNameLike("what*").singleResult(); assertNull(group); } public void testFilterByGroupMember() { List<Group> list = identityService.createGroupQuery().groupMember("daniel").list(); assertEquals(3, list.size()); list = identityService.createGroupQuery().groupMember("oscar").list(); assertEquals(2, list.size()); list = identityService.createGroupQuery().groupMember("ruecker").list(); assertEquals(4, list.size()); list = identityService.createGroupQuery().groupMember("non-existing").list(); assertEquals(0, list.size()); } public void testFilterByGroupMemberSpecialCharacter() { List<Group> list = identityService.createGroupQuery().groupMember("david(IT)").list(); assertEquals(2, list.size()); } public void testFilterByGroupMemberPosix() { // by default the configuration does not use posix groups LdapConfiguration ldapConfiguration = new LdapConfiguration(); ldapConfiguration.setGroupMemberAttribute("memberUid"); ldapConfiguration.setGroupSearchFilter("(someFilter)"); LdapIdentityProviderSession session = new LdapIdentityProviderSession(ldapConfiguration) { // mock getDnForUser protected String getDnForUser(String userId) { return userId+ ", fullDn"; } }; // if I query for groups by group member LdapGroupQuery query = new LdapGroupQuery(); query.groupMember("jonny"); // then the full DN is requested. This is the default behavior. String filter = session.getGroupSearchFilter(query); assertEquals("(&(someFilter)(memberUid=jonny, fullDn))", filter); // If I turn on posix groups ldapConfiguration.setUsePosixGroups(true); // then the filter string does not contain the full DN for the // user but the simple (unqualified) userId as provided in the query filter = session.getGroupSearchFilter(query); assertEquals("(&(someFilter)(memberUid=jonny))", filter); } public void testPagination() { testGroupPaging(identityService); } public void testPaginationWithAuthenticatedUser() { createGrantAuthorization(GROUP, "management", "oscar", READ); createGrantAuthorization(GROUP, "consulting", "oscar", READ); createGrantAuthorization(GROUP, "external", "oscar", READ); try { processEngineConfiguration.setAuthorizationEnabled(true); identityService.setAuthenticatedUserId("oscar"); Set<String> groupNames = new HashSet<>(); List<Group> groups = identityService.createGroupQuery().listPage(0, 2); assertEquals(2, groups.size()); checkPagingResults(groupNames, groups.get(0).getId(), groups.get(1).getId()); groups = identityService.createGroupQuery().listPage(2, 2); assertEquals(1, groups.size()); assertFalse(groupNames.contains(groups.get(0).getId())); groupNames.add(groups.get(0).getId()); groups = identityService.createGroupQuery().listPage(4, 2); assertEquals(0, groups.size()); identityService.setAuthenticatedUserId("daniel"); groups = identityService.createGroupQuery().listPage(0, 2); assertEquals(0, groups.size()); } finally { processEngineConfiguration.setAuthorizationEnabled(false); identityService.clearAuthentication(); for (Authorization authorization : authorizationService.createAuthorizationQuery().list()) { authorizationService.deleteAuthorization(authorization.getId()); } } } protected void createGrantAuthorization(Resource resource, String resourceId, String userId, Permission... permissions) { Authorization authorization = createAuthorization(AUTH_TYPE_GRANT, resource, resourceId); authorization.setUserId(userId); for (Permission permission : permissions) { authorization.addPermission(permission); } authorizationService.saveAuthorization(authorization); } protected Authorization createAuthorization(int type, Resource resource, String resourceId) { Authorization authorization = authorizationService.createNewAuthorization(type); authorization.setResource(resource); if (resourceId != null) { authorization.setResourceId(resourceId); } return authorization; } }
{ "pile_set_name": "Github" }
/* ======================================================================== * Copyright (c) 2005-2017 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * The complete license agreement can be found here: * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ namespace Quickstarts.HistoricalAccess.Client { partial class WriteValueDlg { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.CancelBTN = new System.Windows.Forms.Button(); this.OkBTN = new System.Windows.Forms.Button(); this.ValueLB = new System.Windows.Forms.Label(); this.ValueTB = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // CancelBTN // this.CancelBTN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.CancelBTN.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.CancelBTN.Location = new System.Drawing.Point(305, 36); this.CancelBTN.Name = "CancelBTN"; this.CancelBTN.Size = new System.Drawing.Size(75, 23); this.CancelBTN.TabIndex = 5; this.CancelBTN.Text = "Cancel"; this.CancelBTN.UseVisualStyleBackColor = true; // // OkBTN // this.OkBTN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.OkBTN.Location = new System.Drawing.Point(12, 36); this.OkBTN.Name = "OkBTN"; this.OkBTN.Size = new System.Drawing.Size(75, 23); this.OkBTN.TabIndex = 4; this.OkBTN.Text = "OK"; this.OkBTN.UseVisualStyleBackColor = true; this.OkBTN.Click += new System.EventHandler(this.OkBTN_Click); // // ValueLB // this.ValueLB.AutoSize = true; this.ValueLB.Location = new System.Drawing.Point(12, 9); this.ValueLB.Name = "ValueLB"; this.ValueLB.Size = new System.Drawing.Size(34, 13); this.ValueLB.TabIndex = 0; this.ValueLB.Text = "Value"; // // ValueTB // this.ValueTB.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ValueTB.Location = new System.Drawing.Point(52, 6); this.ValueTB.Name = "ValueTB"; this.ValueTB.Size = new System.Drawing.Size(328, 20); this.ValueTB.TabIndex = 1; // // WriteValueDlg // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(392, 71); this.Controls.Add(this.ValueTB); this.Controls.Add(this.ValueLB); this.Controls.Add(this.OkBTN); this.Controls.Add(this.CancelBTN); this.MaximumSize = new System.Drawing.Size(1024, 107); this.MinimumSize = new System.Drawing.Size(16, 107); this.Name = "WriteValueDlg"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Enter Value to Write"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button CancelBTN; private System.Windows.Forms.Button OkBTN; private System.Windows.Forms.Label ValueLB; private System.Windows.Forms.TextBox ValueTB; } }
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0 /* * bsg.c - block layer implementation of the sg v4 interface */ #include <linux/module.h> #include <linux/init.h> #include <linux/file.h> #include <linux/blkdev.h> #include <linux/cdev.h> #include <linux/jiffies.h> #include <linux/percpu.h> #include <linux/idr.h> #include <linux/bsg.h> #include <linux/slab.h> #include <scsi/scsi.h> #include <scsi/scsi_ioctl.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_device.h> #include <scsi/scsi_driver.h> #include <scsi/sg.h> #define BSG_DESCRIPTION "Block layer SCSI generic (bsg) driver" #define BSG_VERSION "0.4" #define bsg_dbg(bd, fmt, ...) \ pr_debug("%s: " fmt, (bd)->name, ##__VA_ARGS__) struct bsg_device { struct request_queue *queue; spinlock_t lock; struct hlist_node dev_list; refcount_t ref_count; char name[20]; int max_queue; }; #define BSG_DEFAULT_CMDS 64 #define BSG_MAX_DEVS 32768 static DEFINE_MUTEX(bsg_mutex); static DEFINE_IDR(bsg_minor_idr); #define BSG_LIST_ARRAY_SIZE 8 static struct hlist_head bsg_device_list[BSG_LIST_ARRAY_SIZE]; static struct class *bsg_class; static int bsg_major; static inline struct hlist_head *bsg_dev_idx_hash(int index) { return &bsg_device_list[index & (BSG_LIST_ARRAY_SIZE - 1)]; } #define uptr64(val) ((void __user *)(uintptr_t)(val)) static int bsg_scsi_check_proto(struct sg_io_v4 *hdr) { if (hdr->protocol != BSG_PROTOCOL_SCSI || hdr->subprotocol != BSG_SUB_PROTOCOL_SCSI_CMD) return -EINVAL; return 0; } static int bsg_scsi_fill_hdr(struct request *rq, struct sg_io_v4 *hdr, fmode_t mode) { struct scsi_request *sreq = scsi_req(rq); if (hdr->dout_xfer_len && hdr->din_xfer_len) { pr_warn_once("BIDI support in bsg has been removed.\n"); return -EOPNOTSUPP; } sreq->cmd_len = hdr->request_len; if (sreq->cmd_len > BLK_MAX_CDB) { sreq->cmd = kzalloc(sreq->cmd_len, GFP_KERNEL); if (!sreq->cmd) return -ENOMEM; } if (copy_from_user(sreq->cmd, uptr64(hdr->request), sreq->cmd_len)) return -EFAULT; if (blk_verify_command(sreq->cmd, mode)) return -EPERM; return 0; } static int bsg_scsi_complete_rq(struct request *rq, struct sg_io_v4 *hdr) { struct scsi_request *sreq = scsi_req(rq); int ret = 0; /* * fill in all the output members */ hdr->device_status = sreq->result & 0xff; hdr->transport_status = host_byte(sreq->result); hdr->driver_status = driver_byte(sreq->result); hdr->info = 0; if (hdr->device_status || hdr->transport_status || hdr->driver_status) hdr->info |= SG_INFO_CHECK; hdr->response_len = 0; if (sreq->sense_len && hdr->response) { int len = min_t(unsigned int, hdr->max_response_len, sreq->sense_len); if (copy_to_user(uptr64(hdr->response), sreq->sense, len)) ret = -EFAULT; else hdr->response_len = len; } if (rq_data_dir(rq) == READ) hdr->din_resid = sreq->resid_len; else hdr->dout_resid = sreq->resid_len; return ret; } static void bsg_scsi_free_rq(struct request *rq) { scsi_req_free_cmd(scsi_req(rq)); } static const struct bsg_ops bsg_scsi_ops = { .check_proto = bsg_scsi_check_proto, .fill_hdr = bsg_scsi_fill_hdr, .complete_rq = bsg_scsi_complete_rq, .free_rq = bsg_scsi_free_rq, }; static int bsg_sg_io(struct request_queue *q, fmode_t mode, void __user *uarg) { struct request *rq; struct bio *bio; struct sg_io_v4 hdr; int ret; if (copy_from_user(&hdr, uarg, sizeof(hdr))) return -EFAULT; if (!q->bsg_dev.class_dev) return -ENXIO; if (hdr.guard != 'Q') return -EINVAL; ret = q->bsg_dev.ops->check_proto(&hdr); if (ret) return ret; rq = blk_get_request(q, hdr.dout_xfer_len ? REQ_OP_SCSI_OUT : REQ_OP_SCSI_IN, 0); if (IS_ERR(rq)) return PTR_ERR(rq); ret = q->bsg_dev.ops->fill_hdr(rq, &hdr, mode); if (ret) return ret; rq->timeout = msecs_to_jiffies(hdr.timeout); if (!rq->timeout) rq->timeout = q->sg_timeout; if (!rq->timeout) rq->timeout = BLK_DEFAULT_SG_TIMEOUT; if (rq->timeout < BLK_MIN_SG_TIMEOUT) rq->timeout = BLK_MIN_SG_TIMEOUT; if (hdr.dout_xfer_len) { ret = blk_rq_map_user(q, rq, NULL, uptr64(hdr.dout_xferp), hdr.dout_xfer_len, GFP_KERNEL); } else if (hdr.din_xfer_len) { ret = blk_rq_map_user(q, rq, NULL, uptr64(hdr.din_xferp), hdr.din_xfer_len, GFP_KERNEL); } if (ret) goto out_free_rq; bio = rq->bio; blk_execute_rq(q, NULL, rq, !(hdr.flags & BSG_FLAG_Q_AT_TAIL)); ret = rq->q->bsg_dev.ops->complete_rq(rq, &hdr); blk_rq_unmap_user(bio); out_free_rq: rq->q->bsg_dev.ops->free_rq(rq); blk_put_request(rq); if (!ret && copy_to_user(uarg, &hdr, sizeof(hdr))) return -EFAULT; return ret; } static struct bsg_device *bsg_alloc_device(void) { struct bsg_device *bd; bd = kzalloc(sizeof(struct bsg_device), GFP_KERNEL); if (unlikely(!bd)) return NULL; spin_lock_init(&bd->lock); bd->max_queue = BSG_DEFAULT_CMDS; INIT_HLIST_NODE(&bd->dev_list); return bd; } static int bsg_put_device(struct bsg_device *bd) { struct request_queue *q = bd->queue; mutex_lock(&bsg_mutex); if (!refcount_dec_and_test(&bd->ref_count)) { mutex_unlock(&bsg_mutex); return 0; } hlist_del(&bd->dev_list); mutex_unlock(&bsg_mutex); bsg_dbg(bd, "tearing down\n"); /* * close can always block */ kfree(bd); blk_put_queue(q); return 0; } static struct bsg_device *bsg_add_device(struct inode *inode, struct request_queue *rq, struct file *file) { struct bsg_device *bd; unsigned char buf[32]; lockdep_assert_held(&bsg_mutex); if (!blk_get_queue(rq)) return ERR_PTR(-ENXIO); bd = bsg_alloc_device(); if (!bd) { blk_put_queue(rq); return ERR_PTR(-ENOMEM); } bd->queue = rq; refcount_set(&bd->ref_count, 1); hlist_add_head(&bd->dev_list, bsg_dev_idx_hash(iminor(inode))); strncpy(bd->name, dev_name(rq->bsg_dev.class_dev), sizeof(bd->name) - 1); bsg_dbg(bd, "bound to <%s>, max queue %d\n", format_dev_t(buf, inode->i_rdev), bd->max_queue); return bd; } static struct bsg_device *__bsg_get_device(int minor, struct request_queue *q) { struct bsg_device *bd; lockdep_assert_held(&bsg_mutex); hlist_for_each_entry(bd, bsg_dev_idx_hash(minor), dev_list) { if (bd->queue == q) { refcount_inc(&bd->ref_count); goto found; } } bd = NULL; found: return bd; } static struct bsg_device *bsg_get_device(struct inode *inode, struct file *file) { struct bsg_device *bd; struct bsg_class_device *bcd; /* * find the class device */ mutex_lock(&bsg_mutex); bcd = idr_find(&bsg_minor_idr, iminor(inode)); if (!bcd) { bd = ERR_PTR(-ENODEV); goto out_unlock; } bd = __bsg_get_device(iminor(inode), bcd->queue); if (!bd) bd = bsg_add_device(inode, bcd->queue, file); out_unlock: mutex_unlock(&bsg_mutex); return bd; } static int bsg_open(struct inode *inode, struct file *file) { struct bsg_device *bd; bd = bsg_get_device(inode, file); if (IS_ERR(bd)) return PTR_ERR(bd); file->private_data = bd; return 0; } static int bsg_release(struct inode *inode, struct file *file) { struct bsg_device *bd = file->private_data; file->private_data = NULL; return bsg_put_device(bd); } static int bsg_get_command_q(struct bsg_device *bd, int __user *uarg) { return put_user(bd->max_queue, uarg); } static int bsg_set_command_q(struct bsg_device *bd, int __user *uarg) { int queue; if (get_user(queue, uarg)) return -EFAULT; if (queue < 1) return -EINVAL; spin_lock_irq(&bd->lock); bd->max_queue = queue; spin_unlock_irq(&bd->lock); return 0; } static long bsg_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct bsg_device *bd = file->private_data; void __user *uarg = (void __user *) arg; switch (cmd) { /* * Our own ioctls */ case SG_GET_COMMAND_Q: return bsg_get_command_q(bd, uarg); case SG_SET_COMMAND_Q: return bsg_set_command_q(bd, uarg); /* * SCSI/sg ioctls */ case SG_GET_VERSION_NUM: case SCSI_IOCTL_GET_IDLUN: case SCSI_IOCTL_GET_BUS_NUMBER: case SG_SET_TIMEOUT: case SG_GET_TIMEOUT: case SG_GET_RESERVED_SIZE: case SG_SET_RESERVED_SIZE: case SG_EMULATED_HOST: case SCSI_IOCTL_SEND_COMMAND: return scsi_cmd_ioctl(bd->queue, NULL, file->f_mode, cmd, uarg); case SG_IO: return bsg_sg_io(bd->queue, file->f_mode, uarg); default: return -ENOTTY; } } static const struct file_operations bsg_fops = { .open = bsg_open, .release = bsg_release, .unlocked_ioctl = bsg_ioctl, .compat_ioctl = compat_ptr_ioctl, .owner = THIS_MODULE, .llseek = default_llseek, }; void bsg_unregister_queue(struct request_queue *q) { struct bsg_class_device *bcd = &q->bsg_dev; if (!bcd->class_dev) return; mutex_lock(&bsg_mutex); idr_remove(&bsg_minor_idr, bcd->minor); if (q->kobj.sd) sysfs_remove_link(&q->kobj, "bsg"); device_unregister(bcd->class_dev); bcd->class_dev = NULL; mutex_unlock(&bsg_mutex); } EXPORT_SYMBOL_GPL(bsg_unregister_queue); int bsg_register_queue(struct request_queue *q, struct device *parent, const char *name, const struct bsg_ops *ops) { struct bsg_class_device *bcd; dev_t dev; int ret; struct device *class_dev = NULL; /* * we need a proper transport to send commands, not a stacked device */ if (!queue_is_mq(q)) return 0; bcd = &q->bsg_dev; memset(bcd, 0, sizeof(*bcd)); mutex_lock(&bsg_mutex); ret = idr_alloc(&bsg_minor_idr, bcd, 0, BSG_MAX_DEVS, GFP_KERNEL); if (ret < 0) { if (ret == -ENOSPC) { printk(KERN_ERR "bsg: too many bsg devices\n"); ret = -EINVAL; } goto unlock; } bcd->minor = ret; bcd->queue = q; bcd->ops = ops; dev = MKDEV(bsg_major, bcd->minor); class_dev = device_create(bsg_class, parent, dev, NULL, "%s", name); if (IS_ERR(class_dev)) { ret = PTR_ERR(class_dev); goto idr_remove; } bcd->class_dev = class_dev; if (q->kobj.sd) { ret = sysfs_create_link(&q->kobj, &bcd->class_dev->kobj, "bsg"); if (ret) goto unregister_class_dev; } mutex_unlock(&bsg_mutex); return 0; unregister_class_dev: device_unregister(class_dev); idr_remove: idr_remove(&bsg_minor_idr, bcd->minor); unlock: mutex_unlock(&bsg_mutex); return ret; } int bsg_scsi_register_queue(struct request_queue *q, struct device *parent) { if (!blk_queue_scsi_passthrough(q)) { WARN_ONCE(true, "Attempt to register a non-SCSI queue\n"); return -EINVAL; } return bsg_register_queue(q, parent, dev_name(parent), &bsg_scsi_ops); } EXPORT_SYMBOL_GPL(bsg_scsi_register_queue); static struct cdev bsg_cdev; static char *bsg_devnode(struct device *dev, umode_t *mode) { return kasprintf(GFP_KERNEL, "bsg/%s", dev_name(dev)); } static int __init bsg_init(void) { int ret, i; dev_t devid; for (i = 0; i < BSG_LIST_ARRAY_SIZE; i++) INIT_HLIST_HEAD(&bsg_device_list[i]); bsg_class = class_create(THIS_MODULE, "bsg"); if (IS_ERR(bsg_class)) return PTR_ERR(bsg_class); bsg_class->devnode = bsg_devnode; ret = alloc_chrdev_region(&devid, 0, BSG_MAX_DEVS, "bsg"); if (ret) goto destroy_bsg_class; bsg_major = MAJOR(devid); cdev_init(&bsg_cdev, &bsg_fops); ret = cdev_add(&bsg_cdev, MKDEV(bsg_major, 0), BSG_MAX_DEVS); if (ret) goto unregister_chrdev; printk(KERN_INFO BSG_DESCRIPTION " version " BSG_VERSION " loaded (major %d)\n", bsg_major); return 0; unregister_chrdev: unregister_chrdev_region(MKDEV(bsg_major, 0), BSG_MAX_DEVS); destroy_bsg_class: class_destroy(bsg_class); return ret; } MODULE_AUTHOR("Jens Axboe"); MODULE_DESCRIPTION(BSG_DESCRIPTION); MODULE_LICENSE("GPL"); device_initcall(bsg_init);
{ "pile_set_name": "Github" }
require 'rails_helper' RSpec.describe Protip, type: :model do let(:protip) {Fabricate(:protip)} it 'should respond to ownership instance methods' do expect(protip).to respond_to :owned_by? expect(protip).to respond_to :owner? end end
{ "pile_set_name": "Github" }
/** * @fileoverview Rule to flag variable leak in CatchClauses in IE 8 and earlier * @author Ian Christian Myers */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const astUtils = require("../ast-utils"); //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "disallow `catch` clause parameters from shadowing variables in the outer scope", category: "Variables", recommended: false, url: "https://eslint.org/docs/rules/no-catch-shadow" }, schema: [], messages: { mutable: "Value of '{{name}}' may be overwritten in IE 8 and earlier." } }, create(context) { //-------------------------------------------------------------------------- // Helpers //-------------------------------------------------------------------------- /** * Check if the parameters are been shadowed * @param {Object} scope current scope * @param {string} name parameter name * @returns {boolean} True is its been shadowed */ function paramIsShadowing(scope, name) { return astUtils.getVariableByName(scope, name) !== null; } //-------------------------------------------------------------------------- // Public API //-------------------------------------------------------------------------- return { CatchClause(node) { let scope = context.getScope(); /* * When ecmaVersion >= 6, CatchClause creates its own scope * so start from one upper scope to exclude the current node */ if (scope.block === node) { scope = scope.upper; } if (paramIsShadowing(scope, node.param.name)) { context.report({ node, messageId: "mutable", data: { name: node.param.name } }); } } }; } };
{ "pile_set_name": "Github" }
// Check if a user is valid before proceeding with execution user = model("user").new(params.user); if user.valid(){ // Do something here }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_35) on Tue Oct 16 22:49:45 ICT 2012 --> <TITLE> StreamCacheFactory (Apache FOP 1.1 API) </TITLE> <META NAME="date" CONTENT="2012-10-16"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="StreamCacheFactory (Apache FOP 1.1 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/StreamCacheFactory.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> fop 1.1</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/apache/fop/pdf/StreamCache.html" title="interface in org.apache.fop.pdf"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../org/apache/fop/pdf/TempFileStreamCache.html" title="class in org.apache.fop.pdf"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/apache/fop/pdf/StreamCacheFactory.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="StreamCacheFactory.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.apache.fop.pdf</FONT> <BR> Class StreamCacheFactory</H2> <PRE> java.lang.Object <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.fop.pdf.StreamCacheFactory</B> </PRE> <HR> <DL> <DT><PRE>public class <B>StreamCacheFactory</B><DT>extends java.lang.Object</DL> </PRE> <P> This class is serves as a factory from <P> <P> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../org/apache/fop/pdf/StreamCacheFactory.html#StreamCacheFactory(boolean)">StreamCacheFactory</A></B>(boolean&nbsp;cacheToFile)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creates a new StreamCacheFactory.</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../org/apache/fop/pdf/StreamCache.html" title="interface in org.apache.fop.pdf">StreamCache</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/apache/fop/pdf/StreamCacheFactory.html#createStreamCache()">createStreamCache</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Get the correct implementation (based on cacheToFile) of StreamCache.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../org/apache/fop/pdf/StreamCache.html" title="interface in org.apache.fop.pdf">StreamCache</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/apache/fop/pdf/StreamCacheFactory.html#createStreamCache(int)">createStreamCache</A></B>(int&nbsp;hintSize)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Get the correct implementation (based on cacheToFile) of StreamCache.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/apache/fop/pdf/StreamCacheFactory.html#getCacheToFile()">getCacheToFile</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Get the value of the global cacheToFile flag.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../org/apache/fop/pdf/StreamCacheFactory.html" title="class in org.apache.fop.pdf">StreamCacheFactory</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/apache/fop/pdf/StreamCacheFactory.html#getInstance()">getInstance</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns an instance of a StreamCacheFactory depending on the default setting for cacheToFile.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../org/apache/fop/pdf/StreamCacheFactory.html" title="class in org.apache.fop.pdf">StreamCacheFactory</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/apache/fop/pdf/StreamCacheFactory.html#getInstance(boolean)">getInstance</A></B>(boolean&nbsp;cacheToFile)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns an instance of a StreamCacheFactory with the requested features.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/apache/fop/pdf/StreamCacheFactory.html#setDefaultCacheToFile(boolean)">setDefaultCacheToFile</A></B>(boolean&nbsp;cacheToFile)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets the global default for cacheToFile</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="StreamCacheFactory(boolean)"><!-- --></A><H3> StreamCacheFactory</H3> <PRE> public <B>StreamCacheFactory</B>(boolean&nbsp;cacheToFile)</PRE> <DL> <DD>Creates a new StreamCacheFactory. <P> <DL> <DT><B>Parameters:</B><DD><CODE>cacheToFile</CODE> - True if file shall be cached using a temporary file</DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getInstance(boolean)"><!-- --></A><H3> getInstance</H3> <PRE> public static <A HREF="../../../../org/apache/fop/pdf/StreamCacheFactory.html" title="class in org.apache.fop.pdf">StreamCacheFactory</A> <B>getInstance</B>(boolean&nbsp;cacheToFile)</PRE> <DL> <DD>Returns an instance of a StreamCacheFactory with the requested features. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>cacheToFile</CODE> - True if file shall be cached using a temporary file <DT><B>Returns:</B><DD>StreamCacheFactory the requested factory</DL> </DD> </DL> <HR> <A NAME="getInstance()"><!-- --></A><H3> getInstance</H3> <PRE> public static <A HREF="../../../../org/apache/fop/pdf/StreamCacheFactory.html" title="class in org.apache.fop.pdf">StreamCacheFactory</A> <B>getInstance</B>()</PRE> <DL> <DD>Returns an instance of a StreamCacheFactory depending on the default setting for cacheToFile. <P> <DD><DL> <DT><B>Returns:</B><DD>StreamCacheFactory the requested factory</DL> </DD> </DL> <HR> <A NAME="setDefaultCacheToFile(boolean)"><!-- --></A><H3> setDefaultCacheToFile</H3> <PRE> public static void <B>setDefaultCacheToFile</B>(boolean&nbsp;cacheToFile)</PRE> <DL> <DD>Sets the global default for cacheToFile <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>cacheToFile</CODE> - True if stream caches should be held in files.</DL> </DD> </DL> <HR> <A NAME="createStreamCache()"><!-- --></A><H3> createStreamCache</H3> <PRE> public <A HREF="../../../../org/apache/fop/pdf/StreamCache.html" title="interface in org.apache.fop.pdf">StreamCache</A> <B>createStreamCache</B>() throws java.io.IOException</PRE> <DL> <DD>Get the correct implementation (based on cacheToFile) of StreamCache. <P> <DD><DL> <DT><B>Returns:</B><DD>a new StreamCache for caching streams <DT><B>Throws:</B> <DD><CODE>java.io.IOException</CODE> - if there is an IO error</DL> </DD> </DL> <HR> <A NAME="createStreamCache(int)"><!-- --></A><H3> createStreamCache</H3> <PRE> public <A HREF="../../../../org/apache/fop/pdf/StreamCache.html" title="interface in org.apache.fop.pdf">StreamCache</A> <B>createStreamCache</B>(int&nbsp;hintSize) throws java.io.IOException</PRE> <DL> <DD>Get the correct implementation (based on cacheToFile) of StreamCache. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>hintSize</CODE> - a hint about the approximate expected size of the buffer <DT><B>Returns:</B><DD>a new StreamCache for caching streams <DT><B>Throws:</B> <DD><CODE>java.io.IOException</CODE> - if there is an IO error</DL> </DD> </DL> <HR> <A NAME="getCacheToFile()"><!-- --></A><H3> getCacheToFile</H3> <PRE> public boolean <B>getCacheToFile</B>()</PRE> <DL> <DD>Get the value of the global cacheToFile flag. <P> <DD><DL> <DT><B>Returns:</B><DD>the current cache to file flag</DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/StreamCacheFactory.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> fop 1.1</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/apache/fop/pdf/StreamCache.html" title="interface in org.apache.fop.pdf"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../org/apache/fop/pdf/TempFileStreamCache.html" title="class in org.apache.fop.pdf"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/apache/fop/pdf/StreamCacheFactory.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="StreamCacheFactory.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright 1999-2012 The Apache Software Foundation. All Rights Reserved. </BODY> </HTML>
{ "pile_set_name": "Github" }
--- title: Color.Green Property (Visio) keywords: vis_sdr.chm12213610 f1_keywords: - vis_sdr.chm12213610 ms.prod: visio api_name: - Visio.Color.Green ms.assetid: 19d792e0-1fc7-e302-eb7d-8a80ad287a52 ms.date: 06/08/2017 --- # Color.Green Property (Visio) Gets or sets the intensity of the green component of a **Color** object. Read/write. ## Syntax _expression_ . **Green** _expression_ A variable that represents a **Color** object. ### Return Value Integer ## Remarks The **Green** property can be a value from 0 to 255. A color is represented by red, green, and blue components. It also has flags that indicate how the color is to be used. These correspond to members of the Microsoft Windows **PALETTEENTRY** data structure. For details, search for "PALETTEENTRY" in the Microsoft Platform SDK on MSDN, the Microsoft Developer Network.
{ "pile_set_name": "Github" }
--- name: "\U0001F680 Feature Request" about: "I have a suggestion (and may want to implement it \U0001F642)!" --- 👆👆👆 CLICK ON PREVIEW, PLEASE! 👆👆👆 --- ## Awesome, do you have an idea? 😍 Please, if you have any **feature request, improvement or idea** to give us, check it [our official roadmap](http://feedback.docz.site/roadmap) to see if this is already being planned or not! ### 👉 &nbsp; [Go to Roadmap](http://feedback.docz.site/roadmap) If your feature request isn't there, post it here on Github, we will discuss a lot about it and then maybe became official on our roadmap 🤟
{ "pile_set_name": "Github" }
(* *********************************************************************) (* *) (* The Compcert verified compiler *) (* *) (* Xavier Leroy, INRIA Paris-Rocquencourt *) (* Jacques-Henri Jourdan, INRIA Paris-Rocquencourt *) (* *) (* Copyright Institut National de Recherche en Informatique et en *) (* Automatique. All rights reserved. This file is distributed *) (* under the terms of the GNU General Public License as published by *) (* the Free Software Foundation, either version 2 of the License, or *) (* (at your option) any later version. This file is also distributed *) (* under the terms of the INRIA Non-Commercial License Agreement. *) (* *) (* *********************************************************************) (** Additional operations and proofs about IEEE-754 binary floating-point numbers, on top of the Flocq library. *) Require Import Psatz. Require Import Bool. Require Import Eqdep_dec. Require Import Fcore. Require Import Fcore_digits. Require Import Fcalc_digits. Require Import Fcalc_ops. Require Import Fcalc_round. Require Import Fcalc_bracket. Require Import Fprop_Sterbenz. Require Import Fappli_IEEE. Require Import Fappli_rnd_odd. Local Open Scope Z_scope. Section Extra_ops. (** [prec] is the number of bits of the mantissa including the implicit one. [emax] is the exponent of the infinities. Typically p=24 and emax = 128 in single precision. *) Variable prec emax : Z. Context (prec_gt_0_ : Prec_gt_0 prec). Let emin := (3 - emax - prec)%Z. Let fexp := FLT_exp emin prec. Hypothesis Hmax : (prec < emax)%Z. Let binary_float := binary_float prec emax. (** Remarks on [is_finite] *) Remark is_finite_not_is_nan: forall (f: binary_float), is_finite _ _ f = true -> is_nan _ _ f = false. Proof. destruct f; reflexivity || discriminate. Qed. Remark is_finite_strict_finite: forall (f: binary_float), is_finite_strict _ _ f = true -> is_finite _ _ f = true. Proof. destruct f; reflexivity || discriminate. Qed. (** Digression on FP numbers that cannot be [-0.0]. *) Definition is_finite_pos0 (f: binary_float) : bool := match f with | B754_zero _ _ s => negb s | B754_infinity _ _ _ => false | B754_nan _ _ _ _ => false | B754_finite _ _ _ _ _ _ => true end. Lemma Bsign_pos0: forall x, is_finite_pos0 x = true -> Bsign _ _ x = Rlt_bool (B2R _ _ x) 0%R. Proof. intros. destruct x as [ [] | | | [] ex mx Bx ]; try discriminate; simpl. - rewrite Rlt_bool_false; auto. lra. - rewrite Rlt_bool_true; auto. apply F2R_lt_0_compat. compute; auto. - rewrite Rlt_bool_false; auto. assert ((F2R (Float radix2 (Z.pos ex) mx) > 0)%R) by ( apply F2R_gt_0_compat; compute; auto ). lra. Qed. Theorem B2R_inj_pos0: forall x y, is_finite_pos0 x = true -> is_finite_pos0 y = true -> B2R _ _ x = B2R _ _ y -> x = y. Proof. intros. apply B2R_Bsign_inj. destruct x; reflexivity||discriminate. destruct y; reflexivity||discriminate. auto. rewrite ! Bsign_pos0 by auto. rewrite H1; auto. Qed. (** ** Decidable equality *) Definition Beq_dec: forall (f1 f2: binary_float), {f1 = f2} + {f1 <> f2}. Proof. assert (UIP_bool: forall (b1 b2: bool) (e e': b1 = b2), e = e'). { intros. apply UIP_dec. decide equality. } Ltac try_not_eq := try solve [right; congruence]. destruct f1 as [| |? []|], f2 as [| |? []|]; try destruct b; try destruct b0; try solve [left; auto]; try_not_eq. destruct (Pos.eq_dec x x0); try_not_eq; subst; left; f_equal; f_equal; apply UIP_bool. destruct (Pos.eq_dec x x0); try_not_eq; subst; left; f_equal; f_equal; apply UIP_bool. destruct (Pos.eq_dec m m0); try_not_eq; destruct (Z.eq_dec e e1); try solve [right; intro H; inversion H; congruence]; subst; left; f_equal; apply UIP_bool. destruct (Pos.eq_dec m m0); try_not_eq; destruct (Z.eq_dec e e1); try solve [right; intro H; inversion H; congruence]; subst; left; f_equal; apply UIP_bool. Defined. (** ** Conversion from an integer to a FP number *) (** Integers that can be represented exactly as FP numbers. *) Definition integer_representable (n: Z): Prop := Z.abs n <= 2^emax - 2^(emax - prec) /\ generic_format radix2 fexp (Z2R n). Let int_upper_bound_eq: 2^emax - 2^(emax - prec) = (2^prec - 1) * 2^(emax - prec). Proof. red in prec_gt_0_. ring_simplify. rewrite <- (Zpower_plus radix2) by omega. f_equal. f_equal. omega. Qed. Lemma integer_representable_n2p: forall n p, -2^prec < n < 2^prec -> 0 <= p -> p <= emax - prec -> integer_representable (n * 2^p). Proof. intros; split. - red in prec_gt_0_. replace (Z.abs (n * 2^p)) with (Z.abs n * 2^p). rewrite int_upper_bound_eq. apply Zmult_le_compat. zify; omega. apply (Zpower_le radix2); omega. zify; omega. apply (Zpower_ge_0 radix2). rewrite Z.abs_mul. f_equal. rewrite Z.abs_eq. auto. apply (Zpower_ge_0 radix2). - apply generic_format_FLT. exists (Float radix2 n p). unfold F2R; simpl. split. rewrite <- Z2R_Zpower by auto. apply Z2R_mult. split. zify; omega. unfold emin; red in prec_gt_0_; omega. Qed. Lemma integer_representable_2p: forall p, 0 <= p <= emax - 1 -> integer_representable (2^p). Proof. intros; split. - red in prec_gt_0_. rewrite Z.abs_eq by (apply (Zpower_ge_0 radix2)). apply Z.le_trans with (2^(emax-1)). apply (Zpower_le radix2); omega. assert (2^emax = 2^(emax-1)*2). { change 2 with (2^1) at 3. rewrite <- (Zpower_plus radix2) by omega. f_equal. omega. } assert (2^(emax - prec) <= 2^(emax - 1)). { apply (Zpower_le radix2). omega. } omega. - red in prec_gt_0_. apply generic_format_FLT. exists (Float radix2 1 p). unfold F2R; simpl. split. rewrite Rmult_1_l. rewrite <- Z2R_Zpower. auto. omega. split. change 1 with (2^0). apply (Zpower_lt radix2). omega. auto. unfold emin; omega. Qed. Lemma integer_representable_opp: forall n, integer_representable n -> integer_representable (-n). Proof. intros n (A & B); split. rewrite Z.abs_opp. auto. rewrite Z2R_opp. apply generic_format_opp; auto. Qed. Lemma integer_representable_n2p_wide: forall n p, -2^prec <= n <= 2^prec -> 0 <= p -> p < emax - prec -> integer_representable (n * 2^p). Proof. intros. red in prec_gt_0_. destruct (Z.eq_dec n (2^prec)); [idtac | destruct (Z.eq_dec n (-2^prec))]. - rewrite e. rewrite <- (Zpower_plus radix2) by omega. apply integer_representable_2p. omega. - rewrite e. rewrite <- Zopp_mult_distr_l. apply integer_representable_opp. rewrite <- (Zpower_plus radix2) by omega. apply integer_representable_2p. omega. - apply integer_representable_n2p; omega. Qed. Lemma integer_representable_n: forall n, -2^prec <= n <= 2^prec -> integer_representable n. Proof. red in prec_gt_0_. intros. replace n with (n * 2^0) by (change (2^0) with 1; ring). apply integer_representable_n2p_wide. auto. omega. omega. Qed. Lemma round_int_no_overflow: forall n, Z.abs n <= 2^emax - 2^(emax-prec) -> (Rabs (round radix2 fexp (round_mode mode_NE) (Z2R n)) < bpow radix2 emax)%R. Proof. intros. red in prec_gt_0_. rewrite <- round_NE_abs. apply Rle_lt_trans with (Z2R (2^emax - 2^(emax-prec))). apply round_le_generic. apply fexp_correct; auto. apply valid_rnd_N. apply generic_format_FLT. exists (Float radix2 (2^prec-1) (emax-prec)). rewrite int_upper_bound_eq. unfold F2R; simpl. split. rewrite <- Z2R_Zpower by omega. rewrite <- Z2R_mult. auto. split. assert (0 < 2^prec) by (apply (Zpower_gt_0 radix2); omega). zify; omega. unfold emin; omega. rewrite <- Z2R_abs. apply Z2R_le. auto. rewrite <- Z2R_Zpower by omega. apply Z2R_lt. simpl. assert (0 < 2^(emax-prec)) by (apply (Zpower_gt_0 radix2); omega). omega. apply fexp_correct. auto. Qed. (** Conversion from an integer. Round to nearest. *) Definition BofZ (n: Z) : binary_float := binary_normalize prec emax prec_gt_0_ Hmax mode_NE n 0 false. Theorem BofZ_correct: forall n, if Rlt_bool (Rabs (round radix2 fexp (round_mode mode_NE) (Z2R n))) (bpow radix2 emax) then B2R prec emax (BofZ n) = round radix2 fexp (round_mode mode_NE) (Z2R n) /\ is_finite _ _ (BofZ n) = true /\ Bsign prec emax (BofZ n) = Z.ltb n 0 else B2FF prec emax (BofZ n) = binary_overflow prec emax mode_NE (Z.ltb n 0). Proof. intros. generalize (binary_normalize_correct prec emax prec_gt_0_ Hmax mode_NE n 0 false). fold emin; fold fexp; fold (BofZ n). replace (F2R {| Fnum := n; Fexp := 0 |}) with (Z2R n). destruct Rlt_bool. - intros (A & B & C). split; [|split]. + auto. + auto. + rewrite C. change 0%R with (Z2R 0). rewrite Rcompare_Z2R. unfold Z.ltb. auto. - intros A; rewrite A. f_equal. change 0%R with (Z2R 0). generalize (Z.ltb_spec n 0); intros SPEC; inversion SPEC. apply Rlt_bool_true; apply Z2R_lt; auto. apply Rlt_bool_false; apply Z2R_le; auto. - unfold F2R; simpl. ring. Qed. Theorem BofZ_finite: forall n, Z.abs n <= 2^emax - 2^(emax-prec) -> B2R _ _ (BofZ n) = round radix2 fexp (round_mode mode_NE) (Z2R n) /\ is_finite _ _ (BofZ n) = true /\ Bsign _ _ (BofZ n) = Z.ltb n 0%Z. Proof. intros. generalize (BofZ_correct n). rewrite Rlt_bool_true. auto. apply round_int_no_overflow; auto. Qed. Theorem BofZ_representable: forall n, integer_representable n -> B2R _ _ (BofZ n) = Z2R n /\ is_finite _ _ (BofZ n) = true /\ Bsign _ _ (BofZ n) = (n <? 0). Proof. intros. destruct H as (P & Q). destruct (BofZ_finite n) as (A & B & C). auto. intuition. rewrite A. apply round_generic. apply valid_rnd_round_mode. auto. Qed. Theorem BofZ_exact: forall n, -2^prec <= n <= 2^prec -> B2R _ _ (BofZ n) = Z2R n /\ is_finite _ _ (BofZ n) = true /\ Bsign _ _ (BofZ n) = Z.ltb n 0%Z. Proof. intros. apply BofZ_representable. apply integer_representable_n; auto. Qed. Lemma BofZ_finite_pos0: forall n, Z.abs n <= 2^emax - 2^(emax-prec) -> is_finite_pos0 (BofZ n) = true. Proof. intros. generalize (binary_normalize_correct prec emax prec_gt_0_ Hmax mode_NE n 0 false). fold emin; fold fexp; fold (BofZ n). replace (F2R {| Fnum := n; Fexp := 0 |}) with (Z2R n) by (unfold F2R; simpl; ring). rewrite Rlt_bool_true by (apply round_int_no_overflow; auto). intros (A & B & C). destruct (BofZ n); auto; try discriminate. simpl in *. rewrite C. change 0%R with (Z2R 0). rewrite Rcompare_Z2R. generalize (Zcompare_spec n 0); intros SPEC; inversion SPEC; auto. assert ((round radix2 fexp ZnearestE (Z2R n) <= -1)%R). { change (-1)%R with (Z2R (-1)). apply round_le_generic. apply fexp_correct. auto. apply valid_rnd_N. apply (integer_representable_opp 1). apply (integer_representable_2p 0). red in prec_gt_0_; omega. apply Z2R_le; omega. } lra. Qed. Lemma BofZ_finite_equal: forall x y, Z.abs x <= 2^emax - 2^(emax-prec) -> Z.abs y <= 2^emax - 2^(emax-prec) -> B2R _ _ (BofZ x) = B2R _ _ (BofZ y) -> BofZ x = BofZ y. Proof. intros. apply B2R_inj_pos0; auto; apply BofZ_finite_pos0; auto. Qed. (** Commutation properties with addition, subtraction, multiplication. *) Theorem BofZ_plus: forall nan p q, integer_representable p -> integer_representable q -> Bplus _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) = BofZ (p + q). Proof. intros. destruct (BofZ_representable p) as (A & B & C); auto. destruct (BofZ_representable q) as (D & E & F); auto. generalize (Bplus_correct _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) B E). fold emin; fold fexp. rewrite A, D. rewrite <- Z2R_plus. generalize (BofZ_correct (p + q)). destruct Rlt_bool. - intros (P & Q & R) (U & V & W). apply B2R_Bsign_inj; auto. rewrite P, U; auto. rewrite R, W, C, F. change 0%R with (Z2R 0). rewrite Rcompare_Z2R. unfold Z.ltb at 3. generalize (Zcompare_spec (p + q) 0); intros SPEC; inversion SPEC; auto. assert (EITHER: 0 <= p \/ 0 <= q) by omega. destruct EITHER; [apply andb_false_intro1 | apply andb_false_intro2]; apply Zlt_bool_false; auto. - intros P (U & V). apply B2FF_inj. rewrite P, U, C. f_equal. rewrite C, F in V. generalize (Zlt_bool_spec p 0) (Zlt_bool_spec q 0). rewrite <- V. intros SPEC1 SPEC2; inversion SPEC1; inversion SPEC2; try congruence; symmetry. apply Zlt_bool_true; omega. apply Zlt_bool_false; omega. Qed. Theorem BofZ_minus: forall nan p q, integer_representable p -> integer_representable q -> Bminus _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) = BofZ (p - q). Proof. intros. destruct (BofZ_representable p) as (A & B & C); auto. destruct (BofZ_representable q) as (D & E & F); auto. generalize (Bminus_correct _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) B E). fold emin; fold fexp. rewrite A, D. rewrite <- Z2R_minus. generalize (BofZ_correct (p - q)). destruct Rlt_bool. - intros (P & Q & R) (U & V & W). apply B2R_Bsign_inj; auto. rewrite P, U; auto. rewrite R, W, C, F. change 0%R with (Z2R 0). rewrite Rcompare_Z2R. unfold Z.ltb at 3. generalize (Zcompare_spec (p - q) 0); intros SPEC; inversion SPEC; auto. assert (EITHER: 0 <= p \/ q < 0) by omega. destruct EITHER; [apply andb_false_intro1 | apply andb_false_intro2]. rewrite Zlt_bool_false; auto. rewrite Zlt_bool_true; auto. - intros P (U & V). apply B2FF_inj. rewrite P, U, C. f_equal. rewrite C, F in V. generalize (Zlt_bool_spec p 0) (Zlt_bool_spec q 0). rewrite V. intros SPEC1 SPEC2; inversion SPEC1; inversion SPEC2; symmetry. rewrite <- H3 in H1; discriminate. apply Zlt_bool_true; omega. apply Zlt_bool_false; omega. rewrite <- H3 in H1; discriminate. Qed. Theorem BofZ_mult: forall nan p q, integer_representable p -> integer_representable q -> 0 < q -> Bmult _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) = BofZ (p * q). Proof. intros. assert (SIGN: xorb (p <? 0) (q <? 0) = (p * q <? 0)). { rewrite (Zlt_bool_false q) by omega. generalize (Zlt_bool_spec p 0); intros SPEC; inversion SPEC; simpl; symmetry. apply Zlt_bool_true. rewrite Z.mul_comm. apply Z.mul_pos_neg; omega. apply Zlt_bool_false. apply Zsame_sign_imp; omega. } destruct (BofZ_representable p) as (A & B & C); auto. destruct (BofZ_representable q) as (D & E & F); auto. generalize (Bmult_correct _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q)). fold emin; fold fexp. rewrite A, B, C, D, E, F. rewrite <- Z2R_mult. generalize (BofZ_correct (p * q)). destruct Rlt_bool. - intros (P & Q & R) (U & V & W). apply B2R_Bsign_inj; auto. rewrite P, U; auto. rewrite R, W; auto. apply is_finite_not_is_nan; auto. - intros P U. apply B2FF_inj. rewrite P, U. f_equal. auto. Qed. Theorem BofZ_mult_2p: forall nan x p, Z.abs x <= 2^emax - 2^(emax-prec) -> 2^prec <= Z.abs x -> 0 <= p <= emax - 1 -> Bmult _ _ _ Hmax nan mode_NE (BofZ x) (BofZ (2^p)) = BofZ (x * 2^p). Proof. intros. destruct (Z.eq_dec x 0). - subst x. apply BofZ_mult. apply integer_representable_n. generalize (Zpower_ge_0 radix2 prec). simpl; omega. apply integer_representable_2p. auto. apply (Zpower_gt_0 radix2). omega. - assert (Z2R x <> 0%R) by (apply (Z2R_neq _ _ n)). destruct (BofZ_finite x H) as (A & B & C). destruct (BofZ_representable (2^p)) as (D & E & F). apply integer_representable_2p. auto. assert (canonic_exp radix2 fexp (Z2R (x * 2^p)) = canonic_exp radix2 fexp (Z2R x) + p). { unfold canonic_exp, fexp. rewrite Z2R_mult. change (2^p) with (radix2^p). rewrite Z2R_Zpower by omega. rewrite ln_beta_mult_bpow by auto. assert (prec + 1 <= ln_beta radix2 (Z2R x)). { rewrite <- (ln_beta_abs radix2 (Z2R x)). rewrite <- (ln_beta_bpow radix2 prec). apply ln_beta_le. apply bpow_gt_0. rewrite <- Z2R_Zpower by (red in prec_gt_0_;omega). rewrite <- Z2R_abs. apply Z2R_le; auto. } unfold FLT_exp. unfold emin; red in prec_gt_0_; zify; omega. } assert (forall m, round radix2 fexp m (Z2R x) * Z2R (2^p) = round radix2 fexp m (Z2R (x * 2^p)))%R. { intros. unfold round, scaled_mantissa. rewrite H3. rewrite Z2R_mult. rewrite Z.opp_add_distr. rewrite bpow_plus. set (a := Z2R x); set (b := bpow radix2 (- canonic_exp radix2 fexp a)). replace (a * Z2R (2^p) * (b * bpow radix2 (-p)))%R with (a * b)%R. unfold F2R; simpl. rewrite Rmult_assoc. f_equal. rewrite bpow_plus. f_equal. apply (Z2R_Zpower radix2). omega. transitivity ((a * b) * (Z2R (2^p) * bpow radix2 (-p)))%R. rewrite (Z2R_Zpower radix2). rewrite <- bpow_plus. replace (p + -p) with 0 by omega. change (bpow radix2 0) with 1%R. ring. omega. ring. } assert (forall m x, round radix2 fexp (round_mode m) (round radix2 fexp (round_mode m) x) = round radix2 fexp (round_mode m) x). { intros. apply round_generic. apply valid_rnd_round_mode. apply generic_format_round. apply fexp_correct; auto. apply valid_rnd_round_mode. } assert (xorb (x <? 0) (2^p <? 0) = (x * 2^p <? 0)). { assert (0 < 2^p) by (apply (Zpower_gt_0 radix2); omega). rewrite (Zlt_bool_false (2^p)) by omega. rewrite xorb_false_r. symmetry. generalize (Zlt_bool_spec x 0); intros SPEC; inversion SPEC. apply Zlt_bool_true. apply Z.mul_neg_pos; auto. apply Zlt_bool_false. apply Z.mul_nonneg_nonneg; omega. } generalize (Bmult_correct _ _ _ Hmax nan mode_NE (BofZ x) (BofZ (2^p))) (BofZ_correct (x * 2^p)). fold emin; fold fexp. rewrite A, B, C, D, E, F, H4, H5. destruct Rlt_bool. + intros (P & Q & R) (U & V & W). apply B2R_Bsign_inj; auto. rewrite P, U. auto. rewrite R, W. auto. apply is_finite_not_is_nan; auto. + intros P U. apply B2FF_inj. rewrite P, U. f_equal; auto. Qed. (** Rounding to odd the argument of [BofZ]. *) Lemma round_odd_flt: forall prec' emin' x choice, prec > 1 -> prec' > 1 -> prec' >= prec + 2 -> emin' <= emin - 2 -> round radix2 fexp (Znearest choice) (round radix2 (FLT_exp emin' prec') Zrnd_odd x) = round radix2 fexp (Znearest choice) x. Proof. intros. apply round_odd_prop. auto. apply fexp_correct; auto. apply exists_NE_FLT. right; omega. apply FLT_exp_valid. red; omega. apply exists_NE_FLT. right; omega. unfold fexp, FLT_exp; intros. zify; omega. Qed. Corollary round_odd_fix: forall x p choice, prec > 1 -> 0 <= p -> (bpow radix2 (prec + p + 1) <= Rabs x)%R -> round radix2 fexp (Znearest choice) (round radix2 (FIX_exp p) Zrnd_odd x) = round radix2 fexp (Znearest choice) x. Proof. intros. destruct (Req_EM_T x 0%R). - subst x. rewrite round_0. auto. apply valid_rnd_odd. - set (prec' := ln_beta radix2 x - p). set (emin' := emin - 2). assert (PREC: ln_beta radix2 (bpow radix2 (prec + p + 1)) <= ln_beta radix2 x). { rewrite <- (ln_beta_abs radix2 x). apply ln_beta_le; auto. apply bpow_gt_0. } rewrite ln_beta_bpow in PREC. assert (CANON: canonic_exp radix2 (FLT_exp emin' prec') x = canonic_exp radix2 (FIX_exp p) x). { unfold canonic_exp, FLT_exp, FIX_exp. replace (ln_beta radix2 x - prec') with p by (unfold prec'; omega). apply Z.max_l. unfold emin', emin. red in prec_gt_0_; omega. } assert (RND: round radix2 (FIX_exp p) Zrnd_odd x = round radix2 (FLT_exp emin' prec') Zrnd_odd x). { unfold round, scaled_mantissa. rewrite CANON. auto. } rewrite RND. apply round_odd_flt. auto. unfold prec'. red in prec_gt_0_; omega. unfold prec'. omega. unfold emin'. omega. Qed. Definition int_round_odd (x: Z) (p: Z) := (if Z.eqb (x mod 2^p) 0 || Z.odd (x / 2^p) then x / 2^p else x / 2^p + 1) * 2^p. Lemma Zrnd_odd_int: forall n p, 0 <= p -> Zrnd_odd (Z2R n * bpow radix2 (-p)) * 2^p = int_round_odd n p. Proof. intros. assert (0 < 2^p) by (apply (Zpower_gt_0 radix2); omega). assert (n = (n / 2^p) * 2^p + n mod 2^p) by (rewrite Z.mul_comm; apply Z.div_mod; omega). assert (0 <= n mod 2^p < 2^p) by (apply Z_mod_lt; omega). unfold int_round_odd. set (q := n / 2^p) in *; set (r := n mod 2^p) in *. f_equal. pose proof (bpow_gt_0 radix2 (-p)). assert (bpow radix2 p * bpow radix2 (-p) = 1)%R. { rewrite <- bpow_plus. replace (p + -p) with 0 by omega. auto. } assert (Z2R n * bpow radix2 (-p) = Z2R q + Z2R r * bpow radix2 (-p))%R. { rewrite H1. rewrite Z2R_plus, Z2R_mult. change (Z2R (2^p)) with (Z2R (radix2^p)). rewrite Z2R_Zpower by omega. ring_simplify. rewrite Rmult_assoc. rewrite H4. ring. } assert (0 <= Z2R r < bpow radix2 p)%R. { split. change 0%R with (Z2R 0). apply Z2R_le; omega. rewrite <- Z2R_Zpower by omega. apply Z2R_lt; tauto. } assert (0 <= Z2R r * bpow radix2 (-p) < 1)%R. { generalize (bpow_gt_0 radix2 (-p)). intros. split. apply Rmult_le_pos; lra. rewrite <- H4. apply Rmult_lt_compat_r. auto. tauto. } assert (Zfloor (Z2R n * bpow radix2 (-p)) = q). { apply Zfloor_imp. rewrite H5. rewrite Z2R_plus. change (Z2R 1) with 1%R. lra. } unfold Zrnd_odd. destruct Req_EM_T. - assert (Z2R r * bpow radix2 (-p) = 0)%R. { rewrite H8 in e. rewrite e in H5. lra. } apply Rmult_integral in H9. destruct H9; [ | lra ]. apply (eq_Z2R r 0) in H9. apply <- Z.eqb_eq in H9. rewrite H9. assumption. - assert (Z2R r * bpow radix2 (-p) <> 0)%R. { rewrite H8 in n0. lra. } destruct (Z.eqb r 0) eqn:RZ. apply Z.eqb_eq in RZ. rewrite RZ in H9. change (Z2R 0) with 0%R in H9. rewrite Rmult_0_l in H9. congruence. rewrite Zceil_floor_neq by lra. rewrite H8. change Zeven with Z.even. rewrite Zodd_even_bool. destruct (Z.even q); auto. Qed. Lemma int_round_odd_le: forall p x y, 0 <= p -> x <= y -> int_round_odd x p <= int_round_odd y p. Proof. intros. assert (Zrnd_odd (Z2R x * bpow radix2 (-p)) <= Zrnd_odd (Z2R y * bpow radix2 (-p))). { apply Zrnd_le. apply valid_rnd_odd. apply Rmult_le_compat_r. apply bpow_ge_0. apply Z2R_le; auto. } rewrite <- ! Zrnd_odd_int by auto. apply Zmult_le_compat_r. auto. apply (Zpower_ge_0 radix2). Qed. Lemma int_round_odd_exact: forall p x, 0 <= p -> (2^p | x) -> int_round_odd x p = x. Proof. intros. unfold int_round_odd. apply Znumtheory.Zdivide_mod in H0. rewrite H0. simpl. rewrite Z.mul_comm. symmetry. apply Z_div_exact_2. apply Z.lt_gt. apply (Zpower_gt_0 radix2). auto. auto. Qed. Theorem BofZ_round_odd: forall x p, prec > 1 -> Z.abs x <= 2^emax - 2^(emax-prec) -> 0 <= p <= emax - prec -> 2^(prec + p + 1) <= Z.abs x -> BofZ x = BofZ (int_round_odd x p). Proof. intros x p PREC XRANGE PRANGE XGE. assert (DIV: (2^p | 2^emax - 2^(emax - prec))). { rewrite int_upper_bound_eq. apply Z.divide_mul_r. exists (2^(emax - prec - p)). red in prec_gt_0_. rewrite <- (Zpower_plus radix2) by omega. f_equal; omega. } assert (YRANGE: Z.abs (int_round_odd x p) <= 2^emax - 2^(emax-prec)). { apply Z.abs_le. split. replace (-(2^emax - 2^(emax-prec))) with (int_round_odd (-(2^emax - 2^(emax-prec))) p). apply int_round_odd_le; zify; omega. apply int_round_odd_exact. omega. apply Z.divide_opp_r. auto. replace (2^emax - 2^(emax-prec)) with (int_round_odd (2^emax - 2^(emax-prec)) p). apply int_round_odd_le; zify; omega. apply int_round_odd_exact. omega. auto. } destruct (BofZ_finite x XRANGE) as (X1 & X2 & X3). destruct (BofZ_finite (int_round_odd x p) YRANGE) as (Y1 & Y2 & Y3). apply BofZ_finite_equal; auto. rewrite X1, Y1. assert (Z2R (int_round_odd x p) = round radix2 (FIX_exp p) Zrnd_odd (Z2R x)). { unfold round, scaled_mantissa, canonic_exp, FIX_exp. rewrite <- Zrnd_odd_int by omega. unfold F2R; simpl. rewrite Z2R_mult. f_equal. apply (Z2R_Zpower radix2). omega. } rewrite H. symmetry. apply round_odd_fix. auto. omega. rewrite <- Z2R_Zpower. rewrite <- Z2R_abs. apply Z2R_le; auto. red in prec_gt_0_; omega. Qed. Lemma int_round_odd_shifts: forall x p, 0 <= p -> int_round_odd x p = Z.shiftl (if Z.eqb (x mod 2^p) 0 then Z.shiftr x p else Z.lor (Z.shiftr x p) 1) p. Proof. intros. unfold int_round_odd. rewrite Z.shiftl_mul_pow2 by auto. f_equal. rewrite Z.shiftr_div_pow2 by auto. destruct (x mod 2^p =? 0) eqn:E. auto. assert (forall n, (if Z.odd n then n else n + 1) = Z.lor n 1). { destruct n; simpl; auto. destruct p0; auto. destruct p0; auto. induction p0; auto. } simpl. apply H0. Qed. Lemma int_round_odd_bits: forall x y p, 0 <= p -> (forall i, 0 <= i < p -> Z.testbit y i = false) -> Z.testbit y p = (if Z.eqb (x mod 2^p) 0 then Z.testbit x p else true) -> (forall i, p < i -> Z.testbit y i = Z.testbit x i) -> int_round_odd x p = y. Proof. intros until p; intros PPOS BELOW AT ABOVE. rewrite int_round_odd_shifts by auto. apply Z.bits_inj'. intros. generalize (Zcompare_spec n p); intros SPEC; inversion SPEC. - rewrite BELOW by auto. apply Z.shiftl_spec_low; auto. - subst n. rewrite AT. rewrite Z.shiftl_spec_high by omega. replace (p - p) with 0 by omega. destruct (x mod 2^p =? 0). + rewrite Z.shiftr_spec by omega. f_equal; omega. + rewrite Z.lor_spec. apply orb_true_r. - rewrite ABOVE by auto. rewrite Z.shiftl_spec_high by omega. destruct (x mod 2^p =? 0). rewrite Z.shiftr_spec by omega. f_equal; omega. rewrite Z.lor_spec, Z.shiftr_spec by omega. change 1 with (Z.ones 1). rewrite Z.ones_spec_high by omega. rewrite orb_false_r. f_equal; omega. Qed. (** ** Conversion from a FP number to an integer *) (** Always rounds toward zero. *) Definition ZofB (f: binary_float): option Z := match f with | B754_finite _ _ s m (Zpos e) _ => Some (cond_Zopp s (Zpos m) * Z.pow_pos radix2 e)%Z | B754_finite _ _ s m 0 _ => Some (cond_Zopp s (Zpos m)) | B754_finite _ _ s m (Zneg e) _ => Some (cond_Zopp s (Zpos m / Z.pow_pos radix2 e))%Z | B754_zero _ _ _ => Some 0%Z | _ => None end. Theorem ZofB_correct: forall f, ZofB f = if is_finite _ _ f then Some (Ztrunc (B2R _ _ f)) else None. Proof. destruct f; simpl; auto. - f_equal. symmetry. apply (Ztrunc_Z2R 0). - destruct e; f_equal. + unfold F2R; simpl. rewrite Rmult_1_r. rewrite Ztrunc_Z2R. auto. + unfold F2R; simpl. rewrite <- Z2R_mult. rewrite Ztrunc_Z2R. auto. + unfold F2R; simpl. rewrite Z2R_cond_Zopp. rewrite <- cond_Ropp_mult_l. assert (EQ: forall x, Ztrunc (cond_Ropp b x) = cond_Zopp b (Ztrunc x)). { intros. destruct b; simpl; auto. apply Ztrunc_opp. } rewrite EQ. f_equal. generalize (Zpower_pos_gt_0 2 p (eq_refl _)); intros. rewrite Ztrunc_floor. symmetry. apply Zfloor_div. omega. apply Rmult_le_pos. apply (Z2R_le 0). compute; congruence. apply Rlt_le. apply Rinv_0_lt_compat. apply (Z2R_lt 0). auto. Qed. (** Interval properties. *) Remark Ztrunc_range_pos: forall x, 0 < Ztrunc x -> (Z2R (Ztrunc x) <= x < Z2R (Ztrunc x + 1)%Z)%R. Proof. intros. rewrite Ztrunc_floor. split. apply Zfloor_lb. rewrite Z2R_plus. apply Zfloor_ub. generalize (Rle_bool_spec 0%R x). intros RLE; inversion RLE; subst; clear RLE. auto. rewrite Ztrunc_ceil in H by lra. unfold Zceil in H. assert (-x < 0)%R. { apply Rlt_le_trans with (Z2R (Zfloor (-x)) + 1)%R. apply Zfloor_ub. change 0%R with (Z2R 0). change 1%R with (Z2R 1). rewrite <- Z2R_plus. apply Z2R_le. omega. } lra. Qed. Remark Ztrunc_range_zero: forall x, Ztrunc x = 0 -> (-1 < x < 1)%R. Proof. intros; generalize (Rle_bool_spec 0%R x). intros RLE; inversion RLE; subst; clear RLE. - rewrite Ztrunc_floor in H by auto. split. + apply Rlt_le_trans with 0%R; auto. rewrite <- Ropp_0. apply Ropp_lt_contravar. apply Rlt_0_1. + replace 1%R with (Z2R (Zfloor x) + 1)%R. apply Zfloor_ub. rewrite H. simpl. apply Rplus_0_l. - rewrite Ztrunc_ceil in H by (apply Rlt_le; auto). split. + apply (Ropp_lt_cancel (-(1))). rewrite Ropp_involutive. replace 1%R with (Z2R (Zfloor (-x)) + 1)%R. apply Zfloor_ub. unfold Zceil in H. replace (Zfloor (-x)) with 0 by omega. simpl. apply Rplus_0_l. + apply Rlt_le_trans with 0%R; auto. apply Rle_0_1. Qed. Theorem ZofB_range_pos: forall f n, ZofB f = Some n -> 0 < n -> (Z2R n <= B2R _ _ f < Z2R (n + 1)%Z)%R. Proof. intros. rewrite ZofB_correct in H. destruct (is_finite prec emax f) eqn:FIN; inversion H. apply Ztrunc_range_pos. congruence. Qed. Theorem ZofB_range_neg: forall f n, ZofB f = Some n -> n < 0 -> (Z2R (n - 1)%Z < B2R _ _ f <= Z2R n)%R. Proof. intros. rewrite ZofB_correct in H. destruct (is_finite prec emax f) eqn:FIN; inversion H. set (x := B2R prec emax f) in *. set (y := (-x)%R). assert (A: (Z2R (Ztrunc y) <= y < Z2R (Ztrunc y + 1)%Z)%R). { apply Ztrunc_range_pos. unfold y. rewrite Ztrunc_opp. omega. } destruct A as [B C]. unfold y in B, C. rewrite Ztrunc_opp in B, C. replace (- Ztrunc x + 1) with (- (Ztrunc x - 1)) in C by omega. rewrite Z2R_opp in B, C. lra. Qed. Theorem ZofB_range_zero: forall f, ZofB f = Some 0 -> (-1 < B2R _ _ f < 1)%R. Proof. intros. rewrite ZofB_correct in H. destruct (is_finite prec emax f) eqn:FIN; inversion H. apply Ztrunc_range_zero. auto. Qed. Theorem ZofB_range_nonneg: forall f n, ZofB f = Some n -> 0 <= n -> (-1 < B2R _ _ f < Z2R (n + 1)%Z)%R. Proof. intros. destruct (Z.eq_dec n 0). - subst n. apply ZofB_range_zero. auto. - destruct (ZofB_range_pos f n) as (A & B). auto. omega. split; auto. apply Rlt_le_trans with (Z2R 0). simpl; lra. apply Rle_trans with (Z2R n); auto. apply Z2R_le; auto. Qed. (** For representable integers, [ZofB] is left inverse of [BofZ]. *) Theorem ZofBofZ_exact: forall n, integer_representable n -> ZofB (BofZ n) = Some n. Proof. intros. destruct (BofZ_representable n H) as (A & B & C). rewrite ZofB_correct. rewrite A, B. f_equal. apply Ztrunc_Z2R. Qed. (** Compatibility with subtraction *) Remark Zfloor_minus: forall x n, Zfloor (x - Z2R n) = Zfloor x - n. Proof. intros. apply Zfloor_imp. replace (Zfloor x - n + 1) with ((Zfloor x + 1) - n) by omega. rewrite ! Z2R_minus. unfold Rminus. split. apply Rplus_le_compat_r. apply Zfloor_lb. apply Rplus_lt_compat_r. rewrite Z2R_plus. apply Zfloor_ub. Qed. Theorem ZofB_minus: forall minus_nan m f p q, ZofB f = Some p -> 0 <= p < 2*q -> q <= 2^prec -> (Z2R q <= B2R _ _ f)%R -> ZofB (Bminus _ _ _ Hmax minus_nan m f (BofZ q)) = Some (p - q). Proof. intros. assert (Q: -2^prec <= q <= 2^prec). { split; auto. generalize (Zpower_ge_0 radix2 prec); simpl; omega. } assert (RANGE: (-1 < B2R _ _ f < Z2R (p + 1)%Z)%R) by (apply ZofB_range_nonneg; auto; omega). rewrite ZofB_correct in H. destruct (is_finite prec emax f) eqn:FIN; try discriminate. assert (PQ2: (Z2R (p + 1) <= Z2R q * 2)%R). { change 2%R with (Z2R 2). rewrite <- Z2R_mult. apply Z2R_le. omega. } assert (EXACT: round radix2 fexp (round_mode m) (B2R _ _ f - Z2R q)%R = (B2R _ _ f - Z2R q)%R). { apply round_generic. apply valid_rnd_round_mode. apply sterbenz_aux. apply FLT_exp_monotone. apply generic_format_B2R. apply integer_representable_n. auto. lra. } destruct (BofZ_exact q Q) as (A & B & C). generalize (Bminus_correct _ _ _ Hmax minus_nan m f (BofZ q) FIN B). rewrite Rlt_bool_true. - fold emin; fold fexp. intros (D & E & F). rewrite ZofB_correct. rewrite E. rewrite D. rewrite A. rewrite EXACT. inversion H. f_equal. rewrite ! Ztrunc_floor. apply Zfloor_minus. lra. lra. - rewrite A. fold emin; fold fexp. rewrite EXACT. apply Rle_lt_trans with (bpow radix2 prec). apply Rle_trans with (Z2R q). apply Rabs_le. lra. rewrite <- Z2R_Zpower. apply Z2R_le; auto. red in prec_gt_0_; omega. apply bpow_lt. auto. Qed. (** A variant of [ZofB] that bounds the range of representable integers. *) Definition ZofB_range (f: binary_float) (zmin zmax: Z): option Z := match ZofB f with | None => None | Some z => if Z.leb zmin z && Z.leb z zmax then Some z else None end. Theorem ZofB_range_correct: forall f min max, let n := Ztrunc (B2R _ _ f) in ZofB_range f min max = if is_finite _ _ f && Z.leb min n && Z.leb n max then Some n else None. Proof. intros. unfold ZofB_range. rewrite ZofB_correct. fold n. destruct (is_finite prec emax f); auto. Qed. Lemma ZofB_range_inversion: forall f min max n, ZofB_range f min max = Some n -> min <= n /\ n <= max /\ ZofB f = Some n. Proof. intros. rewrite ZofB_range_correct in H. rewrite ZofB_correct. destruct (is_finite prec emax f); try discriminate. set (n1 := Ztrunc (B2R _ _ f)) in *. destruct (min <=? n1) eqn:MIN; try discriminate. destruct (n1 <=? max) eqn:MAX; try discriminate. simpl in H. inversion H. subst n. split. apply Zle_bool_imp_le; auto. split. apply Zle_bool_imp_le; auto. auto. Qed. Theorem ZofB_range_minus: forall minus_nan m f p q, ZofB_range f 0 (2 * q - 1) = Some p -> q <= 2^prec -> (Z2R q <= B2R _ _ f)%R -> ZofB_range (Bminus _ _ _ Hmax minus_nan m f (BofZ q)) (-q) (q - 1) = Some (p - q). Proof. intros. destruct (ZofB_range_inversion _ _ _ _ H) as (A & B & C). set (f' := Bminus prec emax prec_gt_0_ Hmax minus_nan m f (BofZ q)). assert (D: ZofB f' = Some (p - q)). { apply ZofB_minus. auto. omega. auto. auto. } unfold ZofB_range. rewrite D. rewrite Zle_bool_true by omega. rewrite Zle_bool_true by omega. auto. Qed. (** ** Algebraic identities *) (** Commutativity of addition and multiplication *) Theorem Bplus_commut: forall plus_nan mode (x y: binary_float), plus_nan x y = plus_nan y x -> Bplus _ _ _ Hmax plus_nan mode x y = Bplus _ _ _ Hmax plus_nan mode y x. Proof. intros until y; intros NAN. pose proof (Bplus_correct _ _ _ Hmax plus_nan mode x y). pose proof (Bplus_correct _ _ _ Hmax plus_nan mode y x). unfold Bplus in *; destruct x; destruct y; auto. - rewrite (eqb_sym b0 b). destruct (eqb b b0) eqn:EQB; auto. f_equal; apply eqb_prop; auto. - rewrite NAN; auto. - rewrite (eqb_sym b0 b). destruct (eqb b b0) eqn:EQB. f_equal; apply eqb_prop; auto. rewrite NAN; auto. - rewrite NAN; auto. - rewrite NAN; auto. - rewrite NAN; auto. - rewrite NAN; auto. - rewrite NAN; auto. - rewrite NAN; auto. - generalize (H (eq_refl _) (eq_refl _)); clear H. generalize (H0 (eq_refl _) (eq_refl _)); clear H0. fold emin. fold fexp. set (x := B754_finite prec emax b0 m0 e1 e2). set (rx := B2R _ _ x). set (y := B754_finite prec emax b m e e0). set (ry := B2R _ _ y). rewrite (Rplus_comm ry rx). destruct Rlt_bool. + intros (A1 & A2 & A3) (B1 & B2 & B3). apply B2R_Bsign_inj; auto. rewrite <- B1 in A1. auto. rewrite Z.add_comm. rewrite Z.min_comm. auto. + intros (A1 & A2) (B1 & B2). apply B2FF_inj. rewrite B2 in B1. rewrite <- B1 in A1. auto. Qed. Theorem Bmult_commut: forall mult_nan mode (x y: binary_float), mult_nan x y = mult_nan y x -> Bmult _ _ _ Hmax mult_nan mode x y = Bmult _ _ _ Hmax mult_nan mode y x. Proof. intros until y; intros NAN. pose proof (Bmult_correct _ _ _ Hmax mult_nan mode x y). pose proof (Bmult_correct _ _ _ Hmax mult_nan mode y x). unfold Bmult in *; destruct x; destruct y; auto. - rewrite (xorb_comm b0 b); auto. - rewrite NAN; auto. - rewrite NAN; auto. - rewrite (xorb_comm b0 b); auto. - rewrite NAN; auto. - rewrite (xorb_comm b0 b); auto. - rewrite NAN; auto. - rewrite (xorb_comm b0 b); auto. - rewrite NAN; auto. - rewrite NAN; auto. - rewrite NAN; auto. - rewrite NAN; auto. - rewrite (xorb_comm b0 b); auto. - rewrite (xorb_comm b0 b); auto. - rewrite NAN; auto. - revert H H0. fold emin. fold fexp. set (x := B754_finite prec emax b0 m0 e1 e2). set (rx := B2R _ _ x). set (y := B754_finite prec emax b m e e0). set (ry := B2R _ _ y). rewrite (Rmult_comm ry rx). destruct (Rlt_bool (Rabs (round radix2 fexp (round_mode mode) (rx * ry))) (bpow radix2 emax)). + intros (A1 & A2 & A3) (B1 & B2 & B3). apply B2R_Bsign_inj; auto. rewrite <- B1 in A1. auto. rewrite ! Bsign_FF2B. f_equal. f_equal. apply xorb_comm. apply Pos.mul_comm. apply Z.add_comm. + intros A B. apply B2FF_inj. etransitivity. eapply A. rewrite xorb_comm. auto. Qed. (** Multiplication by 2 is diagonal addition. *) Theorem Bmult2_Bplus: forall plus_nan mult_nan mode (f: binary_float), (forall (x y: binary_float), is_nan _ _ x = true -> is_finite _ _ y = true -> plus_nan x x = mult_nan x y) -> Bplus _ _ _ Hmax plus_nan mode f f = Bmult _ _ _ Hmax mult_nan mode f (BofZ 2%Z). Proof. intros until f; intros NAN. destruct (BofZ_representable 2) as (A & B & C). apply (integer_representable_2p 1). red in prec_gt_0_; omega. pose proof (Bmult_correct _ _ _ Hmax mult_nan mode f (BofZ 2%Z)). fold emin in H. rewrite A, B, C in H. rewrite xorb_false_r in H. destruct (is_finite _ _ f) eqn:FIN. - pose proof (Bplus_correct _ _ _ Hmax plus_nan mode f f FIN FIN). fold emin in H0. assert (EQ: (B2R prec emax f * Z2R 2%Z = B2R prec emax f + B2R prec emax f)%R). { change (Z2R 2%Z) with 2%R. ring. } rewrite <- EQ in H0. destruct Rlt_bool. + destruct H0 as (P & Q & R). destruct H as (S & T & U). apply B2R_Bsign_inj; auto. rewrite P, S. auto. rewrite R, U. replace 0%R with (0 * Z2R 2%Z)%R by ring. rewrite Rcompare_mult_r. rewrite andb_diag, orb_diag. destruct f; try discriminate; simpl. rewrite Rcompare_Eq by auto. destruct mode; auto. replace 0%R with (@F2R radix2 {| Fnum := 0%Z; Fexp := e |}). rewrite Rcompare_F2R. destruct b; auto. unfold F2R. simpl. ring. change 0%R with (Z2R 0%Z). apply Z2R_lt. omega. destruct (Bmult prec emax prec_gt_0_ Hmax mult_nan mode f (BofZ 2)); reflexivity || discriminate. + destruct H0 as (P & Q). apply B2FF_inj. rewrite P, H. auto. - destruct f; try discriminate. + simpl Bplus. rewrite eqb_true. destruct (BofZ 2) eqn:B2; try discriminate; simpl in *. assert ((0 = 2)%Z) by (apply eq_Z2R; auto). discriminate. subst b0. rewrite xorb_false_r. auto. auto. + unfold Bplus, Bmult. rewrite <- NAN by auto. auto. Qed. (** Divisions that can be turned into multiplications by an inverse *) Definition Bexact_inverse_mantissa := Z.iter (prec - 1) xO xH. Remark Bexact_inverse_mantissa_value: Zpos Bexact_inverse_mantissa = 2 ^ (prec - 1). Proof. assert (REC: forall n, Z.pos (nat_rect _ xH (fun _ => xO) n) = 2 ^ (Z.of_nat n)). { induction n. reflexivity. simpl nat_rect. transitivity (2 * Z.pos (nat_rect _ xH (fun _ => xO) n)). reflexivity. rewrite Nat2Z.inj_succ. rewrite IHn. unfold Z.succ. rewrite Zpower_plus by omega. change (2 ^ 1) with 2. ring. } red in prec_gt_0_. unfold Bexact_inverse_mantissa. rewrite iter_nat_of_Z by omega. rewrite REC. rewrite Zabs2Nat.id_abs. rewrite Z.abs_eq by omega. auto. Qed. Remark Bexact_inverse_mantissa_digits2_pos: Z.pos (digits2_pos Bexact_inverse_mantissa) = prec. Proof. assert (DIGITS: forall n, digits2_pos (nat_rect _ xH (fun _ => xO) n) = Pos.of_nat (n+1)). { induction n; simpl. auto. rewrite IHn. destruct n; auto. } red in prec_gt_0_. unfold Bexact_inverse_mantissa. rewrite iter_nat_of_Z by omega. rewrite DIGITS. rewrite Zabs2Nat.abs_nat_nonneg, Z2Nat.inj_sub by omega. destruct prec; try discriminate. rewrite Nat.sub_add. simpl. rewrite Pos2Nat.id. auto. simpl. zify; omega. Qed. Remark bounded_Bexact_inverse: forall e, emin <= e <= emax - prec <-> bounded prec emax Bexact_inverse_mantissa e = true. Proof. intros. unfold bounded, canonic_mantissa. rewrite andb_true_iff. rewrite <- Zeq_is_eq_bool. rewrite <- Zle_is_le_bool. rewrite Bexact_inverse_mantissa_digits2_pos. split. - intros; split. unfold FLT_exp. unfold emin in H. zify; omega. omega. - intros [A B]. unfold FLT_exp in A. unfold emin. zify; omega. Qed. Program Definition Bexact_inverse (f: binary_float) : option binary_float := match f with | B754_finite _ _ s m e B => if Pos.eq_dec m Bexact_inverse_mantissa then let e' := -e - (prec - 1) * 2 in if Z_le_dec emin e' then if Z_le_dec e' emax then Some(B754_finite _ _ s m e' _) else None else None else None | _ => None end. Next Obligation. rewrite <- bounded_Bexact_inverse in B. rewrite <- bounded_Bexact_inverse. unfold emin in *. omega. Qed. Lemma Bexact_inverse_correct: forall f f', Bexact_inverse f = Some f' -> is_finite_strict _ _ f = true /\ is_finite_strict _ _ f' = true /\ B2R _ _ f' = (/ B2R _ _ f)%R /\ B2R _ _ f <> 0%R /\ Bsign _ _ f' = Bsign _ _ f. Proof with (try discriminate). intros f f' EI. unfold Bexact_inverse in EI. destruct f... destruct (Pos.eq_dec m Bexact_inverse_mantissa)... set (e' := -e - (prec - 1) * 2) in *. destruct (Z_le_dec emin e')... destruct (Z_le_dec e' emax)... inversion EI; clear EI; subst f' m. split. auto. split. auto. split. unfold B2R. rewrite Bexact_inverse_mantissa_value. unfold F2R; simpl. rewrite Z2R_cond_Zopp. rewrite <- ! cond_Ropp_mult_l. red in prec_gt_0_. replace (Z2R (2 ^ (prec - 1))) with (bpow radix2 (prec - 1)) by (symmetry; apply (Z2R_Zpower radix2); omega). rewrite <- ! bpow_plus. replace (prec - 1 + e') with (- (prec - 1 + e)) by (unfold e'; omega). rewrite bpow_opp. unfold cond_Ropp; destruct b; auto. rewrite Ropp_inv_permute. auto. apply Rgt_not_eq. apply bpow_gt_0. split. simpl. red; intros. apply F2R_eq_0_reg in H. destruct b; simpl in H; discriminate. auto. Qed. Theorem Bdiv_mult_inverse: forall div_nan mult_nan mode x y z, (forall (x y z: binary_float), is_nan _ _ x = true -> is_finite _ _ y = true -> is_finite _ _ z = true -> div_nan x y = mult_nan x z) -> Bexact_inverse y = Some z -> Bdiv _ _ _ Hmax div_nan mode x y = Bmult _ _ _ Hmax mult_nan mode x z. Proof. intros until z; intros NAN; intros. destruct (Bexact_inverse_correct _ _ H) as (A & B & C & D & E). pose proof (Bmult_correct _ _ _ Hmax mult_nan mode x z). fold emin in H0. fold fexp in H0. pose proof (Bdiv_correct _ _ _ Hmax div_nan mode x y D). fold emin in H1. fold fexp in H1. unfold Rdiv in H1. rewrite <- C in H1. destruct (is_finite _ _ x) eqn:FINX. - destruct Rlt_bool. + destruct H0 as (P & Q & R). destruct H1 as (S & T & U). apply B2R_Bsign_inj; auto. rewrite Q. simpl. apply is_finite_strict_finite; auto. rewrite P, S. auto. rewrite R, U, E. auto. apply is_finite_not_is_nan; auto. apply is_finite_not_is_nan. rewrite Q. simpl. apply is_finite_strict_finite; auto. + apply B2FF_inj. rewrite H0, H1. rewrite E. auto. - destruct y; try discriminate. destruct z; try discriminate. destruct x; try discriminate; simpl. + simpl in E; congruence. + erewrite NAN; eauto. Qed. (** ** Conversion from scientific notation *) (** Russian peasant exponentiation *) Fixpoint pos_pow (x y: positive) : positive := match y with | xH => x | xO y => Pos.square (pos_pow x y) | xI y => Pos.mul x (Pos.square (pos_pow x y)) end. Lemma pos_pow_spec: forall x y, Z.pos (pos_pow x y) = Z.pos x ^ Z.pos y. Proof. intros x. assert (REC: forall y a, Pos.iter (Pos.mul x) a y = Pos.mul (pos_pow x y) a). { induction y; simpl; intros. - rewrite ! IHy, Pos.square_spec, ! Pos.mul_assoc. auto. - rewrite ! IHy, Pos.square_spec, ! Pos.mul_assoc. auto. - auto. } intros. simpl. rewrite <- Pos2Z.inj_pow_pos. unfold Pos.pow. rewrite REC. rewrite Pos.mul_1_r. auto. Qed. (** Given a base [base], a mantissa [m] and an exponent [e], the following function computes the FP number closest to [m * base ^ e], using round to odd, ties break to even. The algorithm is naive, computing [base ^ |e|] exactly before doing a multiplication or division with [m]. However, we treat specially very large or very small values of [e], when the result is known to be [+infinity] or [0.0] respectively. *) Definition Bparse (base: positive) (m: positive) (e: Z): binary_float := match e with | Z0 => BofZ (Zpos m) | Zpos p => if e * Z.log2 (Zpos base) <? emax then BofZ (Zpos m * Zpos (pos_pow base p)) else B754_infinity _ _ false | Zneg p => if e * Z.log2 (Zpos base) + Z.log2_up (Zpos m) <? emin then B754_zero _ _ false else FF2B prec emax _ (proj1 (Bdiv_correct_aux prec emax prec_gt_0_ Hmax mode_NE false m Z0 false (pos_pow base p) Z0)) end. (** Properties of [Z.log2] and [Z.log2_up]. *) Lemma Zpower_log: forall (base: radix) n, 0 < n -> 2 ^ (n * Z.log2 base) <= base ^ n <= 2 ^ (n * Z.log2_up base). Proof. intros. assert (A: 0 < base) by apply radix_gt_0. assert (B: 0 <= Z.log2 base) by apply Z.log2_nonneg. assert (C: 0 <= Z.log2_up base) by apply Z.log2_up_nonneg. destruct (Z.log2_spec base) as [D E]; auto. destruct (Z.log2_up_spec base) as [F G]. apply radix_gt_1. assert (K: 0 <= 2 ^ Z.log2 base) by (apply Z.pow_nonneg; omega). rewrite ! (Z.mul_comm n). rewrite ! Z.pow_mul_r by omega. split; apply Z.pow_le_mono_l; omega. Qed. Lemma bpow_log_pos: forall (base: radix) n, 0 < n -> (bpow radix2 (n * Z.log2 base)%Z <= bpow base n)%R. Proof. intros. rewrite <- ! Z2R_Zpower. apply Z2R_le; apply Zpower_log; auto. omega. rewrite Z.mul_comm; apply Zmult_gt_0_le_0_compat. omega. apply Z.log2_nonneg. Qed. Lemma bpow_log_neg: forall (base: radix) n, n < 0 -> (bpow base n <= bpow radix2 (n * Z.log2 base)%Z)%R. Proof. intros. set (m := -n). replace n with (-m) by (unfold m; omega). rewrite ! Z.mul_opp_l, ! bpow_opp. apply Rinv_le. apply bpow_gt_0. apply bpow_log_pos. unfold m; omega. Qed. (** Overflow and underflow conditions. *) Lemma round_integer_overflow: forall (base: radix) e m, 0 < e -> emax <= e * Z.log2 base -> (bpow radix2 emax <= round radix2 fexp (round_mode mode_NE) (Z2R (Zpos m) * bpow base e))%R. Proof. intros. rewrite <- (round_generic radix2 fexp (round_mode mode_NE) (bpow radix2 emax)); auto. apply round_le; auto. apply fexp_correct; auto. apply valid_rnd_round_mode. rewrite <- (Rmult_1_l (bpow radix2 emax)). apply Rmult_le_compat. apply Rle_0_1. apply bpow_ge_0. apply (Z2R_le 1). zify; omega. eapply Rle_trans. eapply bpow_le. eassumption. apply bpow_log_pos; auto. apply generic_format_FLT. exists (Float radix2 1 emax). split. unfold F2R; simpl. ring. split. simpl. apply (Zpower_gt_1 radix2); auto. simpl. unfold emin; red in prec_gt_0_; omega. Qed. Lemma round_NE_underflows: forall x, (0 <= x <= bpow radix2 (emin - 1))%R -> round radix2 fexp (round_mode mode_NE) x = 0%R. Proof. intros. set (eps := bpow radix2 (emin - 1)) in *. assert (A: round radix2 fexp (round_mode mode_NE) eps = 0%R). { unfold round. simpl. assert (E: canonic_exp radix2 fexp eps = emin). { unfold canonic_exp, eps. rewrite ln_beta_bpow. unfold fexp, FLT_exp. zify; red in prec_gt_0_; omega. } unfold scaled_mantissa; rewrite E. assert (P: (eps * bpow radix2 (-emin) = / 2)%R). { unfold eps. rewrite <- bpow_plus. replace (emin - 1 + -emin) with (-1) by omega. auto. } rewrite P. unfold Znearest. assert (F: Zfloor (/ 2)%R = 0). { apply Zfloor_imp. simpl. lra. } rewrite F. change (Z2R 0) with 0%R. rewrite Rminus_0_r. rewrite Rcompare_Eq by auto. simpl. unfold F2R; simpl. apply Rmult_0_l. } apply Rle_antisym. - rewrite <- A. apply round_le. apply fexp_correct; auto. apply valid_rnd_round_mode. tauto. - rewrite <- (round_0 radix2 fexp (round_mode mode_NE)). apply round_le. apply fexp_correct; auto. apply valid_rnd_round_mode. tauto. Qed. Lemma round_integer_underflow: forall (base: radix) e m, e < 0 -> e * Z.log2 base + Z.log2_up (Zpos m) < emin -> round radix2 fexp (round_mode mode_NE) (Z2R (Zpos m) * bpow base e) = 0%R. Proof. intros. apply round_NE_underflows. split. - apply Rmult_le_pos. apply (Z2R_le 0). zify; omega. apply bpow_ge_0. - apply Rle_trans with (bpow radix2 (Z.log2_up (Z.pos m) + e * Z.log2 base)). + rewrite bpow_plus. apply Rmult_le_compat. apply (Z2R_le 0); zify; omega. apply bpow_ge_0. rewrite <- Z2R_Zpower. apply Z2R_le. destruct (Z.eq_dec (Z.pos m) 1). rewrite e0. simpl. omega. apply Z.log2_up_spec. zify; omega. apply Z.log2_up_nonneg. apply bpow_log_neg. auto. + apply bpow_le. omega. Qed. (** Correctness of Bparse *) Theorem Bparse_correct: forall b m e (BASE: 2 <= Zpos b), let base := {| radix_val := Zpos b; radix_prop := Zle_imp_le_bool _ _ BASE |} in let r := round radix2 fexp (round_mode mode_NE) (Z2R (Zpos m) * bpow base e) in if Rlt_bool (Rabs r) (bpow radix2 emax) then B2R _ _ (Bparse b m e) = r /\ is_finite _ _ (Bparse b m e) = true /\ Bsign _ _ (Bparse b m e) = false else B2FF _ _ (Bparse b m e) = F754_infinity false. Proof. intros. assert (A: forall x, @F2R radix2 {| Fnum := x; Fexp := 0 |} = Z2R x). { intros. unfold F2R, Fnum; simpl. ring. } unfold Bparse, r. destruct e as [ | e | e]. - (* e = Z0 *) change (bpow base 0) with 1%R. rewrite Rmult_1_r. exact (BofZ_correct (Z.pos m)). - (* e = Zpos e *) destruct (Z.ltb_spec (Z.pos e * Z.log2 (Z.pos b)) emax). + (* no overflow *) rewrite pos_pow_spec. rewrite <- Z2R_Zpower by (zify; omega). rewrite <- Z2R_mult. replace false with (Z.pos m * Z.pos b ^ Z.pos e <? 0). exact (BofZ_correct (Z.pos m * Z.pos b ^ Z.pos e)). rewrite Z.ltb_ge. rewrite Z.mul_comm. apply Zmult_gt_0_le_0_compat. zify; omega. apply (Zpower_ge_0 base). + (* overflow *) rewrite Rlt_bool_false. auto. eapply Rle_trans; [idtac|apply Rle_abs]. apply (round_integer_overflow base). zify; omega. auto. - (* e = Zneg e *) destruct (Z.ltb_spec (Z.neg e * Z.log2 (Z.pos b) + Z.log2_up (Z.pos m)) emin). + (* undeflow *) rewrite round_integer_underflow; auto. rewrite Rlt_bool_true. auto. replace (Rabs 0)%R with 0%R. apply bpow_gt_0. apply (Z2R_abs 0). zify; omega. + (* no underflow *) generalize (Bdiv_correct_aux prec emax prec_gt_0_ Hmax mode_NE false m 0 false (pos_pow b e) 0). set (f := match Fdiv_core_binary prec (Z.pos m) 0 (Z.pos (pos_pow b e)) 0 with | (0, _, _) => F754_nan false 1 | (Z.pos mz0, ez, lz) => binary_round_aux prec emax mode_NE (xorb false false) mz0 ez lz | (Z.neg _, _, _) => F754_nan false 1 end). fold emin; fold fexp. rewrite ! A. unfold cond_Zopp. rewrite pos_pow_spec. assert (B: (Z2R (Z.pos m) / Z2R (Z.pos b ^ Z.pos e) = Z2R (Z.pos m) * bpow base (Z.neg e))%R). { change (Z.neg e) with (- (Z.pos e)). rewrite bpow_opp. auto. } rewrite B. intros [P Q]. destruct (Rlt_bool (Rabs (round radix2 fexp (round_mode mode_NE) (Z2R (Z.pos m) * bpow base (Z.neg e)))) (bpow radix2 emax)). * destruct Q as (Q1 & Q2 & Q3). split. rewrite B2R_FF2B, Q1. auto. split. rewrite is_finite_FF2B. auto. rewrite Bsign_FF2B. auto. * rewrite B2FF_FF2B. auto. Qed. End Extra_ops. (** ** Conversions between two FP formats *) Section Conversions. Variable prec1 emax1 prec2 emax2 : Z. Context (prec1_gt_0_ : Prec_gt_0 prec1) (prec2_gt_0_ : Prec_gt_0 prec2). Let emin1 := (3 - emax1 - prec1)%Z. Let fexp1 := FLT_exp emin1 prec1. Let emin2 := (3 - emax2 - prec2)%Z. Let fexp2 := FLT_exp emin2 prec2. Hypothesis Hmax1 : (prec1 < emax1)%Z. Hypothesis Hmax2 : (prec2 < emax2)%Z. Let binary_float1 := binary_float prec1 emax1. Let binary_float2 := binary_float prec2 emax2. Definition Bconv (conv_nan: bool -> nan_pl prec1 -> bool * nan_pl prec2) (md: mode) (f: binary_float1) : binary_float2 := match f with | B754_nan _ _ s pl => let '(s, pl) := conv_nan s pl in B754_nan _ _ s pl | B754_infinity _ _ s => B754_infinity _ _ s | B754_zero _ _ s => B754_zero _ _ s | B754_finite _ _ s m e _ => binary_normalize _ _ _ Hmax2 md (cond_Zopp s (Zpos m)) e s end. Theorem Bconv_correct: forall conv_nan m f, is_finite _ _ f = true -> if Rlt_bool (Rabs (round radix2 fexp2 (round_mode m) (B2R _ _ f))) (bpow radix2 emax2) then B2R _ _ (Bconv conv_nan m f) = round radix2 fexp2 (round_mode m) (B2R _ _ f) /\ is_finite _ _ (Bconv conv_nan m f) = true /\ Bsign _ _ (Bconv conv_nan m f) = Bsign _ _ f else B2FF _ _ (Bconv conv_nan m f) = binary_overflow prec2 emax2 m (Bsign _ _ f). Proof. intros. destruct f; try discriminate. - simpl. rewrite round_0. rewrite Rabs_R0. rewrite Rlt_bool_true. auto. apply bpow_gt_0. apply valid_rnd_round_mode. - generalize (binary_normalize_correct _ _ _ Hmax2 m (cond_Zopp b (Zpos m0)) e b). fold emin2; fold fexp2. simpl. destruct Rlt_bool. + intros (A & B & C). split. auto. split. auto. rewrite C. destruct b; simpl. rewrite Rcompare_Lt. auto. apply F2R_lt_0_compat. simpl. compute; auto. rewrite Rcompare_Gt. auto. apply F2R_gt_0_compat. simpl. compute; auto. + intros A. rewrite A. f_equal. destruct b. apply Rlt_bool_true. apply F2R_lt_0_compat. simpl. compute; auto. apply Rlt_bool_false. apply Rlt_le. apply Rgt_lt. apply F2R_gt_0_compat. simpl. compute; auto. Qed. (** Converting a finite FP number to higher or equal precision preserves its value. *) Theorem Bconv_widen_exact: (prec2 >= prec1)%Z -> (emax2 >= emax1)%Z -> forall conv_nan m f, is_finite _ _ f = true -> B2R _ _ (Bconv conv_nan m f) = B2R _ _ f /\ is_finite _ _ (Bconv conv_nan m f) = true /\ Bsign _ _ (Bconv conv_nan m f) = Bsign _ _ f. Proof. intros PREC EMAX; intros. generalize (Bconv_correct conv_nan m f H). assert (LT: (Rabs (B2R _ _ f) < bpow radix2 emax2)%R). { destruct f; try discriminate; simpl. rewrite Rabs_R0. apply bpow_gt_0. apply Rlt_le_trans with (bpow radix2 emax1). rewrite F2R_cond_Zopp. rewrite abs_cond_Ropp. rewrite <- F2R_Zabs. simpl Z.abs. eapply bounded_lt_emax; eauto. apply bpow_le. omega. } assert (EQ: round radix2 fexp2 (round_mode m) (B2R prec1 emax1 f) = B2R prec1 emax1 f). { apply round_generic. apply valid_rnd_round_mode. eapply generic_inclusion_le. 5: apply generic_format_B2R. apply fexp_correct; auto. apply fexp_correct; auto. instantiate (1 := emax2). intros. unfold fexp2, FLT_exp. unfold emin2. zify; omega. apply Rlt_le; auto. } rewrite EQ. rewrite Rlt_bool_true by auto. auto. Qed. (** Conversion from integers and change of format *) Theorem Bconv_BofZ: forall conv_nan n, integer_representable prec1 emax1 n -> Bconv conv_nan mode_NE (BofZ prec1 emax1 _ Hmax1 n) = BofZ prec2 emax2 _ Hmax2 n. Proof. intros. destruct (BofZ_representable _ _ _ Hmax1 n H) as (A & B & C). set (f := BofZ prec1 emax1 prec1_gt_0_ Hmax1 n) in *. generalize (Bconv_correct conv_nan mode_NE f B). unfold BofZ. generalize (binary_normalize_correct _ _ _ Hmax2 mode_NE n 0 false). fold emin2; fold fexp2. rewrite A. replace (F2R {| Fnum := n; Fexp := 0 |}) with (Z2R n). destruct Rlt_bool. - intros (P & Q & R) (D & E & F). apply B2R_Bsign_inj; auto. congruence. rewrite F, C, R. change 0%R with (Z2R 0). rewrite Rcompare_Z2R. unfold Z.ltb. auto. - intros P Q. apply B2FF_inj. rewrite P, Q. rewrite C. f_equal. change 0%R with (Z2R 0). generalize (Zlt_bool_spec n 0); intros LT; inversion LT. rewrite Rlt_bool_true; auto. apply Z2R_lt; auto. rewrite Rlt_bool_false; auto. apply Z2R_le; auto. - unfold F2R; simpl. rewrite Rmult_1_r. auto. Qed. (** Change of format (to higher precision) and conversion to integer. *) Theorem ZofB_Bconv: prec2 >= prec1 -> emax2 >= emax1 -> forall conv_nan m f n, ZofB _ _ f = Some n -> ZofB _ _ (Bconv conv_nan m f) = Some n. Proof. intros. rewrite ZofB_correct in H1. destruct (is_finite _ _ f) eqn:FIN; inversion H1. destruct (Bconv_widen_exact H H0 conv_nan m f) as (A & B & C). auto. rewrite ZofB_correct. rewrite B. rewrite A. auto. Qed. Theorem ZofB_range_Bconv: forall min1 max1 min2 max2, prec2 >= prec1 -> emax2 >= emax1 -> min2 <= min1 -> max1 <= max2 -> forall conv_nan m f n, ZofB_range _ _ f min1 max1 = Some n -> ZofB_range _ _ (Bconv conv_nan m f) min2 max2 = Some n. Proof. intros. destruct (ZofB_range_inversion _ _ _ _ _ _ H3) as (A & B & C). unfold ZofB_range. erewrite ZofB_Bconv by eauto. rewrite ! Zle_bool_true by omega. auto. Qed. (** Change of format (to higher precision) and comparison. *) Theorem Bcompare_Bconv_widen: prec2 >= prec1 -> emax2 >= emax1 -> forall conv_nan m x y, Bcompare _ _ (Bconv conv_nan m x) (Bconv conv_nan m y) = Bcompare _ _ x y. Proof. intros. destruct (is_finite _ _ x && is_finite _ _ y) eqn:FIN. - apply andb_true_iff in FIN. destruct FIN. destruct (Bconv_widen_exact H H0 conv_nan m x H1) as (A & B & C). destruct (Bconv_widen_exact H H0 conv_nan m y H2) as (D & E & F). rewrite ! Bcompare_correct by auto. rewrite A, D. auto. - generalize (Bconv_widen_exact H H0 conv_nan m x) (Bconv_widen_exact H H0 conv_nan m y); intros P Q. destruct x, y; try discriminate; simpl in P, Q; simpl; repeat (match goal with |- context [conv_nan ?b ?pl] => destruct (conv_nan b pl) end); auto. destruct Q as (D & E & F); auto. destruct (binary_normalize prec2 emax2 prec2_gt_0_ Hmax2 m (cond_Zopp b0 (Z.pos m0)) e b0); discriminate || reflexivity. destruct P as (A & B & C); auto. destruct (binary_normalize prec2 emax2 prec2_gt_0_ Hmax2 m (cond_Zopp b (Z.pos m0)) e b); try discriminate; simpl. destruct b; auto. destruct b, b1; auto. destruct P as (A & B & C); auto. destruct (binary_normalize prec2 emax2 prec2_gt_0_ Hmax2 m (cond_Zopp b (Z.pos m0)) e b); try discriminate; simpl. destruct b; auto. destruct b, b2; auto. Qed. End Conversions. Section Compose_Conversions. Variable prec1 emax1 prec2 emax2 : Z. Context (prec1_gt_0_ : Prec_gt_0 prec1) (prec2_gt_0_ : Prec_gt_0 prec2). Let emin1 := (3 - emax1 - prec1)%Z. Let fexp1 := FLT_exp emin1 prec1. Let emin2 := (3 - emax2 - prec2)%Z. Let fexp2 := FLT_exp emin2 prec2. Hypothesis Hmax1 : (prec1 < emax1)%Z. Hypothesis Hmax2 : (prec2 < emax2)%Z. Let binary_float1 := binary_float prec1 emax1. Let binary_float2 := binary_float prec2 emax2. (** Converting to a higher precision then down to the original format is the identity. *) Theorem Bconv_narrow_widen: prec2 >= prec1 -> emax2 >= emax1 -> forall narrow_nan widen_nan m f, is_nan _ _ f = false -> Bconv prec2 emax2 prec1 emax1 _ Hmax1 narrow_nan m (Bconv prec1 emax1 prec2 emax2 _ Hmax2 widen_nan m f) = f. Proof. intros. destruct (is_finite _ _ f) eqn:FIN. - assert (EQ: round radix2 fexp1 (round_mode m) (B2R prec1 emax1 f) = B2R prec1 emax1 f). { apply round_generic. apply valid_rnd_round_mode. apply generic_format_B2R. } generalize (Bconv_widen_exact _ _ _ _ _ _ Hmax2 H H0 widen_nan m f FIN). set (f' := Bconv prec1 emax1 prec2 emax2 _ Hmax2 widen_nan m f). intros (A & B & C). generalize (Bconv_correct _ _ _ _ _ Hmax1 narrow_nan m f' B). fold emin1. fold fexp1. rewrite A, C, EQ. rewrite Rlt_bool_true. intros (D & E & F). apply B2R_Bsign_inj; auto. destruct f; try discriminate; simpl. rewrite Rabs_R0. apply bpow_gt_0. rewrite F2R_cond_Zopp. rewrite abs_cond_Ropp. rewrite <- F2R_Zabs. simpl Z.abs. eapply bounded_lt_emax; eauto. - destruct f; try discriminate. simpl. auto. Qed. End Compose_Conversions.
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <resources> <integer name="movies_columns">3</integer> <dimen name="movie_detail_content_width">@dimen/match_parent</dimen> <dimen name="movie_detail_content_margin_left_right">32dp</dimen> <dimen name="movie_detail_cards_margin_left_right">16dp</dimen> <dimen name="movie_detail_content_overlay">96dp</dimen> </resources>
{ "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. #include "base/strings/stringprintf.h" #include <errno.h> #include <stddef.h> #include <vector> #include "base/macros.h" #include "base/scoped_clear_errno.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" namespace base { namespace { // Overloaded wrappers around vsnprintf and vswprintf. The buf_size parameter // is the size of the buffer. These return the number of characters in the // formatted string excluding the NUL terminator. If the buffer is not // large enough to accommodate the formatted string without truncation, they // return the number of characters that would be in the fully-formatted string // (vsnprintf, and vswprintf on Windows), or -1 (vswprintf on POSIX platforms). inline int vsnprintfT(char* buffer, size_t buf_size, const char* format, va_list argptr) { return base::vsnprintf(buffer, buf_size, format, argptr); } #if defined(OS_WIN) inline int vsnprintfT(wchar_t* buffer, size_t buf_size, const wchar_t* format, va_list argptr) { return base::vswprintf(buffer, buf_size, format, argptr); } #endif // Templatized backend for StringPrintF/StringAppendF. This does not finalize // the va_list, the caller is expected to do that. template <class StringType> static void StringAppendVT(StringType* dst, const typename StringType::value_type* format, va_list ap) { // First try with a small fixed size buffer. // This buffer size should be kept in sync with StringUtilTest.GrowBoundary // and StringUtilTest.StringPrintfBounds. typename StringType::value_type stack_buf[1024]; va_list ap_copy; va_copy(ap_copy, ap); #if !defined(OS_WIN) ScopedClearErrno clear_errno; #endif int result = vsnprintfT(stack_buf, arraysize(stack_buf), format, ap_copy); va_end(ap_copy); if (result >= 0 && result < static_cast<int>(arraysize(stack_buf))) { // It fit. dst->append(stack_buf, result); return; } // Repeatedly increase buffer size until it fits. int mem_length = arraysize(stack_buf); while (true) { if (result < 0) { #if defined(OS_WIN) // On Windows, vsnprintfT always returns the number of characters in a // fully-formatted string, so if we reach this point, something else is // wrong and no amount of buffer-doubling is going to fix it. return; #else if (errno != 0 && errno != EOVERFLOW) return; // Try doubling the buffer size. mem_length *= 2; #endif } else { // We need exactly "result + 1" characters. mem_length = result + 1; } if (mem_length > 32 * 1024 * 1024) { // That should be plenty, don't try anything larger. This protects // against huge allocations when using vsnprintfT implementations that // return -1 for reasons other than overflow without setting errno. DLOG(WARNING) << "Unable to printf the requested string due to size."; return; } std::vector<typename StringType::value_type> mem_buf(mem_length); // NOTE: You can only use a va_list once. Since we're in a while loop, we // need to make a new copy each time so we don't use up the original. va_copy(ap_copy, ap); result = vsnprintfT(&mem_buf[0], mem_length, format, ap_copy); va_end(ap_copy); if ((result >= 0) && (result < mem_length)) { // It fit. dst->append(&mem_buf[0], result); return; } } } } // namespace std::string StringPrintf(const char* format, ...) { va_list ap; va_start(ap, format); std::string result; StringAppendV(&result, format, ap); va_end(ap); return result; } #if defined(OS_WIN) std::wstring StringPrintf(const wchar_t* format, ...) { va_list ap; va_start(ap, format); std::wstring result; StringAppendV(&result, format, ap); va_end(ap); return result; } #endif std::string StringPrintV(const char* format, va_list ap) { std::string result; StringAppendV(&result, format, ap); return result; } const std::string& SStringPrintf(std::string* dst, const char* format, ...) { va_list ap; va_start(ap, format); dst->clear(); StringAppendV(dst, format, ap); va_end(ap); return *dst; } #if defined(OS_WIN) const std::wstring& SStringPrintf(std::wstring* dst, const wchar_t* format, ...) { va_list ap; va_start(ap, format); dst->clear(); StringAppendV(dst, format, ap); va_end(ap); return *dst; } #endif void StringAppendF(std::string* dst, const char* format, ...) { va_list ap; va_start(ap, format); StringAppendV(dst, format, ap); va_end(ap); } #if defined(OS_WIN) void StringAppendF(std::wstring* dst, const wchar_t* format, ...) { va_list ap; va_start(ap, format); StringAppendV(dst, format, ap); va_end(ap); } #endif void StringAppendV(std::string* dst, const char* format, va_list ap) { StringAppendVT(dst, format, ap); } #if defined(OS_WIN) void StringAppendV(std::wstring* dst, const wchar_t* format, va_list ap) { StringAppendVT(dst, format, ap); } #endif } // namespace base
{ "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:53 AEST 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Package org.eclipse.rdf4j.lucene.spin.config (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 Package org.eclipse.rdf4j.lucene.spin.config (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>Class</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/lucene/spin/config/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.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"> <h1 title="Uses of Package org.eclipse.rdf4j.lucene.spin.config" class="title">Uses of Package<br>org.eclipse.rdf4j.lucene.spin.config</h1> </div> <div class="contentContainer">No usage of org.eclipse.rdf4j.lucene.spin.config</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>Class</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/lucene/spin/config/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.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" }
23 859 207 F 23 0 17268 46 0 100.00 23 859 208 F 24 0 17266 44 1 95.74 20 859 208 F 20 0 17271 40 0 100.00 29 561 415 F 29 0 71281 55 1 96.55 333 1265 0 F 330 0 72423 612 17 94.87 78 859 0 F 81 0 72588 129 10 87.42 78 859 0 F 81 0 72588 129 10 87.42 135 859 84 F 135 0 72651 258 4 97.04 167 859 84 F 155 0 72651 271 17 89.44 38 1214 205 F 38 0 77815 76 0 100.00 36 1214 205 F 37 0 77812 70 1 97.26 36 1214 205 F 35 0 77812 68 1 97.18 34 1214 207 F 33 0 77812 64 1 97.01 32 1214 209 F 31 0 77812 60 1 96.83 49 1214 206 F 48 0 77808 70 9 81.44 33 1214 208 F 31 0 77808 55 3 90.62 43 1214 210 F 42 0 77808 61 8 81.18 41 1214 212 F 40 0 77808 57 8 80.25 34 1214 205 F 34 0 77817 68 0 100.00 35 1214 205 F 35 0 77819 67 1 97.14 43 859 208 F 39 0 77821 58 8 80.49 33 1214 205 F 33 0 77821 63 1 96.97 31 1214 205 F 31 0 77823 59 1 96.77 29 1214 205 F 29 0 77825 55 1 96.55 113 1361 1 F 108 0 105325 158 21 81.00 222 1361 148 F 222 0 105629 435 3 98.65 222 1361 148 F 222 0 105629 435 3 98.65 222 1361 148 F 222 0 105629 435 3 98.65 222 1361 148 F 222 0 105629 435 3 98.65
{ "pile_set_name": "Github" }