text
stringlengths
2
1.04M
meta
dict
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>虎门乐诚汽修</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link type="text/css" rel="stylesheet" href="<?php echo base_url("ui_ref/css/bootstrap_mobile.min.css"); ?>"> <link type="text/css" rel="stylesheet" href="<?php echo base_url("ui_ref/css/font-awesome_official.min.css"); ?>"> </head> <body> <div class="bs-component"> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-2"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="<?php echo base_url("index.php/ToMobile"); ?>" class="navbar-brand" href="#"><i class="fa fa-home fa-fw "></i>返回首页</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-2"> <ul class="nav navbar-nav navbar-right"> <li><a href="<?php echo base_url("index.php/ToMobile#qrcode"); ?>">关注微信公众号</a></li> </ul> </div> </div> </nav> </div> <div class="bs-component" style="margin-bottom: 15px;"> <div class="btn-group btn-group-justified"> <a href="<?php echo base_url("index.php/Mservice");?>" class="btn btn-default active" > <i class="fa fa-wrench text-primary"><b>服务</b></i> </a> <a href="<?php echo base_url("index.php/Mintroduction");?>" class="btn btn-default"> <i class="fa fa-book text-info"><b>简介</b></i> </a> <a href="<?php echo base_url("index.php/Mhardware");?>" class="btn btn-default"> <i class="fa fa-cogs "><b >配套</b></i> </a> <a href="<?php echo base_url("index.php/Mcontact");?>" class="btn btn-default"> <i class="fa fa-phone text-warning"><b >联系</b></i> </a> <a href="<?php echo base_url("index.php/Maddress");?>" class="btn btn-default"> <i class="fa fa-map-marker text-danger"><b>地址</b></i> </a> </div> </div> <div class="bs-component"> <ul class="breadcrumb"> <li><a href="<?php echo base_url("index.php/ToMobile"); ?>">首页</a></li> <li ><a href="<?php echo base_url("index.php/Mservice");?>">服务</a></li> <li class="active">乐诚案例</li> </ul> </div> <div class="bs-component"> <div class="alert alert-dismissible alert-success"> <button type="button" class="close" data-dismiss="alert">×</button> <strong class="mobile_font_nor">乐诚电路检测- 2014年</strong><a href="#" class="alert-link">某车辆经故障解码后恢复正常</a>. </div> <div class="panel panel-info"> <div class="panel-heading"> <h3 class="panel-title">修复中-完成</h3> </div> <div class="panel-body"> <img src="<?php echo base_url("ui_ref/images/circuit/process.jpg"); ?>" class="img-responsive"> </div> </div> </div> <footer id="footer"> <div class="container"> <div class="row"> <div class="col-sm-12"> &copy;<b class="mobile_font_nor">2015<a target="_blank" href="#" title="虎门乐诚汽修">虎门乐诚汽修</a>.版权所有.</b> </div> </div> <div class="row"> <div class="col-sm-12 center-block" style="text-align: center"> <a href="<?php echo base_url("index.php/ToDesktop"); ?>"><b><i class="fa fa-desktop fa-lg fa-fw"></i>转至电脑版</b></a> <a href="<?php echo base_url("index.php/ToMobile"); ?>"><b style="color: #222"><i class="fa fa-tablet fa-lg fa-fw "></i>移动版</b></a> </div> </div> </div> </footer> <!--/#footer--> <script src="<?php echo base_url("ui_ref/js/jquery.js"); ?>"></script> <script src="<?php echo base_url("ui_ref/js/bootstrap.min.js"); ?>"></script> </body> </html>
{ "content_hash": "e3e68635e3bdfeb4f61bf9f7ce2b5dfb", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 143, "avg_line_length": 35.766666666666666, "alnum_prop": 0.5400745573159367, "repo_name": "ptangent/lcqxc", "id": "ab738c00fe0ec2bc8c33db3c6e8f78834cac2855", "size": "4461", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lcqxc/application/views/m_service_circuit.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "96549" }, { "name": "HTML", "bytes": "5542424" }, { "name": "JavaScript", "bytes": "63459" }, { "name": "PHP", "bytes": "1824792" } ], "symlink_target": "" }
<?php namespace Tuto\AnimeauxBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('tuto_animeaux'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
{ "content_hash": "85b0662c33bda74054c2231282e2a044", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 131, "avg_line_length": 30.379310344827587, "alnum_prop": 0.717366628830874, "repo_name": "rachednemr/agence_voiture", "id": "569f35a7aa2b3b4cf6f179e4c775e1e2a76cad9a", "size": "881", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Tuto/AnimeauxBundle/DependencyInjection/Configuration.php", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "44969" }, { "name": "Perl", "bytes": "1104" }, { "name": "Shell", "bytes": "1933" } ], "symlink_target": "" }
package virtual; public class CalleeThreeTop { }
{ "content_hash": "bb9f756b25a71fbf5cd54edb096efd51", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 29, "avg_line_length": 10.2, "alnum_prop": 0.7647058823529411, "repo_name": "drunklite/spring-loaded", "id": "fded05278465b7cf3fbaa94b694bdc72f99c4aa6", "size": "51", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "testdata/src/main/java/virtual/CalleeThreeTop.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "25289" }, { "name": "Java", "bytes": "2263958" }, { "name": "Shell", "bytes": "520" } ], "symlink_target": "" }
FROM phusion/baseimage:0.9.11 MAINTAINER kstile <2kwv01@things> ENV DEBIAN_FRONTEND noninteractive # Set correct environment variables ENV HOME /root # Use baseimage-docker's init system CMD ["/sbin/my_init"] # Fix a Debianism of the nobody's uid being 65534 RUN usermod -u 99 nobody RUN usermod -g 100 nobody # install our dependencies and nodejs RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list RUN apt-get update #RUN apt-get -y install python-software-properties git build-essential RUN add-apt-repository -y ppa:chris-lea/node.js RUN apt-get update RUN apt-get -y install nodejs # use changes to package.json to force Docker not to use the cache # when we change our application's nodejs dependencies: ADD package.json /tmp/package.json RUN cd /tmp && npm install RUN mkdir -p /opt/app/podcastSlinger && cp -a /tmp/node_modules /opt/app/podcastSlinger # podcastSlinger Configuration #VOLUME # From here we load our application's code in, therefore the previous docker # "layer" thats been cached will be used if possible WORKDIR /opt/app/podcastSlinger ADD id3.js /opt/app/podcastSlinger/ ADD rss.jade /opt/app/podcastSlinger/ ADD server.js /opt/app/podcastSlinger/ RUN chown -R 99:100 /opt/app/podcastSlinger # Add podcastSlinger to runit RUN mkdir /etc/service/podcastSlinger ADD podcastSlinger.sh /etc/service/podcastSlinger/run RUN chmod +x /etc/service/podcastSlinger/run
{ "content_hash": "c8cfca671d0e789444ff62347aa7cfcb", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 93, "avg_line_length": 31.91111111111111, "alnum_prop": 0.7834261838440112, "repo_name": "kwv/podcastslinger", "id": "8a194897aa4e3198a5f8b739301ecd1aede00b34", "size": "1436", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Dockerfile", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "580" }, { "name": "JavaScript", "bytes": "26951" }, { "name": "Shell", "bytes": "584" } ], "symlink_target": "" }
public static string Abc(int def) { //
{ "content_hash": "20d4ea1d766c92ba8d880592e1240870", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 33, "avg_line_length": 13, "alnum_prop": 0.6923076923076923, "repo_name": "general-language-syntax/GLS", "id": "6f729d5b76da8e172e6f034dbbe21e3099acc5fa", "size": "42", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/integration/StandaloneFunctionDeclareStart/public one parameter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "42230" }, { "name": "Java", "bytes": "42190" }, { "name": "JavaScript", "bytes": "26336" }, { "name": "Python", "bytes": "24737" }, { "name": "Ruby", "bytes": "23191" }, { "name": "TypeScript", "bytes": "845652" } ], "symlink_target": "" }
.bv-form .help-block{margin-bottom:0}.bv-form .tooltip-inner{text-align:left}.nav-tabs li.bv-tab-success>a{color:#3c763d}.nav-tabs li.bv-tab-error>a{color:#a94442}.bv-form .bv-icon-no-label{top:0}.bv-form .bv-icon-input-group{top:0;z-index:100}
{ "content_hash": "e8c7d60bfd29d34bd7a7b1981c130c5c", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 244, "avg_line_length": 82, "alnum_prop": 0.7357723577235772, "repo_name": "iamchriswick/Twilio-SMS-PHP-AJAX-Quickstart", "id": "1789a1567c3a58042a521c1b25c8e1ab70ae59fa", "size": "570", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/bootstrapvalidator/dist/css/bootstrapValidator.min.css", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "2693" }, { "name": "PHP", "bytes": "1750" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { // Used by bindUserDefinedConversion internal readonly struct UdConvInfo { public readonly MethWithType Meth; public readonly bool SrcImplicit; public readonly bool DstImplicit; public UdConvInfo(MethWithType mwt, bool srcImplicit, bool dstImplicit) { Meth = mwt; SrcImplicit = srcImplicit; DstImplicit = dstImplicit; } } ////////////////////////////////////////////////////////////////////////////////////////////// // Small wrapper for passing around argument information for the various BindGrpTo methods // It is used because most things only need the type, but in the case of METHGRPs and ANONMETHs // the expr is also needed to determine if a conversion is possible internal sealed class ArgInfos { public int carg; public TypeArray types; public List<Expr> prgexpr; } internal enum ConstCastResult { Success, // Constant can be cast to type Failure, // Constant cannot be cast to type CheckFailure // Constant cannot be cast to type because of overflow in checked context // (Note that this only happens when the conversion is explicit; implicit // conversions never overflow, that's why they're implicit.) } internal enum AggCastResult { Success, // We found a conversion, stop looking Failure, // This conversion doesn't work, keep looking Abort // No possible conversion can work, stop looking } internal enum UnaryOperatorSignatureFindResult { Match, Continue, Return } internal enum UnaOpKind { Plus, Minus, Tilde, Bang, IncDec, Lim } [Flags] internal enum UnaOpMask { None = 0, Plus = 1 << UnaOpKind.Plus, Minus = 1 << UnaOpKind.Minus, Tilde = 1 << UnaOpKind.Tilde, Bang = 1 << UnaOpKind.Bang, IncDec = 1 << UnaOpKind.IncDec, // The different combinations needed in operators.cs Signed = Plus | Minus | Tilde, Unsigned = Plus | Tilde, Real = Plus | Minus, Bool = Bang, } [Flags] internal enum OpSigFlags { None = 0, Convert = 0x01, // Convert the operands before calling the bind method CanLift = 0x02, // Operator has a lifted form AutoLift = 0x04, // Standard nullable lifting // The different combinations needed in operators.cs Value = Convert | CanLift | AutoLift, Reference = Convert, BoolBit = Convert | CanLift, } [Flags] internal enum LiftFlags { None = 0, Lift1 = 0x01, Lift2 = 0x02, Convert1 = 0x04, Convert2 = 0x08, } internal enum CheckLvalueKind { Assignment, Increment } internal enum BinOpFuncKind { BoolBinOp, BoolBitwiseOp, DecBinOp, DelBinOp, EnumBinOp, IntBinOp, RealBinOp, RefCmpOp, ShiftOp, StrBinOp, StrCmpOp, None } internal enum UnaOpFuncKind { BoolUnaOp, DecUnaOp, EnumUnaOp, IntUnaOp, RealUnaOp, LiftedIncOpCore, None } internal readonly partial struct ExpressionBinder { // ExpressionBinder - General Rules // // Express the Contract // // Use assertions and naming guidelines to express the contract for methods. // The most common issue is whether an argument may be null or not. If an // argument may not be null, then the method must ASSERT that before any other // code. If an argument may be null then the name of the argument should // include 'Optional'. The exception to this rule is the input parse tree // parameter. If the parse tree may be null, then the method name should // include an 'Opt' suffix. For example bindArgumentList should really be // named bindArgumentListOpt. Abbreviations should be avoided, but the 'Opt' // suffix gets an exception because it is used consistently in the language // spec. // // // Error Tolerant // // Do not rely on the input parse tree being complete. Erroneous code may // result in parse trees with required children missing, or with unexpected // structure. Find out what the invariants are for the parse tree being // consumed and code defensively. // // Similarly, the result of binding children nodes may not be 'OK'. The child // node may have contained some semantic errors and the binding code in the // parent must cope gracefully with the result. For example, an EXPRMEMGRP may // contain no members. // // // Error Recovery // // Always attempt to bind children nodes even if errors have already been // detected in other children. Always build a new node representing a 'best // guess' at the semantics of the parse tree. Never discard the results of // binding a child node even if the binding has errors. Since a new node is // always produced there should always be a place to add bindings with errors // to the result. // // This ensures that full semantic information for all nodes is produced - // that the expression binder always produces a 'best guess' for every // expression in source. // // // Error Reporting // // If a child expression has an error, then no new error's for the parent // should be reported, unless there is no way that the new error was caused // by any child errors. If child nodes don't have any errors, and the new // node does have an error, then at least one error must be reported. These // rules ensure that an error is always reported for erroneous code, and that // only the most meaningful error is reported from a set of cascading errors. // // // Map Back To the Source // // When constructing new expression nodes, attach the appropriate parse tree // node. The attached parse tree is used for: // - error location reporting // - debug sequence points // - stepping // - local variable scopes // - finding the most meaningful expression for a parse tree node // // // Meaning not Implementation // // The expression trees resulting from the initial binding pass should // represent the semantics of the input source code. There should be a // direct mapping between the newly constructed expression and the input // parse tree. // // The Whidbey codebase had the habit of producing expressions in the initial // binding which were closer in representation to the generated IL than the // input source code. In Orcas all transformations which may lose semantic // information about the source must be done after the initial expression // binding phase. // // Special Cases // // - Constant folding - Constant folding is a semantic losing // transformation which must be performed to complete expression // analysis. When creating a folded constant, create an expression // node representing the unfolded expression, then pass this as a // child expression of a new constant expression. // - Color Color - The new Type or Instance expression covers this case. // It is produced from bindSimpleName. // - Method Group - Method groups should be preserved in expression trees. // This includes as children of Call expressions, and delegate construction // nodes. // - Type Binding - This is a big one. Whenever a type is bound in an // expression, the binding of the component parts of the type must be // preserved. This includes every identifier in a dotted type or // namespace name, as well as the type binding information for the // type arguments of constructed types. The semantic information for // intermediate type binding results is represented by an // EXPRTYPEORNAMESPACE. Types can be bound in several places in // expressions: // - Sizeof // - Typeof // - New // - Is/As // - Cast // - Type Arguments supplied to generic method calls. // - Left hand side of a dot operator. // - Parameter types in anonymous methods and lambdas. // - Local Variables // // // Want to eventually Have's // // Only build the new node once all children have been built. // Factory should require all children as arguments. // Factory method sets the "Do Children have Errors?" bit - not done manually. // Once constructed Expression trees are not mutated - doesn't work easily for statements unfortunately. private delegate Expr PfnBindBinOp(ExpressionBinder binder, ExpressionKind ek, EXPRFLAG flags, Expr op1, Expr op2); private delegate Expr PfnBindUnaOp(ExpressionBinder binder, ExpressionKind ek, EXPRFLAG flags, Expr op); public BindingContext Context { get; } public ExpressionBinder(BindingContext context) { Context = context; } private static AggregateType GetPredefindType(PredefinedType pt) { Debug.Assert(pt != PredefinedType.PT_VOID); // use getVoidType() return SymbolLoader.GetPredefindType(pt); } private Expr GenerateAssignmentConversion(Expr op1, Expr op2, bool allowExplicit) => allowExplicit ? mustCastCore(op2, op1.Type, 0) : mustConvertCore(op2, op1.Type); //////////////////////////////////////////////////////////////////////////////// // Bind the simple assignment operator =. public Expr BindAssignment(Expr op1, Expr op2, bool allowExplicit) { Debug.Assert(op1 is ExprCast || op1 is ExprArrayIndex || op1 is ExprCall || op1 is ExprProperty || op1 is ExprClass || op1 is ExprField); CheckLvalue(op1, CheckLvalueKind.Assignment); op2 = GenerateAssignmentConversion(op1, op2, allowExplicit); return GenerateOptimizedAssignment(op1, op2); } internal Expr BindArrayIndexCore(Expr pOp1, Expr pOp2) { CType pIntType = GetPredefindType(PredefinedType.PT_INT); ArrayType pArrayType = pOp1.Type as ArrayType; Debug.Assert(pArrayType != null); CType elementType = pArrayType.ElementType; CheckUnsafe(elementType); // added to the binder so we don't bind to pointer ops // Check the rank of the array against the number of indices provided, and // convert the indexes to ints CType pDestType = ChooseArrayIndexType(pOp2); ExpressionBinder binder = this; Expr transformedIndices = pOp2.Map( x => { Expr pTemp = binder.mustConvert(x, pDestType); return pDestType == pIntType ? pTemp : ExprFactory.CreateCast(EXPRFLAG.EXF_INDEXEXPR, pDestType, pTemp); }); // Allocate a new expression, the type is the element type of the array. // Array index operations are always lvalues. return ExprFactory.CreateArrayIndex(elementType, pOp1, transformedIndices); } //////////////////////////////////////////////////////////////////////////////// // Create a cast node with the given expression flags. private void bindSimpleCast(Expr exprSrc, CType typeDest, out Expr pexprDest) => bindSimpleCast(exprSrc, typeDest, out pexprDest, 0); private void bindSimpleCast(Expr exprSrc, CType typeDest, out Expr pexprDest, EXPRFLAG exprFlags) { Debug.Assert(typeDest != null); // If the source is a constant, and cast is really simple (no change in fundamental // type, no flags), then create a new constant node with the new type instead of // creating a cast node. This allows compile-time constants to be easily recognized. Expr exprConst = exprSrc.GetConst(); // Make the cast expr anyway, and if we find that we have a constant, then set the cast expr // as the original tree for the constant. Otherwise, return the cast expr. ExprCast exprCast = ExprFactory.CreateCast(exprFlags, typeDest, exprSrc); if (Context.Checked) { exprCast.Flags |= EXPRFLAG.EXF_CHECKOVERFLOW; } // Check if we have a compile time constant. If we do, create a constant for it and set the // original tree to the cast. if (exprConst is ExprConstant constant && exprFlags == 0 && exprSrc.Type.FundamentalType == typeDest.FundamentalType && (!exprSrc.Type.IsPredefType(PredefinedType.PT_STRING) || constant.Val.IsNullRef)) { ExprConstant expr = ExprFactory.CreateConstant(typeDest, constant.Val); pexprDest = expr; return; } pexprDest = exprCast; Debug.Assert(exprCast.Argument != null); } //////////////////////////////////////////////////////////////////////////////// // Binds a call to a method, return type is an error or an EXPRCALL. // // tree - ParseTree for error messages // pObject - pObject to call method on // pmwi - Meth to bind to. This will be morphed when we remap to an override. // args - arguments // exprFlags - Flags to put on the generated expr private ExprCall BindToMethod(MethWithInst mwi, Expr pArguments, ExprMemberGroup pMemGroup, MemLookFlags flags) { Debug.Assert(mwi.Sym is MethodSymbol && (!mwi.Meth().isOverride || mwi.Meth().isHideByName)); Debug.Assert(pMemGroup != null); Expr pObject = pMemGroup.OptionalObject; CType callingObjectType = pObject?.Type; PostBindMethod(mwi); pObject = AdjustMemberObject(mwi, pObject); pMemGroup.OptionalObject = pObject; CType pReturnType; if ((flags & (MemLookFlags.Ctor | MemLookFlags.NewObj)) == (MemLookFlags.Ctor | MemLookFlags.NewObj)) { pReturnType = mwi.Ats; } else { pReturnType = TypeManager.SubstType(mwi.Meth().RetType, mwi.GetType(), mwi.TypeArgs); } ExprCall pResult = ExprFactory.CreateCall(0, pReturnType, pArguments, pMemGroup, mwi); // Set the return type and flags for constructors. if ((flags & MemLookFlags.Ctor) != 0) { if ((flags & MemLookFlags.NewObj) != 0) { pResult.Flags |= EXPRFLAG.EXF_NEWOBJCALL | EXPRFLAG.EXF_CANTBENULL; } else { Debug.Assert(pResult.Type == VoidType.Instance); } } verifyMethodArgs(pResult, callingObjectType); return pResult; } //////////////////////////////////////////////////////////////////////////////// // Construct the Expr node which corresponds to a field expression // for a given field and pObject pointer. internal Expr BindToField(Expr pOptionalObject, FieldWithType fwt, BindingFlag bindFlags) { Debug.Assert(fwt.GetType() != null && fwt.Field().getClass() == fwt.GetType().OwningAggregate); CType pFieldType = TypeManager.SubstType(fwt.Field().GetType(), fwt.GetType()); pOptionalObject = AdjustMemberObject(fwt, pOptionalObject); CheckUnsafe(pFieldType); // added to the binder so we don't bind to pointer ops // lvalue if the object is an lvalue (or it's static) and the field is not readonly. // Since dynamic objects for fields come from locals or casts/conversions on locals // (never properties) and hence always have EXF_LVALUE set, the first part of this is // always true, leaving the rest to be determined by the field ctor AssertObjectIsLvalue(pOptionalObject); AggregateType fieldType = null; // If this field is the backing field of a WindowsRuntime event then we need to bind to its // invocationlist property which is a delegate containing all the handlers. if (fwt.Field().isEvent && fwt.Field().getEvent() != null && fwt.Field().getEvent().IsWindowsRuntimeEvent) { fieldType = fwt.Field().GetType() as AggregateType; if (fieldType != null) { // Access event backing field (EventRegistrationTokenTable<T>) using // EventRegistrationTokenTable<T>.GetOrCreateEventRegistrationTokenTable() // to ensure non-null pFieldType = TypeManager.GetParameterModifier(pFieldType, false); } } ExprField pResult = ExprFactory.CreateField(pFieldType, pOptionalObject, fwt); Debug.Assert(BindingFlag.BIND_MEMBERSET == (BindingFlag)EXPRFLAG.EXF_MEMBERSET); pResult.Flags |= (EXPRFLAG)(bindFlags & BindingFlag.BIND_MEMBERSET); if (fieldType != null) { Name getOrCreateMethodName = NameManager.GetPredefinedName(PredefinedName.PN_GETORCREATEEVENTREGISTRATIONTOKENTABLE); SymbolTable.PopulateSymbolTableWithName( getOrCreateMethodName.Text, null, fieldType.AssociatedSystemType); MethodSymbol getOrCreateMethod = SymbolLoader.LookupAggMember(getOrCreateMethodName, fieldType.OwningAggregate, symbmask_t.MASK_MethodSymbol) as MethodSymbol; MethPropWithInst getOrCreatempwi = new MethPropWithInst(getOrCreateMethod, fieldType); ExprMemberGroup getOrCreateGrp = ExprFactory.CreateMemGroup(null, getOrCreatempwi); Expr getOrCreateCall = BindToMethod( new MethWithInst(getOrCreatempwi), pResult, getOrCreateGrp, (MemLookFlags)MemLookFlags.None); AggregateSymbol fieldTypeSymbol = fieldType.OwningAggregate; Name invocationListName = NameManager.GetPredefinedName(PredefinedName.PN_INVOCATIONLIST); // InvocationList might not be populated in the symbol table as no one would have called it. SymbolTable.PopulateSymbolTableWithName(invocationListName.Text, null, fieldType.AssociatedSystemType); PropertySymbol invocationList = SymbolLoader.LookupAggMember(invocationListName, fieldTypeSymbol, symbmask_t.MASK_PropertySymbol) as PropertySymbol; MethPropWithInst mpwi = new MethPropWithInst(invocationList, fieldType); ExprMemberGroup memGroup = ExprFactory.CreateMemGroup(getOrCreateCall, mpwi); PropWithType pwt = new PropWithType(invocationList, fieldType); Expr propertyExpr = BindToProperty(getOrCreateCall, pwt, bindFlags, null, memGroup); return propertyExpr; } return pResult; } //////////////////////////////////////////////////////////////////////////////// internal ExprProperty BindToProperty(Expr pObject, PropWithType pwt, BindingFlag bindFlags, Expr args, ExprMemberGroup pMemGroup) { Debug.Assert(pwt.Sym is PropertySymbol && pwt.GetType() != null && pwt.Prop().getClass() == pwt.GetType().OwningAggregate); Debug.Assert(pwt.Prop().Params.Count == 0 || pwt.Prop() is IndexerSymbol); // We keep track of the type of the pObject which we're doing the call through so that we can report // protection access errors later, either below when binding the get, or later when checking that // the setter is actually an lvalue. Expr pObjectThrough = pObject; PostBindProperty(pwt, out MethWithType mwtGet, out MethWithType mwtSet); if (mwtGet && (!mwtSet || mwtSet.GetType() == mwtGet.GetType() || SymbolLoader.HasBaseConversion(mwtGet.GetType(), mwtSet.GetType()) ) ) { pObject = AdjustMemberObject(mwtGet, pObject); } else if (mwtSet) { pObject = AdjustMemberObject(mwtSet, pObject); } else { pObject = AdjustMemberObject(pwt, pObject); } pMemGroup.OptionalObject = pObject; CType pReturnType = TypeManager.SubstType(pwt.Prop().RetType, pwt.GetType()); // if we are doing a get on this thing, and there is no get, and // most importantly, we are not leaving the arguments to be bound by the array index // then error... if ((bindFlags & BindingFlag.BIND_RVALUEREQUIRED) != 0) { if (!mwtGet) { throw ErrorHandling.Error(ErrorCode.ERR_PropertyLacksGet, pwt); } CType type = null; if (pObjectThrough != null) { type = pObjectThrough.Type; } ACCESSERROR error = CSemanticChecker.CheckAccess2(mwtGet.Meth(), mwtGet.GetType(), ContextForMemberLookup, type); if (error != ACCESSERROR.ACCESSERROR_NOERROR) { // if the get exists, but is not accessible, give an error. if (error == ACCESSERROR.ACCESSERROR_NOACCESSTHRU) { throw ErrorHandling.Error(ErrorCode.ERR_BadProtectedAccess, pwt, type, ContextForMemberLookup); } throw ErrorHandling.Error(ErrorCode.ERR_InaccessibleGetter, pwt); } } ExprProperty result = ExprFactory.CreateProperty(pReturnType, pObjectThrough, args, pMemGroup, pwt, mwtSet); if (result.OptionalArguments != null) { verifyMethodArgs(result, pObjectThrough?.Type); } AssertObjectIsLvalue(result.MemberGroup.OptionalObject); return result; } internal Expr bindUDUnop(ExpressionKind ek, Expr arg) { Name pName = ExpressionKindName(ek); Debug.Assert(pName != null); CType typeSrc = arg.Type; LAgain: switch (typeSrc.TypeKind) { case TypeKind.TK_NullableType: typeSrc = typeSrc.StripNubs(); goto LAgain; case TypeKind.TK_AggregateType: if (!typeSrc.IsClassType && !typeSrc.IsStructType || ((AggregateType)typeSrc).OwningAggregate.IsSkipUDOps()) return null; break; default: return null; } ArgInfos info = new ArgInfos(); info.carg = 1; FillInArgInfoFromArgList(info, arg); List<CandidateFunctionMember> methFirstList = new List<CandidateFunctionMember>(); MethodSymbol methCur = null; AggregateType atsCur = (AggregateType)typeSrc; for (;;) { // Find the next operator. methCur = (methCur == null ? SymbolLoader.LookupAggMember(pName, atsCur.OwningAggregate, symbmask_t.MASK_MethodSymbol) : methCur.LookupNext(symbmask_t.MASK_MethodSymbol)) as MethodSymbol; if (methCur == null) { // Find the next type. // If we've found some applicable methods in a class then we don't need to look any further. if (!methFirstList.IsEmpty()) { break; } atsCur = atsCur.BaseClass; if (atsCur == null) { break; } continue; } // Only look at operators with 1 args. if (!methCur.isOperator || methCur.Params.Count != 1) { continue; } Debug.Assert(methCur.typeVars.Count == 0); TypeArray paramsCur = TypeManager.SubstTypeArray(methCur.Params, atsCur); CType typeParam = paramsCur[0]; NullableType nubParam; if (canConvert(arg, typeParam)) { methFirstList.Add(new CandidateFunctionMember( new MethPropWithInst(methCur, atsCur, TypeArray.Empty), paramsCur, 0, false)); } else if (typeParam.IsNonNullableValueType && TypeManager.SubstType(methCur.RetType, atsCur).IsNonNullableValueType && canConvert(arg, nubParam = TypeManager.GetNullable(typeParam))) { methFirstList.Add(new CandidateFunctionMember( new MethPropWithInst(methCur, atsCur, TypeArray.Empty), TypeArray.Allocate(nubParam), 1, false)); } } if (methFirstList.IsEmpty()) return null; CandidateFunctionMember pmethAmbig1; CandidateFunctionMember pmethAmbig2; CandidateFunctionMember pmethBest = FindBestMethod(methFirstList, null, info, out pmethAmbig1, out pmethAmbig2); if (pmethBest == null) { // No winner, so its an ambiguous call... throw ErrorHandling.Error(ErrorCode.ERR_AmbigCall, pmethAmbig1.mpwi, pmethAmbig2.mpwi); } ExprCall call; if (pmethBest.ctypeLift != 0) { call = BindLiftedUDUnop(arg, pmethBest.@params[0], pmethBest.mpwi); } else { call = BindUDUnopCall(arg, pmethBest.@params[0], pmethBest.mpwi); } return ExprFactory.CreateUserDefinedUnaryOperator(ek, call.Type, arg, call, pmethBest.mpwi); } private ExprCall BindLiftedUDUnop(Expr arg, CType typeArg, MethPropWithInst mpwi) { CType typeRaw = typeArg.StripNubs(); if (!(arg.Type is NullableType) || !canConvert(arg.Type.StripNubs(), typeRaw, CONVERTTYPE.NOUDC)) { // Convert then lift. arg = mustConvert(arg, typeArg); } Debug.Assert(arg.Type is NullableType); CType typeRet = TypeManager.SubstType(mpwi.Meth().RetType, mpwi.GetType()); if (!(typeRet is NullableType)) { typeRet = TypeManager.GetNullable(typeRet); } // First bind the non-lifted version for errors. Expr nonLiftedArg = mustCast(arg, typeRaw); ExprCall nonLiftedResult = BindUDUnopCall(nonLiftedArg, typeRaw, mpwi); ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mpwi); ExprCall call = ExprFactory.CreateCall(0, typeRet, arg, pMemGroup, null); call.MethWithInst = new MethWithInst(mpwi); call.CastOfNonLiftedResultToLiftedType = mustCast(nonLiftedResult, typeRet, 0); call.NullableCallLiftKind = NullableCallLiftKind.Operator; return call; } private ExprCall BindUDUnopCall(Expr arg, CType typeArg, MethPropWithInst mpwi) { CType typeRet = TypeManager.SubstType(mpwi.Meth().RetType, mpwi.GetType()); CheckUnsafe(typeRet); // added to the binder so we don't bind to pointer ops ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mpwi); ExprCall call = ExprFactory.CreateCall(0, typeRet, mustConvert(arg, typeArg), pMemGroup, null); call.MethWithInst = new MethWithInst(mpwi); verifyMethodArgs(call, mpwi.GetType()); return call; } //////////////////////////////////////////////////////////////////////////////// // Given a method group or indexer group, bind it to the arguments for an // invocation. private GroupToArgsBinderResult BindMethodGroupToArgumentsCore(BindingFlag bindFlags, ExprMemberGroup grp, Expr args, int carg, NamedArgumentsKind namedArgumentsKind) { ArgInfos pargInfo = new ArgInfos {carg = carg}; FillInArgInfoFromArgList(pargInfo, args); ArgInfos pOriginalArgInfo = new ArgInfos {carg = carg}; FillInArgInfoFromArgList(pOriginalArgInfo, args); GroupToArgsBinder binder = new GroupToArgsBinder(this, bindFlags, grp, pargInfo, pOriginalArgInfo, namedArgumentsKind); binder.Bind(); return binder.GetResultsOfBind(); } //////////////////////////////////////////////////////////////////////////////// // Given a method group or indexer group, bind it to the arguments for an // invocation. internal ExprWithArgs BindMethodGroupToArguments(BindingFlag bindFlags, ExprMemberGroup grp, Expr args) { Debug.Assert(grp.SymKind == SYMKIND.SK_MethodSymbol || grp.SymKind == SYMKIND.SK_PropertySymbol && ((grp.Flags & EXPRFLAG.EXF_INDEXER) != 0)); // Count the args. int carg = CountArguments(args); Debug.Assert(grp.Name != null); // Do we have named arguments specified, are they after fixed arguments (can position) or // non-trailing (can rule out methods only). NamedArgumentsKind namedKind = FindNamedArgumentsType(args); MethPropWithInst mpwiBest = BindMethodGroupToArgumentsCore(bindFlags, grp, args, carg, namedKind).BestResult; if (grp.SymKind == SYMKIND.SK_PropertySymbol) { Debug.Assert((grp.Flags & EXPRFLAG.EXF_INDEXER) != 0); return BindToProperty(grp.OptionalObject, new PropWithType(mpwiBest), bindFlags, args, grp); } return BindToMethod(new MethWithInst(mpwiBest), args, grp, (MemLookFlags)grp.Flags); } ///////////////////////////////////////////////////////////////////////////////// public enum NamedArgumentsKind { None, Positioning, NonTrailing } private static NamedArgumentsKind FindNamedArgumentsType(Expr args) { Expr list = args; while (list != null) { Expr arg; if (list is ExprList next) { arg = next.OptionalElement; list = next.OptionalNextListNode; } else { arg = list; list = null; } Debug.Assert(arg != null); if (arg is ExprNamedArgumentSpecification) { while (list != null) { if (list is ExprList nextList) { arg = nextList.OptionalElement; list = nextList.OptionalNextListNode; } else { arg = list; list = null; } if (!(arg is ExprNamedArgumentSpecification)) { return NamedArgumentsKind.NonTrailing; } } return NamedArgumentsKind.Positioning; } } return NamedArgumentsKind.None; } //////////////////////////////////////////////////////////////////////////////// // Report a bad operator types error to the user. private static RuntimeBinderException BadOperatorTypesError(Expr pOperand1, Expr pOperand2) { // This is a hack, but we need to store the operation somewhere... the first argument's as // good a place as any. string strOp = pOperand1.ErrorString; Debug.Assert(pOperand1 != null); Debug.Assert(pOperand1.Type != null); if (pOperand2 != null) { Debug.Assert(pOperand2.Type != null); return ErrorHandling.Error(ErrorCode.ERR_BadBinaryOps, strOp, pOperand1.Type, pOperand2.Type); } return ErrorHandling.Error(ErrorCode.ERR_BadUnaryOp, strOp, pOperand1.Type); } private static ErrorCode GetStandardLvalueError(CheckLvalueKind kind) { Debug.Assert(kind >= CheckLvalueKind.Assignment && kind <= CheckLvalueKind.Increment); return kind == CheckLvalueKind.Increment ? ErrorCode.ERR_IncrementLvalueExpected : ErrorCode.ERR_AssgLvalueExpected; } private void CheckLvalueProp(ExprProperty prop) { Debug.Assert(prop != null); Debug.Assert(prop.isLvalue()); // We have an lvalue property. Give an error if this is an inaccessible property. CType type = null; if (prop.OptionalObjectThrough != null) { type = prop.OptionalObjectThrough.Type; } CheckPropertyAccess(prop.MethWithTypeSet, prop.PropWithTypeSlot, type); } private void CheckPropertyAccess(MethWithType mwt, PropWithType pwtSlot, CType type) { switch (CSemanticChecker.CheckAccess2(mwt.Meth(), mwt.GetType(), ContextForMemberLookup, type)) { case ACCESSERROR.ACCESSERROR_NOACCESSTHRU: throw ErrorHandling.Error(ErrorCode.ERR_BadProtectedAccess, pwtSlot, type, ContextForMemberLookup); case ACCESSERROR.ACCESSERROR_NOACCESS: throw ErrorHandling.Error(mwt.Meth().isSetAccessor() ? ErrorCode.ERR_InaccessibleSetter : ErrorCode.ERR_InaccessibleGetter, pwtSlot); } } //////////////////////////////////////////////////////////////////////////////// // A false return means not to process the expr any further - it's totally out // of place. For example - a method group or an anonymous method. private void CheckLvalue(Expr expr, CheckLvalueKind kind) { if (expr.isLvalue()) { if (expr is ExprProperty prop) { CheckLvalueProp(prop); } return; } Debug.Assert(!(expr is ExprLocal)); Debug.Assert(!(expr is ExprMemberGroup)); switch (expr.Kind) { case ExpressionKind.Property: ExprProperty prop = (ExprProperty)expr; Debug.Assert(!prop.MethWithTypeSet); // Assigning to a property without a setter. // If we have // bool? b = true; (bool)b = false; // then this is realized immediately as // b.Value = false; // and no ExpressionKind.EK_CAST is generated. We'd rather not give a "you're writing // to a read-only property" error in the case where the property access // is not explicit in the source code. Fortunately in this case the // cast is still hanging around in the parse tree, so we can look for it. // POSSIBLE ERROR: It would be nice to also give this error for other situations // POSSIBLE ERROR: in which the user is attempting to assign to a value, such as // POSSIBLE ERROR: an explicit (bool)b.Value = false; // POSSIBLE ERROR: Unfortunately we cannot use this trick in that situation because // POSSIBLE ERROR: we've already discarded the OperatorKind.OP_CAST node. (This is an SyntaxKind.Dot). // SPEC VIOLATION: More generally: // SPEC VIOLATION: The spec states that the result of any cast is a value, not a // SPEC VIOLATION: variable. Unfortunately we do not correctly implement this // SPEC VIOLATION: and we probably should not start implementing it because this // SPEC VIOLATION: would be a breaking change. We currently discard "no op" casts // SPEC VIOLATION: very aggressively rather than generating an ExpressionKind.EK_CAST node. throw ErrorHandling.Error(ErrorCode.ERR_AssgReadonlyProp, prop.PropWithTypeSlot); case ExpressionKind.Field: ExprField field = (ExprField)expr; Debug.Assert(field.FieldWithType.Field().isReadOnly); throw ErrorHandling.Error( field.FieldWithType.Field().isStatic ? ErrorCode.ERR_AssgReadonlyStatic : ErrorCode.ERR_AssgReadonly); default: throw ErrorHandling.Error(GetStandardLvalueError(kind)); } } private static void PostBindMethod(MethWithInst pMWI) { MethodSymbol meth = pMWI.Meth(); if (meth.RetType != null) { CheckUnsafe(meth.RetType); // We need to check unsafe on the parameters as well, since we cannot check in conversion. foreach (CType type in meth.Params.Items) { CheckUnsafe(type); } } } private static void PostBindProperty(PropWithType pwt, out MethWithType pmwtGet, out MethWithType pmwtSet) { PropertySymbol prop = pwt.Prop(); Debug.Assert(prop != null); // Get the accessors. pmwtGet = prop.GetterMethod != null ? new MethWithType(prop.GetterMethod, pwt.GetType()) : new MethWithType(); pmwtSet = prop.SetterMethod != null ? new MethWithType(prop.SetterMethod, pwt.GetType()) : new MethWithType(); if (prop.RetType != null) { CheckUnsafe(prop.RetType); } } private Expr AdjustMemberObject(SymWithType swt, Expr pObject) { // Assert that the type is present and is an instantiation of the member's parent. Debug.Assert(swt.GetType() != null && swt.GetType().OwningAggregate == swt.Sym.parent as AggregateSymbol); bool bIsMatchingStatic = IsMatchingStatic(swt, pObject); bool isStatic = swt.Sym.isStatic; // If our static doesn't match, bail out of here. if (!bIsMatchingStatic) { if (isStatic) { // If we have a mismatched static, a static method, and the binding flag // that tells us we're binding simple names, then insert a type here instead. if ((pObject.Flags & EXPRFLAG.EXF_SIMPLENAME) != 0) { // We've made the static match now. return null; } throw ErrorHandling.Error(ErrorCode.ERR_ObjectProhibited, swt); } throw ErrorHandling.Error(ErrorCode.ERR_ObjectRequired, swt); } // At this point, all errors for static invocations have been reported, and // the object has been nulled out. So return out of here. if (isStatic) { return null; } // If we're in a constructor, then bail. if ((swt.Sym is MethodSymbol) && swt.Meth().IsConstructor()) { return pObject; } if (pObject == null) { return null; } CType typeObj = pObject.Type; CType typeTmp; if (typeObj is NullableType nubTypeObj && (typeTmp = nubTypeObj.GetAts()) != swt.GetType()) { typeObj = typeTmp; } if (typeObj is TypeParameterType || typeObj is AggregateType) { AggregateSymbol aggCalled = swt.Sym.parent as AggregateSymbol; Debug.Assert(swt.GetType().OwningAggregate == aggCalled); pObject = tryConvert(pObject, swt.GetType(), CONVERTTYPE.NOUDC); Debug.Assert(pObject != null); } return pObject; } ///////////////////////////////////////////////////////////////////////////////// private static bool IsMatchingStatic(SymWithType swt, Expr pObject) { Symbol pSym = swt.Sym; // Instance constructors are always ok, static constructors are never ok. if (pSym is MethodSymbol meth && meth.IsConstructor()) { return !meth.isStatic; } bool isStatic = swt.Sym.isStatic; if (isStatic) { // If we're static and we don't have an object then we're ok. if (pObject == null) { return true; } if ((pObject.Flags & EXPRFLAG.EXF_SAMENAMETYPE) == 0) { return false; } } else if (pObject == null) { // We're not static, and we don't have an object. This is ok in certain scenarios: return false; } return true; } //////////////////////////////////////////////////////////////////////////////// // this determines whether the expression as an pObject of a prop or field is an // lvalue [Conditional("DEBUG")] private static void AssertObjectIsLvalue(Expr pObject) { Debug.Assert ( pObject == null || // statics are always lvalues (((pObject.Flags & EXPRFLAG.EXF_LVALUE) != 0) && (pObject.Kind != ExpressionKind.Property)) || // things marked as lvalues have props/fields which are lvalues, with one exception: props of structs // do not have fields/structs as lvalues !pObject.Type.IsStructOrEnum // non-struct types are lvalues (such as non-struct method returns) ); } private void verifyMethodArgs(ExprWithArgs call, CType callingObjectType) { Debug.Assert(call != null); Expr argsPtr = call.OptionalArguments; SymWithType swt = call.GetSymWithType(); MethodOrPropertySymbol mp = swt.Sym as MethodOrPropertySymbol; TypeArray pTypeArgs = (call as ExprCall)?.MethWithInst.TypeArgs; Expr newArgs; AdjustCallArgumentsForParams(callingObjectType, swt.GetType(), mp, pTypeArgs, argsPtr, out newArgs); call.OptionalArguments = newArgs; } private void AdjustCallArgumentsForParams(CType callingObjectType, CType type, MethodOrPropertySymbol mp, TypeArray pTypeArgs, Expr argsPtr, out Expr newArgs) { Debug.Assert(mp != null); Debug.Assert(mp.Params != null); newArgs = null; Expr newArgsTail = null; MethodOrPropertySymbol mostDerivedMethod = GroupToArgsBinder.FindMostDerivedMethod(mp, callingObjectType); int paramCount = mp.Params.Count; TypeArray @params = mp.Params; int iDst = 0; MethodSymbol m = mp as MethodSymbol; int argCount = ExpressionIterator.Count(argsPtr); Debug.Assert(!@params.Items.Any(p => p is ArgumentListType)); // We should never have picked a varargs method to bind to. bool bDontFixParamArray = false; ExpressionIterator it = new ExpressionIterator(argsPtr); if (argsPtr == null) { if (mp.isParamArray) goto FIXUPPARAMLIST; return; } for (; !it.AtEnd(); it.MoveNext()) { Expr indir = it.Current(); // this will splice the optional arguments into the list if (indir.Type is ParameterModifierType) { if (paramCount != 0) paramCount--; ExprFactory.AppendItemToList(indir, ref newArgs, ref newArgsTail); } else if (paramCount != 0) { if (paramCount == 1 && mp.isParamArray && argCount > mp.Params.Count) { // we arrived at the last formal, and we have more than one actual, so // we need to put the rest in an array... goto FIXUPPARAMLIST; } Expr argument = indir; Expr rval; if (argument is ExprNamedArgumentSpecification named) { int index = 0; // If we're named, look for the type of the matching name. foreach (Name i in mostDerivedMethod.ParameterNames) { if (i == named.Name) { break; } index++; } Debug.Assert(index != mp.Params.Count); CType substDestType = TypeManager.SubstType(@params[index], type, pTypeArgs); // If we cant convert the argument and we're the param array argument, then deal with it. if (!canConvert(named.Value, substDestType) && mp.isParamArray && index == mp.Params.Count - 1) { // We have a param array, but we're not at the end yet. This will happen // with named arguments when the user specifies a name for the param array, // and its not an actual array. // // For example: // void Foo(int y, params int[] x); // ... // Foo(x:1, y:1); CType arrayType = (ArrayType)TypeManager.SubstType(mp.Params[mp.Params.Count - 1], type, pTypeArgs); // Use an EK_ARRINIT even in the empty case so empty param arrays in attributes work. ExprArrayInit arrayInit = ExprFactory.CreateArrayInit(arrayType, null, null, new[] { 0 }); arrayInit.GeneratedForParamArray = true; arrayInit.OptionalArguments = named.Value; named.Value = arrayInit; bDontFixParamArray = true; } else { // Otherwise, force the conversion and get errors if needed. named.Value = tryConvert(named.Value, substDestType); } rval = argument; } else { CType substDestType = TypeManager.SubstType(@params[iDst], type, pTypeArgs); rval = tryConvert(indir, substDestType); } if (rval == null) { // the last arg failed to fix up, so it must fixup into the array element // if we have a param array (we will be passing a 1 element array...) if (mp.isParamArray && paramCount == 1 && argCount >= mp.Params.Count) { goto FIXUPPARAMLIST; } else { // This is either the error case that the args are of the wrong type, // or that we have some optional arguments being used. Either way, // we won't need to expand the param array. return; } } Debug.Assert(rval != null); indir = rval; ExprFactory.AppendItemToList(rval, ref newArgs, ref newArgsTail); paramCount--; } // note that destype might not be valid if we are in varargs, but then we won't ever use it... iDst++; if (paramCount != 0 && mp.isParamArray && iDst == argCount) { // we run out of actuals, but we still have formals, so this is an empty array being passed // into the last param... indir = null; it.MoveNext(); goto FIXUPPARAMLIST; } } return; FIXUPPARAMLIST: if (bDontFixParamArray) { // We've already fixed the param array for named arguments. return; } // we need to create an array and put it as the last arg... CType substitutedArrayType = TypeManager.SubstType(mp.Params[mp.Params.Count - 1], type, pTypeArgs); if (!(substitutedArrayType is ArrayType subArr) || !subArr.IsSZArray) { // Invalid type for params array parameter. Happens in LAF scenarios, e.g. // // void Foo(int i, params int ar = null) { } // ... // Foo(1); return; } CType elementType = subArr.ElementType; // Use an EK_ARRINIT even in the empty case so empty param arrays in attributes work. ExprArrayInit exprArrayInit = ExprFactory.CreateArrayInit(substitutedArrayType, null, null, new[] { 0 }); exprArrayInit.GeneratedForParamArray = true; if (it.AtEnd()) { exprArrayInit.DimensionSizes[0] = 0; exprArrayInit.OptionalArguments = null; if (argsPtr == null) { argsPtr = exprArrayInit; } else { argsPtr = ExprFactory.CreateList(argsPtr, exprArrayInit); } ExprFactory.AppendItemToList(exprArrayInit, ref newArgs, ref newArgsTail); } else { // Go through the list - for each argument, do the conversion and append it to the new list. Expr newList = null; Expr newListTail = null; int count = 0; for (; !it.AtEnd(); it.MoveNext()) { Expr expr = it.Current(); count++; if (expr is ExprNamedArgumentSpecification named) { named.Value = tryConvert(named.Value, elementType); } else { expr = tryConvert(expr, elementType); } ExprFactory.AppendItemToList(expr, ref newList, ref newListTail); } exprArrayInit.DimensionSizes[0] = count; exprArrayInit.OptionalArguments = newList; ExprFactory.AppendItemToList(exprArrayInit, ref newArgs, ref newArgsTail); } } private static readonly PredefinedType[] s_rgptIntOp = { PredefinedType.PT_INT, PredefinedType.PT_UINT, PredefinedType.PT_LONG, PredefinedType.PT_ULONG }; internal CType ChooseArrayIndexType(Expr args) { // first, select the allowable types foreach (PredefinedType predef in s_rgptIntOp) { CType type = GetPredefindType(predef); foreach (Expr arg in args.ToEnumerable()) { if (!canConvert(arg, type)) { goto NEXTI; } } return type; NEXTI: ; } // Provide better error message in attempting cast to int. return GetPredefindType(PredefinedType.PT_INT); } internal static void FillInArgInfoFromArgList(ArgInfos argInfo, Expr args) { CType[] prgtype = new CType[argInfo.carg]; argInfo.prgexpr = new List<Expr>(); int iarg = 0; for (Expr list = args; list != null; iarg++) { Expr arg; if (list is ExprList next) { arg = next.OptionalElement; list = next.OptionalNextListNode; } else { arg = list; list = null; } Debug.Assert(arg != null); Debug.Assert(arg.Type != null); prgtype[iarg] = arg.Type; argInfo.prgexpr.Add(arg); } Debug.Assert(iarg <= argInfo.carg); argInfo.types = TypeArray.Allocate(prgtype); } private static bool TryGetExpandedParams(TypeArray @params, int count, out TypeArray ppExpandedParams) { CType[] prgtype; if (count < @params.Count - 1) { // The user has specified less arguments than our parameters, but we still // need to return our set of types without the param array. This is in the // case that all the parameters are optional. prgtype = new CType[@params.Count - 1]; @params.CopyItems(0, @params.Count - 1, prgtype); ppExpandedParams = TypeArray.Allocate(prgtype); return true; } prgtype = new CType[count]; @params.CopyItems(0, @params.Count - 1, prgtype); CType type = @params[@params.Count - 1]; if (!(type is ArrayType arr)) { ppExpandedParams = null; // If we don't have an array sym, we don't have expanded parameters. return false; } // At this point, we have an array sym. CType elementType = arr.ElementType; for (int itype = @params.Count - 1; itype < count; itype++) { prgtype[itype] = elementType; } ppExpandedParams = TypeArray.Allocate(prgtype); return true; } // Is the method/property callable. Not if it's an override or not user-callable. public static bool IsMethPropCallable(MethodOrPropertySymbol sym, bool requireUC) { // The hide-by-pName option for binding other languages takes precedence over general // rules of not binding to overrides. return (!sym.isOverride || sym.isHideByName) && (!requireUC || sym.isUserCallable()); } private static bool IsConvInTable(List<UdConvInfo> convTable, MethodSymbol meth, AggregateType ats, bool fSrc, bool fDst) { foreach (UdConvInfo conv in convTable) { if (conv.Meth.Meth() == meth && conv.Meth.GetType() == ats && conv.SrcImplicit == fSrc && conv.DstImplicit == fDst) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // Check to see if an integral constant is within range of a integral // destination type. private static bool isConstantInRange(ExprConstant exprSrc, CType typeDest) { return isConstantInRange(exprSrc, typeDest, false); } private static bool isConstantInRange(ExprConstant exprSrc, CType typeDest, bool realsOk) { FUNDTYPE ftSrc = exprSrc.Type.FundamentalType; FUNDTYPE ftDest = typeDest.FundamentalType; if (ftSrc > FUNDTYPE.FT_LASTINTEGRAL || ftDest > FUNDTYPE.FT_LASTINTEGRAL) { if (!realsOk) { return false; } else if (ftSrc > FUNDTYPE.FT_LASTNUMERIC || ftDest > FUNDTYPE.FT_LASTNUMERIC) { return false; } } // if converting to a float type, this always succeeds... if (ftDest > FUNDTYPE.FT_LASTINTEGRAL) { return true; } // if converting from float to an integral type, we need to check whether it fits if (ftSrc > FUNDTYPE.FT_LASTINTEGRAL) { double dvalue = exprSrc.Val.DoubleVal; switch (ftDest) { case FUNDTYPE.FT_I1: if (dvalue > -0x81 && dvalue < 0x80) return true; break; case FUNDTYPE.FT_I2: if (dvalue > -0x8001 && dvalue < 0x8000) return true; break; case FUNDTYPE.FT_I4: if (dvalue > I64(-0x80000001) && dvalue < I64(0x80000000)) return true; break; case FUNDTYPE.FT_I8: // 0x7FFFFFFFFFFFFFFFFFFF is rounded to 0x800000000000000000000 in 64 bit double precision // floating point representation. The conversion back to ulong is not possible. if (dvalue >= -9223372036854775808.0 && dvalue < 9223372036854775808.0) { return true; } break; case FUNDTYPE.FT_U1: if (dvalue > -1 && dvalue < 0x100) return true; break; case FUNDTYPE.FT_U2: if (dvalue > -1 && dvalue < 0x10000) return true; break; case FUNDTYPE.FT_U4: if (dvalue > -1 && dvalue < I64(0x100000000)) return true; break; case FUNDTYPE.FT_U8: // 0xFFFFFFFFFFFFFFFFFFFF is rounded to 0x100000000000000000000 in 64 bit double precision // floating point representation. The conversion back to ulong is not possible. if (dvalue > -1.0 && dvalue < 18446744073709551616.0) { return true; } break; default: break; } return false; } // U8 src is unsigned, so deal with values > MAX_LONG here. if (ftSrc == FUNDTYPE.FT_U8) { ulong value = exprSrc.UInt64Value; switch (ftDest) { case FUNDTYPE.FT_I1: if (value <= (ulong)sbyte.MaxValue) return true; break; case FUNDTYPE.FT_I2: if (value <= (ulong)short.MaxValue) return true; break; case FUNDTYPE.FT_I4: if (value <= int.MaxValue) return true; break; case FUNDTYPE.FT_I8: if (value <= long.MaxValue) return true; break; case FUNDTYPE.FT_U1: if (value <= byte.MaxValue) return true; break; case FUNDTYPE.FT_U2: if (value <= ushort.MaxValue) return true; break; case FUNDTYPE.FT_U4: if (value <= uint.MaxValue) return true; break; case FUNDTYPE.FT_U8: return true; default: break; } } else { long value = exprSrc.Int64Value; switch (ftDest) { case FUNDTYPE.FT_I1: if (value >= -128 && value <= 127) return true; break; case FUNDTYPE.FT_I2: if (value >= -0x8000 && value <= 0x7fff) return true; break; case FUNDTYPE.FT_I4: if (value >= I64(-0x80000000) && value <= I64(0x7fffffff)) return true; break; case FUNDTYPE.FT_I8: return true; case FUNDTYPE.FT_U1: if (value >= 0 && value <= 0xff) return true; break; case FUNDTYPE.FT_U2: if (value >= 0 && value <= 0xffff) return true; break; case FUNDTYPE.FT_U4: if (value >= 0 && value <= I64(0xffffffff)) return true; break; case FUNDTYPE.FT_U8: if (value >= 0) return true; break; default: break; } } return false; } private static readonly PredefinedName[] s_EK2NAME = { PredefinedName.PN_OPEQUALS, PredefinedName.PN_OPCOMPARE, PredefinedName.PN_OPTRUE, PredefinedName.PN_OPFALSE, PredefinedName.PN_OPINCREMENT, PredefinedName.PN_OPDECREMENT, PredefinedName.PN_OPNEGATION, PredefinedName.PN_OPEQUALITY, PredefinedName.PN_OPINEQUALITY, PredefinedName.PN_OPLESSTHAN, PredefinedName.PN_OPLESSTHANOREQUAL, PredefinedName.PN_OPGREATERTHAN, PredefinedName.PN_OPGREATERTHANOREQUAL, PredefinedName.PN_OPPLUS, PredefinedName.PN_OPMINUS, PredefinedName.PN_OPMULTIPLY, PredefinedName.PN_OPDIVISION, PredefinedName.PN_OPMODULUS, PredefinedName.PN_OPUNARYMINUS, PredefinedName.PN_OPUNARYPLUS, PredefinedName.PN_OPBITWISEAND, PredefinedName.PN_OPBITWISEOR, PredefinedName.PN_OPXOR, PredefinedName.PN_OPCOMPLEMENT, PredefinedName.PN_OPLEFTSHIFT, PredefinedName.PN_OPRIGHTSHIFT, }; private static Name ExpressionKindName(ExpressionKind ek) { Debug.Assert(ek >= ExpressionKind.FirstOp && (ek - ExpressionKind.FirstOp) < (int)s_EK2NAME.Length); return NameManager.GetPredefinedName(s_EK2NAME[ek - ExpressionKind.FirstOp]); } private static void CheckUnsafe(CType type) { if (type == null || type.IsUnsafe()) { throw ErrorHandling.Error(ErrorCode.ERR_UnsafeNeeded); } } private AggregateSymbol ContextForMemberLookup => Context.ContextForMemberLookup; private static ExprWrap WrapShortLivedExpression(Expr expr) => ExprFactory.CreateWrap(expr); private static ExprAssignment GenerateOptimizedAssignment(Expr op1, Expr op2) => ExprFactory.CreateAssignment(op1, op2); internal static int CountArguments(Expr args) { int carg = 0; for (Expr list = args; list != null; carg++) { Expr arg; if (list is ExprList next) { arg = next.OptionalElement; list = next.OptionalNextListNode; } else { arg = list; list = null; } Debug.Assert(arg != null); } return carg; } } }
{ "content_hash": "cb474eb4a0d8b38ac429507a6d9bd63a", "timestamp": "", "source": "github", "line_count": 1664, "max_line_length": 174, "avg_line_length": 40.875, "alnum_prop": 0.5160403434486003, "repo_name": "mmitche/corefx", "id": "4565b8f15aba587c743cd21ad6de35d959eca467", "size": "68220", "binary": false, "copies": "48", "ref": "refs/heads/master", "path": "src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExpressionBinder.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "280724" }, { "name": "ASP", "bytes": "1687" }, { "name": "Batchfile", "bytes": "20096" }, { "name": "C", "bytes": "3730054" }, { "name": "C#", "bytes": "166928159" }, { "name": "C++", "bytes": "117360" }, { "name": "CMake", "bytes": "77718" }, { "name": "DIGITAL Command Language", "bytes": "26402" }, { "name": "Groovy", "bytes": "50984" }, { "name": "HTML", "bytes": "653" }, { "name": "Makefile", "bytes": "13780" }, { "name": "OpenEdge ABL", "bytes": "137969" }, { "name": "Perl", "bytes": "3895" }, { "name": "PowerShell", "bytes": "95072" }, { "name": "Python", "bytes": "1535" }, { "name": "Roff", "bytes": "9387" }, { "name": "Shell", "bytes": "119395" }, { "name": "Visual Basic", "bytes": "1001421" }, { "name": "XSLT", "bytes": "513537" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.apache.camel</groupId> <artifactId>components</artifactId> <version>2.21.0-SNAPSHOT</version> </parent> <artifactId>camel-twitter</artifactId> <packaging>jar</packaging> <name>Camel :: Twitter</name> <description>Camel Twitter support</description> <properties> <camel.osgi.export.pkg>org.apache.camel.component.twitter.*</camel.osgi.export.pkg> <camel.osgi.export.service>org.apache.camel.spi.ComponentResolver;component=twitter</camel.osgi.export.service> </properties> <dependencies> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-core</artifactId> </dependency> <dependency> <groupId>org.twitter4j</groupId> <artifactId>twitter4j-core</artifactId> <version>${twitter4j-version}</version> </dependency> <dependency> <groupId>org.twitter4j</groupId> <artifactId>twitter4j-stream</artifactId> <version>${twitter4j-version}</version> </dependency> <!-- test dependencies --> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-surefire-plugin</artifactId> <configuration> <includes> <!-- Here we only run test of --> <include>**/*UriConfigurationTest.java</include> </includes> </configuration> </plugin> </plugins> </build> <profiles> <profile> <id>twitter-test</id> <build> <plugins> <plugin> <artifactId>maven-surefire-plugin</artifactId> <configuration> <childDelegation>false</childDelegation> <useFile>true</useFile> <forkCount>1</forkCount> <reuseForks>true</reuseForks> <forkedProcessTimeoutInSeconds>300</forkedProcessTimeoutInSeconds> <includes> <include>**/*Test.java</include> </includes> </configuration> </plugin> </plugins> </build> </profile> </profiles> </project>
{ "content_hash": "887b8a0baa7031830455fe0ce2f0d072", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 201, "avg_line_length": 31.975409836065573, "alnum_prop": 0.6465008972058447, "repo_name": "rmarting/camel", "id": "54d132ba5e4048059ca3e3c479ebcf06f9f5c3fe", "size": "3901", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "components/camel-twitter/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6519" }, { "name": "Batchfile", "bytes": "1518" }, { "name": "CSS", "bytes": "30373" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "11410" }, { "name": "Groovy", "bytes": "53380" }, { "name": "HTML", "bytes": "183702" }, { "name": "Java", "bytes": "63735850" }, { "name": "JavaScript", "bytes": "90230" }, { "name": "Makefile", "bytes": "513" }, { "name": "Python", "bytes": "36" }, { "name": "Ruby", "bytes": "4802" }, { "name": "Scala", "bytes": "323662" }, { "name": "Shell", "bytes": "17092" }, { "name": "Tcl", "bytes": "4974" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "284638" } ], "symlink_target": "" }
/*************************************************************************/ /* register_types.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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. */ /*************************************************************************/ #include "register_types.h" #include "image_loader_tinyexr.h" #include "image_saver_tinyexr.h" static ImageLoaderTinyEXR *image_loader_tinyexr = nullptr; void register_tinyexr_types() { image_loader_tinyexr = memnew(ImageLoaderTinyEXR); ImageLoader::add_image_format_loader(image_loader_tinyexr); Image::save_exr_func = save_exr; } void unregister_tinyexr_types() { memdelete(image_loader_tinyexr); Image::save_exr_func = nullptr; }
{ "content_hash": "3d28d18eb48b75df1fb164b7ff23ff69", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 75, "avg_line_length": 54.06122448979592, "alnum_prop": 0.4971687429218573, "repo_name": "Faless/godot", "id": "0879a55b6e9b021b36fb7841c584056dcf4a5875", "size": "2649", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "modules/tinyexr/register_types.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "AIDL", "bytes": "1633" }, { "name": "C", "bytes": "820090" }, { "name": "C#", "bytes": "954253" }, { "name": "C++", "bytes": "36679303" }, { "name": "CMake", "bytes": "538" }, { "name": "GAP", "bytes": "62" }, { "name": "GDScript", "bytes": "59146" }, { "name": "GLSL", "bytes": "802565" }, { "name": "Java", "bytes": "512268" }, { "name": "JavaScript", "bytes": "184665" }, { "name": "Kotlin", "bytes": "16172" }, { "name": "Makefile", "bytes": "1421" }, { "name": "Objective-C", "bytes": "20550" }, { "name": "Objective-C++", "bytes": "315906" }, { "name": "PowerShell", "bytes": "2713" }, { "name": "Python", "bytes": "427946" }, { "name": "Shell", "bytes": "27482" } ], "symlink_target": "" }
import pandas as pd import pytz from itertools import cycle import numpy as np from six import integer_types from unittest import TestCase import zipline.utils.factory as factory from zipline.sources import (DataFrameSource, DataPanelSource, RandomWalkSource) from zipline.utils import tradingcalendar as calendar_nyse from zipline.finance.trading import with_environment class TestDataFrameSource(TestCase): def test_df_source(self): source, df = factory.create_test_df_source() assert isinstance(source.start, pd.lib.Timestamp) assert isinstance(source.end, pd.lib.Timestamp) for expected_dt, expected_price in df.iterrows(): sid0 = next(source) assert expected_dt == sid0.dt assert expected_price[0] == sid0.price def test_df_sid_filtering(self): _, df = factory.create_test_df_source() source = DataFrameSource(df, sids=[0]) assert 1 not in [event.sid for event in source], \ "DataFrameSource should only stream selected sid 0, not sid 1." def test_panel_source(self): source, panel = factory.create_test_panel_source(source_type=5) assert isinstance(source.start, pd.lib.Timestamp) assert isinstance(source.end, pd.lib.Timestamp) for event in source: self.assertTrue('sid' in event) self.assertTrue('arbitrary' in event) self.assertTrue('type' in event) self.assertTrue(hasattr(event, 'volume')) self.assertTrue(hasattr(event, 'price')) self.assertEquals(event['type'], 5) self.assertEquals(event['arbitrary'], 1.) self.assertEquals(event['sid'], 0) self.assertTrue(isinstance(event['volume'], int)) self.assertTrue(isinstance(event['arbitrary'], float)) @with_environment() def test_yahoo_bars_to_panel_source(self, env=None): stocks = ['AAPL', 'GE'] start = pd.datetime(1993, 1, 1, 0, 0, 0, 0, pytz.utc) end = pd.datetime(2002, 1, 1, 0, 0, 0, 0, pytz.utc) data = factory.load_bars_from_yahoo(stocks=stocks, indexes={}, start=start, end=end) check_fields = ['sid', 'open', 'high', 'low', 'close', 'volume', 'price'] source = DataPanelSource(data) sids = [ asset.sid for asset in [env.asset_finder.lookup_symbol(symbol, as_of_date=end) for symbol in stocks] ] stocks_iter = cycle(sids) for event in source: for check_field in check_fields: self.assertIn(check_field, event) self.assertTrue(isinstance(event['volume'], (integer_types))) self.assertEqual(next(stocks_iter), event['sid']) @with_environment() def test_nan_filter_dataframe(self, env=None): env.update_asset_finder(identifiers=[4, 5]) dates = pd.date_range('1/1/2000', periods=2, freq='B', tz='UTC') df = pd.DataFrame(np.random.randn(2, 2), index=dates, columns=[4, 5]) # should be filtered df.loc[dates[0], 4] = np.nan # should not be filtered, should have been ffilled df.loc[dates[1], 5] = np.nan source = DataFrameSource(df) event = next(source) self.assertEqual(5, event.sid) event = next(source) self.assertEqual(4, event.sid) event = next(source) self.assertEqual(5, event.sid) self.assertFalse(np.isnan(event.price)) @with_environment() def test_nan_filter_panel(self, env=None): env.update_asset_finder(identifiers=[4, 5]) dates = pd.date_range('1/1/2000', periods=2, freq='B', tz='UTC') df = pd.Panel(np.random.randn(2, 2, 2), major_axis=dates, items=[4, 5], minor_axis=['price', 'volume']) # should be filtered df.loc[4, dates[0], 'price'] = np.nan # should not be filtered, should have been ffilled df.loc[5, dates[1], 'price'] = np.nan source = DataPanelSource(df) event = next(source) self.assertEqual(5, event.sid) event = next(source) self.assertEqual(4, event.sid) event = next(source) self.assertEqual(5, event.sid) self.assertFalse(np.isnan(event.price)) class TestRandomWalkSource(TestCase): def test_minute(self): np.random.seed(123) start_prices = {0: 100, 1: 500} start = pd.Timestamp('1990-01-01', tz='UTC') end = pd.Timestamp('1991-01-01', tz='UTC') source = RandomWalkSource(start_prices=start_prices, calendar=calendar_nyse, start=start, end=end) self.assertIsInstance(source.start, pd.lib.Timestamp) self.assertIsInstance(source.end, pd.lib.Timestamp) for event in source: self.assertIn(event.sid, start_prices.keys()) self.assertIn(event.dt.replace(minute=0, hour=0), calendar_nyse.trading_days) self.assertGreater(event.dt, start) self.assertLess(event.dt, end) self.assertGreater(event.price, 0, "price should never go negative.") self.assertTrue(13 <= event.dt.hour <= 21, "event.dt.hour == %i, not during market \ hours." % event.dt.hour) def test_day(self): np.random.seed(123) start_prices = {0: 100, 1: 500} start = pd.Timestamp('1990-01-01', tz='UTC') end = pd.Timestamp('1992-01-01', tz='UTC') source = RandomWalkSource(start_prices=start_prices, calendar=calendar_nyse, start=start, end=end, freq='daily') self.assertIsInstance(source.start, pd.lib.Timestamp) self.assertIsInstance(source.end, pd.lib.Timestamp) for event in source: self.assertIn(event.sid, start_prices.keys()) self.assertIn(event.dt.replace(minute=0, hour=0), calendar_nyse.trading_days) self.assertGreater(event.dt, start) self.assertLess(event.dt, end) self.assertGreater(event.price, 0, "price should never go negative.") self.assertEqual(event.dt.hour, 0)
{ "content_hash": "0445364ea2c108bafbf92cec340446bb", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 75, "avg_line_length": 40.97560975609756, "alnum_prop": 0.5583333333333333, "repo_name": "mmilutinovic1313/zipline-with-algorithms", "id": "3664acdd656bd1672aab548357645409ccf4bf4b", "size": "7302", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_sources.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "564" }, { "name": "Emacs Lisp", "bytes": "138" }, { "name": "Python", "bytes": "1047562" }, { "name": "Shell", "bytes": "3962" } ], "symlink_target": "" }
<!--- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!--- +======================================================================+ |**** ****| |**** THIS FILE IS GENERATED BY THE COMMONS BUILD PLUGIN ****| |**** DO NOT EDIT DIRECTLY ****| |**** ****| +======================================================================+ | TEMPLATE FILE: contributing-md-template.md | | commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates | +======================================================================+ | | | 1) Re-generate using: mvn commons:contributing-md | | | | 2) Set the following properties in the component's pom: | | - commons.jira.id (required, alphabetic, upper case) | | | | 3) Example Properties | | | | <properties> | | <commons.jira.id>MATH</commons.jira.id> | | </properties> | | | +======================================================================+ ---> Contributing to Apache Commons IO ====================== You have found a bug or you have an idea for a cool new feature? Contributing code is a great way to give something back to the open source community. Before you dig right into the code there are a few guidelines that we need contributors to follow so that we can have a chance of keeping on top of things. Getting Started --------------- + Make sure you have a [JIRA account](https://issues.apache.org/jira/). + Make sure you have a [GitHub account](https://github.com/signup/free). + If you're planning to implement a new feature it makes sense to discuss you're changes on the [dev list](https://commons.apache.org/mail-lists.html) first. This way you can make sure you're not wasting your time on something that isn't considered to be in Apache Commons IO's scope. + Submit a ticket for your issue, assuming one does not already exist. + Clearly describe the issue including steps to reproduce when it is a bug. + Make sure you fill in the earliest version that you know has the issue. + Fork the repository on GitHub. Making Changes -------------- + Create a topic branch from where you want to base your work (this is usually the master/trunk branch). + Make commits of logical units. + Respect the original code style: + Only use spaces for indentation. + Create minimal diffs - disable on save actions like reformat source code or organize imports. If you feel the source code should be reformatted create a separate PR for this change. + Check for unnecessary whitespace with git diff --check before committing. + Make sure your commit messages are in the proper format. Your commit message should contain the key of the JIRA issue. + Make sure you have added the necessary tests for your changes. + Run all the tests with `mvn clean verify` to assure nothing else was accidentally broken. Making Trivial Changes ---------------------- For changes of a trivial nature to comments and documentation, it is not always necessary to create a new ticket in JIRA. In this case, it is appropriate to start the first line of a commit with '(doc)' instead of a ticket number. Submitting Changes ------------------ + Sign the [Contributor License Agreement][cla] if you haven't already. + Push your changes to a topic branch in your fork of the repository. + Submit a pull request to the repository in the apache organization. + Update your JIRA ticket and include a link to the pull request in the ticket. Additional Resources -------------------- + [Contributing patches](https://commons.apache.org/patches.html) + [Apache Commons IO JIRA project page](https://issues.apache.org/jira/browse/IO) + [Contributor License Agreement][cla] + [General GitHub documentation](https://help.github.com/) + [GitHub pull request documentation](https://help.github.com/send-pull-requests/) + [Apache Commons Twitter Account](https://twitter.com/ApacheCommons) + #apachecommons IRC channel on freenode.org [cla]:https://www.apache.org/licenses/#clas
{ "content_hash": "2bffd9f01928bd6150137a23ca5386d2", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 284, "avg_line_length": 56, "alnum_prop": 0.5889175257731959, "repo_name": "krosenvold/commons-io", "id": "11e9dd75c65475b8092a5e3bb3d533306ee27fd3", "size": "5432", "binary": false, "copies": "8", "ref": "refs/heads/trunk", "path": "CONTRIBUTING.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "23795" }, { "name": "Java", "bytes": "2082360" }, { "name": "Shell", "bytes": "157" } ], "symlink_target": "" }
FILE(REMOVE_RECURSE "CMakeFiles/gtest_catch_exceptions_no_ex_test_.dir/test/gtest_catch_exceptions_test_.cc.o" "gtest_catch_exceptions_no_ex_test_.pdb" "gtest_catch_exceptions_no_ex_test_" ) # Per-language clean rules from dependency scanning. FOREACH(lang CXX) INCLUDE(CMakeFiles/gtest_catch_exceptions_no_ex_test_.dir/cmake_clean_${lang}.cmake OPTIONAL) ENDFOREACH(lang)
{ "content_hash": "0dea5cc6a0764ff07ddd43a4bf3fb8a7", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 95, "avg_line_length": 38.2, "alnum_prop": 0.7696335078534031, "repo_name": "ivansoban/ILEngine", "id": "d3ac280608edc89834b87719d8b6fc069709cb4b", "size": "382", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "thirdparty/gtest-1.7.0/build/CMakeFiles/gtest_catch_exceptions_no_ex_test_.dir/cmake_clean.cmake", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "516" }, { "name": "C++", "bytes": "37989" } ], "symlink_target": "" }
"""bigtable instances update command.""" from googlecloudsdk.api_lib.bigtable import util from googlecloudsdk.calliope import base from googlecloudsdk.command_lib.bigtable import arguments from googlecloudsdk.core import log from googlecloudsdk.core import resources class UpdateInstance(base.UpdateCommand): """Modify an existing Bigtable instance.""" @staticmethod def Args(parser): """Register flags for this command.""" arguments.ArgAdder(parser).AddInstance().AddInstanceDescription() def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: Some value that we want to have printed later. """ cli = util.GetAdminClient() ref = resources.REGISTRY.Parse( args.instance, collection='bigtableadmin.projects.instances') msg = util.GetAdminMessages().BigtableadminProjectsInstancesGetRequest( name=ref.RelativeName()) instance = cli.projects_instances.Get(msg) instance.state = None # must be unset when calling Update if args.description: instance.displayName = args.description instance = cli.projects_instances.Update(instance) log.UpdatedResource(instance.name, kind='instance') return instance
{ "content_hash": "ce9653c98abb970e8813b7c062267222", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 79, "avg_line_length": 34.61538461538461, "alnum_prop": 0.7377777777777778, "repo_name": "Sorsly/subtle", "id": "2b28fb6b90c0c4e4433b4d912ea87009364cdd5e", "size": "1945", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "google-cloud-sdk/lib/surface/bigtable/instances/update.py", "mode": "33261", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1581" }, { "name": "CSS", "bytes": "226" }, { "name": "HTML", "bytes": "4637" }, { "name": "JavaScript", "bytes": "3037" }, { "name": "PHP", "bytes": "4543" }, { "name": "Pascal", "bytes": "31" }, { "name": "Python", "bytes": "13243860" }, { "name": "Roff", "bytes": "1050600" }, { "name": "Shell", "bytes": "16136" }, { "name": "Smarty", "bytes": "2484" }, { "name": "SourcePawn", "bytes": "308" } ], "symlink_target": "" }
# Run Coverage report require 'simplecov' SimpleCov.start do add_group 'Controllers', 'app/controllers' add_group 'Helpers', 'app/helpers' add_group 'Mailers', 'app/mailers' add_group 'Models', 'app/models' add_group 'Views', 'app/views' add_group 'Libraries', 'lib' end # Configure Rails Environment ENV['RAILS_ENV'] = 'test' require File.expand_path('../dummy/config/environment.rb', __FILE__) require 'rspec/rails' require 'database_cleaner' require 'ffaker' # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[File.join(File.dirname(__FILE__), 'support/**/*.rb')].each { |f| require f } # Requires factories defined in spree_core require 'spree/testing_support/factories' require 'spree/testing_support/controller_requests' require 'spree/testing_support/authorization_helpers' require 'spree/testing_support/url_helpers' # Requires factories defined in lib/spree_multi_domain_themes/factories.rb require 'spree_multi_domain_themes/factories' RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods # == URL Helpers # # Allows access to Spree's routes in specs: # # visit spree.admin_path # current_path.should eql(spree.products_path) config.include Spree::TestingSupport::UrlHelpers # == Mock Framework # # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr config.mock_with :rspec config.color = true # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # Capybara javascript drivers require transactional fixtures set to false, and we use DatabaseCleaner # to cleanup after each test instead. Without transactional fixtures set to false the records created # to setup a test will be unavailable to the browser, which runs under a seperate server instance. config.use_transactional_fixtures = false # Ensure Suite is set to use transactions for speed. config.before :suite do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with :truncation end # Before each spec check if it is a Javascript test and switch between using database transactions or not where necessary. config.before :each do DatabaseCleaner.strategy = example.metadata[:js] ? :truncation : :transaction DatabaseCleaner.start end # After each spec clean the database. config.after :each do DatabaseCleaner.clean end config.fail_fast = ENV['FAIL_FAST'] || false end
{ "content_hash": "03f0a63f8be121e48289379909669a85", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 124, "avg_line_length": 32.48148148148148, "alnum_prop": 0.7438236412010643, "repo_name": "cgservices/spree_multi_domain_themes", "id": "48748a3c7430e3f7aef5320a54cda25d96dcb7db", "size": "2631", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/spec_helper.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Ruby", "bytes": "12176" } ], "symlink_target": "" }
package org.ode4j.tests.joints; import static org.ode4j.cpp.internal.ApiCppBody.dBodyAddForce; import static org.ode4j.cpp.internal.ApiCppJoint.dJointGetSliderPosition; import static org.ode4j.cpp.internal.ApiCppJoint.dJointGetSliderPositionRate; import static org.ode4j.cpp.internal.ApiCppWorld.dWorldQuickStep; import static org.ode4j.tests.UnitTestPlusPlus.CheckMacros.CHECK_CLOSE; import org.junit.Test; //This file create unit test for some of the functions found in: //ode/src/joinst/slider.cpp public class Fixture_dxJointSlider_B1_and_B2_At_Zero_Axis_Along_X3 extends Fixture_dxJointSlider_B1_and_B2_At_Zero_Axis_Along_X { // Apply force on 1st body in the X direction also the Axis direction // // X-------> X---------> Axis --> // B1 => B1 // B2 F-> B2 //TEST_FIXTURE (Fixture_dxJointSlider_B1_and_B2_At_Zero_Axis_Along_X, @Test public void test_dJointSetSliderPositionRate_Force_Along_Axis_on_B2() { CHECK_CLOSE (0.0, dJointGetSliderPosition(jId), 1e-4); CHECK_CLOSE (0.0, dJointGetSliderPositionRate(jId), 1e-4); dBodyAddForce(bId2, 1.0, 0, 0); dWorldQuickStep (wId, 1.0); CHECK_CLOSE (-1, dJointGetSliderPositionRate(jId), 1e-4); } // Apply force on 1st body in the inverse X direction // // X-------> X---------> Axis --> // B1 => B1 // B2 <-F B2 //TEST_FIXTURE (Fixture_dxJointSlider_B1_and_B2_At_Zero_Axis_Along_X, @Test public void test_dJointSetSliderPositionRate_Force_Inverse_of_Axis_on_B2() { CHECK_CLOSE (0.0, dJointGetSliderPosition(jId), 1e-4); CHECK_CLOSE (0.0, dJointGetSliderPositionRate(jId), 1e-4); dBodyAddForce(bId2, -1.0, 0, 0); dWorldQuickStep (wId, 1.0); CHECK_CLOSE (1, dJointGetSliderPositionRate(jId), 1e-4); } }
{ "content_hash": "120ad1b3ee3ee0b3afb8d137633b5609", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 82, "avg_line_length": 37.42857142857143, "alnum_prop": 0.6717557251908397, "repo_name": "billhj/Etoile-java", "id": "4a038bccce93ff1ef626c4d2ad9a8ae838ca2f2e", "size": "3635", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OdeDemos/src/org/ode4j/tests/joints/Fixture_dxJointSlider_B1_and_B2_At_Zero_Axis_Along_X3.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "6078891" } ], "symlink_target": "" }
@interface UIView (SubviewHunting) - (UIView *)huntedSubviewWithClassName:(NSString*)className; - (void)debugSubviews; @end
{ "content_hash": "b07b8ba16d88342610486cd19f61ca93", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 60, "avg_line_length": 21, "alnum_prop": 0.7777777777777778, "repo_name": "ntaku/ASExtensions", "id": "7524e52b5498492c98fce1368aaec0680e268856", "size": "152", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ASExtensions/ASUIview+SubviewHunting.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "18996" }, { "name": "Ruby", "bytes": "601" } ], "symlink_target": "" }
using namespace llvm; MCContext::MCContext() { } MCContext::~MCContext() { // NOTE: The sections are all allocated out of a bump pointer allocator, // we don't need to free them here. } MCSymbol *MCContext::CreateSymbol(StringRef Name) { assert(Name[0] != '\0' && "Normal symbols cannot be unnamed!"); // Create and bind the symbol, and ensure that names are unique. MCSymbol *&Entry = Symbols[Name]; assert(!Entry && "Duplicate symbol definition!"); return Entry = new (*this) MCSymbol(Name, false); } MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) { MCSymbol *&Entry = Symbols[Name]; if (Entry) return Entry; return Entry = new (*this) MCSymbol(Name, false); } MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) { SmallString<128> NameSV; Name.toVector(NameSV); return GetOrCreateSymbol(NameSV.str()); } MCSymbol *MCContext::CreateTemporarySymbol(StringRef Name) { // If unnamed, just create a symbol. if (Name.empty()) new (*this) MCSymbol("", true); // Otherwise create as usual. MCSymbol *&Entry = Symbols[Name]; assert(!Entry && "Duplicate symbol definition!"); return Entry = new (*this) MCSymbol(Name, true); } MCSymbol *MCContext::LookupSymbol(StringRef Name) const { return Symbols.lookup(Name); }
{ "content_hash": "d4d59676c56c25b007bebc3fd37bcc6f", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 74, "avg_line_length": 27.27659574468085, "alnum_prop": 0.6981279251170047, "repo_name": "wrmsr/lljvm", "id": "45d2c025361dfdf1b0f16029a9cfd1cabdf61e45", "size": "1807", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "thirdparty/llvm/lib/MC/MCContext.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "4870" }, { "name": "C++", "bytes": "91265" }, { "name": "Java", "bytes": "149125" }, { "name": "Lua", "bytes": "177" }, { "name": "Makefile", "bytes": "21245" }, { "name": "Python", "bytes": "8641" }, { "name": "Shell", "bytes": "218" } ], "symlink_target": "" }
<?php namespace Hal\Application\Command; use Hal\Application\Command\Job\QueueFactory; use Hal\Application\Config\ConfigFactory; use Hal\Component\Bounds\Bounds; use Hal\Component\Evaluation\Evaluator; use Hal\Component\File\Finder; use Hal\Component\OOP\Reflected\ReflectedMethod; use Hal\Pattern\Resolver\PatternResolver; use Hal\Pattern\Resolver\ResolvedClass; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Hal\Application\Command\Job\Analyze\CardAndAgrestiAnalyzer; use Hal\Application\Command\Job\Analyze\CouplingAnalyzer; use Hal\Application\Command\Job\Analyze\FileAnalyzer; use Hal\Application\Command\Job\Analyze\LcomAnalyzer; use Hal\Component\Cache\CacheMemory; use Hal\Component\File\SyntaxChecker; use Hal\Component\OOP\Extractor\ClassMap; use Hal\Component\OOP\Extractor\Extractor; use Hal\Component\Result\ResultCollection; use Hal\Component\Token\NoTokenizableException; use Hal\Component\Token\Tokenizer; use Symfony\Component\Console\Helper\ProgressBar; /** * Command for run analysis * * @author Jean-François Lépine <https://twitter.com/Halleck45> */ class RunPatternCommand extends Command { /** * @inheritdoc */ protected function configure() { $this ->setName('patterns') ->setDescription('Run analysis') ->addArgument( 'path', InputArgument::REQUIRED, 'Path to explore' ) ->addOption( 'extensions', null, InputOption::VALUE_REQUIRED, 'Regex of extensions to include', 'php' ) ->addOption( 'excluded-dirs', null, InputOption::VALUE_REQUIRED, 'Regex of subdirectories to exclude', 'Tests|tests|Features|features|\.svn|\.git|vendor' ) ; } /** * @inheritdoc */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Design pattern detector by Jean-François Lépine <https://twitter.com/Halleck45>'); $output->writeln(''); $finder = new Finder($input->getOption('extensions'), $input->getOption('excluded-dirs')); $files = $finder->find($input->getArgument('path')); if(0 == sizeof($files, COUNT_NORMAL)) { throw new \LogicException('No file found'); } // // 1. Extracting classes $output->writeln('<info>Extracting classes</info>'); $progress = new ProgressBar($output); $progress->start(sizeof($files, COUNT_NORMAL)); $collection = array(); $tokenizer = new Tokenizer(new CacheMemory()); $extractor = new Extractor($tokenizer); $nbClasses = 0; foreach($files as $k => $filename) { $progress->advance(); $collection[] = $classes = $extractor->extract($filename); $nbClasses += sizeof($classes->getClasses()); } $progress->clear(); $progress->finish(); // inform user $output->writeln(''); $output->writeln(''); $output->writeln(sprintf("<info>Found %d classes</info>", $nbClasses)); // // 2. Extracting patterns $output->writeln('<info>Extracting design patterns</info>'); $patterns = array(); foreach($collection as $oop) { $classes = $oop->getClasses(); $resolver = new PatternResolver($classes); foreach($classes as $class) { $resolvedClass = new ResolvedClass($class); $resolver->resolve($resolvedClass); if($resolvedClass->getPatterns()) { $patterns = array_merge($patterns, $resolvedClass->getPatterns()); } } } // inform user $output->writeln(sprintf("<info>Found %d design patterns</info>", sizeof($patterns))); foreach($patterns as $pattern) { $output->writeln(sprintf("\t<info>[%s]</info> %s", $pattern->getName(), $pattern->describe())); } } }
{ "content_hash": "c75fc50fa64f1b3f60c291d25b3c9521", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 160, "avg_line_length": 33.55905511811024, "alnum_prop": 0.6234162365086814, "repo_name": "Halleck45/DesignPatternDetector", "id": "652fca8090ccc1d181c84ce004332290ad10d785", "size": "4464", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Hal/Application/Command/RunPatternCommand.php", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "28" }, { "name": "PHP", "bytes": "50264" } ], "symlink_target": "" }
The information below contains information specific to Python. For further guidance, review the [documentation](http://frameworkbenchmarks.readthedocs.org/en/latest/). ## Infrastructure Software Versions * [CPython3](https://www.python.org/) * [CPython2](https://www.python.org/) * [PyPy3](http://pypy.org/) * [PyPy2](http://pypy.org/) * [nginx](http://nginx.org/) * [uWSGI](https://uwsgi-docs.readthedocs.org/en/latest/) ## Get Help ### Python Experts * INADA Naoki (@methane) -- CPython core developer and expert of Python's MySQL driver. * Ludovic Gasc (@GMLudo) -- AsyncIO and aiohttp user. ### [Python Community](https://www.python.org/community/) * `#python` IRC Channel ([irc.freenode.net](http://freenode.net/)) * `#python-dev` IRC Channel ([irc.freenode.net](http://freenode.net/)) ## Python interpreters ### (C)Python 3 Newest Python. It is the most major interpreter for Web Development. ### (C)Python 2 Legacy Python. Still used for widely. ### PyPy3 PyPy is the fastest Python implementation with JIT. ### PyPy2 Legacy PyPy. Still used for widely. ## WSGI Servers ### Nginx + uWSGI This is one of fast and realistic way to serve Python web application. Use unix domain socket between nginx and uWSGI to avoid additional TCP/IP overhead. ### Gunicorn + Meinheld [Meinheld](https://github.com/mopemope/meinheld) is very fast WSGI server. Since Meinheld is safe against slowloris and support Keep-Alive, you can use it without buffered HTTP reverse proxy (like nginx). We use meinheld to measure bare (without DB access) performance of framework without overhead of reverse proxying. (plaintext, json test) Meinheld does not provide worker process management. [Gunicorn](http://gunicorn.org/) provide it for Meinheld. ### Gunicorn + Tornado uWSGI + PyPy is difficult to setup. Meinheld doesn't so fast with PyPy because it uses Python/C API heavily. So we use Tornado as HTTP/WSGI server. It supports keep-alive. So it have nice performance about json or plaintext benchmark. ## Before writing new tests. **Don't increase matrix without significant purpose.** We can't maintain matrix of frameworks (5~) * servers (3~) * DBs (3) * Interpreters (3). If you want to know about performance difference between MySQL and PostgreSQL, there are no need to all frameworks implement both of them. Additionally, Python is not a good language to measure performance of DBs because web application written in Python is slower than DBs. If you want to benchmark http server, you should not port all tests or frameworks. Simple json or plaintext test is enough. If your framework uses SQLAlchemy, Flask may be enough to know performance of SQLAlchemy. ## Advice when writing new tests ### Interpreter Consider Python 3 first. -- Python 3 is mainstream for web development. ### Server Try Gunicorn + Meinheld first. All WSGI apps in this benchmark uses it. You can compare your framework performance with others. ### Files you should provide You can see Flask's files to know how to write new test. `requirements.txt` is standard way to define depending libraries. `install.sh` is executed before running test. You should create virtualenv on `$TROOT/py2` (or py3 for Python 3 and pypy for PyPy). Then `$TROOT/py2/bin/pip install -r requirements.txt`. virtualenv is installed on Python 2 and PyPy. Use `$IROOT/py3/bin/python3 -m venv $TROOT/py3` for Python 3. You can set environment variables within `install.sh` or within `setup.sh`. `bechmark_config` is json file to define test. See [here](http://frameworkbenchmarks.readthedocs.org/en/latest/Codebase/Framework-Files/#benchmark-config-file). `setup_py2.sh` is used to run test on Python 2. `gunicorn_conf.py` is configuration for gunicorn. `setup_py2.sh` and `gunicorn_conf.py` are written as generic as possible. You may be able to use it with changing wsgi callable. (`$PY2_GUNICORN wsgimodule:callable -c gunicorn_conf.py`)
{ "content_hash": "47930c75b32edc577b91d7616517fc7d", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 113, "avg_line_length": 31.488, "alnum_prop": 0.7525406504065041, "repo_name": "saturday06/FrameworkBenchmarks", "id": "3e5fa14d8f1e0e465f7f90ad37d97fdadc811a5b", "size": "3957", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "frameworks/Python/README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "838" }, { "name": "ApacheConf", "bytes": "21433" }, { "name": "Batchfile", "bytes": "1623" }, { "name": "C", "bytes": "39458" }, { "name": "C#", "bytes": "137488" }, { "name": "C++", "bytes": "43250" }, { "name": "CMake", "bytes": "731" }, { "name": "CSS", "bytes": "200358" }, { "name": "Clojure", "bytes": "44993" }, { "name": "Crystal", "bytes": "13299" }, { "name": "D", "bytes": "3922" }, { "name": "DIGITAL Command Language", "bytes": "34" }, { "name": "Dart", "bytes": "36881" }, { "name": "Elixir", "bytes": "12253" }, { "name": "Erlang", "bytes": "28319" }, { "name": "Go", "bytes": "74311" }, { "name": "Groff", "bytes": "49" }, { "name": "Groovy", "bytes": "18156" }, { "name": "HTML", "bytes": "71005" }, { "name": "Haskell", "bytes": "22349" }, { "name": "Java", "bytes": "485442" }, { "name": "JavaScript", "bytes": "437290" }, { "name": "Lua", "bytes": "9410" }, { "name": "Makefile", "bytes": "1640" }, { "name": "MoonScript", "bytes": "2398" }, { "name": "Nginx", "bytes": "132894" }, { "name": "Nim", "bytes": "5106" }, { "name": "PHP", "bytes": "1428322" }, { "name": "Perl", "bytes": "11179" }, { "name": "PowerShell", "bytes": "38184" }, { "name": "Python", "bytes": "283608" }, { "name": "QMake", "bytes": "2080" }, { "name": "Racket", "bytes": "5298" }, { "name": "Ruby", "bytes": "68434" }, { "name": "Rust", "bytes": "2525" }, { "name": "Scala", "bytes": "104470" }, { "name": "Shell", "bytes": "241006" }, { "name": "Smarty", "bytes": "1338" }, { "name": "UrWeb", "bytes": "65535" }, { "name": "Volt", "bytes": "769" } ], "symlink_target": "" }
template <typename T> T Add(const T& a, const T& b) { return a + b; } template <typename T> void Print(const T& value1, const T& value2, const T& result) { std::cout << "The result of adding " << value1 << " to " << value2 << " is " << result << std::endl; } int main() { const int number1{ 1 }; const int number2{ 2 }; const int intResult{ Add(number1, number2) }; Print(number1, number2, intResult); const float floatResults{ Add(static_cast<float>(number1), static_cast<float>(number2)) }; Print<float>(number1, number2, floatResults); return 0; }
{ "content_hash": "f4e1eed6ff53203b92c2ae7b2af44bab", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 93, "avg_line_length": 26.26086956521739, "alnum_prop": 0.6142384105960265, "repo_name": "ordinary-developer/education", "id": "027c0b3f19091e761abf792f663dd0eae64d80f5", "size": "625", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cpp/std-11/b_sutherland-cpp_recipes/ch_09-templates/recipe_9_01-create_a_template_function/02-implicit_and_explicit_template_specialization/main.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2435" }, { "name": "C", "bytes": "109331" }, { "name": "C#", "bytes": "163418" }, { "name": "C++", "bytes": "2504348" }, { "name": "CMake", "bytes": "24185" }, { "name": "GLSL", "bytes": "10134" }, { "name": "HTML", "bytes": "58556" }, { "name": "JavaScript", "bytes": "46010" }, { "name": "Makefile", "bytes": "748" }, { "name": "Python", "bytes": "189834" }, { "name": "QML", "bytes": "191657" }, { "name": "QMake", "bytes": "265220" }, { "name": "Scheme", "bytes": "32484" }, { "name": "Shell", "bytes": "2412" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>About Us - About Us | Cinema - Free Website Template from Templates.com</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="description" content="Place your description here" /> <meta name="keywords" content="put, your, keyword, here" /> <meta name="author" content="Templates.com - website templates provider" /> <link href="style.css" rel="stylesheet" type="text/css" /> <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="js/cufon-yui.js" type="text/javascript"></script> <script src="js/cufon-replace.js" type="text/javascript"></script> <script src="js/Gill_Sans_400.font.js" type="text/javascript"></script> <script src="js/script.js" type="text/javascript"></script> <!--[if lt IE 7]> <script type="text/javascript" src="js/ie_png.js"></script> <script type="text/javascript"> ie_png.fix('.png, .link1 span, .link1'); </script> <link href="ie6.css" rel="stylesheet" type="text/css" /> <![endif]--> </head> <body id="page2"> <div class="tail-top"> <div class="tail-bottom"> <div id="main"> <!-- HEADER --> <div id="header"> <div class="row-1"> <div class="fleft"><a href="index.html">Cinema <span>World</span></a></div> <ul> <li><a href="index.html"><img src="images/icon1.gif" alt="" /></a></li> <li><a href="contact-us.html"><img src="images/icon2.gif" alt="" /></a></li> <li><a href="sitemap.html"><img src="images/icon3.gif" alt="" /></a></li> </ul> </div> <div class="row-2"> <ul> <li><a href="index.html">Home</a></li> <li><a href="about-us.html" class="active">About</a></li> <li><a href="articles.html">Articles</a></li> <li><a href="contact-us.html">Contacts</a></li> <li class="last"><a href="sitemap.html">Sitemap</a></li> </ul> </div> </div> <!-- CONTENT --> <div id="content"><div class="ic">More Website Templates at TemplateMonster.com!</div> <div class="line-hor"></div> <div class="box"> <div class="border-right"> <div class="border-left"> <div class="inner"> <h3>About <span>Us</span></h3> <p class="p1">Numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur. Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis.</p> <p>Upraesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus.</p> </div> </div> </div> </div> <div class="content"> <h3>Our <span>Team</span></h3> <ul class="list"> <li><img src="images/2page-img1.jpg" alt="" /><a href="#">Team Member One</a><br /> He is the most important member of your team. Usually this is the person who started the website. Maybe it is worth to write why he has made such a decision and what has inspired him.</li> <li><img src="images/2page-img2.jpg" alt="" /><a href="#">Another Team Member</a><br /> We are completly lost on what he's responsible for, but we hope that you know it ;) We also hope that you will tell it to the rest of the world including us by placing some real text here.</li> <li><img src="images/2page-img3.jpg" alt="" /><a href="#">Another Team Member</a><br /> We are completly lost on what he's responsible for, but we hope that you know it ;) We also hope that you will tell it to the rest of the world including us by placing some real text here.</li> </ul> </div> </div> <!-- FOOTER --> <div id="footer"> <div class="left"> <div class="right"> <div class="inside">Copyright - Type in your name here<br /> <a rel="nofollow" href="http://www.templatemonster.com/" class="new_window">Website template</a> designed by TemplateMonster.com<br /> <a href="http://www.templates.com/product/3d-models/" class="new_window">3D Models</a> provided by Templates.com </div> </div> </div> </div> </div> </div> </div> <script type="text/javascript"> Cufon.now(); </script> </body> </html>
{ "content_hash": "c36127baa427cca8b161260ef78c4b5c", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 484, "avg_line_length": 53.73033707865169, "alnum_prop": 0.6572563780844835, "repo_name": "Neyton/kino_dom", "id": "0e21fd6a6dcbe60a2f62665b6b8402436790bdab", "size": "4782", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kino_dom/Content/about-us.html", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "99" }, { "name": "C#", "bytes": "67815" }, { "name": "CSS", "bytes": "15315" }, { "name": "HTML", "bytes": "32479" }, { "name": "JavaScript", "bytes": "9501" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns:ng="http://angularjs.org" xmlns:th="http://www.thymeleaf.org" lang="pt"> <eits-vbox vertical-align="center" horizontal-align="center"> </eits-vbox> </html>
{ "content_hash": "0ca26027142d9c7df2b2d76e172d8456", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 62, "avg_line_length": 26.857142857142858, "alnum_prop": 0.6914893617021277, "repo_name": "felipenami/SISCEI", "id": "04174e8306bdbbe826600e00704ab66233008dbd", "size": "188", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "4-Implementacao/4.1-Codigo_Fonte/solution/src/main/resources/META-INF/resources/modules/home/views/user/user-index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "312060" }, { "name": "HTML", "bytes": "219067" }, { "name": "Java", "bytes": "223903" }, { "name": "JavaScript", "bytes": "101776" } ], "symlink_target": "" }
La facon la plus rapide d'installer Frappe sur un système Unix est d'utiliser frappe-bench. Lisez les instructions détaillées sur comment installer et utiliser Frappe Bench. > [https://github.com/frappe/bench](https://github.com/frappe/bench) Avec Frappe Bench vous pourrez configurer et héberger de multiples applications et sites. Frappe Bench configure aussi un Virtualenv Python donc vos applications seront isolées les unes des autres (et vous n'aurez pas de conflits avce d'autres environnements de developpement). La commande `bench` sera installé et vous aidera aidera dans le développement et la gestion des vos applications. {suite}
{ "content_hash": "3c5405c1f258b7d43cb70899e7b95a97", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 144, "avg_line_length": 58.90909090909091, "alnum_prop": 0.808641975308642, "repo_name": "Amber-Creative/amber-frappe", "id": "65a82f29a2c4230160a775a66b5f7353e6ef92be", "size": "687", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "frappe/docs/user/fr/tutorial/bench.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "308404" }, { "name": "HTML", "bytes": "168691" }, { "name": "JavaScript", "bytes": "1005383" }, { "name": "Python", "bytes": "1365708" }, { "name": "Shell", "bytes": "517" } ], "symlink_target": "" }
require_relative 'ecomdev/chefspec'
{ "content_hash": "18a5ada4e7525a3d8ae89801afb8b5db", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 35, "avg_line_length": 35, "alnum_prop": 0.8571428571428571, "repo_name": "EcomDev/ecomdev-chefspec", "id": "98a15b3a2747ec8cd20402ce7469ff456251e9ac", "size": "68", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/ecomdev-chefspec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "72064" } ], "symlink_target": "" }
#!/bin/bash typeset __abspath=$(cd ${0%/*} && echo $PWD/${0##*/}) typeset __shelldir=`dirname "${__abspath}"` typeset __testdir=`dirname "${__shelldir}"` typeset __tmp=`mktemp /tmp/avn-test.XXXXXX` typeset __written="" export HOME="${__testdir}/fixtures" # start in a known location cd "${__testdir}/fixtures/home" function _avn() { echo "$@" >> ${__tmp} } source "${__shelldir}/helpers.sh" source "${__testdir}/../bin/avn.sh" # change to a directory where the after hook will be called cd "../v0.10.11/lib" __written=`echo $(cat ${__tmp})` assertEqual "chpwd --color ${__testdir}/fixtures/v0.10.11 .node-version" "${__written}" || exit 1 # same config file should not trigger a change echo "" > ${__tmp} # clear output cd "../src" __written=`echo $(cat ${__tmp})` assertEqual "" "${__written}" || exit 1 # same config file should not trigger a change echo "" > ${__tmp} # clear output cd "../src" __written=`echo $(cat ${__tmp})` assertEqual "" "${__written}" || exit 1 # change to a directory where the after hook will be called echo "" > ${__tmp} # clear output cd "../../../fixtures/v0.10" __written=`echo $(cat ${__tmp})` assertEqual "chpwd --color ${__testdir}/fixtures/v0.10 .node-version" "${__written}" || exit 1 rm ${__tmp}
{ "content_hash": "eff7c69f3335010dcbe33fc80361470c", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 97, "avg_line_length": 28.953488372093023, "alnum_prop": 0.6176706827309237, "repo_name": "wbyoung/avn", "id": "3260ec120c2ebbefe5959bbac4d0d17a2861e6db", "size": "1245", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/shell/unchanged.sh", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "45564" }, { "name": "Shell", "bytes": "15385" } ], "symlink_target": "" }
<?php namespace Ufuturelabs\Ufuturedesk\MainBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class CourseType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name') ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Ufuturelabs\Ufuturedesk\MainBundle\Entity\Course' )); } /** * @return string */ public function getName() { return 'ufuturelabs_ufuturedesk_mainbundle_course'; } }
{ "content_hash": "248c1839e2c58b26ef733f40c1ee9ba5", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 78, "avg_line_length": 23.41025641025641, "alnum_prop": 0.6538882803943045, "repo_name": "avegao/ufuturedesk-server", "id": "a398cc952146bd73420df2278ad9407a84864810", "size": "913", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Ufuturelabs/Ufuturedesk/MainBundle/Form/CourseType.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4320" }, { "name": "PHP", "bytes": "185122" } ], "symlink_target": "" }
/* Some portions of this code are Copyright (c) 2014, Yahoo! Inc. All rights reserved. */ package com.yahoo.sshd.server.command; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.Map; import javax.annotation.Nonnull; import org.apache.sshd.common.file.FileSystemAware; import org.apache.sshd.common.file.SshFile; import org.apache.sshd.common.scp.ScpHelper; import org.apache.sshd.server.Command; import org.apache.sshd.server.Environment; import org.apache.sshd.server.SessionAware; import org.apache.sshd.server.command.ScpCommand; import org.apache.sshd.server.session.ServerSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.yahoo.sshd.server.logging.LoggingHelper; import com.yahoo.sshd.server.logging.SshRequestInfo; import com.yahoo.sshd.server.logging.SshRequestLog; import com.yahoo.sshd.server.logging.SshRequestLogListener; import com.yahoo.sshd.server.logging.SshRequestStatus; /** * This commands provide SCP support on both server and client side. Permissions and preservation of access / * modification times on files are not supported. * * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a> */ /** * This was adapted directly from the ScpCommand class in Apache Mina, so leaving license and original comment in place. * * This exists to allow use to replace parts of ScpCommand. */ public abstract class AbstractScpCommand extends ScpCommand implements Command, Runnable, FileSystemAware, SessionAware { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractScpCommand.class); protected ServerSession session; protected SshRequestLogListener requestLogListener; protected ScpCommandSessionListener scpCommandSessionListener; protected Environment env; protected Map<String, String> envToAfPropertyMapping; public AbstractScpCommand(@Nonnull final String command, @Nonnull Map<String, String> envToAfPropertyMapping) { super(command); this.envToAfPropertyMapping = envToAfPropertyMapping; } protected NewScpHelper createScpHelper() { SshRequestInfo.Builder sshRequestInfo = new SshRequestInfo.Builder(this.session).setStartTimestamp(System.currentTimeMillis()); if (optT) { sshRequestInfo.setMethod(SshRequestStatus.CREATED.getReasonPhrase()).setStatus( SshRequestStatus.CREATED.getStatusCode()); } else if (optF) { sshRequestInfo.setMethod(SshRequestStatus.OK.getReasonPhrase()).setStatus( SshRequestStatus.OK.getStatusCode()); } else { sshRequestInfo.setMethod(SshRequestStatus.BAD_REQUEST.getReasonPhrase()).setStatus( SshRequestStatus.BAD_REQUEST.getStatusCode()); } LoggingHelper loggingHelper = new LoggingHelper(sshRequestInfo, requestLogListener); return new NewScpHelper(in, out, root, loggingHelper, env, envToAfPropertyMapping); } @Override public void start(Environment env) throws IOException { // save the env. this.env = env; super.start(env); } @Override public void run() { int exitValue = ScpHelper.OK; String exitMessage = null; // ScpHelper helper = new ScpHelper(in, out, root); NewScpHelper helper = createScpHelper(); SshFile sshFile = null; registerScpCommandSessionListener(this.session); try { if (optT) { // upload sshFile = root.getFile(path); if (null == sshFile) { throw new IOException("Unable to get path for " + path); } helper.receive(sshFile, optR, optD, optP); } else if (optF) { // download helper.send(Collections.singletonList(path), optR, optP); } else { throw new IOException("Unsupported mode"); } } catch (Throwable e) { exitValue = ScpHelper.ERROR; exitMessage = e.getMessage() == null ? "" : e.getMessage(); // out.write(exitValue); // out.write(exitMessage.getBytes()); // out.write('\n'); // out.flush(); writeBackErrorMessage(out, exitValue, exitMessage); helper.doLogging(e, path); LOGGER.info("Error in scp command", e); } finally { if (null != sshFile) { try { sshFile.handleClose(); } catch (IOException e) { LOGGER.error("Error when closing the SshFile: {}", sshFile.getName(), e); } } if (callback != null) { callback.onExit(exitValue, exitMessage); } } } @Override public void setSession(ServerSession session) { this.session = session; @SuppressWarnings("resource") SshRequestLog requestLog = getSshRequestLog(); if (null == requestLog) { return; } requestLogListener = new SshRequestLogListener(requestLog); requestLogListener.registerSession(session); } private void writeBackErrorMessage(@Nonnull OutputStream out, int exitValue, @Nonnull String exitMessage) { try { out.write(exitValue); out.write(exitMessage.getBytes()); out.write('\n'); out.flush(); } catch (IOException e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("flush failed", e); } } } private void registerScpCommandSessionListener(ServerSession session) { if (null != session) { this.scpCommandSessionListener = new ScpCommandSessionListener(Thread.currentThread()); this.scpCommandSessionListener.registerSession(session); } } /** * * @return an instance of {@link SshRequestLog} that can be used to log all requests. */ protected abstract SshRequestLog getSshRequestLog(); }
{ "content_hash": "4eab34e98228e2e7ec56bf5f09fcce34", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 121, "avg_line_length": 37.01807228915663, "alnum_prop": 0.6434499593165175, "repo_name": "charlesk40/artifactory_ssh_proxy", "id": "7fd60acfd1faee00385a4c1e5a4aaa64d332b5f7", "size": "6930", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/main/java/com/yahoo/sshd/server/command/AbstractScpCommand.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "550469" }, { "name": "Shell", "bytes": "3563" } ], "symlink_target": "" }
module Mongo module Helpers VERSION = "1.0.0" end end
{ "content_hash": "6e17d3b87d877eeef3ce3e2467f6e681", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 21, "avg_line_length": 12.4, "alnum_prop": 0.6451612903225806, "repo_name": "kuldeepaggarwal/mongo-helpers", "id": "71bde791eb6456f2e80b04ed7d5bb2ed378390e8", "size": "62", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/mongo/helpers/version.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "2355" }, { "name": "Shell", "bytes": "115" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/kds_support_700" android:state_enabled="true"/> <item android:alpha="0.12" android:color="?attr/colorOnSurface"/> </selector>
{ "content_hash": "e0a9dc4c5367c4a61f908a72fb5d636b", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 77, "avg_line_length": 53.4, "alnum_prop": 0.7191011235955056, "repo_name": "kickstarter/android-oss", "id": "828ef424e1b0e1e50a4db2c6902d3a871e23dbc0", "size": "267", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/color/button_select.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "432540" }, { "name": "Kotlin", "bytes": "4385880" }, { "name": "Makefile", "bytes": "3750" }, { "name": "Ruby", "bytes": "22397" }, { "name": "Shell", "bytes": "6325" } ], "symlink_target": "" }
<html lang="en"> <head> <title>Thread-Local - Using the GNU Compiler Collection (GCC)</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Using the GNU Compiler Collection (GCC)"> <meta name="generator" content="makeinfo 4.13"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="C-Extensions.html#C-Extensions" title="C Extensions"> <link rel="prev" href="Unnamed-Fields.html#Unnamed-Fields" title="Unnamed Fields"> <link rel="next" href="Binary-constants.html#Binary-constants" title="Binary constants"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- Copyright (C) 1988-2018 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being ``Funding Free Software'', the Front-Cover Texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the section entitled ``GNU Free Documentation License''. (a) The FSF's Front-Cover Text is: A GNU Manual (b) The FSF's Back-Cover Text is: You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development.--> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <a name="Thread-Local"></a> <a name="Thread_002dLocal"></a> <p> Next:&nbsp;<a rel="next" accesskey="n" href="Binary-constants.html#Binary-constants">Binary constants</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="Unnamed-Fields.html#Unnamed-Fields">Unnamed Fields</a>, Up:&nbsp;<a rel="up" accesskey="u" href="C-Extensions.html#C-Extensions">C Extensions</a> <hr> </div> <h3 class="section">6.63 Thread-Local Storage</h3> <p><a name="index-Thread_002dLocal-Storage-4777"></a><a name="index-g_t_0040acronym_007bTLS_007d-4778"></a><a name="index-g_t_0040code_007b_005f_005fthread_007d-4779"></a> Thread-local storage (<acronym>TLS</acronym>) is a mechanism by which variables are allocated such that there is one instance of the variable per extant thread. The runtime model GCC uses to implement this originates in the IA-64 processor-specific ABI, but has since been migrated to other processors as well. It requires significant support from the linker (<samp><span class="command">ld</span></samp>), dynamic linker (<samp><span class="command">ld.so</span></samp>), and system libraries (<samp><span class="file">libc.so</span></samp> and <samp><span class="file">libpthread.so</span></samp>), so it is not available everywhere. <p>At the user level, the extension is visible with a new storage class keyword: <code>__thread</code>. For example: <pre class="smallexample"> __thread int i; extern __thread struct state s; static __thread char *p; </pre> <p>The <code>__thread</code> specifier may be used alone, with the <code>extern</code> or <code>static</code> specifiers, but with no other storage class specifier. When used with <code>extern</code> or <code>static</code>, <code>__thread</code> must appear immediately after the other storage class specifier. <p>The <code>__thread</code> specifier may be applied to any global, file-scoped static, function-scoped static, or static data member of a class. It may not be applied to block-scoped automatic or non-static data member. <p>When the address-of operator is applied to a thread-local variable, it is evaluated at run time and returns the address of the current thread's instance of that variable. An address so obtained may be used by any thread. When a thread terminates, any pointers to thread-local variables in that thread become invalid. <p>No static initialization may refer to the address of a thread-local variable. <p>In C++, if an initializer is present for a thread-local variable, it must be a <var>constant-expression</var>, as defined in 5.19.2 of the ANSI/ISO C++ standard. <p>See <a href="https://www.akkadia.org/drepper/tls.pdf">ELF Handling For Thread-Local Storage</a> for a detailed explanation of the four thread-local storage addressing models, and how the runtime is expected to function. <ul class="menu"> <li><a accesskey="1" href="C99-Thread_002dLocal-Edits.html#C99-Thread_002dLocal-Edits">C99 Thread-Local Edits</a> <li><a accesskey="2" href="C_002b_002b98-Thread_002dLocal-Edits.html#C_002b_002b98-Thread_002dLocal-Edits">C++98 Thread-Local Edits</a> </ul> </body></html>
{ "content_hash": "9db132584d23328c8a40ba9b17e2ba5f", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 171, "avg_line_length": 48.5188679245283, "alnum_prop": 0.7365350962473265, "repo_name": "bouffalolab/bl_iot_sdk_matter", "id": "fd81982ed32f65e150a51c5ef256b28d10d4ba3d", "size": "5143", "binary": false, "copies": "1", "ref": "refs/heads/release_spiwifi_bl602", "path": "toolchain/riscv/Linux/share/doc/gcc/Thread_002dLocal.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "46671" }, { "name": "Batchfile", "bytes": "1603" }, { "name": "C", "bytes": "24837905" }, { "name": "C++", "bytes": "14471862" }, { "name": "CMake", "bytes": "124252" }, { "name": "HTML", "bytes": "24826" }, { "name": "Makefile", "bytes": "114632" }, { "name": "Perl", "bytes": "2589" }, { "name": "Python", "bytes": "273291" }, { "name": "Roff", "bytes": "3255873" }, { "name": "Shell", "bytes": "27722" }, { "name": "XC", "bytes": "18410" } ], "symlink_target": "" }
/* * linux/kernel/time/tick-broadcast-hrtimer.c * This file emulates a local clock event device * via a pseudo clock device. */ #include <linux/cpu.h> #include <linux/err.h> #include <linux/hrtimer.h> #include <linux/interrupt.h> #include <linux/percpu.h> #include <linux/profile.h> #include <linux/clockchips.h> #include <linux/sched.h> #include <linux/smp.h> #include <linux/module.h> #include "tick-internal.h" static struct hrtimer bctimer; static int bc_shutdown(struct clock_event_device *evt) { /* * Note, we cannot cancel the timer here as we might * run into the following live lock scenario: * * cpu 0 cpu1 * lock(broadcast_lock); * hrtimer_interrupt() * bc_handler() * tick_handle_oneshot_broadcast(); * lock(broadcast_lock); * hrtimer_cancel() * wait_for_callback() */ hrtimer_try_to_cancel(&bctimer); return 0; } /* * This is called from the guts of the broadcast code when the cpu * which is about to enter idle has the earliest broadcast timer event. */ static int bc_set_next(ktime_t expires, struct clock_event_device *bc) { int bc_moved; /* * We try to cancel the timer first. If the callback is on * flight on some other cpu then we let it handle it. If we * were able to cancel the timer nothing can rearm it as we * own broadcast_lock. * * However we can also be called from the event handler of * ce_broadcast_hrtimer itself when it expires. We cannot * restart the timer because we are in the callback, but we * can set the expiry time and let the callback return * HRTIMER_RESTART. * * Since we are in the idle loop at this point and because * hrtimer_{start/cancel} functions call into tracing, * calls to these functions must be bound within RCU_NONIDLE. */ RCU_NONIDLE({ bc_moved = hrtimer_try_to_cancel(&bctimer) >= 0; if (bc_moved) hrtimer_start(&bctimer, expires, HRTIMER_MODE_ABS_PINNED);}); if (bc_moved) { /* Bind the "device" to the cpu */ bc->bound_on = smp_processor_id(); } else if (bc->bound_on == smp_processor_id()) { hrtimer_set_expires(&bctimer, expires); } return 0; } static struct clock_event_device ce_broadcast_hrtimer = { .set_state_shutdown = bc_shutdown, .set_next_ktime = bc_set_next, .features = CLOCK_EVT_FEAT_ONESHOT | CLOCK_EVT_FEAT_KTIME | CLOCK_EVT_FEAT_HRTIMER, .rating = 0, .bound_on = -1, .min_delta_ns = 1, .max_delta_ns = KTIME_MAX, .min_delta_ticks = 1, .max_delta_ticks = ULONG_MAX, .mult = 1, .shift = 0, .cpumask = cpu_all_mask, }; static enum hrtimer_restart bc_handler(struct hrtimer *t) { ce_broadcast_hrtimer.event_handler(&ce_broadcast_hrtimer); if (clockevent_state_oneshot(&ce_broadcast_hrtimer)) if (ce_broadcast_hrtimer.next_event.tv64 != KTIME_MAX) return HRTIMER_RESTART; return HRTIMER_NORESTART; } void tick_setup_hrtimer_broadcast(void) { hrtimer_init(&bctimer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS); bctimer.function = bc_handler; clockevents_register_device(&ce_broadcast_hrtimer); }
{ "content_hash": "a55a5c31c10befe03be5c446a7a434bb", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 71, "avg_line_length": 27.581818181818182, "alnum_prop": 0.6895187870797627, "repo_name": "KristFoundation/Programs", "id": "53d7184da0bedb5d7df959d09c2b787f77f0682b", "size": "3034", "binary": false, "copies": "483", "ref": "refs/heads/master", "path": "luaide/kernel/time/tick-broadcast-hrtimer.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "10201036" }, { "name": "Awk", "bytes": "30879" }, { "name": "C", "bytes": "539626448" }, { "name": "C++", "bytes": "3413466" }, { "name": "Clojure", "bytes": "1570" }, { "name": "Cucumber", "bytes": "4809" }, { "name": "Groff", "bytes": "46837" }, { "name": "Lex", "bytes": "55541" }, { "name": "Lua", "bytes": "59745" }, { "name": "Makefile", "bytes": "1601043" }, { "name": "Objective-C", "bytes": "521706" }, { "name": "Perl", "bytes": "730609" }, { "name": "Perl6", "bytes": "3783" }, { "name": "Python", "bytes": "296036" }, { "name": "Shell", "bytes": "357961" }, { "name": "SourcePawn", "bytes": "4687" }, { "name": "UnrealScript", "bytes": "12797" }, { "name": "XS", "bytes": "1239" }, { "name": "Yacc", "bytes": "115572" } ], "symlink_target": "" }
import sys import imp import contextlib @contextlib.contextmanager def preserve_value(namespace, name): """ A context manager to preserve, then restore, the specified binding. :param namespace: The namespace object (e.g. a class or dict) containing the name binding. :param name: The name of the binding to be preserved. :yield: None. When the context manager is entered, the current value bound to `name` in `namespace` is saved. When the context manager is exited, the binding is re-established to the saved value. """ saved_value = getattr(namespace, name) yield setattr(namespace, name, saved_value) def make_module_from_file(module_name, module_filepath): """ Make a new module object from the source code in specified file. :param module_name: The name of the resulting module object. :param module_filepath: The filesystem path to open for reading the module's Python source. :return: The module object. The Python import mechanism is not used. No cached bytecode file is created, and no entry is placed in `sys.modules`. """ py_source_open_mode = 'U' py_source_description = (b".py", py_source_open_mode, imp.PY_SOURCE) with open(module_filepath, py_source_open_mode) as module_file: with preserve_value(sys, 'dont_write_bytecode'): sys.dont_write_bytecode = True module = imp.load_module( module_name, module_file, module_filepath, py_source_description) return module
{ "content_hash": "18f58c4593698f7eea56f492546820c6", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 78, "avg_line_length": 33.673469387755105, "alnum_prop": 0.6442424242424243, "repo_name": "kyleterry/tenyksclient", "id": "f631707919076da94d7482af01e73b4cff1b41fe", "size": "1786", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tenyksclient/module_loader.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "10496" } ], "symlink_target": "" }
// // CLBeaconRegion+LoadPlist.h // iBeaconNotifier // // Created by Masahiro Murase on 2014/02/24. // Copyright (c) 2014年 calmscape. All rights reserved. // #import <CoreLocation/CoreLocation.h> @interface CLBeaconRegion (LoadPlist) /** 監視するビーコン領域が定義されたplistを読み込んでCLBeacolRegionオブジェクトのセットとして返す */ + (NSSet *)beaconRegionsFromPlist:(NSString *)plistName; @end
{ "content_hash": "51e5efa3c0873213916865923ed145b5", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 57, "avg_line_length": 21.705882352941178, "alnum_prop": 0.7560975609756098, "repo_name": "calmscape/iBeaconNotifier", "id": "90e0b0488e7e633c9c108cfbb458f14431552dd1", "size": "445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "iBeaconNotifier/CLBeaconRegion+LoadPlist.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "29803" } ], "symlink_target": "" }
package com.timgroup.jpoeisis.matchers; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher; import com.timgroup.jpoeisis.reflection.MethodCallArgument; public final class AnArgument<C> extends TypeSafeDiagnosingMatcher<MethodCallArgument<C>> { private final C value; public static <C> AnArgument<C> of(C value) { return new AnArgument<C>(value); } private AnArgument(C value) { this.value = value; } @Override public void describeTo(Description description) { description.appendText(" an argument with the value ").appendValue(value); } @Override protected boolean matchesSafely(MethodCallArgument<C> item, Description mismatchDescription) { if (item.value().equals(value)) { return true; } mismatchDescription.appendText(" had the value ").appendValue(value); return false; } }
{ "content_hash": "bb5c0591ed21fed55018e61e084e120e", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 98, "avg_line_length": 28.424242424242426, "alnum_prop": 0.6876332622601279, "repo_name": "tim-group/jpoeisis", "id": "f1553689e7bc091d9132ec081e6e17977ebc562a", "size": "938", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/timgroup/jpoeisis/matchers/AnArgument.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "273467" } ], "symlink_target": "" }
@implementation MasterViewController { NSArray *demos_; NSArray *demoSections_; BOOL isPhone_; UIPopoverController *popover_; UIBarButtonItem *samplesButton_; __weak UIViewController *controller_; } - (void)viewDidLoad { [super viewDidLoad]; isPhone_ = ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone); if (!isPhone_) { self.clearsSelectionOnViewWillAppear = NO; } else { UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Back", @"Back") style:UIBarButtonItemStyleBordered target:nil action:nil]; [self.navigationItem setBackBarButtonItem:backButton]; } self.title = NSLocalizedString(@"SDK Demos", @"SDK Demos"); self.title = [NSString stringWithFormat:@"%@: %@", self.title, [GMSServices SDKVersion]]; self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth; self.tableView.delegate = self; self.tableView.dataSource = self; demoSections_ = [Samples loadSections]; demos_ = [Samples loadDemos]; if (!isPhone_) { [self loadDemo:0 atIndex:0]; } } #pragma mark - UITableViewController - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return demoSections_.count; } - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 35.0; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return [demoSections_ objectAtIndex:section]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [[demos_ objectAtIndex: section] count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier]; if (isPhone_) { [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; } } NSDictionary *demo = [[demos_ objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]; cell.textLabel.text = [demo objectForKey:@"title"]; cell.detailTextLabel.text = [demo objectForKey:@"description"]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // The user has chosen a sample; load it and clear the selection! [self loadDemo:indexPath.section atIndex:indexPath.row]; [tableView deselectRowAtIndexPath:indexPath animated:YES]; } #pragma mark - Split view - (void)splitViewController:(UISplitViewController *)splitController willHideViewController:(UIViewController *)viewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)popoverController { popover_ = popoverController; samplesButton_ = barButtonItem; samplesButton_.title = NSLocalizedString(@"Samples", @"Samples"); samplesButton_.style = UIBarButtonItemStyleDone; [self updateSamplesButton]; } - (void)splitViewController:(UISplitViewController *)splitController willShowViewController:(UIViewController *)viewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem { popover_ = nil; samplesButton_ = nil; [self updateSamplesButton]; } #pragma mark - Private methods - (NSDictionary *)newDemo:(Class) class withTitle:(NSString *)title andDescription:(NSString *)description { return [[NSDictionary alloc] initWithObjectsAndKeys:class, @"controller", title, @"title", description, @"description", nil]; } - (void)loadDemo:(int)section atIndex:(int)index { NSDictionary *demo = [[demos_ objectAtIndex:section] objectAtIndex:index]; UIViewController *controller = [[[demo objectForKey:@"controller"] alloc] init]; controller_ = controller; if (controller != nil) { controller.title = [demo objectForKey:@"title"]; if (isPhone_) { [self.navigationController pushViewController:controller animated:YES]; } else { [self.appDelegate setSample:controller]; [popover_ dismissPopoverAnimated:YES]; } [self updateSamplesButton]; } } // This method is invoked when the left 'back' button in the split view // controller on iPad should be updated (either made visible or hidden). // It assumes that the left bar button item may be safely modified to contain // the samples button. - (void)updateSamplesButton { controller_.navigationItem.leftBarButtonItem = samplesButton_; } @end
{ "content_hash": "46b79429949921b1baedf35170493f35", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 81, "avg_line_length": 32.19078947368421, "alnum_prop": 0.7110157367668097, "repo_name": "tuanvu89/MyFirstIOSApp", "id": "a2f601a4a4aa40eb36891ee346a55dbd42e3dd6b", "size": "5048", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "GoogleMaps-iOS-1.4.2/GoogleMapsSDKDemos/SDKDemos/MasterViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "265697" } ], "symlink_target": "" }
namespace hiberlite{ template<class AV> void KillChildren::notifyInitWalk(AV& av) { rowId=std::stack<sqlid_t>(); rowId.push(av.getRootId()); } template<class AV> void KillChildren::notifyDoneWalk(AV& av) { } template<class AV, class E, class S> void KillChildren::act(AV& av, collection_nvp<E,S> nvp ) { av.diveTable(nvp.name); std::string tab=av.getScope().table(); std::vector<sqlid_t> children=Database::dbSelectChildIds(av.getConnection(), tab, rowId.top()); for(size_t i=0;i<children.size();i++){ E* entry; construct(av,&entry,static_cast<unsigned int>(0)); rowId.push(children[i]); sql_nvp<E> el("item",*entry); av & el; rowId.pop(); destroy(*this, entry, static_cast<unsigned int>(0)); } av.pop(); Database::dbDeleteRows(av.getConnection(),tab,HIBERLITE_PARENTID_COLUMN,rowId.top()); } template<class C> void ChildKiller::killChildren(bean_key key, C& bean) { startWalk(bean, key); } } //namespace hiberlite #endif // BEANUPDATER_IMPL_HPP_INCLUDED
{ "content_hash": "41353fb7ce30ed953a9834ccc636cd0b", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 97, "avg_line_length": 22.818181818181817, "alnum_prop": 0.6872509960159362, "repo_name": "paulftw/hiberlite", "id": "99f926c6ec7a342e4545ea37a0720a29ce6a922e", "size": "1081", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "include/ChildKiller_impl.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "21" }, { "name": "C", "bytes": "721" }, { "name": "C++", "bytes": "62844" }, { "name": "CMake", "bytes": "1610" }, { "name": "Lua", "bytes": "2277" }, { "name": "Makefile", "bytes": "33868" } ], "symlink_target": "" }
<?php namespace Hetic\SiteBundle\Controller; /** * This code has been auto-generated by the JMSDiExtraBundle. * * Manual changes to it will be lost. */ class CommandesController__JMSInjector { public static function inject($container) { $instance = new \Hetic\SiteBundle\Controller\CommandesController(); return $instance; } }
{ "content_hash": "877a270c94ccc451e773e41eb108e5f6", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 75, "avg_line_length": 22.3125, "alnum_prop": 0.7058823529411765, "repo_name": "Symfomany/Hetic", "id": "24b66ccf4624c1ce76aea9c1a0204705fba76d84", "size": "357", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/cache/dev/jms_diextra/controller_injectors/HeticSiteBundleControllerCommandesController.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "460551" }, { "name": "CoffeeScript", "bytes": "5086" }, { "name": "JavaScript", "bytes": "291198" }, { "name": "PHP", "bytes": "485644" }, { "name": "Perl", "bytes": "2282" }, { "name": "Ruby", "bytes": "19" }, { "name": "Shell", "bytes": "5" } ], "symlink_target": "" }
<?php /** * @see Zend_Gdata_Entry */ //require_once 'Zend/Gdata/Entry.php'; /** * @category Zend * @package Zend_Gdata * @subpackage Analytics */ class Zend_Gdata_Analytics_DataEntry extends Zend_Gdata_Entry { /** * @var array */ protected $_dimensions = array(); /** * @var array */ protected $_metrics = array(); /** * @param DOMElement $element */ public function __construct($element = null) { $this->registerAllNamespaces(Zend_Gdata_Analytics::$namespaces); parent::__construct($element); } /** * @param DOMElement $child * @return void */ protected function takeChildFromDOM($child) { $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; switch ($absoluteNodeName) { case $this->lookupNamespace('analytics') . ':' . 'dimension'; $dimension = new Zend_Gdata_Analytics_Extension_Dimension(); $dimension->transferFromDOM($child); $this->_dimensions[] = $dimension; break; case $this->lookupNamespace('analytics') . ':' . 'metric'; $metric = new Zend_Gdata_Analytics_Extension_Metric(); $metric->transferFromDOM($child); $this->_metrics[] = $metric; break; default: parent::takeChildFromDOM($child); break; } } /** * @param string $name * @return mixed */ public function getDimension($name) { foreach ($this->_dimensions as $dimension) { if ($dimension->getName() == $name) { return $dimension; } } return null; } /** * @param string $name * @return mixed */ public function getMetric($name) { foreach ($this->_metrics as $metric) { if ($metric->getName() == $name) { return $metric; } } return null; } /** * @param string $name * @return mixed */ public function getValue($name) { if (null !== ($metric = $this->getMetric($name))) { return $metric; } return $this->getDimension($name); } }
{ "content_hash": "2740886189eb817b916062da20172afc", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 76, "avg_line_length": 23.97938144329897, "alnum_prop": 0.5004299226139295, "repo_name": "webino/ZF1Gdata", "id": "66dfb976863aa92bd679bf1fcd670b730ea6eda1", "size": "3042", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Zend/Gdata/Analytics/DataEntry.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "1512987" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "1f3fbfe06a1d10c0905a8c6883a9c650", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "cb70087a9c9538b6f97c56bc43900eca9c72b685", "size": "188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Orobanchaceae/Orobanche/Orobanche crithmi-maritimi/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CHAIN_H #define BITCOIN_CHAIN_H #include <arith_uint256.h> #include <consensus/params.h> #include <primitives/block.h> #include <tinyformat.h> #include <uint256.h> #include <vector> /** * Maximum amount of time that a block timestamp is allowed to exceed the * current network-adjusted time before the block will be accepted. */ static const int64_t MAX_FUTURE_BLOCK_TIME = 2 * 60 * 60; /** * Timestamp window used as a grace period by code that compares external * timestamps (such as timestamps passed to RPCs, or wallet key creation times) * to block timestamps. This should be set at least as high as * MAX_FUTURE_BLOCK_TIME. */ static const int64_t TIMESTAMP_WINDOW = MAX_FUTURE_BLOCK_TIME; class CBlockFileInfo { public: unsigned int nBlocks; //!< number of blocks stored in file unsigned int nSize; //!< number of used bytes of block file unsigned int nUndoSize; //!< number of used bytes in the undo file unsigned int nHeightFirst; //!< lowest height of block in file unsigned int nHeightLast; //!< highest height of block in file uint64_t nTimeFirst; //!< earliest time of block in file uint64_t nTimeLast; //!< latest time of block in file ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(VARINT(nBlocks)); READWRITE(VARINT(nSize)); READWRITE(VARINT(nUndoSize)); READWRITE(VARINT(nHeightFirst)); READWRITE(VARINT(nHeightLast)); READWRITE(VARINT(nTimeFirst)); READWRITE(VARINT(nTimeLast)); } void SetNull() { nBlocks = 0; nSize = 0; nUndoSize = 0; nHeightFirst = 0; nHeightLast = 0; nTimeFirst = 0; nTimeLast = 0; } CBlockFileInfo() { SetNull(); } std::string ToString() const; /** update statistics (does not update nSize) */ void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) { if (nBlocks==0 || nHeightFirst > nHeightIn) nHeightFirst = nHeightIn; if (nBlocks==0 || nTimeFirst > nTimeIn) nTimeFirst = nTimeIn; nBlocks++; if (nHeightIn > nHeightLast) nHeightLast = nHeightIn; if (nTimeIn > nTimeLast) nTimeLast = nTimeIn; } }; struct CDiskBlockPos { int nFile; unsigned int nPos; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(VARINT(nFile, VarIntMode::NONNEGATIVE_SIGNED)); READWRITE(VARINT(nPos)); } CDiskBlockPos() { SetNull(); } CDiskBlockPos(int nFileIn, unsigned int nPosIn) { nFile = nFileIn; nPos = nPosIn; } friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) { return (a.nFile == b.nFile && a.nPos == b.nPos); } friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) { return !(a == b); } void SetNull() { nFile = -1; nPos = 0; } bool IsNull() const { return (nFile == -1); } std::string ToString() const { return strprintf("CBlockDiskPos(nFile=%i, nPos=%i)", nFile, nPos); } }; enum BlockStatus: uint32_t { //! Unused. BLOCK_VALID_UNKNOWN = 0, //! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future BLOCK_VALID_HEADER = 1, //! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents //! are also at least TREE. BLOCK_VALID_TREE = 2, /** * Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, * sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all * parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set. */ BLOCK_VALID_TRANSACTIONS = 3, //! Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends, BIP30. //! Implies all parents are also at least CHAIN. BLOCK_VALID_CHAIN = 4, //! Scripts & signatures ok. Implies all parents are also at least SCRIPTS. BLOCK_VALID_SCRIPTS = 5, //! All validity bits. BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS | BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS, BLOCK_HAVE_DATA = 8, //!< full block available in blk*.dat BLOCK_HAVE_UNDO = 16, //!< undo data available in rev*.dat BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO, BLOCK_FAILED_VALID = 32, //!< stage after last reached validness failed BLOCK_FAILED_CHILD = 64, //!< descends from failed block BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD, BLOCK_OPT_WITNESS = 128, //!< block data in blk*.data was received with a witness-enforcing client }; /** The block chain is a tree shaped structure starting with the * genesis block at the root, with each block potentially having multiple * candidates to be the next block. A blockindex may have multiple pprev pointing * to it, but at most one of them can be part of the currently active branch. */ class CBlockIndex { public: //! pointer to the hash of the block, if any. Memory is owned by this CBlockIndex const uint256* phashBlock; //! pointer to the index of the predecessor of this block CBlockIndex* pprev; //! pointer to the index of some further predecessor of this block CBlockIndex* pskip; //! height of the entry in the chain. The genesis block has height 0 int nHeight; //! Which # file this block is stored in (blk?????.dat) int nFile; //! Byte offset within blk?????.dat where this block's data is stored unsigned int nDataPos; //! Byte offset within rev?????.dat where this block's undo data is stored unsigned int nUndoPos; //! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block arith_uint256 nChainWork; //! Number of transactions in this block. //! Note: in a potential headers-first mode, this number cannot be relied upon unsigned int nTx; //! (memory only) Number of transactions in the chain up to and including this block. //! This value will be non-zero only if and only if transactions for this block and all its parents are available. //! Change to 64-bit type when necessary; won't happen before 2030 unsigned int nChainTx; //! Verification status of this block. See enum BlockStatus uint32_t nStatus; //! block header int32_t nVersion; uint256 hashMerkleRoot; uint32_t nTime; uint32_t nBits; uint32_t nNonce; //! (memory only) Sequential id assigned to distinguish order in which blocks are received. int32_t nSequenceId; //! (memory only) Maximum nTime in the chain up to and including this block. unsigned int nTimeMax; void SetNull() { phashBlock = nullptr; pprev = nullptr; pskip = nullptr; nHeight = 0; nFile = 0; nDataPos = 0; nUndoPos = 0; nChainWork = arith_uint256(); nTx = 0; nChainTx = 0; nStatus = 0; nSequenceId = 0; nTimeMax = 0; nVersion = 0; hashMerkleRoot = uint256(); nTime = 0; nBits = 0; nNonce = 0; } CBlockIndex() { SetNull(); } explicit CBlockIndex(const CBlockHeader& block) { SetNull(); nVersion = block.nVersion; hashMerkleRoot = block.hashMerkleRoot; nTime = block.nTime; nBits = block.nBits; nNonce = block.nNonce; } CDiskBlockPos GetBlockPos() const { CDiskBlockPos ret; if (nStatus & BLOCK_HAVE_DATA) { ret.nFile = nFile; ret.nPos = nDataPos; } return ret; } CDiskBlockPos GetUndoPos() const { CDiskBlockPos ret; if (nStatus & BLOCK_HAVE_UNDO) { ret.nFile = nFile; ret.nPos = nUndoPos; } return ret; } CBlockHeader GetBlockHeader() const { CBlockHeader block; block.nVersion = nVersion; if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } uint256 GetBlockHash() const { return *phashBlock; } int64_t GetBlockTime() const { return (int64_t)nTime; } int64_t GetBlockTimeMax() const { return (int64_t)nTimeMax; } static constexpr int nMedianTimeSpan = 11; int64_t GetMedianTimePast() const { int64_t pmedian[nMedianTimeSpan]; int64_t* pbegin = &pmedian[nMedianTimeSpan]; int64_t* pend = &pmedian[nMedianTimeSpan]; const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev) *(--pbegin) = pindex->GetBlockTime(); std::sort(pbegin, pend); return pbegin[(pend - pbegin)/2]; } std::string ToString() const { return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)", pprev, nHeight, hashMerkleRoot.ToString(), GetBlockHash().ToString()); } //! Check whether this block index entry is valid up to the passed validity level. bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const { assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed. if (nStatus & BLOCK_FAILED_MASK) return false; return ((nStatus & BLOCK_VALID_MASK) >= nUpTo); } //! Raise the validity level of this block index entry. //! Returns true if the validity was changed. bool RaiseValidity(enum BlockStatus nUpTo) { assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed. if (nStatus & BLOCK_FAILED_MASK) return false; if ((nStatus & BLOCK_VALID_MASK) < nUpTo) { nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo; return true; } return false; } //! Build the skiplist pointer for this entry. void BuildSkip(); //! Efficiently find an ancestor of this block. CBlockIndex* GetAncestor(int height); const CBlockIndex* GetAncestor(int height) const; }; arith_uint256 GetBlockProof(const CBlockIndex& block); /** Return the time it would take to redo the work difference between from and to, assuming the current hashrate corresponds to the difficulty at tip, in seconds. */ int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&); /** Find the forking point between two chain tips. */ const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb); /** Used to marshal pointers into hashes for db storage. */ class CDiskBlockIndex : public CBlockIndex { public: uint256 hashPrev; CDiskBlockIndex() { hashPrev = uint256(); } explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) { hashPrev = (pprev ? pprev->GetBlockHash() : uint256()); } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { int _nVersion = s.GetVersion(); if (!(s.GetType() & SER_GETHASH)) READWRITE(VARINT(_nVersion, VarIntMode::NONNEGATIVE_SIGNED)); READWRITE(VARINT(nHeight, VarIntMode::NONNEGATIVE_SIGNED)); READWRITE(VARINT(nStatus)); READWRITE(VARINT(nTx)); if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO)) READWRITE(VARINT(nFile, VarIntMode::NONNEGATIVE_SIGNED)); if (nStatus & BLOCK_HAVE_DATA) READWRITE(VARINT(nDataPos)); if (nStatus & BLOCK_HAVE_UNDO) READWRITE(VARINT(nUndoPos)); // block header READWRITE(this->nVersion); READWRITE(hashPrev); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); } uint256 GetBlockHash() const { CBlockHeader block; block.nVersion = nVersion; block.hashPrevBlock = hashPrev; block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block.GetHash(); } std::string ToString() const { std::string str = "CDiskBlockIndex("; str += CBlockIndex::ToString(); str += strprintf("\n hashBlock=%s, hashPrev=%s)", GetBlockHash().ToString(), hashPrev.ToString()); return str; } }; /** An in-memory indexed chain of blocks. */ class CChain { private: std::vector<CBlockIndex*> vChain; public: /** Returns the index entry for the genesis block of this chain, or nullptr if none. */ CBlockIndex *Genesis() const { return vChain.size() > 0 ? vChain[0] : nullptr; } /** Returns the index entry for the tip of this chain, or nullptr if none. */ CBlockIndex *Tip() const { return vChain.size() > 0 ? vChain[vChain.size() - 1] : nullptr; } /** Returns the index entry at a particular height in this chain, or nullptr if no such height exists. */ CBlockIndex *operator[](int nHeight) const { if (nHeight < 0 || nHeight >= (int)vChain.size()) return nullptr; return vChain[nHeight]; } /** Compare two chains efficiently. */ friend bool operator==(const CChain &a, const CChain &b) { return a.vChain.size() == b.vChain.size() && a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1]; } /** Efficiently check whether a block is present in this chain. */ bool Contains(const CBlockIndex *pindex) const { return (*this)[pindex->nHeight] == pindex; } /** Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip. */ CBlockIndex *Next(const CBlockIndex *pindex) const { if (Contains(pindex)) return (*this)[pindex->nHeight + 1]; else return nullptr; } /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */ int Height() const { return vChain.size() - 1; } /** Set/initialize a chain with a given tip. */ void SetTip(CBlockIndex *pindex); /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */ CBlockLocator GetLocator(const CBlockIndex *pindex = nullptr) const; /** Find the last common block between this chain and a block index entry. */ const CBlockIndex *FindFork(const CBlockIndex *pindex) const; /** Find the earliest block with timestamp equal or greater than the given. */ CBlockIndex* FindEarliestAtLeast(int64_t nTime) const; }; #endif // BITCOIN_CHAIN_H
{ "content_hash": "6157fe5ba2a72351a8cf5c5754078055", "timestamp": "", "source": "github", "line_count": 494, "max_line_length": 165, "avg_line_length": 32.19433198380567, "alnum_prop": 0.6200955734406438, "repo_name": "randy-waterhouse/bitcoin", "id": "8e6ac8d821377c6e624dadc16b3400476f63b20a", "size": "15904", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/chain.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "28453" }, { "name": "C", "bytes": "682915" }, { "name": "C++", "bytes": "5817343" }, { "name": "HTML", "bytes": "21860" }, { "name": "Java", "bytes": "30290" }, { "name": "M4", "bytes": "196424" }, { "name": "Makefile", "bytes": "115481" }, { "name": "Objective-C", "bytes": "148160" }, { "name": "Objective-C++", "bytes": "6614" }, { "name": "Python", "bytes": "1378668" }, { "name": "QMake", "bytes": "756" }, { "name": "Shell", "bytes": "84491" } ], "symlink_target": "" }
package com.bean.simplenews.module.news.presenter; import android.os.Handler; import android.util.Log; import com.bean.simplenews.common.Constants; import com.bean.simplenews.module.news.model.bean.NewsDetailBean; import com.bean.simplenews.common.base.BasePresenter; import com.bean.simplenews.module.news.model.NewsDetailHelper; import com.bean.simplenews.module.news.view.NewsDetailView; import com.bean.simplenews.util.ToastUtils; import java.util.Iterator; public class NewsDetailPresenter extends BasePresenter<NewsDetailView> implements NewsDetailPresenterBiz, NewsDetailHelper.OnLoadNewsDetailListener { public NewsDetailPresenter(NewsDetailView NewsDetailView) { onInitial(NewsDetailView); } @Override public void onInitial(NewsDetailView view) { super.onInitial(view); } @Override public void loadNewsDetail(final String docId) { obtainView().showProgress(); NewsDetailHelper.getInstance().loadNewsDetail(docId,this); } @Override public void onSuccess(NewsDetailBean newsDetailBean) { new Handler().postDelayed(new Runnable() { @Override public void run() { if (obtainView() != null){ obtainView().hideProgress(); } } },2000); if(newsDetailBean != null) { obtainView().showNewsDetailContent(parse(newsDetailBean)); } } @Override public void onFailure(Throwable t) { obtainView().hideProgress(); obtainView().showFailContent(); } private String parse(NewsDetailBean newsDetailBean) { String body = newsDetailBean.getBody(); Iterator iterator = newsDetailBean.getImg().iterator(); while ( iterator.hasNext()) { NewsDetailBean.Image img = (NewsDetailBean.Image) iterator.next(); String ref = img.getRef(); String src = img.getSrc(); body = body.replace(ref,"<br/><img width=100% src=\"" + src + "\"/><br/>"); } return Constants.prefix + "<h3>" + newsDetailBean.getTitle() + "<br/>" + body + Constants.suffix; } }
{ "content_hash": "f70fb54116b01437b1a86612e5f3d927", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 149, "avg_line_length": 33.78125, "alnum_prop": 0.6581868640148011, "repo_name": "binzhihao/Reader", "id": "41f38a8b4f281b0f99dd4a2990a4d4a5cb32d3d9", "size": "2162", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/bean/simplenews/module/news/presenter/NewsDetailPresenter.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "81877" } ], "symlink_target": "" }
package dynamodb import ( "context" "fmt" "strings" "github.com/Clever/wag/samples/v8/gen-go-db-only/db" "github.com/Clever/wag/samples/v8/gen-go-db-only/models" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" "github.com/go-openapi/strfmt" ) var _ = strfmt.DateTime{} // TeacherSharingRuleTable represents the user-configurable properties of the TeacherSharingRule table. type TeacherSharingRuleTable struct { DynamoDBAPI dynamodbiface.DynamoDBAPI Prefix string TableName string ReadCapacityUnits int64 WriteCapacityUnits int64 } // ddbTeacherSharingRulePrimaryKey represents the primary key of a TeacherSharingRule in DynamoDB. type ddbTeacherSharingRulePrimaryKey struct { Teacher string `dynamodbav:"teacher"` SchoolApp string `dynamodbav:"school_app"` } // ddbTeacherSharingRuleGSIDistrictSchoolTeacherApp represents the district_school_teacher_app GSI. type ddbTeacherSharingRuleGSIDistrictSchoolTeacherApp struct { District string `dynamodbav:"district"` SchoolTeacherApp string `dynamodbav:"school_teacher_app"` } // ddbTeacherSharingRule represents a TeacherSharingRule as stored in DynamoDB. type ddbTeacherSharingRule struct { models.TeacherSharingRule } func (t TeacherSharingRuleTable) name() string { if t.TableName != "" { return t.TableName } return fmt.Sprintf("%s-teacher-sharing-rules", t.Prefix) } func (t TeacherSharingRuleTable) create(ctx context.Context) error { if _, err := t.DynamoDBAPI.CreateTableWithContext(ctx, &dynamodb.CreateTableInput{ AttributeDefinitions: []*dynamodb.AttributeDefinition{ { AttributeName: aws.String("district"), AttributeType: aws.String("S"), }, { AttributeName: aws.String("school_app"), AttributeType: aws.String("S"), }, { AttributeName: aws.String("school_teacher_app"), AttributeType: aws.String("S"), }, { AttributeName: aws.String("teacher"), AttributeType: aws.String("S"), }, }, KeySchema: []*dynamodb.KeySchemaElement{ { AttributeName: aws.String("teacher"), KeyType: aws.String(dynamodb.KeyTypeHash), }, { AttributeName: aws.String("school_app"), KeyType: aws.String(dynamodb.KeyTypeRange), }, }, GlobalSecondaryIndexes: []*dynamodb.GlobalSecondaryIndex{ { IndexName: aws.String("district_school_teacher_app"), Projection: &dynamodb.Projection{ ProjectionType: aws.String("KEYS_ONLY"), }, KeySchema: []*dynamodb.KeySchemaElement{ { AttributeName: aws.String("district"), KeyType: aws.String(dynamodb.KeyTypeHash), }, { AttributeName: aws.String("school_teacher_app"), KeyType: aws.String(dynamodb.KeyTypeRange), }, }, ProvisionedThroughput: &dynamodb.ProvisionedThroughput{ ReadCapacityUnits: aws.Int64(t.ReadCapacityUnits), WriteCapacityUnits: aws.Int64(t.WriteCapacityUnits), }, }, }, ProvisionedThroughput: &dynamodb.ProvisionedThroughput{ ReadCapacityUnits: aws.Int64(t.ReadCapacityUnits), WriteCapacityUnits: aws.Int64(t.WriteCapacityUnits), }, TableName: aws.String(t.name()), }); err != nil { return err } return nil } func (t TeacherSharingRuleTable) saveTeacherSharingRule(ctx context.Context, m models.TeacherSharingRule) error { data, err := encodeTeacherSharingRule(m) if err != nil { return err } _, err = t.DynamoDBAPI.PutItemWithContext(ctx, &dynamodb.PutItemInput{ TableName: aws.String(t.name()), Item: data, }) return err } func (t TeacherSharingRuleTable) getTeacherSharingRule(ctx context.Context, teacher string, school string, app string) (*models.TeacherSharingRule, error) { key, err := dynamodbattribute.MarshalMap(ddbTeacherSharingRulePrimaryKey{ Teacher: teacher, SchoolApp: fmt.Sprintf("%s_%s", school, app), }) if err != nil { return nil, err } res, err := t.DynamoDBAPI.GetItemWithContext(ctx, &dynamodb.GetItemInput{ Key: key, TableName: aws.String(t.name()), ConsistentRead: aws.Bool(true), }) if err != nil { return nil, err } if len(res.Item) == 0 { return nil, db.ErrTeacherSharingRuleNotFound{ Teacher: teacher, School: school, App: app, } } var m models.TeacherSharingRule if err := decodeTeacherSharingRule(res.Item, &m); err != nil { return nil, err } return &m, nil } func (t TeacherSharingRuleTable) scanTeacherSharingRules(ctx context.Context, input db.ScanTeacherSharingRulesInput, fn func(m *models.TeacherSharingRule, lastTeacherSharingRule bool) bool) error { scanInput := &dynamodb.ScanInput{ TableName: aws.String(t.name()), ConsistentRead: aws.Bool(!input.DisableConsistentRead), Limit: input.Limit, } if input.StartingAfter != nil { exclusiveStartKey, err := dynamodbattribute.MarshalMap(input.StartingAfter) if err != nil { return fmt.Errorf("error encoding exclusive start key for scan: %s", err.Error()) } // must provide only the fields constituting the index scanInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{ "teacher": exclusiveStartKey["teacher"], "school_app": &dynamodb.AttributeValue{ S: aws.String(fmt.Sprintf("%s_%s", input.StartingAfter.School, input.StartingAfter.App)), }, } } totalRecordsProcessed := int64(0) var innerErr error err := t.DynamoDBAPI.ScanPagesWithContext(ctx, scanInput, func(out *dynamodb.ScanOutput, lastPage bool) bool { items, err := decodeTeacherSharingRules(out.Items) if err != nil { innerErr = fmt.Errorf("error decoding %s", err.Error()) return false } for i := range items { if input.Limiter != nil { if err := input.Limiter.Wait(ctx); err != nil { innerErr = err return false } } isLastModel := lastPage && i == len(items)-1 if shouldContinue := fn(&items[i], isLastModel); !shouldContinue { return false } totalRecordsProcessed++ // if the Limit of records have been passed to fn, don't pass anymore records. if input.Limit != nil && totalRecordsProcessed == *input.Limit { return false } } return true }) if innerErr != nil { return innerErr } return err } func (t TeacherSharingRuleTable) getTeacherSharingRulesByTeacherAndSchoolAppParseFilters(queryInput *dynamodb.QueryInput, input db.GetTeacherSharingRulesByTeacherAndSchoolAppInput) { for _, filterValue := range input.FilterValues { switch filterValue.AttributeName { case db.TeacherSharingRuleDistrict: queryInput.ExpressionAttributeNames["#DISTRICT"] = aws.String(string(db.TeacherSharingRuleDistrict)) for i, attributeValue := range filterValue.AttributeValues { queryInput.ExpressionAttributeValues[fmt.Sprintf(":%s_value%d", string(db.TeacherSharingRuleDistrict), i)] = &dynamodb.AttributeValue{ S: aws.String(attributeValue.(string)), } } } } } func (t TeacherSharingRuleTable) getTeacherSharingRulesByTeacherAndSchoolApp(ctx context.Context, input db.GetTeacherSharingRulesByTeacherAndSchoolAppInput, fn func(m *models.TeacherSharingRule, lastTeacherSharingRule bool) bool) error { if input.StartingAt != nil && input.StartingAfter != nil { return fmt.Errorf("Can specify only one of StartingAt or StartingAfter") } if input.Teacher == "" { return fmt.Errorf("Hash key input.Teacher cannot be empty") } queryInput := &dynamodb.QueryInput{ TableName: aws.String(t.name()), ExpressionAttributeNames: map[string]*string{ "#TEACHER": aws.String("teacher"), }, ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{ ":teacher": &dynamodb.AttributeValue{ S: aws.String(input.Teacher), }, }, ScanIndexForward: aws.Bool(!input.Descending), ConsistentRead: aws.Bool(!input.DisableConsistentRead), } if input.Limit != nil { queryInput.Limit = input.Limit } if input.StartingAt == nil { queryInput.KeyConditionExpression = aws.String("#TEACHER = :teacher") } else { queryInput.ExpressionAttributeNames["#SCHOOL_APP"] = aws.String("school_app") queryInput.ExpressionAttributeValues[":schoolApp"] = &dynamodb.AttributeValue{ S: aws.String(fmt.Sprintf("%s_%s", input.StartingAt.School, input.StartingAt.App)), } if input.Descending { queryInput.KeyConditionExpression = aws.String("#TEACHER = :teacher AND #SCHOOL_APP <= :schoolApp") } else { queryInput.KeyConditionExpression = aws.String("#TEACHER = :teacher AND #SCHOOL_APP >= :schoolApp") } } if input.StartingAfter != nil { queryInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{ "school_app": &dynamodb.AttributeValue{ S: aws.String(fmt.Sprintf("%s_%s", input.StartingAfter.School, input.StartingAfter.App)), }, "teacher": &dynamodb.AttributeValue{ S: aws.String(input.StartingAfter.Teacher), }, } } if len(input.FilterValues) > 0 && input.FilterExpression != "" { t.getTeacherSharingRulesByTeacherAndSchoolAppParseFilters(queryInput, input) queryInput.FilterExpression = aws.String(input.FilterExpression) } totalRecordsProcessed := int64(0) var pageFnErr error pageFn := func(queryOutput *dynamodb.QueryOutput, lastPage bool) bool { // Only assume an empty page means no more results if there are no filters applied if (len(input.FilterValues) == 0 || input.FilterExpression == "") && len(queryOutput.Items) == 0 { return false } items, err := decodeTeacherSharingRules(queryOutput.Items) if err != nil { pageFnErr = err return false } hasMore := true for i := range items { if lastPage == true { hasMore = i < len(items)-1 } if !fn(&items[i], !hasMore) { return false } totalRecordsProcessed++ // if the Limit of records have been passed to fn, don't pass anymore records. if input.Limit != nil && totalRecordsProcessed == *input.Limit { return false } } return true } err := t.DynamoDBAPI.QueryPagesWithContext(ctx, queryInput, pageFn) if err != nil { return err } if pageFnErr != nil { return pageFnErr } return nil } func (t TeacherSharingRuleTable) deleteTeacherSharingRule(ctx context.Context, teacher string, school string, app string) error { key, err := dynamodbattribute.MarshalMap(ddbTeacherSharingRulePrimaryKey{ Teacher: teacher, SchoolApp: fmt.Sprintf("%s_%s", school, app), }) if err != nil { return err } _, err = t.DynamoDBAPI.DeleteItemWithContext(ctx, &dynamodb.DeleteItemInput{ Key: key, TableName: aws.String(t.name()), }) if err != nil { return err } return nil } func (t TeacherSharingRuleTable) getTeacherSharingRulesByDistrictAndSchoolTeacherApp(ctx context.Context, input db.GetTeacherSharingRulesByDistrictAndSchoolTeacherAppInput, fn func(m *models.TeacherSharingRule, lastTeacherSharingRule bool) bool) error { if input.StartingAt != nil && input.StartingAfter != nil { return fmt.Errorf("Can specify only one of input.StartingAt or input.StartingAfter") } if input.District == "" { return fmt.Errorf("Hash key input.District cannot be empty") } queryInput := &dynamodb.QueryInput{ TableName: aws.String(t.name()), IndexName: aws.String("district_school_teacher_app"), ExpressionAttributeNames: map[string]*string{ "#DISTRICT": aws.String("district"), }, ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{ ":district": &dynamodb.AttributeValue{ S: aws.String(input.District), }, }, ScanIndexForward: aws.Bool(!input.Descending), ConsistentRead: aws.Bool(false), } if input.Limit != nil { queryInput.Limit = input.Limit } if input.StartingAt == nil { queryInput.KeyConditionExpression = aws.String("#DISTRICT = :district") } else { queryInput.ExpressionAttributeNames["#SCHOOL_TEACHER_APP"] = aws.String("school_teacher_app") queryInput.ExpressionAttributeValues[":schoolTeacherApp"] = &dynamodb.AttributeValue{ S: aws.String(fmt.Sprintf("%s_%s_%s", input.StartingAt.School, input.StartingAt.Teacher, input.StartingAt.App)), } if input.Descending { queryInput.KeyConditionExpression = aws.String("#DISTRICT = :district AND #SCHOOL_TEACHER_APP <= :schoolTeacherApp") } else { queryInput.KeyConditionExpression = aws.String("#DISTRICT = :district AND #SCHOOL_TEACHER_APP >= :schoolTeacherApp") } } if input.StartingAfter != nil { queryInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{ "school_teacher_app": &dynamodb.AttributeValue{ S: aws.String(fmt.Sprintf("%s_%s_%s", input.StartingAfter.School, input.StartingAfter.Teacher, input.StartingAfter.App)), }, "district": &dynamodb.AttributeValue{ S: aws.String(input.StartingAfter.District), }, "school_app": &dynamodb.AttributeValue{ S: aws.String(fmt.Sprintf("%s_%s", input.StartingAfter.School, input.StartingAfter.App)), }, "teacher": &dynamodb.AttributeValue{ S: aws.String(input.StartingAfter.Teacher), }, } } totalRecordsProcessed := int64(0) var pageFnErr error pageFn := func(queryOutput *dynamodb.QueryOutput, lastPage bool) bool { if len(queryOutput.Items) == 0 { return false } items, err := decodeTeacherSharingRules(queryOutput.Items) if err != nil { pageFnErr = err return false } hasMore := true for i := range items { if lastPage == true { hasMore = i < len(items)-1 } if !fn(&items[i], !hasMore) { return false } totalRecordsProcessed++ // if the Limit of records have been passed to fn, don't pass anymore records. if input.Limit != nil && totalRecordsProcessed == *input.Limit { return false } } return true } err := t.DynamoDBAPI.QueryPagesWithContext(ctx, queryInput, pageFn) if err != nil { return err } if pageFnErr != nil { return pageFnErr } return nil } func (t TeacherSharingRuleTable) scanTeacherSharingRulesByDistrictAndSchoolTeacherApp(ctx context.Context, input db.ScanTeacherSharingRulesByDistrictAndSchoolTeacherAppInput, fn func(m *models.TeacherSharingRule, lastTeacherSharingRule bool) bool) error { scanInput := &dynamodb.ScanInput{ TableName: aws.String(t.name()), ConsistentRead: aws.Bool(!input.DisableConsistentRead), Limit: input.Limit, IndexName: aws.String("district_school_teacher_app"), } if input.StartingAfter != nil { exclusiveStartKey, err := dynamodbattribute.MarshalMap(input.StartingAfter) if err != nil { return fmt.Errorf("error encoding exclusive start key for scan: %s", err.Error()) } // must provide the fields constituting the index and the primary key // https://stackoverflow.com/questions/40988397/dynamodb-pagination-with-withexclusivestartkey-on-a-global-secondary-index scanInput.ExclusiveStartKey = map[string]*dynamodb.AttributeValue{ "teacher": exclusiveStartKey["teacher"], "school_app": &dynamodb.AttributeValue{ S: aws.String(fmt.Sprintf("%s_%s", input.StartingAfter.School, input.StartingAfter.App)), }, "district": exclusiveStartKey["district"], "school_teacher_app": &dynamodb.AttributeValue{ S: aws.String(fmt.Sprintf("%s_%s_%s", input.StartingAfter.School, input.StartingAfter.Teacher, input.StartingAfter.App)), }, } } totalRecordsProcessed := int64(0) var innerErr error err := t.DynamoDBAPI.ScanPagesWithContext(ctx, scanInput, func(out *dynamodb.ScanOutput, lastPage bool) bool { items, err := decodeTeacherSharingRules(out.Items) if err != nil { innerErr = fmt.Errorf("error decoding %s", err.Error()) return false } for i := range items { if input.Limiter != nil { if err := input.Limiter.Wait(ctx); err != nil { innerErr = err return false } } isLastModel := lastPage && i == len(items)-1 if shouldContinue := fn(&items[i], isLastModel); !shouldContinue { return false } totalRecordsProcessed++ // if the Limit of records have been passed to fn, don't pass anymore records. if input.Limit != nil && totalRecordsProcessed == *input.Limit { return false } } return true }) if innerErr != nil { return innerErr } return err } // encodeTeacherSharingRule encodes a TeacherSharingRule as a DynamoDB map of attribute values. func encodeTeacherSharingRule(m models.TeacherSharingRule) (map[string]*dynamodb.AttributeValue, error) { val, err := dynamodbattribute.MarshalMap(ddbTeacherSharingRule{ TeacherSharingRule: m, }) if err != nil { return nil, err } // make sure composite attributes don't contain separator characters if strings.Contains(m.App, "_") { return nil, fmt.Errorf("app cannot contain '_': %s", m.App) } if strings.Contains(m.School, "_") { return nil, fmt.Errorf("school cannot contain '_': %s", m.School) } if strings.Contains(m.Teacher, "_") { return nil, fmt.Errorf("teacher cannot contain '_': %s", m.Teacher) } // add in composite attributes primaryKey, err := dynamodbattribute.MarshalMap(ddbTeacherSharingRulePrimaryKey{ Teacher: m.Teacher, SchoolApp: fmt.Sprintf("%s_%s", m.School, m.App), }) if err != nil { return nil, err } for k, v := range primaryKey { val[k] = v } districtSchoolTeacherApp, err := dynamodbattribute.MarshalMap(ddbTeacherSharingRuleGSIDistrictSchoolTeacherApp{ District: m.District, SchoolTeacherApp: fmt.Sprintf("%s_%s_%s", m.School, m.Teacher, m.App), }) if err != nil { return nil, err } for k, v := range districtSchoolTeacherApp { val[k] = v } return val, err } // decodeTeacherSharingRule translates a TeacherSharingRule stored in DynamoDB to a TeacherSharingRule struct. func decodeTeacherSharingRule(m map[string]*dynamodb.AttributeValue, out *models.TeacherSharingRule) error { var ddbTeacherSharingRule ddbTeacherSharingRule if err := dynamodbattribute.UnmarshalMap(m, &ddbTeacherSharingRule); err != nil { return err } *out = ddbTeacherSharingRule.TeacherSharingRule // parse composite attributes from projected secondary indexes and fill // in model properties if v, ok := m["school_teacher_app"]; ok && v.S != nil { parts := strings.Split(*v.S, "_") if len(parts) != 3 { return fmt.Errorf("expected 3 parts: '%s'", *v.S) } out.School = parts[0] out.Teacher = parts[1] out.App = parts[2] } return nil } // decodeTeacherSharingRules translates a list of TeacherSharingRules stored in DynamoDB to a slice of TeacherSharingRule structs. func decodeTeacherSharingRules(ms []map[string]*dynamodb.AttributeValue) ([]models.TeacherSharingRule, error) { teacherSharingRules := make([]models.TeacherSharingRule, len(ms)) for i, m := range ms { var teacherSharingRule models.TeacherSharingRule if err := decodeTeacherSharingRule(m, &teacherSharingRule); err != nil { return nil, err } teacherSharingRules[i] = teacherSharingRule } return teacherSharingRules, nil }
{ "content_hash": "ab858f45c34e74d60a982a9a03f8897d", "timestamp": "", "source": "github", "line_count": 560, "max_line_length": 255, "avg_line_length": 33.5375, "alnum_prop": 0.7158830733187797, "repo_name": "Clever/wag", "id": "599004083fb926b0d4d80a41c1abfc3b4c33bf71", "size": "18781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/gen-go-db-only/db/dynamodb/teachersharingrule.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "138" }, { "name": "Go", "bytes": "231712" }, { "name": "Makefile", "bytes": "12255" }, { "name": "Shell", "bytes": "704" } ], "symlink_target": "" }
/* Warning: This CSS file has been auto-generated from a .less file. If you edit it your edits will be lost the next time LessCSS is run. It would be best to make a separate CSS file and place any overriding CSS in there. If you must access the original CSS, do so by editing the .less files. */ /* global settings */ *, *:after, *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } body { margin: 0px; } /* grid */ .grid { width: 100%; } .upage-content > .grid { max-width: none; margin-left: auto; margin-right: auto; } /* gutter around whole design */ /* .upage-content > .grid-pad { padding: @gutter @gutter 0px @gutter; } */ /* column */ .urow:not(.cright) > .col { float: left; } .urow.cright > .col { float: right; } .col { position: relative; min-height: 1px; } .content-area { position: relative; } /* row */ .urow { clear: both; position: relative; } form.urow { margin-bottom: 0px; } .widget { position: relative; } /* for widgets and the like <div class="table-thing widget"> <div class="narrow-control w85"> my width is set </div> <div class="wide-control"> my width is 100%, minus the set width of the narrow-control</div> </div> .w85 { width:85px; } */ .vertical-col > *, .vertical-col > .table-thing, .vertical-col > .afScrollPanel > .table-thing, .wrapping-col > .no_wrap.table-thing, .wrapping-col > .afScrollPanel > .no_wrap.table-thing { width: 100%; } #afui .vertical-col > .afScrollPanel > .widget, #afui .vertical-col > .widget, .vertical-col > .widget { width: calc(100% - 10px); margin-left: 5px; } .col > .vertical-col > .widget { width: 100%; margin-left: 0; } .table-thing { display: table; } .wide-control { display: table-cell; width: 100%; } .narrow-control { display: table-cell; } /* wrapping column */ .wrapping-col.right > *, .wrapping-col.right > .afScrollPanel > * { float: right; } /* margin: 0 5px; move margin to another class */ .wrapping-col.left > *, .wrapping-col.left > .afScrollPanel > * { float: left; } /* center and right alignment */ .vertical-col.center { text-align: center; } .vertical-col.right { text-align: right; } .vertical-col.right > *, .col > .vertical-col.right > .widget, .vertical-col.right > .afScrollPanel > * { margin-left: auto; } .vertical-col.center > *, .col > .vertical-col.center > .widget, .vertical-col.center > .afScrollPanel > * { margin-left: auto; margin-right: auto; } .wrapping-col:not(.horiz-area) > .no_wrap, .wrapping-col:not(.horiz-area) > .afScrollPanel > .no_wrap { float: none; clear: both; /* margin: 8px 0px; */ } .center-h-v-col > .widget { position: absolute !important; left: 50%; top: 50%; transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); margin-top: 0 !important; } /* shim */ .uib_shim { clear: both; float: none !important; width: 100%; position: relative; height: 0px; line-height: 0px; font-size: 0px; display: block; } /* content-box fix for box-sizing */ .content-box, .content-box:before, .content-box:after { -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; } /* page */ .hidden:not(.afPopup) { display: none; } .upage-content, .upage-outer { position: relative; } html, body { height: 100%; } body:not(#afui) .upage, body:not(#afui) .upage-content { height: 100%; } body:not(#afui) .upage-outer { height: auto; } /* position relative works fine. but fixed can be elected as well */ /* .upage-content, .upage-outer { position: fixed; height:100%; } */ .upage { overflow-x: hidden; } .upage-content { z-index: 1; } #afui .upage { padding: 0; } /* sidebars and crossbars */ .uib_sidebar { position: fixed; height: 100%; top: 0px; } .uib_crossbar { position: fixed; width: 100%; left: 0px; } .leftbar, .rightbar { z-index: 2; } .reveal.leftbar { left: 0px; z-index: 0; } .reveal.rightbar { right: 0px; z-index: 0; } .leftbar.oh, .rightbar.oh { z-index: 3; } .reveal { z-index: 0; visibility: hidden; } .topbar { z-index: 3; } .topbar.reveal { top: 0px; z-index: 0; } .botbar { z-index: 3; position: fixed; } .botbar.oh, .topbar.oh { z-index: 4; } .sidebar-content { height: 100%; overflow-y: auto; position: relative; margin: 0; } .sidebar-thumb { position: relative; margin: 0; /* background-image:url('images/gripper.png'); */ } .template { display: none !important; } .uib-absolute { position: absolute !important; } .uib-grid { display: -webkit-flex; display: -moz-flex; display: -ms-flexbox; display: -o-flex; display: flex; -webkit-flex-direction: column; -moz-flex-direction: column; -ms-flex-direction: column; -o-flex-direction: column; flex-direction: column; } .uib-grid > .uib-grid-row { display: -webkit-flex; display: -moz-flex; display: -ms-flexbox; display: -o-flex; display: flex; -webkit-flex: 1; -moz-flex: 1; -ms-flex: 1; -o-flex: 1; flex: 1; } .uib-grid > .uib-grid-row > .uib-grid-cell { -webkit-flex: 1; -moz-flex: 1; -ms-flex: 1; -o-flex: 1; flex: 1; display: -webkit-flex; display: -moz-flex; display: -ms-flexbox; display: -o-flex; display: flex; } .uib-grid > .uib-grid-row > .uib-grid-cell > * { -webkit-flex: 1; -moz-flex: 1; -ms-flex: 1; -o-flex: 1; flex: 1; margin: 0 !important; height: auto !important; } .uib-grid > .uib-grid-row > .uib-grid-cell > .button, .uib-grid > .uib-grid-row > .uib-grid-cell > [data-role="button"] { padding: 0 !important; display: -webkit-flex !important; display: -moz-flex !important; display: -ms-flexbox !important; display: -o-flex !important; display: flex !important; -webkit-align-items: center; -moz-align-items: center; -ms-align-items: center; -o-align-items: center; align-items: center; -webkit-justify-content: center; -moz-justify-content: center; -ms-justify-content: center; -o-justify-content: center; justify-content: center; } .uib-grid > .uib-grid-row > .uib-grid-cell > .table-thing { display: -webkit-flex; display: -moz-flex; display: -ms-flexbox; display: -o-flex; display: flex; } .uib-grid > .uib-grid-row > .uib-grid-cell > .table-thing > label.narrow-control { display: none; } .uib-grid > .uib-grid-row > .uib-grid-cell > .table-thing > label.narrow-control + .wide-control { -webkit-flex: 1; -moz-flex: 1; -ms-flex: 1; -o-flex: 1; flex: 1; height: auto !important; } .uib-grid > .uib-grid-row:first-child > .uib-grid-cell > *, .uib-grid > .uib-grid-row:first-child > .uib-grid-cell .wide-control { border-bottom-left-radius: 0 !important; border-bottom-right-radius: 0 !important; } .uib-grid > .uib-grid-row:first-child > .uib-grid-cell:not(:first-child) > *, .uib-grid > .uib-grid-row:first-child > .uib-grid-cell:not(:first-child) .wide-control { border-top-left-radius: 0 !important; } .uib-grid > .uib-grid-row:first-child > .uib-grid-cell:not(:last-child) > *, .uib-grid > .uib-grid-row:first-child > .uib-grid-cell:not(:last-child) .wide-control { border-top-right-radius: 0 !important; } .uib-grid > .uib-grid-row:not(:first-child):not(:last-child) > .uib-grid-cell > *, .uib-grid > .uib-grid-row:not(:first-child):not(:last-child) > .uib-grid-cell .wide-control { border-radius: 0 !important; } .uib-grid > .uib-grid-row:last-child > .uib-grid-cell > *, .uib-grid > .uib-grid-row:last-child > .uib-grid-cell .wide-control { border-top-left-radius: 0 !important; border-top-right-radius: 0 !important; } .uib-grid > .uib-grid-row:last-child > .uib-grid-cell:not(:first-child) > *, .uib-grid > .uib-grid-row:last-child > .uib-grid-cell:not(:first-child) .wide-control { border-bottom-left-radius: 0 !important; } .uib-grid > .uib-grid-row:last-child > .uib-grid-cell:not(:last-child) > *, .uib-grid > .uib-grid-row:last-child > .uib-grid-cell:not(:last-child) .wide-control { border-bottom-right-radius: 0 !important; } @media all { .grid-text, .grid-text * { font-size: 4vmax !important; } .grid-text, .grid-text * { font-size: 4vmax !important; } } @media all { .grid-height { height: 20vh; } } @media all { .wrapping-col > .d-margins, .wrapping-col > .afScrollPanel > .d-margins { margin-left: 3px; margin-right: 4px; } .wrapping-col > .d-margins, .wrapping-col > .afScrollPanel > .d-margins { margin-left: 3px; margin-right: 4px; } .d-margins { margin-top: 5px; margin-bottom: 6px; } } .figure-align { display: table; margin: 0px auto; } .figure-align img { width: 100%; } .image-cell { display: table-cell; vertical-align: middle; } @media all { .scale-image img { width: 100%; height: 100%; } } .left-receptacle { float: left; } .right-receptacle { float: right; } .button-icon-top { display: block; margin: auto; } .button-icon-bottom { display: block; margin: auto; } .button-icon-left { float: left; } .button-icon-right { float: right; } @media all { .hello-class p { color: #1525cf; text-decoration: underline; text-align: center; } } @media all { .default-sprite-button div.uib-sprite { background-image: url(../images/Arrow.png); background-size: cover; background-repeat: no-repeat; } } @media all { .hover-sprite-button:hover div.uib-sprite { background-image: url(../images/Arrow.png); background-size: cover; background-repeat: no-repeat; } } @media all { .active-sprite-button:active div.uib-sprite { background-image: url(../images/Arrow.png); background-size: cover; background-repeat: no-repeat; } } @media all { .sprite-sizing { height: 100% !important; width: 100% !important; -webkit-flex: 0 0 auto !important; -moz-flex: 0 0 auto !important; -ms-flex: 0 0 auto !important; -o-flex: 0 0 auto !important; flex: 0 0 auto !important; } } .allow-badge > .badge.glyphicon { display: inline-block; } .list-group .d-margins { margin: 0; } .align-widget { margin: 5px 0 !important; } .full-width-widget { width: 100%; } .inline-widget { display: inline-block; } label { width: auto; float: none; } label + *:not(div.inline-widget) { width: 100% !important; margin-bottom: 0 !important; } label:empty { display: none; } .label-inline { vertical-align: middle; } .label-top-left, .label-top-right { display: block; padding: 0; margin: 0; } .label-top-left + *, .label-top-right + * { display: block; } .label-top-left { text-align: left; } .label-top-right { text-align: right; } .tail-c { display: table-cell; width: 15px; } @media all { } @media all { } /* .test-test > .narrow-control - affects control label .test-test > textarea - affects textarea */ @media all and (min-width: 360px) { .row-height-1 > .col > .content-area { min-height: 184px; } } @media all { .grid-pad { padding-top: 10px; padding-bottom: 10px; padding-left: 20px; padding-right: 20px; } } .uib-card { position: relative; margin: 0px; box-sizing: border-box; } .card-header, .card-left, .card-footer, .card-right { position: absolute; box-sizing: border-box; padding: 0px; margin: 0px; } .card-header { top: 0px; left: 0px; right: 0px; } .card-footer { bottom: 0px; left: 0px; right: 0px; } .card-left { top: 0px; left: 0px; bottom: 0px; } .card-right { top: 0px; right: 0px; bottom: 0px; } .uib-card section .widget-divider:only-of-type { position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; height: auto !important; width: auto !important; } .uib-card .widget-divider:only-of-type div { height: 100%; } @media all { .section-dimension-13 .card-header { height: 40px; } .section-dimension-13 .card-footer { height: 40px; } .section-dimension-13 .card-left { width: 50px; } .section-dimension-13 .card-right { width: 50px; } .section-dimension-13 { min-height: 100px; } div.section-dimension-13.header-on-left .card-left { top: 40px; } div.section-dimension-13.header-on-left .card-header { left: 0px; } div.section-dimension-13.left-on-header .card-left { top: 0px; } div.section-dimension-13.left-on-header .card-header { left: 50px; } div.section-dimension-13.header-on-right .card-right { top: 40px; } div.section-dimension-13.header-on-right .card-header { right: 0px; } div.section-dimension-13.right-on-header .card-right { top: 0px; } div.section-dimension-13.right-on-header .card-header { right: 50px; } div.section-dimension-13.footer-on-left .card-left { bottom: 40px; } div.section-dimension-13.footer-on-left .card-footer { left: 0px; } div.section-dimension-13.left-on-footer .card-left { bottom: 0px; } div.section-dimension-13.left-on-footer .card-footer { left: 50px; } div.section-dimension-13.footer-on-right .card-right { bottom: 40px; } div.section-dimension-13.footer-on-right .card-footer { right: 0px; } div.section-dimension-13.right-on-footer .card-right { bottom: 0px; } div.section-dimension-13.right-on-footer .card-footer { right: 50px; } .section-dimension-13.cpad-1 { padding: 40px 0px 0px 0px; } .section-dimension-13.cpad-1 > .widget-divider:only-of-type { position: absolute; top: 40px; right: 0px; bottom: 0px; left: 0px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-8 { padding: 0px 50px 0px 0px; } .section-dimension-13.cpad-8 > .widget-divider:only-of-type { position: absolute; top: 0px; right: 50px; bottom: 0px; left: 0px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-9 { padding: 40px 50px 0px 0px; } .section-dimension-13.cpad-9 > .widget-divider:only-of-type { position: absolute; top: 40px; right: 50px; bottom: 0px; left: 0px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-4 { padding: 0px 0px 40px 0px; } .section-dimension-13.cpad-4 > .widget-divider:only-of-type { position: absolute; top: 0px; right: 0px; bottom: 40px; left: 0px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-5 { padding: 40px 0px 40px 0px; } .section-dimension-13.cpad-5 > .widget-divider:only-of-type { position: absolute; top: 40px; right: 0px; bottom: 40px; left: 0px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-12 { padding: 0px 50px 40px 0px; } .section-dimension-13.cpad-12 > .widget-divider:only-of-type { position: absolute; top: 0px; right: 50px; bottom: 40px; left: 0px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-13 { padding: 40px 50px 40px 0px; } .section-dimension-13.cpad-13 > .widget-divider:only-of-type { position: absolute; top: 40px; right: 50px; bottom: 40px; left: 0px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-2 { padding: 0px 0px 0px 50px; } .section-dimension-13.cpad-2 > .widget-divider:only-of-type { position: absolute; top: 0px; right: 0px; bottom: 0px; left: 50px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-3 { padding: 40px 0px 0px 50px; } .section-dimension-13.cpad-3 > .widget-divider:only-of-type { position: absolute; top: 40px; right: 0px; bottom: 0px; left: 50px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-10 { padding: 0px 50px 0px 50px; } .section-dimension-13.cpad-10 > .widget-divider:only-of-type { position: absolute; top: 0px; right: 50px; bottom: 0px; left: 50px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-11 { padding: 40px 50px 0px 50px; } .section-dimension-13.cpad-11 > .widget-divider:only-of-type { position: absolute; top: 40px; right: 50px; bottom: 0px; left: 50px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-6 { padding: 0px 0px 40px 50px; } .section-dimension-13.cpad-6 > .widget-divider:only-of-type { position: absolute; top: 0px; right: 0px; bottom: 40px; left: 50px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-7 { padding: 40px 0px 40px 50px; } .section-dimension-13.cpad-7 > .widget-divider:only-of-type { position: absolute; top: 40px; right: 0px; bottom: 40px; left: 50px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-14 { padding: 0px 50px 40px 50px; } .section-dimension-13.cpad-14 > .widget-divider:only-of-type { position: absolute; top: 0px; right: 50px; bottom: 40px; left: 50px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-15 { padding: 40px 50px 40px 50px; } .section-dimension-13.cpad-15 > .widget-divider:only-of-type { position: absolute; top: 40px; right: 50px; bottom: 40px; left: 50px; height: auto !important; width: auto !important; } .section-dimension-13.cpad-0 { padding: 0px 0px 0px 0px; } .section-dimension-13.cpad-0 > .widget-divider:only-of-type { position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; height: auto !important; width: auto !important; } }
{ "content_hash": "4b7660a1cf95031c5b014f933d41e599", "timestamp": "", "source": "github", "line_count": 842, "max_line_length": 157, "avg_line_length": 21.100950118764846, "alnum_prop": 0.6349411830922497, "repo_name": "taessina/workshop-client-code", "id": "7934dc38528760101841173471c9e9500a71b7f3", "size": "17767", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "www/css/index_main.less.css", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "53680" }, { "name": "HTML", "bytes": "8207" }, { "name": "JavaScript", "bytes": "27183" } ], "symlink_target": "" }
package com.balonbal.slybot.commands; import com.balonbal.slybot.Main; import com.balonbal.slybot.SlyBot; import com.balonbal.slybot.config.ChannelConfig; import com.balonbal.slybot.lib.Reference; import com.balonbal.slybot.lib.Settings; import org.apache.commons.lang3.StringUtils; import org.pircbotx.Colors; import org.pircbotx.User; import org.pircbotx.hooks.Event; import org.pircbotx.hooks.events.MessageEvent; import org.pircbotx.hooks.events.PrivateMessageEvent; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; public class CommandConfig implements Command { @Override public String getTrigger() { return "CONFIG"; } @Override public int requiresOP() { return Reference.REQUIRES_OP_BOT; } @Override public boolean channelCommand() { return true; } @Override public boolean pmCommand() { return true; } @Override public String[] help() { return new String[] { "Used to set configuration values", "SYNTAX: " + Colors.BOLD + getTrigger() + " <set|load|save> [key] [value]", "Set with no key will return a list of keys + values", "Keys for channel configuration: " + Colors.BOLD + "triggers" + Colors.NORMAL + " (the regex to look for in front of commands) and <command> (see help for a list). Commands can be restricted to different access levels (none, channel, bot, any or all)." }; } @Override public String run(String[] parameters, Event<SlyBot> event) { if (parameters.length < 2) return "false"; if (event instanceof MessageEvent) { /** Do channel configs **/ if (parameters[1].equalsIgnoreCase("set")) { ChannelConfig channelConfig = (ChannelConfig) Main.getConfig().getConfig("config" + ((MessageEvent) event).getChannel().getName()); if (parameters.length < 3) { //List current configs String channelOPpermissions = ""; String botOPpermissions = ""; String anyOPpermissions = ""; String bothOPpermissions = ""; String noPermissions = ""; String triggers = ""; for (String command: channelConfig.getPermissionsMap().keySet()) { switch (channelConfig.getPermission(command)) { case Reference.REQUIRES_OP_NONE: noPermissions += (noPermissions.equals("") ? "" : ", ") + Colors.GREEN + command + Colors.NORMAL; break; case Reference.REQUIRES_OP_ANY: anyOPpermissions += (anyOPpermissions.equals("") ? "" : ", ") + Colors.BLUE + command + Colors.NORMAL; break; case Reference.REQUIRES_OP_CHANNEL: channelOPpermissions += (channelOPpermissions.equals("") ? "" : ", ") + Colors.OLIVE + command + Colors.NORMAL; break; case Reference.REQUIRES_OP_BOT: botOPpermissions +=(botOPpermissions.equals("") ? "" : ", ") + Colors.DARK_BLUE + command +Colors.NORMAL; break; case Reference.REQUIRES_OP_BOTH: bothOPpermissions += (bothOPpermissions.equals("") ? "" : ", ") + Colors.MAGENTA + command + Colors.NORMAL; break; } } triggers = channelConfig.getTriggerString(); event.getBot().reply(event, "Configuration for " + Colors.BOLD + Colors.BLUE + channelConfig.getChannelName() + Colors.NORMAL + ":"); event.getBot().reply(event, "Channel triggers: " + Colors.RED + triggers); event.getBot().reply(event, "User commands (level " + Colors.BOLD + "none" + Colors.NORMAL + "): " + noPermissions); event.getBot().reply(event, "Channel OP commands (level " + Colors.BOLD + "channel" + Colors.NORMAL + "): " + channelOPpermissions); event.getBot().reply(event, "Bot OP commands (level " + Colors.BOLD + "bot" + Colors.NORMAL + "): " + botOPpermissions); event.getBot().reply(event, "Any OP commands (level " + Colors.BOLD + "any" + Colors.NORMAL + "): " + anyOPpermissions); event.getBot().reply(event, "Channel+bot OP commands (level " + Colors.BOLD + "all" + Colors.NORMAL + "): " + bothOPpermissions); } else { switch (parameters[2].toLowerCase()) { case "triggers": channelConfig.setTrigger(StringUtils.join(parameters, " ", 3, parameters.length)); break; default: Command c = Main.getCommandListener().getCommandHandler().getCommand(parameters[2]); if (c != null) { int level = -1; try { level = Integer.parseInt(parameters[3]); //Not a number } catch (NumberFormatException e) { //Try to get the number from a string switch (parameters[3].toLowerCase()) { case "none": level = Reference.REQUIRES_OP_NONE; break; case "channel": level = Reference.REQUIRES_OP_CHANNEL; break; case "bot": level = Reference.REQUIRES_OP_BOT; break; case "any": level = Reference.REQUIRES_OP_ANY; break; case "all": level = Reference.REQUIRES_OP_BOTH; break; default: //No valid input event.getBot().reply(event, "Invalid permissions level, try NONE (-1), ANY (0), CHANNEL (1), BOT (2) or ALL (3)"); return ""; } } //Invalid level if (level < -1 || level > 3) { event.getBot().reply(event, "Invalid permissions level, try NONE (-1), ANY (0), CHANNEL (1), BOT (2) or ALL (3)"); return ""; } //Verify that the user has permission to use the command both before and after updating if (!(Main.getCommandListener().getCommandHandler().hasPermission(event, c.requiresOP()) && Main.getCommandListener().getCommandHandler().hasPermission(event, level))) { event.getBot().reply(event, ((MessageEvent) event).getUser().getNick() + ": You do not have permissions to do that."); } //Update permission channelConfig.setPermission(c.getTrigger(), level); } else { event.getBot().reply(event, "Error, invalid key."); return ""; } } event.getBot().reply(event, "Updated setting"); return ""; } } } else if (event instanceof PrivateMessageEvent) { /** Do bot configs **/ User u = ((PrivateMessageEvent) event).getUser(); String command = parameters[1]; HashMap<String, Object> map = event.getBot().getConfig().getSaveValues(); if (command.equalsIgnoreCase("set")) { //If no key has been specified, return keys and values if (parameters.length < 3) { for (String key : map.keySet()) { String value = ""; switch (key.toLowerCase()) { case Reference.CONFIG_ALIASES: break; //This is a lot of output, so hide it case Reference.CONFIG_BOTPASS: case Reference.CONFIG_NICKPASS: //Hide passwords value = (map.get(key).equals("") ? "Not set" : "Set"); break; default: if (map.get(key) instanceof ArrayList) { ArrayList<String> list = (ArrayList<String>) map.get(key); value = StringUtils.join(list.toArray(new String[list.size()]), ", "); } else { value = map.containsKey(key) ? String.valueOf(map.get(key)) : "Not recognized"; } } //Send the key and value event.getBot().reply(event, String.format(" - %s: %s", key, (value.equals("") ? "Not set" : value))); } return "true"; } else if (parameters.length > 3) { //Verify that it is a valid key String key = parameters[2]; if (map.containsKey(key)) { //Get the value to be set String[] value = new String[parameters.length - 3]; System.arraycopy(parameters, 3, value, 0, value.length); //Get the current value from the map Object currValue = map.get(key); Object newValue = ""; //Aliases can not be changed this way if (key.equalsIgnoreCase(Reference.CONFIG_ALIASES)) return "false"; //Only owners can change ownership if ((key.equalsIgnoreCase(Reference.CONFIG_OWNER) || key.equalsIgnoreCase(Reference.CONFIG_BOTPASS)) && (!Settings.owner.equalsIgnoreCase(u.getNick()) || !u.isVerified())) return "false"; if (currValue instanceof ArrayList) { ArrayList<String> list = new ArrayList<String>(); Collections.addAll(list, value); newValue = list; } else { newValue = StringUtils.join(value, " "); } event.getBot().getConfig().updateSetting(key, newValue); //Change the bot's nickname if (key.equals(Reference.CONFIG_BOTNICK)) event.getBot().updateNick(String.valueOf(newValue)); event.getBot().reply(event, "Successfully updated key: " + key); return "true"; } else { event.getBot().reply(event, "No such key: " + key); } } else { event.getBot().reply(event, "Invalid number of arguments, try again"); } } else if (command.equalsIgnoreCase("load")) { try { Main.getConfig().loadFromFile(Reference.CONFIG_BOTCONFIG_ID); event.getBot().reply(event, "Successfully reloaded bot configuration from file."); return "true"; } catch (FileNotFoundException e) { event.getBot().reply(event, "Could not load config: File not found."); } } else if (command.equalsIgnoreCase("save")) { Main.getConfig().save(Reference.CONFIG_BOTCONFIG_ID); event.getBot().reply(event, "Successfully saved bot configuration to file."); return "true"; } return "false"; } return ""; } }
{ "content_hash": "ebb13d00daddb65a91f81a9d6759ea0f", "timestamp": "", "source": "github", "line_count": 233, "max_line_length": 268, "avg_line_length": 53.407725321888414, "alnum_prop": 0.4766152362584378, "repo_name": "Balonbal/slybot", "id": "9a5091d7b0a5036bd5873d88eb52b612cae0125f", "size": "12444", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/balonbal/slybot/commands/CommandConfig.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Java", "bytes": "185977" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "3ea75971f89171745eb174b6bc083869", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "a8bfb262b09efa567605c62f02a2ee64480eaab0", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Thymelaeaceae/Daphnopsis/Daphnopsis emarginata/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import {parseAndGetStatement} from '../../../utils'; import {expect} from 'chai'; describe('SwitchStatement', () => { it('should return correct type', () => { expect(parseAndGetStatement('switch(0){}').type).to.equal('SwitchStatement'); }); it('should accept expression in parentheses', () => { var statement = parseAndGetStatement('switch ( ( true ) ) {};'); expect(statement.discriminant.type).to.equal('BooleanLiteral'); expect(statement.discriminant.value).to.equal(true); expect(statement.cases).to.deep.equal([]); }); it('should accept single case', () => { var statement = parseAndGetStatement('switch ( true ) { case 1 : x; break; }'); expect(statement.discriminant.type).to.equal('BooleanLiteral'); expect(statement.discriminant.value).to.equal(true); var case1 = statement.cases[0]; expect(case1.test.type).to.equal('NumericLiteral'); expect(case1.test.value).to.equal(1); expect(case1.consequent[0].type).to.equal('ExpressionStatement'); expect(case1.consequent[0].expression.type).to.equal('Identifier'); expect(case1.consequent[0].expression.name).to.equal('x'); expect(case1.consequent[1].type).to.equal('BreakStatement'); }); it('should accept single default', () => { var statement = parseAndGetStatement('switch ( true ) { default: x; break; }'); expect(statement.discriminant.type).to.equal('BooleanLiteral'); expect(statement.discriminant.value).to.equal(true); var case1 = statement.cases[0]; expect(case1.test).to.equal(null); expect(case1.consequent[0].type).to.equal('ExpressionStatement'); expect(case1.consequent[0].expression.type).to.equal('Identifier'); expect(case1.consequent[0].expression.name).to.equal('x'); expect(case1.consequent[1].type).to.equal('BreakStatement'); }); it('should accept case with parentheses', () => { var statement = parseAndGetStatement('switch ( true ) { case ( 1 ) : x; break; }'); expect(statement.discriminant.type).to.equal('BooleanLiteral'); expect(statement.discriminant.value).to.equal(true); var case1 = statement.cases[0]; expect(case1.test.type).to.equal('NumericLiteral'); expect(case1.test.value).to.equal(1); expect(case1.consequent[0].type).to.equal('ExpressionStatement'); expect(case1.consequent[0].expression.type).to.equal('Identifier'); expect(case1.consequent[0].expression.name).to.equal('x'); expect(case1.consequent[1].type).to.equal('BreakStatement'); }); it('should accept single default', () => { var statement = parseAndGetStatement('switch ( true ) { case 1 : x; break; }'); expect(statement.discriminant.type).to.equal('BooleanLiteral'); expect(statement.discriminant.value).to.equal(true); var case1 = statement.cases[0]; expect(case1.test.type).to.equal('NumericLiteral'); expect(case1.test.value).to.equal(1); expect(case1.consequent[0].type).to.equal('ExpressionStatement'); expect(case1.consequent[0].expression.type).to.equal('Identifier'); expect(case1.consequent[0].expression.name).to.equal('x'); expect(case1.consequent[1].type).to.equal('BreakStatement'); }); it('should accept multiple cases', () => { var statement = parseAndGetStatement('switch ( true ) { case 1 : x; break; case 2 : break; }'); expect(statement.discriminant.type).to.equal('BooleanLiteral'); expect(statement.discriminant.value).to.equal(true); var case1 = statement.cases[0]; expect(case1.test.type).to.equal('NumericLiteral'); expect(case1.test.value).to.equal(1); expect(case1.consequent[0].type).to.equal('ExpressionStatement'); expect(case1.consequent[0].expression.type).to.equal('Identifier'); expect(case1.consequent[0].expression.name).to.equal('x'); expect(case1.consequent[1].type).to.equal('BreakStatement'); var case2 = statement.cases[1]; expect(case2.test.type).to.equal('NumericLiteral'); expect(case2.test.value).to.equal(2); expect(case2.consequent[0].type).to.equal('BreakStatement'); }); it('should accept multiple cases with default', () => { var statement = parseAndGetStatement('switch ( true ) { case 1 : x; break; case 2 : break; default: ; }'); expect(statement.discriminant.type).to.equal('BooleanLiteral'); expect(statement.discriminant.value).to.equal(true); var case1 = statement.cases[0]; expect(case1.test.type).to.equal('NumericLiteral'); expect(case1.test.value).to.equal(1); expect(case1.consequent[0].type).to.equal('ExpressionStatement'); expect(case1.consequent[0].expression.type).to.equal('Identifier'); expect(case1.consequent[0].expression.name).to.equal('x'); expect(case1.consequent[1].type).to.equal('BreakStatement'); var case2 = statement.cases[1]; expect(case2.test.type).to.equal('NumericLiteral'); expect(case2.test.value).to.equal(2); expect(case2.consequent[0].type).to.equal('BreakStatement'); var case3 = statement.cases[2]; expect(case3.test).to.equal(null); expect(case3.consequent[0].type).to.equal('EmptyStatement'); }); });
{ "content_hash": "e3a4786ceff598ff44bea4e16847b639", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 114, "avg_line_length": 52.650485436893206, "alnum_prop": 0.6476120228655725, "repo_name": "markelog/cst", "id": "b1af46ba2db029ae708d4cdb75c7e7949f130524", "size": "5423", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/lib/elements/types/SwitchStatement.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "562330" } ], "symlink_target": "" }
UserActionsUI::UserActionsUI(content::WebUI* web_ui) : content::WebUIController(web_ui) { // Set up the chrome://user-actions/ source. content::WebUIDataSource* html_source = content::WebUIDataSource::Create(chrome::kChromeUIUserActionsHost); html_source->SetDefaultResource(IDR_USER_ACTIONS_HTML); html_source->AddResourcePath("user_actions.css", IDR_USER_ACTIONS_CSS); html_source->AddResourcePath("user_actions.js", IDR_USER_ACTIONS_JS); Profile* profile = Profile::FromWebUI(web_ui); content::WebUIDataSource::Add(profile, html_source); web_ui->AddMessageHandler(std::make_unique<UserActionsUIHandler>()); } UserActionsUI::~UserActionsUI() {}
{ "content_hash": "9fb508517d706274712cf41748d824c3", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 73, "avg_line_length": 42.25, "alnum_prop": 0.7470414201183432, "repo_name": "chromium/chromium", "id": "641b3dad49e53e0b1fdefb94aa8bdc8b4611851f", "size": "1276", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "chrome/browser/ui/webui/user_actions/user_actions_ui.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
Article 1247 ---- Le paiement doit être exécuté dans le lieu désigné par la convention. Si le lieu n'y est pas désigné, le paiement, lorsqu'il s'agit d'un corps certain et déterminé, doit être fait dans le lieu où était, au temps de l'obligation, la chose qui en fait l'objet. Les aliments alloués en justice doivent être versés, sauf décision contraire du juge, au domicile ou à la résidence de celui qui doit les recevoir. Hors ces cas, le paiement doit être fait au domicile du débiteur.
{ "content_hash": "346e82d67431431ab8385dfb6e70e534", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 80, "avg_line_length": 44.81818181818182, "alnum_prop": 0.7768762677484787, "repo_name": "oneminot/illacceptanything", "id": "3abb2b7cf52387d7de154ffa74f7cbd96e7b712a", "size": "513", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "data/france.code-civil/Livre III/Titre III/Article 1247.md", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "109" }, { "name": "AppleScript", "bytes": "61" }, { "name": "Arduino", "bytes": "709" }, { "name": "Assembly", "bytes": "2005" }, { "name": "Brainfuck", "bytes": "66542" }, { "name": "C", "bytes": "38598" }, { "name": "C#", "bytes": "55496" }, { "name": "C++", "bytes": "16638" }, { "name": "CMake", "bytes": "235" }, { "name": "CSS", "bytes": "97227" }, { "name": "Clojure", "bytes": "94838" }, { "name": "CoffeeScript", "bytes": "153782" }, { "name": "Common Lisp", "bytes": "1120" }, { "name": "Crystal", "bytes": "7261" }, { "name": "Dart", "bytes": "800" }, { "name": "Eagle", "bytes": "1297646" }, { "name": "Emacs Lisp", "bytes": "60" }, { "name": "Go", "bytes": "19658" }, { "name": "HTML", "bytes": "6432616" }, { "name": "Haskell", "bytes": "100" }, { "name": "JSONiq", "bytes": "536" }, { "name": "Java", "bytes": "14922" }, { "name": "JavaScript", "bytes": "5422014" }, { "name": "Julia", "bytes": "25" }, { "name": "KiCad", "bytes": "321244" }, { "name": "Lua", "bytes": "336811" }, { "name": "Makefile", "bytes": "1019" }, { "name": "OCaml", "bytes": "78" }, { "name": "Objective-C", "bytes": "3260" }, { "name": "PHP", "bytes": "1039" }, { "name": "Python", "bytes": "106335" }, { "name": "Racket", "bytes": "4918" }, { "name": "Ruby", "bytes": "18502" }, { "name": "Rust", "bytes": "42" }, { "name": "Shell", "bytes": "42068" }, { "name": "Swift", "bytes": "12055" }, { "name": "VimL", "bytes": "60880" }, { "name": "Visual Basic", "bytes": "1007" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="Source to the Rust file `/home/jacob/.cargo/registry/src/github.com-1ecc6299db9ec823/ncollide_pipeline-0.10.0/narrow_phase/contact_generator/plane_support_map_contact_generator.rs`."> <meta name="keywords" content="rust, rustlang, rust-lang"> <title>plane_support_map_contact_generator.rs.html -- source</title> <link rel="stylesheet" type="text/css" href="../../../../normalize.css"> <link rel="stylesheet" type="text/css" href="../../../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../../../main.css"> </head> <body class="rustdoc source"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content"><pre class="line-numbers"><span id="1"> 1</span> <span id="2"> 2</span> <span id="3"> 3</span> <span id="4"> 4</span> <span id="5"> 5</span> <span id="6"> 6</span> <span id="7"> 7</span> <span id="8"> 8</span> <span id="9"> 9</span> <span id="10"> 10</span> <span id="11"> 11</span> <span id="12"> 12</span> <span id="13"> 13</span> <span id="14"> 14</span> <span id="15"> 15</span> <span id="16"> 16</span> <span id="17"> 17</span> <span id="18"> 18</span> <span id="19"> 19</span> <span id="20"> 20</span> <span id="21"> 21</span> <span id="22"> 22</span> <span id="23"> 23</span> <span id="24"> 24</span> <span id="25"> 25</span> <span id="26"> 26</span> <span id="27"> 27</span> <span id="28"> 28</span> <span id="29"> 29</span> <span id="30"> 30</span> <span id="31"> 31</span> <span id="32"> 32</span> <span id="33"> 33</span> <span id="34"> 34</span> <span id="35"> 35</span> <span id="36"> 36</span> <span id="37"> 37</span> <span id="38"> 38</span> <span id="39"> 39</span> <span id="40"> 40</span> <span id="41"> 41</span> <span id="42"> 42</span> <span id="43"> 43</span> <span id="44"> 44</span> <span id="45"> 45</span> <span id="46"> 46</span> <span id="47"> 47</span> <span id="48"> 48</span> <span id="49"> 49</span> <span id="50"> 50</span> <span id="51"> 51</span> <span id="52"> 52</span> <span id="53"> 53</span> <span id="54"> 54</span> <span id="55"> 55</span> <span id="56"> 56</span> <span id="57"> 57</span> <span id="58"> 58</span> <span id="59"> 59</span> <span id="60"> 60</span> <span id="61"> 61</span> <span id="62"> 62</span> <span id="63"> 63</span> <span id="64"> 64</span> <span id="65"> 65</span> <span id="66"> 66</span> <span id="67"> 67</span> <span id="68"> 68</span> <span id="69"> 69</span> <span id="70"> 70</span> <span id="71"> 71</span> <span id="72"> 72</span> <span id="73"> 73</span> <span id="74"> 74</span> <span id="75"> 75</span> <span id="76"> 76</span> <span id="77"> 77</span> <span id="78"> 78</span> <span id="79"> 79</span> <span id="80"> 80</span> <span id="81"> 81</span> <span id="82"> 82</span> <span id="83"> 83</span> <span id="84"> 84</span> <span id="85"> 85</span> <span id="86"> 86</span> <span id="87"> 87</span> <span id="88"> 88</span> <span id="89"> 89</span> <span id="90"> 90</span> <span id="91"> 91</span> <span id="92"> 92</span> <span id="93"> 93</span> <span id="94"> 94</span> <span id="95"> 95</span> <span id="96"> 96</span> <span id="97"> 97</span> <span id="98"> 98</span> <span id="99"> 99</span> <span id="100">100</span> <span id="101">101</span> <span id="102">102</span> <span id="103">103</span> <span id="104">104</span> <span id="105">105</span> <span id="106">106</span> <span id="107">107</span> <span id="108">108</span> <span id="109">109</span> <span id="110">110</span> <span id="111">111</span> <span id="112">112</span> <span id="113">113</span> <span id="114">114</span> <span id="115">115</span> <span id="116">116</span> <span id="117">117</span> <span id="118">118</span> <span id="119">119</span> <span id="120">120</span> <span id="121">121</span> <span id="122">122</span> <span id="123">123</span> <span id="124">124</span> <span id="125">125</span> </pre><pre class="rust "> <span class="kw">use</span> <span class="ident">std</span>::<span class="ident">marker</span>::<span class="ident">PhantomData</span>; <span class="kw">use</span> <span class="ident">math</span>::{<span class="ident">Point</span>, <span class="ident">Isometry</span>}; <span class="kw">use</span> <span class="ident">geometry</span>::<span class="ident">shape</span>::{<span class="ident">Shape</span>, <span class="ident">Plane</span>}; <span class="kw">use</span> <span class="ident">geometry</span>::<span class="ident">query</span>::<span class="ident">Contact</span>; <span class="kw">use</span> <span class="ident">geometry</span>::<span class="ident">query</span>::<span class="ident">contacts_internal</span>; <span class="kw">use</span> <span class="ident">narrow_phase</span>::{<span class="ident">ContactGenerator</span>, <span class="ident">ContactDispatcher</span>}; <span class="doccomment">/// Collision detector between a plane and a shape implementing the `SupportMap` trait.</span> <span class="doccomment">///</span> <span class="doccomment">/// This detector generates only one contact point. For a full manifold generation, see</span> <span class="doccomment">/// `IncrementalContactManifoldGenerator`.</span> <span class="attribute">#[<span class="ident">derive</span>(<span class="ident">Clone</span>)]</span> <span class="kw">pub</span> <span class="kw">struct</span> <span class="ident">PlaneSupportMapContactGenerator</span><span class="op">&lt;</span><span class="ident">P</span>: <span class="ident">Point</span>, <span class="ident">M</span><span class="op">&gt;</span> { <span class="ident">contact</span>: <span class="prelude-ty">Option</span><span class="op">&lt;</span><span class="ident">Contact</span><span class="op">&lt;</span><span class="ident">P</span><span class="op">&gt;&gt;</span>, <span class="ident">mat_type</span>: <span class="ident">PhantomData</span><span class="op">&lt;</span><span class="ident">M</span><span class="op">&gt;</span> <span class="comment">// FIXME: can we avoid this?</span> } <span class="kw">impl</span><span class="op">&lt;</span><span class="ident">P</span>: <span class="ident">Point</span>, <span class="ident">M</span><span class="op">&gt;</span> <span class="ident">PlaneSupportMapContactGenerator</span><span class="op">&lt;</span><span class="ident">P</span>, <span class="ident">M</span><span class="op">&gt;</span> { <span class="doccomment">/// Creates a new persistent collision detector between a plane and a shape with a support</span> <span class="doccomment">/// mapping function.</span> <span class="attribute">#[<span class="ident">inline</span>]</span> <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">new</span>() <span class="op">-&gt;</span> <span class="ident">PlaneSupportMapContactGenerator</span><span class="op">&lt;</span><span class="ident">P</span>, <span class="ident">M</span><span class="op">&gt;</span> { <span class="ident">PlaneSupportMapContactGenerator</span> { <span class="ident">contact</span>: <span class="prelude-val">None</span>, <span class="ident">mat_type</span>: <span class="ident">PhantomData</span> } } } <span class="doccomment">/// Collision detector between a plane and a shape implementing the `SupportMap` trait.</span> <span class="doccomment">///</span> <span class="doccomment">/// This detector generates only one contact point. For a full manifold generation, see</span> <span class="doccomment">/// `IncrementalContactManifoldGenerator`.</span> <span class="attribute">#[<span class="ident">derive</span>(<span class="ident">Clone</span>)]</span> <span class="kw">pub</span> <span class="kw">struct</span> <span class="ident">SupportMapPlaneContactGenerator</span><span class="op">&lt;</span><span class="ident">P</span>: <span class="ident">Point</span>, <span class="ident">M</span><span class="op">&gt;</span> { <span class="ident">contact</span>: <span class="prelude-ty">Option</span><span class="op">&lt;</span><span class="ident">Contact</span><span class="op">&lt;</span><span class="ident">P</span><span class="op">&gt;&gt;</span>, <span class="ident">mat_type</span>: <span class="ident">PhantomData</span><span class="op">&lt;</span><span class="ident">M</span><span class="op">&gt;</span> <span class="comment">// FIXME: can we avoid this.</span> } <span class="kw">impl</span><span class="op">&lt;</span><span class="ident">P</span>: <span class="ident">Point</span>, <span class="ident">M</span><span class="op">&gt;</span> <span class="ident">SupportMapPlaneContactGenerator</span><span class="op">&lt;</span><span class="ident">P</span>, <span class="ident">M</span><span class="op">&gt;</span> { <span class="doccomment">/// Creates a new persistent collision detector between a plane and a shape with a support</span> <span class="doccomment">/// mapping function.</span> <span class="attribute">#[<span class="ident">inline</span>]</span> <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">new</span>() <span class="op">-&gt;</span> <span class="ident">SupportMapPlaneContactGenerator</span><span class="op">&lt;</span><span class="ident">P</span>, <span class="ident">M</span><span class="op">&gt;</span> { <span class="ident">SupportMapPlaneContactGenerator</span> { <span class="ident">contact</span>: <span class="prelude-val">None</span>, <span class="ident">mat_type</span>: <span class="ident">PhantomData</span> } } } <span class="kw">impl</span><span class="op">&lt;</span><span class="ident">P</span>: <span class="ident">Point</span>, <span class="ident">M</span>: <span class="ident">Isometry</span><span class="op">&lt;</span><span class="ident">P</span><span class="op">&gt;&gt;</span> <span class="ident">ContactGenerator</span><span class="op">&lt;</span><span class="ident">P</span>, <span class="ident">M</span><span class="op">&gt;</span> <span class="kw">for</span> <span class="ident">PlaneSupportMapContactGenerator</span><span class="op">&lt;</span><span class="ident">P</span>, <span class="ident">M</span><span class="op">&gt;</span> { <span class="attribute">#[<span class="ident">inline</span>]</span> <span class="kw">fn</span> <span class="ident">update</span>(<span class="kw-2">&amp;</span><span class="kw-2">mut</span> <span class="self">self</span>, _: <span class="kw-2">&amp;</span><span class="ident">ContactDispatcher</span><span class="op">&lt;</span><span class="ident">P</span>, <span class="ident">M</span><span class="op">&gt;</span>, <span class="ident">ma</span>: <span class="kw-2">&amp;</span><span class="ident">M</span>, <span class="ident">plane</span>: <span class="kw-2">&amp;</span><span class="ident">Shape</span><span class="op">&lt;</span><span class="ident">P</span>, <span class="ident">M</span><span class="op">&gt;</span>, <span class="ident">mb</span>: <span class="kw-2">&amp;</span><span class="ident">M</span>, <span class="ident">b</span>: <span class="kw-2">&amp;</span><span class="ident">Shape</span><span class="op">&lt;</span><span class="ident">P</span>, <span class="ident">M</span><span class="op">&gt;</span>, <span class="ident">prediction</span>: <span class="ident">P</span>::<span class="ident">Real</span>) <span class="op">-&gt;</span> <span class="ident">bool</span> { <span class="kw">if</span> <span class="kw">let</span> (<span class="prelude-val">Some</span>(<span class="ident">p</span>), <span class="prelude-val">Some</span>(<span class="ident">sm</span>)) <span class="op">=</span> (<span class="ident">plane</span>.<span class="ident">as_shape</span>::<span class="op">&lt;</span><span class="ident">Plane</span><span class="op">&lt;</span><span class="ident">P</span>::<span class="ident">Vector</span><span class="op">&gt;&gt;</span>(), <span class="ident">b</span>.<span class="ident">as_support_map</span>()) { <span class="self">self</span>.<span class="ident">contact</span> <span class="op">=</span> <span class="ident">contacts_internal</span>::<span class="ident">plane_against_support_map</span>(<span class="ident">ma</span>, <span class="ident">p</span>, <span class="ident">mb</span>, <span class="ident">sm</span>, <span class="ident">prediction</span>); <span class="bool-val">true</span> } <span class="kw">else</span> { <span class="bool-val">false</span> } } <span class="attribute">#[<span class="ident">inline</span>]</span> <span class="kw">fn</span> <span class="ident">num_contacts</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="ident">usize</span> { <span class="kw">match</span> <span class="self">self</span>.<span class="ident">contact</span> { <span class="prelude-val">None</span> <span class="op">=&gt;</span> <span class="number">0</span>, <span class="prelude-val">Some</span>(_) <span class="op">=&gt;</span> <span class="number">1</span> } } <span class="attribute">#[<span class="ident">inline</span>]</span> <span class="kw">fn</span> <span class="ident">contacts</span>(<span class="kw-2">&amp;</span><span class="self">self</span>, <span class="ident">out_contacts</span>: <span class="kw-2">&amp;</span><span class="kw-2">mut</span> <span class="ident">Vec</span><span class="op">&lt;</span><span class="ident">Contact</span><span class="op">&lt;</span><span class="ident">P</span><span class="op">&gt;&gt;</span>) { <span class="kw">match</span> <span class="self">self</span>.<span class="ident">contact</span> { <span class="prelude-val">Some</span>(<span class="kw-2">ref</span> <span class="ident">c</span>) <span class="op">=&gt;</span> <span class="ident">out_contacts</span>.<span class="ident">push</span>(<span class="ident">c</span>.<span class="ident">clone</span>()), <span class="prelude-val">None</span> <span class="op">=&gt;</span> () } } } <span class="kw">impl</span><span class="op">&lt;</span><span class="ident">P</span>: <span class="ident">Point</span>, <span class="ident">M</span>: <span class="ident">Isometry</span><span class="op">&lt;</span><span class="ident">P</span><span class="op">&gt;&gt;</span> <span class="ident">ContactGenerator</span><span class="op">&lt;</span><span class="ident">P</span>, <span class="ident">M</span><span class="op">&gt;</span> <span class="kw">for</span> <span class="ident">SupportMapPlaneContactGenerator</span><span class="op">&lt;</span><span class="ident">P</span>, <span class="ident">M</span><span class="op">&gt;</span> { <span class="attribute">#[<span class="ident">inline</span>]</span> <span class="kw">fn</span> <span class="ident">update</span>(<span class="kw-2">&amp;</span><span class="kw-2">mut</span> <span class="self">self</span>, _: <span class="kw-2">&amp;</span><span class="ident">ContactDispatcher</span><span class="op">&lt;</span><span class="ident">P</span>, <span class="ident">M</span><span class="op">&gt;</span>, <span class="ident">ma</span>: <span class="kw-2">&amp;</span><span class="ident">M</span>, <span class="ident">a</span>: <span class="kw-2">&amp;</span><span class="ident">Shape</span><span class="op">&lt;</span><span class="ident">P</span>, <span class="ident">M</span><span class="op">&gt;</span>, <span class="ident">mb</span>: <span class="kw-2">&amp;</span><span class="ident">M</span>, <span class="ident">plane</span>: <span class="kw-2">&amp;</span><span class="ident">Shape</span><span class="op">&lt;</span><span class="ident">P</span>, <span class="ident">M</span><span class="op">&gt;</span>, <span class="ident">prediction</span>: <span class="ident">P</span>::<span class="ident">Real</span>) <span class="op">-&gt;</span> <span class="ident">bool</span> { <span class="kw">if</span> <span class="kw">let</span> (<span class="prelude-val">Some</span>(<span class="ident">sm</span>), <span class="prelude-val">Some</span>(<span class="ident">p</span>)) <span class="op">=</span> (<span class="ident">a</span>.<span class="ident">as_support_map</span>(), <span class="ident">plane</span>.<span class="ident">as_shape</span>::<span class="op">&lt;</span><span class="ident">Plane</span><span class="op">&lt;</span><span class="ident">P</span>::<span class="ident">Vector</span><span class="op">&gt;&gt;</span>()) { <span class="self">self</span>.<span class="ident">contact</span> <span class="op">=</span> <span class="ident">contacts_internal</span>::<span class="ident">support_map_against_plane</span>(<span class="ident">ma</span>, <span class="ident">sm</span>, <span class="ident">mb</span>, <span class="ident">p</span>, <span class="ident">prediction</span>); <span class="bool-val">true</span> } <span class="kw">else</span> { <span class="bool-val">false</span> } } <span class="attribute">#[<span class="ident">inline</span>]</span> <span class="kw">fn</span> <span class="ident">num_contacts</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="ident">usize</span> { <span class="kw">match</span> <span class="self">self</span>.<span class="ident">contact</span> { <span class="prelude-val">None</span> <span class="op">=&gt;</span> <span class="number">0</span>, <span class="prelude-val">Some</span>(_) <span class="op">=&gt;</span> <span class="number">1</span> } } <span class="attribute">#[<span class="ident">inline</span>]</span> <span class="kw">fn</span> <span class="ident">contacts</span>(<span class="kw-2">&amp;</span><span class="self">self</span>, <span class="ident">out_contacts</span>: <span class="kw-2">&amp;</span><span class="kw-2">mut</span> <span class="ident">Vec</span><span class="op">&lt;</span><span class="ident">Contact</span><span class="op">&lt;</span><span class="ident">P</span><span class="op">&gt;&gt;</span>) { <span class="kw">match</span> <span class="self">self</span>.<span class="ident">contact</span> { <span class="prelude-val">Some</span>(<span class="kw-2">ref</span> <span class="ident">c</span>) <span class="op">=&gt;</span> <span class="ident">out_contacts</span>.<span class="ident">push</span>(<span class="ident">c</span>.<span class="ident">clone</span>()), <span class="prelude-val">None</span> <span class="op">=&gt;</span> () } } } </pre> </section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../../../"; window.currentCrate = "ncollide_pipeline"; </script> <script src="../../../../jquery.js"></script> <script src="../../../../main.js"></script> <script defer src="../../../../search-index.js"></script> </body> </html>
{ "content_hash": "7658d3dc20b91fdbc6dc3b72a09f93e8", "timestamp": "", "source": "github", "line_count": 359, "max_line_length": 634, "avg_line_length": 60.061281337047355, "alnum_prop": 0.5972544290882107, "repo_name": "nitro-devs/nitro-game-engine", "id": "b0d3c896a8ed64d58a7e44d7ff72e0d1ab646bb6", "size": "21572", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/src/ncollide_pipeline/narrow_phase/contact_generator/plane_support_map_contact_generator.rs.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CMake", "bytes": "1032" }, { "name": "Rust", "bytes": "59380" } ], "symlink_target": "" }
require 'spec_helper' describe MatchBetPresenter do let(:bet) { build(:bet) } let(:team_a) { create(:team, name_en: 'Brazil', name_pt: 'Brasil', acronym: 'BRA', group: 'A') } let(:team_b) { create(:other_team, name_en: 'Croatia', name_pt: 'Croácia', acronym: 'CRO', group: 'A') } let(:match) { build(:match, team_a: team_a, team_b: team_b) } let(:match_bet) do build(:match_bet, id: 49, bet: bet, match: match, goals_a: 3, goals_b: 3, penalty_winner_id: match.team_a.id, points: 33, created_at: '2014-06-12 17:00:00 -0300'.to_time, updated_at: '2014-06-13 17:00:00 -0300'.to_time ) end subject { described_class.new(match_bet) } its(:to_key) { should eql([49]) } its(:to_param) { should eql('49') } its(:goals_a) { should eql(3) } its(:goals_b) { should eql(3) } its(:penalty_winner_id) { should eql(match.team_a.id) } its(:points) { should eql(33) } its(:created_at) { should eql('2014-06-12 17:00:00 -0300'.to_time) } its(:updated_at) { should eql('2014-06-13 17:00:00 -0300'.to_time) } it 'wraps associated match in a presenter' do expect(subject.match).to be_an_instance_of(MatchPresenter) expect(subject.match.send(:subject)).to eq(match) end it 'wraps associated bet in a presenter' do expect(subject.bet).to be_an_instance_of(BetPresenter) expect(subject.bet.send(:subject)).to eq(bet) end describe '#one_line_summary', locale: :pt do it 'returns a string with all information of the match_bet with penalty information' do expect(subject.one_line_summary).to eql('Brasil 3 x 3 Croácia, com Brasil ganhando nos pênaltis') end it 'returns a string with all information of the match_bet when draw' do match_bet.penalty_winner_id = nil expect(subject.one_line_summary).to eql('Brasil 3 x 3 Croácia') end it 'returns a string with all information of the match_bet when normal victory' do match_bet.penalty_winner_id = nil match_bet.goals_b = 2 expect(subject.one_line_summary).to eql('Brasil 3 x 2 Croácia') end end end
{ "content_hash": "34ec6132a9349fca1eefb836ada82ba6", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 106, "avg_line_length": 36.98245614035088, "alnum_prop": 0.6461100569259962, "repo_name": "rtopitt/bolao2014", "id": "e9ed374b7e575a050aed346a4824a09211ed461e", "size": "2113", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/presenters/match_bet_presenter_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "44997" }, { "name": "JavaScript", "bytes": "3537" }, { "name": "Ruby", "bytes": "393257" } ], "symlink_target": "" }
"""Provides device automations for Alarm control panel.""" from typing import List import voluptuous as vol from homeassistant.components.alarm_control_panel.const import ( SUPPORT_ALARM_ARM_AWAY, SUPPORT_ALARM_ARM_HOME, SUPPORT_ALARM_ARM_NIGHT, ) from homeassistant.components.automation import AutomationActionType, state from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.const import ( CONF_DEVICE_ID, CONF_DOMAIN, CONF_ENTITY_ID, CONF_PLATFORM, CONF_TYPE, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_NIGHT, STATE_ALARM_DISARMED, STATE_ALARM_PENDING, STATE_ALARM_TRIGGERED, ) from homeassistant.core import CALLBACK_TYPE, HomeAssistant from homeassistant.helpers import config_validation as cv, entity_registry from homeassistant.helpers.typing import ConfigType from . import DOMAIN TRIGGER_TYPES = { "triggered", "disarmed", "armed_home", "armed_away", "armed_night", } TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES), } ) async def async_get_triggers(hass: HomeAssistant, device_id: str) -> List[dict]: """List device triggers for Alarm control panel devices.""" registry = await entity_registry.async_get_registry(hass) triggers = [] # Get all the integrations entities for this device for entry in entity_registry.async_entries_for_device(registry, device_id): if entry.domain != DOMAIN: continue entity_state = hass.states.get(entry.entity_id) # We need a state or else we can't populate the HVAC and preset modes. if entity_state is None: continue supported_features = entity_state.attributes["supported_features"] # Add triggers for each entity that belongs to this integration triggers += [ { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "disarmed", }, { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "triggered", }, ] if supported_features & SUPPORT_ALARM_ARM_HOME: triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "armed_home", } ) if supported_features & SUPPORT_ALARM_ARM_AWAY: triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "armed_away", } ) if supported_features & SUPPORT_ALARM_ARM_NIGHT: triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "armed_night", } ) return triggers async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, ) -> CALLBACK_TYPE: """Attach a trigger.""" config = TRIGGER_SCHEMA(config) if config[CONF_TYPE] == "triggered": from_state = STATE_ALARM_PENDING to_state = STATE_ALARM_TRIGGERED elif config[CONF_TYPE] == "disarmed": from_state = STATE_ALARM_TRIGGERED to_state = STATE_ALARM_DISARMED elif config[CONF_TYPE] == "armed_home": from_state = STATE_ALARM_PENDING to_state = STATE_ALARM_ARMED_HOME elif config[CONF_TYPE] == "armed_away": from_state = STATE_ALARM_PENDING to_state = STATE_ALARM_ARMED_AWAY elif config[CONF_TYPE] == "armed_night": from_state = STATE_ALARM_PENDING to_state = STATE_ALARM_ARMED_NIGHT state_config = { state.CONF_PLATFORM: "state", CONF_ENTITY_ID: config[CONF_ENTITY_ID], state.CONF_FROM: from_state, state.CONF_TO: to_state, } state_config = state.TRIGGER_SCHEMA(state_config) return await state.async_attach_trigger( hass, state_config, action, automation_info, platform_type="device" )
{ "content_hash": "95a5450d7c66404ac61f8bc5f888135f", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 80, "avg_line_length": 31.814569536423843, "alnum_prop": 0.5868026644462948, "repo_name": "postlund/home-assistant", "id": "95ae17aaaf5621041afa501292be150ce0a13bfd", "size": "4804", "binary": false, "copies": "4", "ref": "refs/heads/dev", "path": "homeassistant/components/alarm_control_panel/device_trigger.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "20215859" }, { "name": "Shell", "bytes": "6663" } ], "symlink_target": "" }
<!-- HTML header for doxygen 1.8.13--> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>CAT2 Peripheral Driver Library: Functions</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen_style.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><a href="http://www.cypress.com/"><img alt="Logo" src="logo.png"/></a></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">CAT2 Peripheral Driver Library</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('group__group__systick__functions.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">Functions<div class="ingroups"><a class="el" href="group__group__arm__system__timer.html">SysTick (ARM System Timer)</a></div></div> </div> </div><!--header--> <div class="contents"> <a name="details" id="details"></a><h2 class="groupheader">General Description</h2> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:gac600820b0201e4ad5a171e97f7642c62"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#gac600820b0201e4ad5a171e97f7642c62">Cy_SysTick_Init</a> (<a class="el" href="group__group__systick__data__structures.html#ga466b1e8fe4278011eab77a691ce2b8f9">cy_en_systick_clock_source_t</a> clockSource, uint32_t interval)</td></tr> <tr class="memdesc:gac600820b0201e4ad5a171e97f7642c62"><td class="mdescLeft">&#160;</td><td class="mdescRight">Initializes the SysTick driver: <a href="#gac600820b0201e4ad5a171e97f7642c62">More...</a><br /></td></tr> <tr class="separator:gac600820b0201e4ad5a171e97f7642c62"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga14017a044d9158c88c6cd589b6bd6895"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#ga14017a044d9158c88c6cd589b6bd6895">Cy_SysTick_Enable</a> (void)</td></tr> <tr class="memdesc:ga14017a044d9158c88c6cd589b6bd6895"><td class="mdescLeft">&#160;</td><td class="mdescRight">Enables the SysTick timer and its interrupt. <a href="#ga14017a044d9158c88c6cd589b6bd6895">More...</a><br /></td></tr> <tr class="separator:ga14017a044d9158c88c6cd589b6bd6895"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaf371c2b11a3b5bb8241842298137167b"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#gaf371c2b11a3b5bb8241842298137167b">Cy_SysTick_Disable</a> (void)</td></tr> <tr class="memdesc:gaf371c2b11a3b5bb8241842298137167b"><td class="mdescLeft">&#160;</td><td class="mdescRight">Disables the SysTick timer and its interrupt. <a href="#gaf371c2b11a3b5bb8241842298137167b">More...</a><br /></td></tr> <tr class="separator:gaf371c2b11a3b5bb8241842298137167b"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga3f8081d5b34edcaabf394b86b87f1147"><td class="memItemLeft" align="right" valign="top">__STATIC_INLINE bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#ga3f8081d5b34edcaabf394b86b87f1147">Cy_SysTick_IsEnabled</a> (void)</td></tr> <tr class="memdesc:ga3f8081d5b34edcaabf394b86b87f1147"><td class="mdescLeft">&#160;</td><td class="mdescRight">Returns the SysTick enable/disable state. <a href="#ga3f8081d5b34edcaabf394b86b87f1147">More...</a><br /></td></tr> <tr class="separator:ga3f8081d5b34edcaabf394b86b87f1147"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gac20a2349069c5268c6e3f05c6777b9c9"><td class="memItemLeft" align="right" valign="top">Cy_SysTick_Callback&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#gac20a2349069c5268c6e3f05c6777b9c9">Cy_SysTick_SetCallback</a> (uint32_t number, Cy_SysTick_Callback function)</td></tr> <tr class="memdesc:gac20a2349069c5268c6e3f05c6777b9c9"><td class="mdescLeft">&#160;</td><td class="mdescRight">Sets the callback function to the specified callback number. <a href="#gac20a2349069c5268c6e3f05c6777b9c9">More...</a><br /></td></tr> <tr class="separator:gac20a2349069c5268c6e3f05c6777b9c9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga3fb4a65fcdb113c20d679e5d9ae5f2e8"><td class="memItemLeft" align="right" valign="top">Cy_SysTick_Callback&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#ga3fb4a65fcdb113c20d679e5d9ae5f2e8">Cy_SysTick_GetCallback</a> (uint32_t number)</td></tr> <tr class="memdesc:ga3fb4a65fcdb113c20d679e5d9ae5f2e8"><td class="mdescLeft">&#160;</td><td class="mdescRight">Gets the specified callback function address. <a href="#ga3fb4a65fcdb113c20d679e5d9ae5f2e8">More...</a><br /></td></tr> <tr class="separator:ga3fb4a65fcdb113c20d679e5d9ae5f2e8"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaa8a72d8a278e4a3a970b4c4a021f3647"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#gaa8a72d8a278e4a3a970b4c4a021f3647">Cy_SysTick_SetClockSource</a> (<a class="el" href="group__group__systick__data__structures.html#ga466b1e8fe4278011eab77a691ce2b8f9">cy_en_systick_clock_source_t</a> clockSource)</td></tr> <tr class="memdesc:gaa8a72d8a278e4a3a970b4c4a021f3647"><td class="mdescLeft">&#160;</td><td class="mdescRight">Sets the clock source for the SysTick counter. <a href="#gaa8a72d8a278e4a3a970b4c4a021f3647">More...</a><br /></td></tr> <tr class="separator:gaa8a72d8a278e4a3a970b4c4a021f3647"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga6d72adec7b58994ff9097bb4a301fa95"><td class="memItemLeft" align="right" valign="top"><a class="el" href="group__group__systick__data__structures.html#ga466b1e8fe4278011eab77a691ce2b8f9">cy_en_systick_clock_source_t</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#ga6d72adec7b58994ff9097bb4a301fa95">Cy_SysTick_GetClockSource</a> (void)</td></tr> <tr class="memdesc:ga6d72adec7b58994ff9097bb4a301fa95"><td class="mdescLeft">&#160;</td><td class="mdescRight">Gets the clock source for the SysTick counter. <a href="#ga6d72adec7b58994ff9097bb4a301fa95">More...</a><br /></td></tr> <tr class="separator:ga6d72adec7b58994ff9097bb4a301fa95"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga6c04d89a211060b93ae5c108e98fe679"><td class="memItemLeft" align="right" valign="top">__STATIC_INLINE void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#ga6c04d89a211060b93ae5c108e98fe679">Cy_SysTick_EnableInterrupt</a> (void)</td></tr> <tr class="memdesc:ga6c04d89a211060b93ae5c108e98fe679"><td class="mdescLeft">&#160;</td><td class="mdescRight">Enables the SysTick interrupt. <a href="#ga6c04d89a211060b93ae5c108e98fe679">More...</a><br /></td></tr> <tr class="separator:ga6c04d89a211060b93ae5c108e98fe679"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga4fbd44faae1f1e469e5361fee310a71e"><td class="memItemLeft" align="right" valign="top">__STATIC_INLINE void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#ga4fbd44faae1f1e469e5361fee310a71e">Cy_SysTick_DisableInterrupt</a> (void)</td></tr> <tr class="memdesc:ga4fbd44faae1f1e469e5361fee310a71e"><td class="mdescLeft">&#160;</td><td class="mdescRight">Disables the SysTick interrupt. <a href="#ga4fbd44faae1f1e469e5361fee310a71e">More...</a><br /></td></tr> <tr class="separator:ga4fbd44faae1f1e469e5361fee310a71e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga55c016caf7558ec00f1e8cd3d77e36da"><td class="memItemLeft" align="right" valign="top">__STATIC_INLINE void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#ga55c016caf7558ec00f1e8cd3d77e36da">Cy_SysTick_SetReload</a> (uint32_t value)</td></tr> <tr class="memdesc:ga55c016caf7558ec00f1e8cd3d77e36da"><td class="mdescLeft">&#160;</td><td class="mdescRight">Sets the value the counter is set to on a startup and after it reaches zero. <a href="#ga55c016caf7558ec00f1e8cd3d77e36da">More...</a><br /></td></tr> <tr class="separator:ga55c016caf7558ec00f1e8cd3d77e36da"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gadd8f7ae211b60d3c36e218590da1e27c"><td class="memItemLeft" align="right" valign="top">__STATIC_INLINE uint32_t&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#gadd8f7ae211b60d3c36e218590da1e27c">Cy_SysTick_GetReload</a> (void)</td></tr> <tr class="memdesc:gadd8f7ae211b60d3c36e218590da1e27c"><td class="mdescLeft">&#160;</td><td class="mdescRight">Gets the value the counter is set to on a startup and after it reaches zero. <a href="#gadd8f7ae211b60d3c36e218590da1e27c">More...</a><br /></td></tr> <tr class="separator:gadd8f7ae211b60d3c36e218590da1e27c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga4fed98e2937079051e3c804b9f997cd3"><td class="memItemLeft" align="right" valign="top">__STATIC_INLINE uint32_t&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#ga4fed98e2937079051e3c804b9f997cd3">Cy_SysTick_GetValue</a> (void)</td></tr> <tr class="memdesc:ga4fed98e2937079051e3c804b9f997cd3"><td class="mdescLeft">&#160;</td><td class="mdescRight">Gets the current SysTick counter value. <a href="#ga4fed98e2937079051e3c804b9f997cd3">More...</a><br /></td></tr> <tr class="separator:ga4fed98e2937079051e3c804b9f997cd3"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gad89db2823028712f57e8f81e9e0be8a5"><td class="memItemLeft" align="right" valign="top">__STATIC_INLINE uint32_t&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#gad89db2823028712f57e8f81e9e0be8a5">Cy_SysTick_GetCountFlag</a> (void)</td></tr> <tr class="memdesc:gad89db2823028712f57e8f81e9e0be8a5"><td class="mdescLeft">&#160;</td><td class="mdescRight">Gets the values of the count flag. <a href="#gad89db2823028712f57e8f81e9e0be8a5">More...</a><br /></td></tr> <tr class="separator:gad89db2823028712f57e8f81e9e0be8a5"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga39bb8fea3eca13cedba526c2babf2013"><td class="memItemLeft" align="right" valign="top">__STATIC_INLINE void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__systick__functions.html#ga39bb8fea3eca13cedba526c2babf2013">Cy_SysTick_Clear</a> (void)</td></tr> <tr class="memdesc:ga39bb8fea3eca13cedba526c2babf2013"><td class="mdescLeft">&#160;</td><td class="mdescRight">Clears the SysTick counter for a well-defined startup. <a href="#ga39bb8fea3eca13cedba526c2babf2013">More...</a><br /></td></tr> <tr class="separator:ga39bb8fea3eca13cedba526c2babf2013"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Function Documentation</h2> <a id="gac600820b0201e4ad5a171e97f7642c62"></a> <h2 class="memtitle"><span class="permalink"><a href="#gac600820b0201e4ad5a171e97f7642c62">&#9670;&nbsp;</a></span>Cy_SysTick_Init()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void Cy_SysTick_Init </td> <td>(</td> <td class="paramtype"><a class="el" href="group__group__systick__data__structures.html#ga466b1e8fe4278011eab77a691ce2b8f9">cy_en_systick_clock_source_t</a>&#160;</td> <td class="paramname"><em>clockSource</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">uint32_t&#160;</td> <td class="paramname"><em>interval</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>Initializes the SysTick driver: </p> <ul> <li>Initializes the callback addresses with pointers to NULL</li> <li>Associates the SysTick system vector with the callback functions</li> <li>Sets the SysTick clock by calling <a class="el" href="group__group__systick__functions.html#gaa8a72d8a278e4a3a970b4c4a021f3647">Cy_SysTick_SetClockSource()</a></li> <li>Sets the SysTick reload interval by calling <a class="el" href="group__group__systick__functions.html#ga55c016caf7558ec00f1e8cd3d77e36da">Cy_SysTick_SetReload()</a></li> <li>Clears the SysTick counter value by calling <a class="el" href="group__group__systick__functions.html#ga39bb8fea3eca13cedba526c2babf2013">Cy_SysTick_Clear()</a></li> <li>Enables the SysTick by calling <a class="el" href="group__group__systick__functions.html#ga14017a044d9158c88c6cd589b6bd6895">Cy_SysTick_Enable()</a>. Note the <a class="el" href="group__group__systick__functions.html#ga14017a044d9158c88c6cd589b6bd6895">Cy_SysTick_Enable()</a> function also enables the SysTick interrupt by calling <a class="el" href="group__group__systick__functions.html#ga6c04d89a211060b93ae5c108e98fe679">Cy_SysTick_EnableInterrupt()</a>.</li> </ul> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">clockSource</td><td>The SysTick clock source <a class="el" href="group__group__systick__data__structures.html#ga466b1e8fe4278011eab77a691ce2b8f9">cy_en_systick_clock_source_t</a> </td></tr> <tr><td class="paramname">interval</td><td>The SysTick reload value. The valid range is [0x0-0x00FFFFFF]. </td></tr> </table> </dd> </dl> <dl class="section note"><dt>Note</dt><dd>Zero has no effect because the SysTick exception request and count flag are activated when counting from 1 to 0.</dd></dl> <dl class="section user"><dt>Side Effects</dt><dd>Clears the SysTick count flag if it was set. </dd></dl> </div> </div> <a id="ga14017a044d9158c88c6cd589b6bd6895"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga14017a044d9158c88c6cd589b6bd6895">&#9670;&nbsp;</a></span>Cy_SysTick_Enable()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void Cy_SysTick_Enable </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Enables the SysTick timer and its interrupt. </p> <dl class="section user"><dt>Side Effects</dt><dd>Clears the SysTick count flag if it was set </dd></dl> </div> </div> <a id="gaf371c2b11a3b5bb8241842298137167b"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaf371c2b11a3b5bb8241842298137167b">&#9670;&nbsp;</a></span>Cy_SysTick_Disable()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void Cy_SysTick_Disable </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Disables the SysTick timer and its interrupt. </p> <dl class="section user"><dt>Side Effects</dt><dd>Clears the SysTick count flag if it was set </dd></dl> </div> </div> <a id="ga3f8081d5b34edcaabf394b86b87f1147"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga3f8081d5b34edcaabf394b86b87f1147">&#9670;&nbsp;</a></span>Cy_SysTick_IsEnabled()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">__STATIC_INLINE bool Cy_SysTick_IsEnabled </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Returns the SysTick enable/disable state. </p> <dl class="section return"><dt>Returns</dt><dd>Returns true is the timer is enabled; otherwise false is returned. </dd></dl> </div> </div> <a id="gac20a2349069c5268c6e3f05c6777b9c9"></a> <h2 class="memtitle"><span class="permalink"><a href="#gac20a2349069c5268c6e3f05c6777b9c9">&#9670;&nbsp;</a></span>Cy_SysTick_SetCallback()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">Cy_SysTick_Callback Cy_SysTick_SetCallback </td> <td>(</td> <td class="paramtype">uint32_t&#160;</td> <td class="paramname"><em>number</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">Cy_SysTick_Callback&#160;</td> <td class="paramname"><em>function</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>Sets the callback function to the specified callback number. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">number</td><td>The number of the callback function addresses to be set. The valid range is from 0 to <a class="el" href="group__group__systick__macros.html#ga13b753449adfc0805c73bf3fdd2c03e6">CY_SYS_SYST_NUM_OF_CALLBACKS</a> - 1.</td></tr> <tr><td class="paramname">function</td><td>The pointer to the function that will be associated with the SysTick ISR for the specified number.</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd>Returns the address of the previous callback function. The NULL is returned if the specified address in not set or incorrect parameter is specified.</dd></dl> <dl class="section user"><dt>Side Effects</dt><dd>The registered callback functions will be executed in the interrupt. </dd></dl> </div> </div> <a id="ga3fb4a65fcdb113c20d679e5d9ae5f2e8"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga3fb4a65fcdb113c20d679e5d9ae5f2e8">&#9670;&nbsp;</a></span>Cy_SysTick_GetCallback()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">Cy_SysTick_Callback Cy_SysTick_GetCallback </td> <td>(</td> <td class="paramtype">uint32_t&#160;</td> <td class="paramname"><em>number</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Gets the specified callback function address. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">number</td><td>The number of the callback function address to get. The valid range is from 0 to <a class="el" href="group__group__systick__macros.html#ga13b753449adfc0805c73bf3fdd2c03e6">CY_SYS_SYST_NUM_OF_CALLBACKS</a> - 1.</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd>Returns the address of the specified callback function. The NULL is returned if the specified address in not initialized or incorrect parameter is specified. </dd></dl> </div> </div> <a id="gaa8a72d8a278e4a3a970b4c4a021f3647"></a> <h2 class="memtitle"><span class="permalink"><a href="#gaa8a72d8a278e4a3a970b4c4a021f3647">&#9670;&nbsp;</a></span>Cy_SysTick_SetClockSource()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void Cy_SysTick_SetClockSource </td> <td>(</td> <td class="paramtype"><a class="el" href="group__group__systick__data__structures.html#ga466b1e8fe4278011eab77a691ce2b8f9">cy_en_systick_clock_source_t</a>&#160;</td> <td class="paramname"><em>clockSource</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Sets the clock source for the SysTick counter. </p> <p>Clears the SysTick count flag if it was set. If the clock source is not ready this function call will have no effect. After changing the clock source to the low frequency clock, the counter and reload register values will remain unchanged so the time to the interrupt will be significantly longer and vice versa.</p> <p>Changing the SysTick clock source and/or its frequency will change the interrupt interval and <a class="el" href="group__group__systick__functions.html#ga55c016caf7558ec00f1e8cd3d77e36da" title="Sets the value the counter is set to on a startup and after it reaches zero. ">Cy_SysTick_SetReload()</a> should be called to compensate this change.</p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">clockSource</td><td><a class="el" href="group__group__systick__data__structures.html#ga466b1e8fe4278011eab77a691ce2b8f9">cy_en_systick_clock_source_t</a> Clock source. </td></tr> </table> </dd> </dl> </div> </div> <a id="ga6d72adec7b58994ff9097bb4a301fa95"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga6d72adec7b58994ff9097bb4a301fa95">&#9670;&nbsp;</a></span>Cy_SysTick_GetClockSource()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="group__group__systick__data__structures.html#ga466b1e8fe4278011eab77a691ce2b8f9">cy_en_systick_clock_source_t</a> Cy_SysTick_GetClockSource </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Gets the clock source for the SysTick counter. </p> <dl class="section return"><dt>Returns</dt><dd><a class="el" href="group__group__systick__data__structures.html#ga466b1e8fe4278011eab77a691ce2b8f9">cy_en_systick_clock_source_t</a> Clock source </dd></dl> </div> </div> <a id="ga6c04d89a211060b93ae5c108e98fe679"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga6c04d89a211060b93ae5c108e98fe679">&#9670;&nbsp;</a></span>Cy_SysTick_EnableInterrupt()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">__STATIC_INLINE void Cy_SysTick_EnableInterrupt </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Enables the SysTick interrupt. </p> <dl class="section user"><dt>Side Effects</dt><dd>Clears the SysTick count flag if it was set </dd></dl> </div> </div> <a id="ga4fbd44faae1f1e469e5361fee310a71e"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga4fbd44faae1f1e469e5361fee310a71e">&#9670;&nbsp;</a></span>Cy_SysTick_DisableInterrupt()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">__STATIC_INLINE void Cy_SysTick_DisableInterrupt </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Disables the SysTick interrupt. </p> <dl class="section user"><dt>Side Effects</dt><dd>Clears the SysTick count flag if it was set </dd></dl> </div> </div> <a id="ga55c016caf7558ec00f1e8cd3d77e36da"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga55c016caf7558ec00f1e8cd3d77e36da">&#9670;&nbsp;</a></span>Cy_SysTick_SetReload()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">__STATIC_INLINE void Cy_SysTick_SetReload </td> <td>(</td> <td class="paramtype">uint32_t&#160;</td> <td class="paramname"><em>value</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Sets the value the counter is set to on a startup and after it reaches zero. </p> <p>This function does not change or reset the current sysTick counter value, so it should be cleared using the <a class="el" href="group__group__systick__functions.html#ga39bb8fea3eca13cedba526c2babf2013" title="Clears the SysTick counter for a well-defined startup. ">Cy_SysTick_Clear()</a> API.</p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">value</td><td>The valid range is [0x0-0x00FFFFFF]. The counter reset value. </td></tr> </table> </dd> </dl> <dl class="section note"><dt>Note</dt><dd>Zero no effect because the SysTick exception request and count flag are activated when counting from 1 to 0. </dd></dl> </div> </div> <a id="gadd8f7ae211b60d3c36e218590da1e27c"></a> <h2 class="memtitle"><span class="permalink"><a href="#gadd8f7ae211b60d3c36e218590da1e27c">&#9670;&nbsp;</a></span>Cy_SysTick_GetReload()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">__STATIC_INLINE uint32_t Cy_SysTick_GetReload </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Gets the value the counter is set to on a startup and after it reaches zero. </p> <dl class="section return"><dt>Returns</dt><dd>The counter reset value. </dd></dl> </div> </div> <a id="ga4fed98e2937079051e3c804b9f997cd3"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga4fed98e2937079051e3c804b9f997cd3">&#9670;&nbsp;</a></span>Cy_SysTick_GetValue()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">__STATIC_INLINE uint32_t Cy_SysTick_GetValue </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Gets the current SysTick counter value. </p> <dl class="section return"><dt>Returns</dt><dd>The current SysTick counter value. </dd></dl> </div> </div> <a id="gad89db2823028712f57e8f81e9e0be8a5"></a> <h2 class="memtitle"><span class="permalink"><a href="#gad89db2823028712f57e8f81e9e0be8a5">&#9670;&nbsp;</a></span>Cy_SysTick_GetCountFlag()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">__STATIC_INLINE uint32_t Cy_SysTick_GetCountFlag </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Gets the values of the count flag. </p> <p>The count flag is set once the SysTick counter reaches zero. The flag is cleared on read.</p> <dl class="section return"><dt>Returns</dt><dd>Returns a non-zero value if a flag is set; otherwise a zero is returned.</dd></dl> <dl class="section user"><dt>Side Effects</dt><dd>Clears the SysTick count flag.</dd></dl> <dl class="section note"><dt>Note</dt><dd>Applicable only in Polling mode. If the SysTick interrupt is enabled, the count flag will be cleared automatically on interrupt event. </dd></dl> </div> </div> <a id="ga39bb8fea3eca13cedba526c2babf2013"></a> <h2 class="memtitle"><span class="permalink"><a href="#ga39bb8fea3eca13cedba526c2babf2013">&#9670;&nbsp;</a></span>Cy_SysTick_Clear()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">__STATIC_INLINE void Cy_SysTick_Clear </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Clears the SysTick counter for a well-defined startup. </p> <dl class="section user"><dt>Side Effects</dt><dd>Clears the SysTick count flag. </dd></dl> </div> </div> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part <div id="nav-path" class="navpath"> <ul> <li class="footer"> Generated for <b>CAT2 Peripheral Driver Library</b> by <b>Infineon Technologies</b>. All rights reserved. </li> </ul> </div> --> </body> </html>
{ "content_hash": "6ab444ebeb29c21b00c7cac25f3d6a6e", "timestamp": "", "source": "github", "line_count": 535, "max_line_length": 468, "avg_line_length": 58.17943925233645, "alnum_prop": 0.6871104542825933, "repo_name": "Infineon/mtb-pdl-cat2", "id": "4e4d6e6ad15a5d38300dfad4fc7a6f3f6a7eb65c", "size": "31126", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/pdl_api_reference_manual/html/group__group__systick__functions.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "25316" }, { "name": "C", "bytes": "20311744" }, { "name": "Tcl", "bytes": "34353" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "46f53c73e9df3b2e74ff707ea48e948a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "ede655014180fd15ce826f2cde52a098744575a7", "size": "181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rhamnaceae/Colubrina/Colubrina verrucosa/ Syn. Hybosperma spinosum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_fscanf_84a.cpp Label Definition File: CWE789_Uncontrolled_Mem_Alloc__new.label.xml Template File: sources-sinks-84a.tmpl.cpp */ /* * @description * CWE: 789 Uncontrolled Memory Allocation * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Small number greater than zero * Sinks: * GoodSink: Allocate memory with new [] and check the size of the memory to be allocated * BadSink : Allocate memory with new [], but incorrectly check the size of the memory to be allocated * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use * * */ #include "std_testcase.h" #include "CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_fscanf_84.h" namespace CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_fscanf_84 { #ifndef OMITBAD void bad() { size_t data; /* Initialize data */ data = 0; CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_fscanf_84_bad * badObject = new CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_fscanf_84_bad(data); delete badObject; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { size_t data; /* Initialize data */ data = 0; CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_fscanf_84_goodG2B * goodG2BObject = new CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_fscanf_84_goodG2B(data); delete goodG2BObject; } /* goodG2B uses the BadSource with the GoodSink */ static void goodB2G() { size_t data; /* Initialize data */ data = 0; CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_fscanf_84_goodB2G * goodB2GObject = new CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_fscanf_84_goodB2G(data); delete goodB2GObject; } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_fscanf_84; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "3c05db91ce032fd6822ccc0bd1f3c05e", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 154, "avg_line_length": 29.621052631578948, "alnum_prop": 0.6794598436389481, "repo_name": "JianpingZeng/xcc", "id": "9f76cf168c74ffc8e6f9d8191bfef95189fd0604", "size": "2814", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "xcc/test/juliet/testcases/CWE789_Uncontrolled_Mem_Alloc/s02/CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_fscanf_84a.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
export default function makeDeferred() { let reject, resolve, promise = new Promise(function (res, rej) { resolve = res; reject = rej; }); return Object.freeze({ promise, resolve, reject }); }
{ "content_hash": "a116e7b8fdb83f3bb95cf88e96e62025", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 66, "avg_line_length": 29.571428571428573, "alnum_prop": 0.6618357487922706, "repo_name": "OHIF/Viewers", "id": "0f5a0fa9f7b401d55098e5d8643caa63716ed0f1", "size": "207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platform/core/src/utils/makeDeferred.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "60896" }, { "name": "Dockerfile", "bytes": "2104" }, { "name": "HTML", "bytes": "23872" }, { "name": "JavaScript", "bytes": "1779271" }, { "name": "Shell", "bytes": "8467" }, { "name": "Stylus", "bytes": "62420" } ], "symlink_target": "" }
<?php include("../config/config.inc.php"); if(empty($_REQUEST['aid']) | empty($_REQUEST['time'])){ echo "error encountered please check your settings"; exit; }else{ $obj = db_fetch_object(db_query("select * from auction left join products p on p.productID = auction.productID where auctionID = '$_REQUEST[aid]'")); db_query("update auction set time_duration = '$_REQUEST[time]' where auctionID = '$_REQUEST[aid]'"); db_query("update auction_running set time_duration = '$_REQUEST[time]' where auctionID = '$_REQUEST[aid]'"); echo "success"; $qry = db_query("select * from comet_users"); while($row = db_fetch_array($qry)){ $tstamp = time(); db_query("insert into cometchat_announcements (`id`, `announcement`, `time`, `to`) values(null, 'Auction Duration has been changed to " . str_replace('sa', ' Seconds', $_REQUEST['time']) . " for <a href=\"viewproduct.php?aid=" . $obj->auctionID . "\">" . $obj->name . "</a>', '$tstamp', '$row[userid]');"); db_query("insert into cometchat_chatroommessages(`id`, `userid`, `chatroomid`, `message`, `sent`) values(null, '1', '1', '<span style=\"color:red;font-weight:bold;\">Auction Duration has been changed to " . str_replace('sa', ' Seconds', $_REQUEST['time']) . " for <a href=\"viewproduct.php?aid=" . $obj->auctionID . "\">#" . $obj->auctionID . ' ' . $obj->name . "</a></p>', NOW());"); echo db_error(); db_query("insert into cometchat(`id`, `from`, `to`, `message`) values(null, '1', '$row[userid]', '<span style=\"color:red;font-weight:bold;\">Auction Duration has been changed to " . str_replace('sa', ' Seconds', $_REQUEST['time']) . " for <a href=\"viewproduct.php?aid=" . $obj->auctionID . "\">#" . $obj->auctionID . ' ' . $obj->name . "</a></p>');"); echo db_error(); } }
{ "content_hash": "4e448484bbe05ad1f3a775ec9e7a3b4b", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 390, "avg_line_length": 74.66666666666667, "alnum_prop": 0.6143973214285714, "repo_name": "exhibia/exhibia", "id": "f484a1fbfe267aa20c1208ad3214fddcd4192bc9", "size": "1792", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backendadmin/change_duration.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "9307" }, { "name": "JavaScript", "bytes": "126410" }, { "name": "PHP", "bytes": "2449281" }, { "name": "Shell", "bytes": "2611" } ], "symlink_target": "" }
<?php /* Unsafe sample input : reads the field UserData from the variable $_GET Uses a special_chars_filter via filter_var function construction : concatenation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = $_GET['UserData']; $sanitized = filter_var($tainted, FILTER_SANITIZE_SPECIAL_CHARS); $tainted = $sanitized ; //flaw $var = http_redirect("'" . $tainted . "'"); ?>
{ "content_hash": "44327767c8bea2945efe879a6835be5a", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 75, "avg_line_length": 22.49122807017544, "alnum_prop": 0.7644305772230889, "repo_name": "stivalet/PHP-Vulnerability-test-suite", "id": "bda33d5e334076ede362e56bb6b99507d8a37231", "size": "1282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "URF/CWE_601/unsafe/CWE_601__GET__func_FILTER-CLEANING-special_chars_filter__http_redirect_url-concatenation_simple_quote.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64184004" } ], "symlink_target": "" }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geometry; using ClonableObj; namespace TestApp { public sealed class TestClass { #region class constructor (empty constructor) public TestClass() { } #endregion public void Test() { Console.WriteLine("Creating an instance of the clonable object."); ClonableObjClass cloneable = new ClonableObjClass(); Console.WriteLine("Assigning properties"); cloneable.SpatialReference = CreateGeographicSpatialReference(); cloneable.Name = "test 1"; cloneable.Point = new PointClass(); cloneable.Point.PutCoords(35.02, 31.4); cloneable.ManagedArray = new ArrayList(); cloneable.ManagedArray.Add("One"); cloneable.ManagedArray.Add("Two"); cloneable.ManagedArray.Add("Three"); Console.WriteLine("New object's properties"); Console.WriteLine("-----------------------"); Console.WriteLine("Name: " + cloneable.Name); Console.WriteLine("ID: " + cloneable.ID.ToString()); Console.WriteLine("Version: " + cloneable.Version.ToString()); Console.WriteLine("Array values: "); foreach (object obj in cloneable.ManagedArray) { Console.WriteLine((string)obj); } Console.WriteLine("Spatial Reference parameters:"); Console.WriteLine("Name: " + cloneable.SpatialReference.Name); IGeographicCoordinateSystem gcs = (IGeographicCoordinateSystem)cloneable.SpatialReference; Console.WriteLine("Alias: " + gcs.Alias); Console.WriteLine("Datum: " + gcs.Datum.Name); Console.WriteLine(""); Console.WriteLine("Cloning the object..."); ClonableObjClass clonee = cloneable.Clone() as ClonableObjClass; Console.WriteLine(""); Console.WriteLine("Cloned object's properties:"); Console.WriteLine("---------------------------"); Console.WriteLine("Name: " + clonee.Name); Console.WriteLine("ID: " + clonee.ID.ToString()); Console.WriteLine("Version: " + clonee.Version.ToString()); Console.WriteLine("Array values: "); foreach (object obj in clonee.ManagedArray) { Console.WriteLine((string)obj); } Console.WriteLine("Spatial Reference parameters:"); Console.WriteLine("Name: " + clonee.SpatialReference.Name); gcs = (IGeographicCoordinateSystem)clonee.SpatialReference; Console.WriteLine("Alias: " + gcs.Alias); Console.WriteLine("Datum: " + gcs.Datum.Name); Console.WriteLine(""); } /// <summary> /// create a crazy coordinate system /// </summary> /// <returns></returns> private ISpatialReference CreateGeographicSpatialReference() { ISpatialReferenceFactory spatialRefFatcory = new SpatialReferenceEnvironmentClass(); IGeographicCoordinateSystem geoCoordSys; geoCoordSys = spatialRefFatcory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); //assign a user defined datum to the SR (just for the test) IDatum datum = new DatumClass(); IDatumEdit datumEdit = (IDatumEdit)datum; ISpheroid spheroid = spatialRefFatcory.CreateSpheroid((int)esriSRSpheroidType.esriSRSpheroid_Clarke1880); datumEdit.DefineEx("MyDatum", "My Datum", "MDTM", "", spheroid); IPrimeMeridian primeMeridian = spatialRefFatcory.CreatePrimeMeridian((int)esriSRPrimeMType.esriSRPrimeM_Greenwich); IAngularUnit angularUnits = spatialRefFatcory.CreateUnit((int)esriSRUnitType.esriSRUnit_Degree) as IAngularUnit; IGeographicCoordinateSystemEdit geoCoordSysEdit = (IGeographicCoordinateSystemEdit)geoCoordSys; geoCoordSysEdit.DefineEx("MyGeoCoordSys", "MyGeoCoordSys", "MGCS", "", "", datum, primeMeridian, angularUnits); geoCoordSys.SetFalseOriginAndUnits(-180.0, -180.0, 5000000.0); geoCoordSys.SetZFalseOriginAndUnits(0.0, 100000.0); geoCoordSys.SetMFalseOriginAndUnits(0.0, 100000.0); return geoCoordSys as ISpatialReference; } } }
{ "content_hash": "2243bed35afb6f860721dcce29a83689", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 121, "avg_line_length": 38.532710280373834, "alnum_prop": 0.6929420325006064, "repo_name": "Esri/arcobjects-sdk-community-samples", "id": "29e9c75f368ec827943f010b6884a4aba276867c", "size": "4706", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Net/SDK_General/PersistStream/CSharp/ClonableObj/TestApp/TestClass.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "17067" }, { "name": "C#", "bytes": "7769223" }, { "name": "C++", "bytes": "454756" }, { "name": "HTML", "bytes": "6209" }, { "name": "JavaScript", "bytes": "3064" }, { "name": "Makefile", "bytes": "570" }, { "name": "Objective-C", "bytes": "2417" }, { "name": "Visual Basic .NET", "bytes": "5250403" }, { "name": "XSLT", "bytes": "73678" } ], "symlink_target": "" }
<!doctype html> <html> <head> <title>touch-action: parent: none + two embedded children</title> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" type="text/css" href="pointerevent_styles.css"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/resources/testdriver.js"></script> <script src="/resources/testdriver-actions.js"></script> <script src="/resources/testdriver-vendor.js"></script> <script src="pointerevent_support.js"></script> <style> #divParent { touch-action: none; } </style> </head> <body onload="run()"> <h1>Pointer Events touch-action attribute support</h1> <h4 id="desc">Test Description: Try to scroll text DOWN inside blue rectangle. Wait for description update. Expected: pan enabled</h4> <p>Note: this test is for touch-devices only</p> <div id="divParent"> <div class="scroller" id="target0"> <div id="scrollTarget"> <p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. </p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. </p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. </p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. </p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> <p>Lorem ipsum dolor sit amet...</p> </div> </div> </div> <script type='text/javascript'> var detected_pointertypes = {}; var xScrollIsReceived = false; var yScrollIsReceived = false; var xScr0, yScr0, xScr1, yScr1; add_completion_callback(showPointerTypes); add_completion_callback(enableScrolling); function run() { var target0 = document.getElementById("target0"); var test_touchaction = async_test("touch-action attribute test"); var actions_promise; xScr0 = target0.scrollLeft; yScr0 = target0.scrollTop; on_event(target0, 'pointerdown', function(event) { detected_pointertypes[event.pointerType] = true; }); // Check if touch-action attribute works properly for embedded divs // // TA: 15. on_event(target0, 'scroll', function(event) { xScr1 = target0.scrollLeft; yScr1 = target0.scrollTop; if(xScr1 != xScr0) { xScrollIsReceived = true; } if(yScr1 != yScr0) { yScrollIsReceived = true; updateDescriptionNextStep(); } if(xScrollIsReceived && yScrollIsReceived) { // Make sure the test finishes after all the input actions are completed. actions_promise.then( () => { test_touchaction.done(); }); updateDescriptionComplete(); } }); // Inject touch inputs and wait for all the actions finish to end the test. actions_promise = touchScrollInTarget(target0, 'down').then(function() { return touchScrollInTarget(target0, 'right'); }); } function enableScrolling() { document.getElementById('divParent').setAttribute('style', 'touch-action: auto'); } </script> <h1>behaviour: auto</h1> <div id="complete-notice"> <p>The following pointer types were detected: <span id="pointertype-log"></span>.</p> </div> <div id="log"></div> </body> </html>
{ "content_hash": "def3f16a56e39bb139a5ac3f8625060f", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 142, "avg_line_length": 47.5448275862069, "alnum_prop": 0.502901073397157, "repo_name": "scheib/chromium", "id": "3ec5998b54d1677dee7dc15b6a6c5cec1750a55d", "size": "6894", "binary": false, "copies": "32", "ref": "refs/heads/main", "path": "third_party/blink/web_tests/external/wpt/pointerevents/pointerevent_touch-action-inherit_highest-parent-none_touch.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
/* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the top of the * compiled file, but it's generally better to create a new file per style scope. * *= require_self *= require_tree . *= require jquery.ui.all */
{ "content_hash": "3befddd745f39fa9e8d1e3e5575f514b", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 101, "avg_line_length": 40.785714285714285, "alnum_prop": 0.7373029772329247, "repo_name": "billywatson/rails-movie-database", "id": "380f6bf801a5ddf2da2a82333245984d118074b3", "size": "571", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/assets/stylesheets/application.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CoffeeScript", "bytes": "458" }, { "name": "JavaScript", "bytes": "667" }, { "name": "Ruby", "bytes": "32097" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "e367b4be3a9d8ec339c280e62463d0dc", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "b6648f2cc80d18479c9534704ee30155d413b564", "size": "182", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Commelinales/Haemodoraceae/Blancoa/Blancoa canescens/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
'use strict' const JsonApi = require('devour-client') const Kitsu = new JsonApi({ apiUrl: 'https://kitsu.io/api/edge', logger: false, }) module.exports = Kitsu
{ "content_hash": "8006d1dd97978a73f570e1a7f084ef42", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 40, "avg_line_length": 16.7, "alnum_prop": 0.6826347305389222, "repo_name": "arandilopez/kijutsu", "id": "4fd49a95d485c0752a0741c44f57722f27a9398d", "size": "167", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/api/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "9749" } ], "symlink_target": "" }
<?php namespace admin\models; use common\helpers\ArrayHelper; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; /** * OrderInfoSearch represents the model behind the search form about `admin\models\OrderInfo`. */ class ReportSearch extends OrderDetail { public function rules() { return [ [['oid', 'gid','pay_id'], 'integer'], [['single_price', 'total_price'], 'number'], [['order_date','sid','good_type'],'safe'], [['order_code'],'string'] ]; } public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } public static function getOrderCode(){ //pay_id in (2,3) and4 $admin = Yii::$app->user->identity; $admin_type = $admin->wa_type; $admin_id = $admin->wa_id; $query = OrderInfo::find()->where("state between 2 and 7"); if($admin_type==3){ $merchant_info = MerchantInfo::findOne(['wa_id'=>$admin_id]); $query->andWhere("good_info.merchant=$merchant_info->id"); } $orders = $query->all(); $data = ArrayHelper::getColumn($orders,'order_code'); return $data; } public static function getShops(){ $admin = Yii::$app->user->identity; $admin_type = $admin->wa_type; $admin_id = $admin->wa_id; $query = ShopInfo::find()->joinWith('orderInfos')->where("order_info.id>0 and state between 2 and 7"); if($admin_type==3){ $merchant_info = MerchantInfo::findOne(['wa_id'=>$admin_id]); $query->andWhere("good_info.merchant=$merchant_info->id"); } $shops = $query->all(); $data = ArrayHelper::map($shops,'id','name'); return $data; } public static function getTypes(){ $admin = Yii::$app->user->identity; $admin_type = $admin->wa_type; $admin_id = $admin->wa_id; $query = OrderDetail::find()->joinWith(['o','g'])->leftJoin('good_type','good_type.id=good_info.type')->addSelect([ 'good_type.id as good_type', 'good_type.name as type_name', ])->where("state between 2 and 7"); if($admin_type==3){ $merchant_info = MerchantInfo::findOne(['wa_id'=>$admin_id]); $query->andWhere("good_info.merchant=$merchant_info->id"); } $types = $query->all(); $data = ArrayHelper::map($types,'good_type','type_name'); return $data; } public static function getGoods(){ $admin = Yii::$app->user->identity; $admin_type = $admin->wa_type; $admin_id = $admin->wa_id; $query = OrderDetail::find()->joinWith(['o','g'])->addSelect([ 'gid', 'concat(good_info.name,good_info.volum) as good_name', ])->where("state between 2 and 7")->groupBy('gid'); $goods = $query->all(); if($admin_type==3){ $merchant_info = MerchantInfo::findOne(['wa_id'=>$admin_id]); $query->andWhere("good_info.merchant=$merchant_info->id"); } $data = ArrayHelper::map($goods,'gid','good_name'); return $data; } public function search($params) { $admin = Yii::$app->user->identity; $admin_type = $admin->wa_type; $admin_id = $admin->wa_id; //pay_id in (2,3) and4 $query = OrderDetail::find()->joinWith(['o','g'])->leftJoin('good_type','good_type.id=good_info.type') ->leftJoin(" (select sum(good_info.cost*order_detail.amount) as cost,oid from order_detail left join good_info on order_detail.gid=good_info.id group by oid) cost ",'cost.oid=order_detail.oid')->addSelect([ 'order_detail.*', 'order_info.order_date as order_date', 'order_info.order_code as order_code', 'order_info.sid as sid', 'order_info.pay_id as pay_id', 'order_info.discount as discount', 'order_info.point as point', 'order_info.pay_bill as pay_bill', 'good_type.id as good_type', '(cost.cost+order_info.send_bill) as cost', '(order_info.pay_bill-cost.cost-order_info.send_bill) as real_profit', '(order_info.pay_bill+order_info.discount+order_info.point-cost.cost-order_info.send_bill) as profit' ])->where("state between 2 and 7 and order_info.status=1"); if($admin_type==3){ $manager = MerchantInfo::findOne(['wa_id'=>$admin_id]); if(!empty($manager)){ $shops = ShopInfo::find()->where(['merchant'=>$manager->id])->all(); $idArr = array_values(ArrayHelper::getColumn($shops,'id')); if(!empty($idArr)){ $query->andWhere("order_info.sid in (".implode(',',$idArr).")"); }else{ $query->andWhere('order_info.sid=0'); } }else{ $query->andWhere('order_info.sid=0'); } }elseif ($admin_type==4){ $manager = ShopInfo::findOne(['wa_id'=>$admin_id]); if(!empty($manager)){ $query->andWhere("order_info.sid=$manager->id"); }else{ $query->andWhere('order_info.sid=0'); } } $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $sort = $dataProvider->getSort(); $sort->attributes = [ 'profit'=>[ 'asc' => ['profit' => SORT_ASC], 'desc' => ['profit' => SORT_DESC], 'label' => 'profit', ], 'real_profit'=>[ 'asc' => ['real_profit' => SORT_ASC], 'desc' => ['real_profit' => SORT_DESC], 'label' => 'real_profit', ], 'discount'=>[ 'asc' => ['discount' => SORT_ASC], 'desc' => ['discount' => SORT_DESC], 'label' => 'discount', ], 'point'=>[ 'asc' => ['point' => SORT_ASC], 'desc' => ['point' => SORT_DESC], 'label' => 'point', ], 'cost'=>[ 'asc' => ['cost' => SORT_ASC], 'desc' => ['cost' => SORT_DESC], 'label' => 'cost', ], 'order_date'=>[ 'asc' => ['order_info.order_date' => SORT_ASC], 'desc' => ['order_info.order_date' => SORT_DESC], 'label' => 'order_info.order_date', ], 'pay_bill'=>[ 'asc' => ['order_info.pay_bill' => SORT_ASC], 'desc' => ['order_info.pay_bill' => SORT_DESC], 'label' => 'order_info.pay_bill', ], ]; $sort->defaultOrder = ['order_date' => SORT_DESC]; $dataProvider->pagination->pageSize=100; if (!($this->load($params) && $this->validate())) { $start = date('Y-m-01',time()); $end = date('Y-m-d', strtotime($start . ' +1 month -1 day')); $params['ReportSearch']['order_date'] = $start.' to '.$end; $this->load($params); $query->andWhere(['between', 'order_info.order_date', strtotime("$start 00:00:00"),strtotime("$end 23:59:59")]); return $dataProvider; } $query->andFilterWhere(['like', 'order_info.order_code', $this->order_code]); if(!empty($this->sid)){ $query->andFilterWhere(['in','order_info.sid',$this->sid]); } if(!empty($this->good_type)){ $query->andFilterWhere(['in','good_type.id',$this->good_type]); } $query->andFilterWhere(['=', 'order_info.pay_id', $this->pay_id]) ->andFilterWhere(['=', 'gid', $this->gid]); if(!empty($this->order_date)){ $order_date = explode('to',str_replace(' ','',$this->order_date)); $query->andFilterWhere(['between', 'order_info.order_date', strtotime("$order_date[0] 00:00:00"),strtotime("$order_date[1] 23:59:59")]); } return $dataProvider; } }
{ "content_hash": "99f6add7117d5efd823b7893bb0c9cad", "timestamp": "", "source": "github", "line_count": 204, "max_line_length": 161, "avg_line_length": 40.46078431372549, "alnum_prop": 0.49600193845408286, "repo_name": "shenzhongwei/wine", "id": "9e498a1cff706de7d3b4b9903927157295cfc4e1", "size": "8254", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "admin/models/ReportSearch.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "300" }, { "name": "Batchfile", "bytes": "2061" }, { "name": "CSS", "bytes": "877774" }, { "name": "HTML", "bytes": "26485" }, { "name": "JavaScript", "bytes": "1788932" }, { "name": "PHP", "bytes": "1583831" }, { "name": "Shell", "bytes": "3257" } ], "symlink_target": "" }
import java.util.Random; import java.util.Scanner; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class PrimMain { public static boolean isPrimzahl(int zahl) { boolean values[] = new boolean[zahl + 2]; for (int i = 2; i <= zahl; ++i) { for (int j = i + i; j <= zahl; j += i) { values[j] = true; } } return values[zahl]; } public static void main(String[] args) { long eingabe = -1; Scanner sc = new Scanner(System.in); ExecutorService pool = Executors.newFixedThreadPool(5); // Testdaten, einkommentieren fuer viele Werte /*int anzahl = 10000000; for (int i = anzahl; i < anzahl * 10; ++i) { Callable<Boolean> pr = new Primzahl((long) (Math.random() * anzahl)); Future<Boolean> future = pool.submit(pr); }*/ do { System.out.println("Eingabe: "); eingabe = Long.parseLong(sc.nextLine()); if (eingabe > 0) { Callable<Boolean> pr = new Primzahl(eingabe); Future<Boolean> ft = pool.submit(pr); // Berechnung gibt Ergebnis aus, boolean wird nur zurueck gegeben weil Java bloed ist und kein void erlaubt } else { System.out.println("Nur Werte groesser 0 sind erlaubt."); } } while (eingabe != -1); pool.shutdown(); System.out.println("Programm wird beendet ..."); sc.close(); } }
{ "content_hash": "e5c47ef44e2c5525d12d4222176bb3e8", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 151, "avg_line_length": 28.183673469387756, "alnum_prop": 0.664011585807386, "repo_name": "florianm93/studium", "id": "0a405400bcce0269145faf9aa77f6a0cfa5d5365", "size": "1381", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "its/ue05.02/aufgabe_c/PrimMain.java", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "1046" }, { "name": "C", "bytes": "2548" }, { "name": "C++", "bytes": "22146" }, { "name": "CSS", "bytes": "3237" }, { "name": "HTML", "bytes": "2129534" }, { "name": "Java", "bytes": "35971" }, { "name": "Makefile", "bytes": "641" }, { "name": "Python", "bytes": "10459" }, { "name": "Shell", "bytes": "396" }, { "name": "TeX", "bytes": "24983" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="../includes/main.css" type="text/css"> <link rel="shortcut icon" href="../favicon.ico" type="image/x-icon"> <title>Apache CloudStack | The Power Behind Your Cloud</title> </head> <body> <div id="insidetopbg"> <div id="inside_wrapper"> <div class="uppermenu_panel"> <div class="uppermenu_box"></div> </div> <div id="main_master"> <div id="inside_header"> <div class="header_top"> <a class="cloud_logo" href="http://cloudstack.org"></a> <div class="mainemenu_panel"></div> </div> </div> <div id="main_content"> <div class="inside_apileftpanel"> <div class="inside_contentpanel" style="width:930px;"> <div class="api_titlebox"> <div class="api_titlebox_left"> <span> Apache CloudStack v4.9.0 Root Admin API Reference </span> <p></p> <h1>rebootSystemVm</h1> <p>Reboots a system VM.</p> </div> <div class="api_titlebox_right"> <a class="api_backbutton" href="../index.html"></a> </div> </div> <div class="api_tablepanel"> <h2>Request parameters</h2> <table class="apitable"> <tr class="hed"> <td style="width:200px;"><strong>Parameter Name</strong></td><td style="width:500px;">Description</td><td style="width:180px;">Required</td> </tr> <tr> <td style="width:200px;"><strong>id</strong></td><td style="width:500px;"><strong>The ID of the system virtual machine</strong></td><td style="width:180px;"><strong>true</strong></td> </tr> </table> </div> <div class="api_tablepanel"> <h2>Response Tags</h2> <table class="apitable"> <tr class="hed"> <td style="width:200px;"><strong>Response Name</strong></td><td style="width:500px;">Description</td> </tr> <tr> <td style="width:200px;"><strong>id</strong></td><td style="width:500px;">the ID of the system VM</td> </tr> <tr> <td style="width:200px;"><strong>activeviewersessions</strong></td><td style="width:500px;">the number of active console sessions for the console proxy system vm</td> </tr> <tr> <td style="width:200px;"><strong>created</strong></td><td style="width:500px;">the date and time the system VM was created</td> </tr> <tr> <td style="width:200px;"><strong>dns1</strong></td><td style="width:500px;">the first DNS for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>dns2</strong></td><td style="width:500px;">the second DNS for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>gateway</strong></td><td style="width:500px;">the gateway for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>hostid</strong></td><td style="width:500px;">the host ID for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>hostname</strong></td><td style="width:500px;">the hostname for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>hypervisor</strong></td><td style="width:500px;">the hypervisor on which the template runs</td> </tr> <tr> <td style="width:200px;"><strong>jobid</strong></td><td style="width:500px;">the job ID associated with the system VM. This is only displayed if the router listed is part of a currently running asynchronous job.</td> </tr> <tr> <td style="width:200px;"><strong>jobstatus</strong></td><td style="width:500px;">the job status associated with the system VM. This is only displayed if the router listed is part of a currently running asynchronous job.</td> </tr> <tr> <td style="width:200px;"><strong>linklocalip</strong></td><td style="width:500px;">the link local IP address for the system vm</td> </tr> <tr> <td style="width:200px;"><strong>linklocalmacaddress</strong></td><td style="width:500px;">the link local MAC address for the system vm</td> </tr> <tr> <td style="width:200px;"><strong>linklocalnetmask</strong></td><td style="width:500px;">the link local netmask for the system vm</td> </tr> <tr> <td style="width:200px;"><strong>name</strong></td><td style="width:500px;">the name of the system VM</td> </tr> <tr> <td style="width:200px;"><strong>networkdomain</strong></td><td style="width:500px;">the network domain for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>podid</strong></td><td style="width:500px;">the Pod ID for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>privateip</strong></td><td style="width:500px;">the private IP address for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>privatemacaddress</strong></td><td style="width:500px;">the private MAC address for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>privatenetmask</strong></td><td style="width:500px;">the private netmask for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>publicip</strong></td><td style="width:500px;">the public IP address for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>publicmacaddress</strong></td><td style="width:500px;">the public MAC address for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>publicnetmask</strong></td><td style="width:500px;">the public netmask for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>state</strong></td><td style="width:500px;">the state of the system VM</td> </tr> <tr> <td style="width:200px;"><strong>systemvmtype</strong></td><td style="width:500px;">the system VM type</td> </tr> <tr> <td style="width:200px;"><strong>templateid</strong></td><td style="width:500px;">the template ID for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>zoneid</strong></td><td style="width:500px;">the Zone ID for the system VM</td> </tr> <tr> <td style="width:200px;"><strong>zonename</strong></td><td style="width:500px;">the Zone name for the system VM</td> </tr> </table> </div> </div> </div> </div> </div> <div id="footer"> <div id="comments_thread"> <script type="text/javascript" src="https://comments.apache.org/show_comments.lua?site=test" async="true"></script> <noscript> <iframe width="930" height="500" src="https://comments.apache.org/iframe.lua?site=test&amp;page=4.2.0/rootadmin"></iframe> </noscript> </div> <div id="footer_mainmaster"> <p>Copyright &copy; 2015 The Apache Software Foundation, Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0.</a> <br> Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo and the Apache feather logo are trademarks of The Apache Software Foundation.</p> </div> </div> </div> </div> </body> </html>
{ "content_hash": "01260da471a9ea37660eff8b0f81490f", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 225, "avg_line_length": 40.4478527607362, "alnum_prop": 0.69164265129683, "repo_name": "terbolous/cloudstack-www", "id": "62b485ebb0bc4e948ac4ef068260c115ecc7c2ad", "size": "6593", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "source/api/apidocs-4.9/apis/rebootSystemVm.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "303768" }, { "name": "HTML", "bytes": "123165841" }, { "name": "Python", "bytes": "2684" }, { "name": "Ruby", "bytes": "1967" }, { "name": "Shell", "bytes": "861" } ], "symlink_target": "" }
const shell = require('shelljs') const successMessage = 'The build folder is ready to be deployed.' const result = shell.exec('timeout react-scripts build -t 1m') if (result.stdout.includes(successMessage)) process.exit(0) else process.exit(result.code)
{ "content_hash": "06ea2dd34e7867c48eddfc630f116fda", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 66, "avg_line_length": 28.88888888888889, "alnum_prop": 0.7538461538461538, "repo_name": "entirc/kanban-board", "id": "fec0807e89c1a217395cba1aab1161a09f009fa4", "size": "260", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2042" }, { "name": "HTML", "bytes": "1593" }, { "name": "JavaScript", "bytes": "17339" } ], "symlink_target": "" }
package org.wso2.bench; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.LastHttpContent; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; public class DelayedElement implements Delayed { private long DELAY; private ChannelHandlerContext ctx; private LastHttpContent trailer; private HttpRequest request; private byte[] buf; private String responseContentType; protected long timestamp; public DelayedElement(ChannelHandlerContext ctx, LastHttpContent trailer, HttpRequest request, byte[] buf, long receivedTime, int delay, String responseContentType) { DELAY = delay; this.ctx = ctx; this.trailer = trailer; this.request = request; this.buf = buf; this.timestamp = receivedTime; this.responseContentType = responseContentType; } public long getDelay(TimeUnit unit) { return DELAY - (System.currentTimeMillis() - this.timestamp); } public int compareTo(Delayed other) { long comparison = ((org.wso2.bench.DelayedElement) other).timestamp - this.timestamp; if(comparison > 0) { return -1; } else if(comparison < 0) { return 1; } else { return 0; } } public byte[] getBuf() { return buf; } public ChannelHandlerContext getContext() { return ctx; } public LastHttpContent getTrailer() { return trailer; } public HttpRequest getRequest() { return this.request; } public String getResponseContentType() { return this.responseContentType; } }
{ "content_hash": "c77ebd315aaf760bd5c7c5a278228b9e", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 170, "avg_line_length": 25.83582089552239, "alnum_prop": 0.659734257654535, "repo_name": "isururanawaka/netty5-mock-backend", "id": "fae07299372720bd05f8843af1107299c2d88a1c", "size": "1731", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/org/wso2/bench/DelayedElement.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "20773" } ], "symlink_target": "" }
SpecBegin(Sale); describe(@"past auction", ^{ __block Sale *_pastAuction; beforeEach(^{ _pastAuction = [Sale saleWithStart:[NSDate distantPast] end:[NSDate distantPast]]; }); it(@"is not active", ^{ expect(_pastAuction.isCurrentlyActive).to.beFalsy(); }); }); describe(@"current auction", ^{ __block Sale *_currentAuction; beforeEach(^{ _currentAuction = [Sale saleWithStart:[NSDate distantPast] end:[NSDate distantFuture]]; }); it(@"is active", ^{ expect(_currentAuction.isCurrentlyActive).to.beTruthy(); }); }); describe(@"future auction", ^{ __block Sale *_futureAuction; beforeEach(^{ _futureAuction = [Sale saleWithStart:[NSDate distantFuture] end:[NSDate distantFuture]]; }); it(@"is active", ^{ expect(_futureAuction.isCurrentlyActive).to.beFalsy(); }); }); describe(@"propertiess", ^{ __block Sale *auction; it(@"has a buyers premium", ^{ auction = [Sale saleWithBuyersPremium]; expect([auction hasBuyersPremium]).to.beTruthy(); }); it(@"has a buyers premium", ^{ auction = [Sale modelWithJSON:@{}]; expect([auction hasBuyersPremium]).to.beFalsy(); }); }); SpecEnd
{ "content_hash": "cb93f9404d5396e64b80d2284911fdda", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 96, "avg_line_length": 23.09259259259259, "alnum_prop": 0.6070569366479551, "repo_name": "TribeMedia/eigen", "id": "0ee653d3d52a422c8b6fc6d1262410dd3243ddc6", "size": "1247", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "Artsy_Tests/Model_Tests/SaleTests.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1628" }, { "name": "C++", "bytes": "2858" }, { "name": "HTML", "bytes": "624" }, { "name": "JavaScript", "bytes": "2463" }, { "name": "Makefile", "bytes": "5950" }, { "name": "Objective-C", "bytes": "2045552" }, { "name": "Ruby", "bytes": "13499" }, { "name": "VimL", "bytes": "428" } ], "symlink_target": "" }
title: 'Hey, you got your Ruby in my Clojure!' author: Jim Crossley layout: news sequence: 2 tags: [ overlay, torquebox, polyglot, app-server ] --- <div class="notice big"> <i><b>UPDATE</b></i>: This article is obsolete. See <a href="/tutorials/overlay/">the Overlay Tutorial</a> for current documentation and examples. </div> Recently, we've made some progress toward the promise of a polyglot application server. With the introduction of the [Overlay] project, it's now very easy to create a single app server capable of deploying both Ruby and Clojure (not to mention Java, of course) applications. ## Laying TorqueBox over Immutant The same [Leiningen Immutant plugin][plugin] that you use to install Immutant may be used to overlay the latest [TorqueBox] as well: $ lein immutant overlay torquebox And voila, your Immutant is suddenly also a TorqueBox! Now we need to set up your environment for TorqueBox development. $ export TORQUEBOX_HOME=$HOME/.lein/immutant/current $ export PATH=$TORQUEBOX_HOME/jruby/bin:$PATH The TorqueBox distribution provides its own JRuby with the TorqueBox gems pre-installed. You can now use the `torquebox` command to deploy your Ruby applications to your Immutant! ## Laying Immutant over TorqueBox If you'd rather use your own JRuby, and you've already installed the `torquebox-server` gem, you can overlay the latest Immutant by cloning the [Overlay] project locally, installing [Leiningen] and running the following: $ lein run :overlay $(torquebox env TORQUEBOX_HOME) immutant All that's left is to set `IMMUTANT_HOME` and [proceed as you normally would][deploying]: $ export IMMUTANT_HOME=$(torquebox env TORQUEBOX_HOME) The [Overlay] project is capable of overlaying features from any JBoss AS7 distribution onto another one. ## Convenient Combo-Pack For your convenience, we've set up a job on our CI server to overlay the latest Immutant build atop the latest [TorqueBox] build whenever either is updated. So you can be on the bleeding edge of both projects by downloading and extracting this link: <http://immutant.org/builds/torquebox-immutant.zip> Set both `TORQUEBOX_HOME` and `IMMUTANT_HOME` to the extracted directory, and... ## Get Your Polyglot On! Your overlaid server may be started however you're comfortable: either using the [Leiningen] Immutant plugin, the [TorqueBox] command or even the standard JBoss commands. It will start up all the apps you've deployed to it, regardless of their language. If you have any trouble at all, please drop by #torquebox or #immutant on freenode, and we'll get you going. [TorqueBox]: http://torquebox.org/ [Overlay]: http://github.com/immutant/overlay [deploying]: http://immutant.org/news/2011/11/08/deploying-an-application/ [Leiningen]: https://github.com/technomancy/leiningen [plugin]: http://immutant.org/news/2011/12/21/installing-redux/
{ "content_hash": "3bd7048d8d98418f422a7e0e50d34e8b", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 89, "avg_line_length": 36.2, "alnum_prop": 0.7662292817679558, "repo_name": "immutant/immutant.org", "id": "5e6f6b8a12b2f86d101be2cb9c3fe5c6ecb5847c", "size": "2900", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "news/2011-12-21-overlay.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "170161" }, { "name": "HTML", "bytes": "9208445" }, { "name": "JavaScript", "bytes": "93858" }, { "name": "Ruby", "bytes": "17263" } ], "symlink_target": "" }
#ifndef GRPC_SUPPORT_CMDLINE_H #define GRPC_SUPPORT_CMDLINE_H #include <grpc/support/port_platform.h> #ifdef __cplusplus extern "C" { #endif /** Simple command line parser. Supports flags that can be specified as -foo, --foo, --no-foo, -no-foo, etc And integers, strings that can be specified as -foo=4, -foo blah, etc No support for short command line options (but we may get that in the future.) Usage (for a program with a single flag argument 'foo'): int main(int argc, char **argv) { gpr_cmdline *cl; int verbose = 0; cl = gpr_cmdline_create("My cool tool"); gpr_cmdline_add_int(cl, "verbose", "Produce verbose output?", &verbose); gpr_cmdline_parse(cl, argc, argv); gpr_cmdline_destroy(cl); if (verbose) { gpr_log(GPR_INFO, "Goodbye cruel world!"); } return 0; } */ typedef struct gpr_cmdline gpr_cmdline; /** Construct a command line parser: takes a short description of the tool doing the parsing */ GPRAPI gpr_cmdline *gpr_cmdline_create(const char *description); /** Add an integer parameter, with a name (used on the command line) and some helpful text (used in the command usage) */ GPRAPI void gpr_cmdline_add_int(gpr_cmdline *cl, const char *name, const char *help, int *value); /** The same, for a boolean flag */ GPRAPI void gpr_cmdline_add_flag(gpr_cmdline *cl, const char *name, const char *help, int *value); /** And for a string */ GPRAPI void gpr_cmdline_add_string(gpr_cmdline *cl, const char *name, const char *help, char **value); /** Set a callback for non-named arguments */ GPRAPI void gpr_cmdline_on_extra_arg( gpr_cmdline *cl, const char *name, const char *help, void (*on_extra_arg)(void *user_data, const char *arg), void *user_data); /** Enable surviving failure: default behavior is to exit the process */ GPRAPI void gpr_cmdline_set_survive_failure(gpr_cmdline *cl); /** Parse the command line; returns 1 on success, on failure either dies (by default) or returns 0 if gpr_cmdline_set_survive_failure() has been called */ GPRAPI int gpr_cmdline_parse(gpr_cmdline *cl, int argc, char **argv); /** Destroy the parser */ GPRAPI void gpr_cmdline_destroy(gpr_cmdline *cl); /** Get a string describing usage */ GPRAPI char *gpr_cmdline_usage_string(gpr_cmdline *cl, const char *argv0); #ifdef __cplusplus } #endif #endif /* GRPC_SUPPORT_CMDLINE_H */
{ "content_hash": "fcc88bfd95d25236bb56cdf809b2d974", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 78, "avg_line_length": 34.541666666666664, "alnum_prop": 0.6658624849215923, "repo_name": "vsco/grpc", "id": "5a83afb464ebf10424fe3a49aa3b372df9c2c811", "size": "4055", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "include/grpc/support/cmdline.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "22179" }, { "name": "C", "bytes": "7323483" }, { "name": "C#", "bytes": "1548283" }, { "name": "C++", "bytes": "2289323" }, { "name": "CMake", "bytes": "442139" }, { "name": "DTrace", "bytes": "147" }, { "name": "JavaScript", "bytes": "413281" }, { "name": "M4", "bytes": "41851" }, { "name": "Makefile", "bytes": "868728" }, { "name": "Objective-C", "bytes": "357513" }, { "name": "PHP", "bytes": "301699" }, { "name": "Protocol Buffer", "bytes": "127949" }, { "name": "PureBasic", "bytes": "147" }, { "name": "Python", "bytes": "1489401" }, { "name": "Ruby", "bytes": "708431" }, { "name": "Shell", "bytes": "59819" }, { "name": "Swift", "bytes": "5418" } ], "symlink_target": "" }
<?php defined('BX_DOL') or die('hack attempt'); require_once('BxDolMData.php'); bx_import('BxDolStudioLanguagesUtils'); class BxDolMProfilesFields extends BxDolMData { /** * @var $_aProfileFields profile fields for transfer */ private $_aProfileFields = array(); /** * @var $_aFiltered exclude listed filed from migration list */ private $_aFiltered = array( 'ID', 'NickName', 'Email', 'Password', 'Role', 'LangID', 'DateLastNav', 'DateReg', 'DateLastEdit', 'DateLastLogin', 'Sex', 'DateOfBirth', 'EmailNotify', 'Avatar', 'allow_view_to', 'Featured', 'DescriptionMe', 'FullName' ); /** * @var $_oAssocFields list of the fields from Dolphin */ private $_oAssocFields = null; public function __construct($oMigrationModule, &$mDb) { parent::__construct($oMigrationModule, $mDb); $this -> _sModuleName = 'profile_fields'; $this -> _sTableWithTransKey = 'sys_form_inputs'; } public function getTotalRecords() { $this -> _oAssocFields = $this -> getAssocFields(); foreach($this -> _oAssocFields as $sKey => $aValue) { if (in_array($aValue['name'], $this -> _aFiltered) || (!$aValue['add'] && !$aValue['edit'] && !$aValue['view'])) continue; $this -> _aProfileFields[$aValue['name']] = array( 'name' => $aValue['name'], 'type' => $this -> getConvertToUnaType($aValue['type']), 'caption' => $this -> getLKeyTranslations($aValue['title']), 'required' => $aValue['required'], 'add' => $aValue['add'], 'edit' => $aValue['edit'], 'view' => $aValue['view'], 'values' => $this -> getFieldValues($sKey) ); } return sizeof($this -> _aProfileFields); } /** * Convert Dolphin's fields types to UNA format * * @param int $sType Dolphin's field * @return array */ private function getConvertToUnaType($sType) { $aM2UNATypes = array( 'text' => array( 'type' => 'text', 'db_pass' => 'Xss', 'sql' => "varchar(255) default ''", ), 'system' => array( 'type' => 'text', 'db_pass' => 'Xss', 'sql' => "varchar(255) default ''", ), 'html_area' => array( 'type' => 'textarea', 'db_pass' => 'XssMultiline', 'sql' => "text default ''", ), 'area' => array( 'type' => 'textarea', 'db_pass' => 'XssMultiline', 'sql' => "text default ''", ), 'select_one' => array( 'type' => 'select', 'db_pass' => 'Xss', 'sql' => "varchar(255) default NULL", ), 'date' => array( 'type' => 'date', 'db_pass' => 'Date', 'sql' => "date default NULL", ), 'num' => array( 'type' => 'text', 'db_pass' => 'Int', 'sql' => "int(10) default NULL", ), 'bool' => array( 'type' => 'checkbox', 'db_pass' => 'Xss', 'sql' => "varchar(255) default NULL", ), 'select_set' => array( 'type' => 'checkbox_set', 'db_pass' => 'Set', 'sql' => "bigint(20) default NULL", ), 'pass' => array( 'type' => 'password', 'sql' => "varchar(40) default NULL", ), 'range' => array( 'type' => 'doublerange', 'db_pass' => 'Xss', 'sql' => "varchar(255) default NULL", ) ); return $aM2UNATypes[$sType] ? $aM2UNATypes[$sType] : $aM2UNATypes['text']; } public function runMigration() { if (!$this -> getTotalRecords()) { $this -> setResultStatus(_t('_bx_dolphin_migration_no_data_to_transfer')); return BX_MIG_SUCCESSFUL; } $this -> createMIdField(); $this -> setResultStatus(_t('_bx_dolphin_migration_started_migration_profile_fields')); $i = 0; foreach($this -> _aProfileFields as $sKey => $aItem) { if (!$this -> _oDb -> isFieldExists('bx_persons_data', $sKey)) { if (!$this -> _oDb -> query("ALTER TABLE `bx_persons_data` ADD `{$sKey}` {$aItem['type']['sql']}")){ $this -> setResultStatus(_t('_bx_dolphin_migration_started_migration_profile_field_can_not_be_transferred')); return BX_MIG_FAILED; } } //continue; if ($this -> isFieldTransfered($sKey)) continue; $iKeyID = time() + $i++; // unique language keys postfix $sQuery = $this -> _oDb -> prepare(" INSERT INTO `{$this -> _sTableWithTransKey}` SET `object` = 'bx_person', `module` = 'custom', `values` = ?, `name` = ?, `db_pass` = ?, `type` = ?, `required` = ?, `caption_system` = ?, `caption` = ?", $this -> transferPreValues($sKey, $aItem['name'], $aItem['values']), $sKey, $aItem['type']['db_pass'], $aItem['type']['type'], $aItem['required'], '_sys_form_txt_field_caption_system_' . $iKeyID, '_sys_form_txt_field_caption_' . $iKeyID ); if (!$this -> _oDb -> query($sQuery)) { $this -> setResultStatus(_t('_bx_dolphin_migration_started_migration_profile_field_can_not_be_transferred')); return BX_MIG_FAILED; } $iFieldId = $this -> _oDb -> lastId(); $this -> setMID($iFieldId, $iFieldId); // create form fields $this -> _oDb -> query($sQuery); $sQueryDisplay = "INSERT INTO `sys_form_display_inputs` (`id`, `display_name`, `input_name`, `visible_for_levels`, `active`, `order`) VALUES"; if ($aItem['view']) $sQueryDisplay .= "(NULL, 'bx_person_view', '{$sKey}', 2147483647, 1, 0),"; if ($aItem['add']) $sQueryDisplay .= "(NULL, 'bx_person_add', '{$sKey}', 2147483647, 1, 0),"; if ($aItem['edit']) $sQueryDisplay .= "(NULL, 'bx_person_edit', '{$sKey}', 2147483647, 1, 0),"; // add display for view and add forms $this -> _oDb -> query(trim($sQueryDisplay, ',')); // add lanungage keys with translations foreach($this -> _aLanguages as $sLangKey => $sValue) { $sTitle = isset($aItem['caption'][$sLangKey]) ? $aItem['caption'][$sLangKey] : $sKey; $this -> _oLanguage -> addLanguageString('_sys_form_txt_field_caption_system_' . $iKeyID, $sTitle, $this -> _aLanguages[$sLangKey], 0, false); $this -> _oLanguage -> addLanguageString('_sys_form_txt_field_caption_' . $iKeyID, $sTitle, $this -> _aLanguages[$sLangKey]); } $this -> _iTransferred++; } $this -> migrateProfileFieldsInfo(); $this -> setResultStatus(_t('_bx_dolphin_migration_started_migration_profile_fields_finished', $this -> _iTransferred)); return BX_MIG_SUCCESSFUL; } private function isFieldTransfered($sName) { $sQuery = $this -> _oDb -> prepare("SELECT COUNT(*) FROM `sys_form_inputs` WHERE `object` = 'bx_person' AND `module` = 'custom' AND `name` = ? LIMIT 1", $sName); return (int)$this -> _oDb -> getOne($sQuery) > 0; } /** * Returns Una profile fields list * @param int $iProfileId profile ID * @return array */ private function getPersonsFieldValues($iProfileId) { return $this -> _oDb -> getRow("SELECT * FROM `bx_persons_data` WHERE `id` = {$iProfileId} LIMIT 1"); } /** * Builds value for multivalues type fields * * @param array $aFiled fields params * @param string $sFiledValue value * @return int value */ private function convertValues($aFiled, $sFiledValue) { $aOriginalFields = $this -> getAssocFields(); if (!$aOriginalFields[$aFiled['name']]['values'] || $aOriginalFields[$aFiled['name']]['values'] && substr($aOriginalFields[$aFiled['name']]['values'], 0, 2) != '#!') return $sFiledValue; $aItems = explode(',', $sFiledValue); $aPairs = $this -> getPreValuesBy(substr($aOriginalFields[$aFiled['name']]['values'], 2), 'Value', 'Order'); $iResult = 0; foreach($aItems as $iKey => $sValue) $iResult += pow(2, (int)$aPairs[$sValue] - 1); return $iResult ? $iResult : $sFiledValue; } /** * Migrate profile fields values for transferred profiles * * @return void */ private function migrateProfileFieldsInfo() { $sQuery = "SELECT * FROM `" . $this -> _oConfig -> _aMigrationModules['profiles']['table_name'] . "`"; $aProfiles = $this -> _mDb -> getAll($sQuery); foreach($aProfiles as $iKey => $aProfile) { if (!($iProfileId = $this -> getContentId($aProfile['ID']))) continue; $aValues = array(); $sNewField = ''; $aCurrentMembersValues = $this -> getPersonsFieldValues($iProfileId); foreach($this -> _aProfileFields as $sFieldName => $aItem) { if (!(isset($aProfile[$sFieldName]) && $aProfile[$sFieldName] && empty($aCurrentMembersValues[$sFieldName]))) continue; $sNewField .= "`{$aItem['name']}` = :{$aItem['name']},"; $aValues[$sFieldName] = $this -> convertValues($aItem, $aProfile[$sFieldName]); } if ($sNewField) { $sNewField = trim($sNewField, ','); $sQuery = " UPDATE `bx_persons_data` SET {$sNewField} WHERE `id` = {$iProfileId} "; $this -> _oDb -> query($sQuery, $aValues); } } } /** * Builds list for fields lists with translations * * @param int $sField fields list's name * @param int $bGetKeyIfExists dont add values if list exists. * @return mixed array with fields list or pre values key list name */ public function getFieldValues($sField, $bGetKeyIfExists = true) { $sValues = $this -> _mDb -> getOne("SELECT `Values` FROM `sys_profile_fields` WHERE `name` = :name", array('name' => $sField)); if (empty($sValues)) return ''; $aItems = array(); if (substr($sValues, 0, 2) == '#!') { $sKey = substr($sValues, 2); if ($this -> isKeyPreKeyExits($sKey) && $bGetKeyIfExists) return $sValues; $aValues = $this -> getPreValuesBy($sKey); foreach($aValues as $iKey => $sValue) $aItems[$iKey] = $this -> getLKeyTranslations($sValue); } else { $aValues = preg_split('/\r\n|\n|\r/', $sValues); foreach($aValues as $iKey => $sValue) $aItems[$sValue] = $this -> getLKeyTranslations("_FieldValues_{$sValue}"); } return $aItems; } public function removeContent() { if (!$this -> _oDb -> isTableExists($this -> _sTableWithTransKey) || !$this -> _oDb -> isFieldExists($this -> _sTableWithTransKey, $this -> _sTransferFieldIdent)) return false; $aRecords = $this -> _oDb -> getAll("SELECT `ti` . * , `tdi`.`id` AS `di_id` , `tdi`.`display_name` AS `display_name` , `tdi`.`visible_for_levels` AS `visible_for_levels` FROM `sys_form_display_inputs` AS `tdi` LEFT JOIN `sys_form_inputs` AS `ti` ON `tdi`.`input_name` = `ti`.`name` WHERE `ti`.`object` = 'bx_person' AND `ti`.`{$this -> _sTransferFieldIdent}` !=0"); if (!empty($aRecords)) { $iNumber = 0; foreach($aRecords as $iKey => $aValue) { $sSql = $this -> _oDb -> prepare("DELETE `td`, `tdi` FROM `sys_form_display_inputs` AS `tdi` LEFT JOIN `sys_form_inputs` AS `td` ON `tdi`.`input_name`=`td`.`name` WHERE `td`.`object`='bx_person' AND `td`.`name` = ?", $aValue['name']); if ($this-> _oDb -> query($sSql)) { $oLanguage = BxDolStudioLanguagesUtils::getInstance(); if(!empty($aValue['caption'])) $oLanguage->deleteLanguageString($aValue['caption']); if(!empty($aValue['caption_system'])) $oLanguage->deleteLanguageString($aValue['caption_system']); if(!empty($aValue['info'])) $oLanguage->deleteLanguageString($aValue['info']); if(!empty($aValue['checker_error'])) $oLanguage->deleteLanguageString($aValue['checker_error']); (int)$this -> _oDb -> query("ALTER TABLE `bx_persons_data` DROP `{$aValue['name']}`"); $iNumber++; } } } parent::removeContent(); return $iNumber; } } /** @} */
{ "content_hash": "cfb6c1e43f60a53482ac088ed2a19010", "timestamp": "", "source": "github", "line_count": 375, "max_line_length": 238, "avg_line_length": 31.221333333333334, "alnum_prop": 0.5708062862999659, "repo_name": "unaio/una", "id": "8c4b7541f53e8bba5cad527f8f6ba0908d640635", "size": "11902", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modules/boonex/dolphin_migration/updates/9.0.4_9.0.5/source/classes/BxDolMProfilesFields.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9522763" }, { "name": "Dockerfile", "bytes": "2367" }, { "name": "HTML", "bytes": "6194660" }, { "name": "JavaScript", "bytes": "24733694" }, { "name": "Less", "bytes": "3020615" }, { "name": "Makefile", "bytes": "1196" }, { "name": "PHP", "bytes": "158741504" }, { "name": "Ruby", "bytes": "210" }, { "name": "Shell", "bytes": "3327" }, { "name": "Smarty", "bytes": "3461" } ], "symlink_target": "" }
function callPageDossiers(page, pagelimit, numForPage){ document.getElementsByClassName('current')[0].className=''; document.getElementById('ativo'+page).className = 'current'; var strURL = '/get_pageUPPPPDossiers/'+page+'/'+numForPage; $.ajax({type: 'GET', url: strURL }).done(function(r) { $('#pagDossiers').html(r); }).fail(function(r) { $('#pagDossiers').html('Erro'); }); } function callPageConcurso(page, pagelimit, numForPage){ document.getElementsByClassName('current')[0].className=''; document.getElementById('ativo'+page).className = 'current'; var strURL = '/get_pageUPPPPConcurso/'+page+'/'+numForPage; $.ajax({type: 'GET', url: strURL }).done(function(r) { $('#pagConcurso').html(r); }).fail(function(r) { $('#pagConcurso').html('Erro'); }); } function callPageEstudo(page, pagelimit, numForPage){ document.getElementsByClassName('current')[0].className=''; document.getElementById('ativo'+page).className = 'current'; var strURL = '/get_pageUPPPPEstudo/'+page+'/'+numForPage; $.ajax({type: 'GET', url: strURL }).done(function(r) { $('#pagEstudo').html(r); }).fail(function(r) { $('#pagEstudo').html('Erro'); }); } function callPageFaqs(page, pagelimit, numForPage){ document.getElementsByClassName('current')[0].className=''; document.getElementById('ativo'+page).className = 'current'; var strURL = '/get_pageUPPPPFaqs/'+page+'/'+numForPage; $.ajax({type: 'GET', url: strURL }).done(function(r) { $('#pagFaqs').html(r); }).fail(function(r) { $('#pagEstudo').html('Erro'); }); } //chamar por uma senha especifica function registarPergunta() { var pergunta = $('#pergunta_duvida').val(); if(pergunta == null || pergunta == ""){ alert("Por favor digite a sua pergunta ou duvida!"); }else{ $.ajax({type: 'POST', url: '/registarPergunta/' + pergunta }).done(function(r) { closeModel(); }).fail(function(r) { //$('#pergunta_duvida').val(''); alert("Erro no envio!"); }); } } //fecha o model function closeModel(){ $('#pergunta_duvida').val(''); $('#myModalPergunta').foundation('reveal', 'close'); }
{ "content_hash": "87da43f71868e581fa76d2bc9bb2a749", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 66, "avg_line_length": 36.088235294117645, "alnum_prop": 0.5590872045639772, "repo_name": "IdeaSolutionsOnline/ERP4R", "id": "b19ddbf99d3035c8feff5290264219b66433d60f", "size": "2455", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/static/js/upppp.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "280709" }, { "name": "HTML", "bytes": "631043" }, { "name": "JavaScript", "bytes": "90675" }, { "name": "PHP", "bytes": "2199" }, { "name": "Python", "bytes": "1808337" }, { "name": "Smarty", "bytes": "523490" } ], "symlink_target": "" }
package com.theseventhsense.datetime import com.theseventhsense.utils.types.SSDateTime.DateTime /** * Created by erik on 6/15/16. */ object Implicits extends AbstractImplicits { // implicit class RichDateTime(dateTime: DateTime) extends JavaTimeRichDateTime(dateTime: DateTime) }
{ "content_hash": "8d280033e089ada3e4a47a3b2bb0a092", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 102, "avg_line_length": 28.9, "alnum_prop": 0.7889273356401384, "repo_name": "7thsense/utils-datetime", "id": "b5dcbcaae6dcd18f80f824b3008eb9ad31eda152", "size": "289", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jvm/src/main/scala/com/theseventhsense/datetime/Implicits.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "57482" } ], "symlink_target": "" }
junit-extras ============ Helper listeners, runners and classes for JUnit
{ "content_hash": "1c2877abd9282bb27629fa94772860b0", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 47, "avg_line_length": 18.75, "alnum_prop": 0.68, "repo_name": "bivas/junit-extras", "id": "3f878fa91a8d302fb5b1de9afafe710ac6d4f4c9", "size": "75", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "1461" }, { "name": "Java", "bytes": "7900" } ], "symlink_target": "" }
/* * @test * @bug 4476378 * @summary Check that SO_REUSEADDR allows a server to restart * after a crash. */ import java.net.*; public class Restart { /* * Test that a server can bind to the same port after * a crash -- ie: while previous connection still in * TIME_WAIT state we should be able to re-bind if * SO_REUSEADDR is enabled. */ public static void main(String args[]) throws Exception { ServerSocket ss = new ServerSocket(0); Socket s1 = null, s2 = null; try { int port = ss.getLocalPort(); s1 = new Socket(InetAddress.getLocalHost(), port); s2 = ss.accept(); // close server socket and the accepted connection ss.close(); s2.close(); ss = new ServerSocket(); ss.bind( new InetSocketAddress(port) ); ss.close(); // close the client socket s1.close(); } finally { if (ss != null) ss.close(); if (s1 != null) s1.close(); if (s2 != null) s2.close(); } } }
{ "content_hash": "1e87e0c3d9737c56384d59dfb180a55d", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 62, "avg_line_length": 25.11111111111111, "alnum_prop": 0.5247787610619469, "repo_name": "rokn/Count_Words_2015", "id": "051e322e43f9b1b2c237ad4e6702686aa7e03e3f", "size": "2186", "binary": false, "copies": "21", "ref": "refs/heads/master", "path": "testing/openjdk/jdk/test/java/net/Socket/setReuseAddress/Restart.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "61802" }, { "name": "Ruby", "bytes": "18888605" } ], "symlink_target": "" }
#import "NSObject.h" @interface MSImageScalingSpecification : NSObject { int _assetTypeFlags; double _nominalShortSideLength; double _minimumLongSideLength; double _maximumLongSideLength; } + (id)assetsToGenerateFromImageWithInputSize:(struct CGSize)arg1 toConformToSpecifications:(id)arg2; + (id)specificationWithSharedAlbumSpecificationString:(id)arg1; @property(nonatomic) int assetTypeFlags; // @synthesize assetTypeFlags=_assetTypeFlags; @property(nonatomic) double maximumLongSideLength; // @synthesize maximumLongSideLength=_maximumLongSideLength; @property(nonatomic) double minimumLongSideLength; // @synthesize minimumLongSideLength=_minimumLongSideLength; @property(nonatomic) double nominalShortSideLength; // @synthesize nominalShortSideLength=_nominalShortSideLength; - (id)description; - (double)scaleFactorForInputSize:(struct CGSize)arg1; @end
{ "content_hash": "93c0f12e47ef22e85f50a75e4eeb0cb5", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 114, "avg_line_length": 38.391304347826086, "alnum_prop": 0.8199320498301246, "repo_name": "matthewsot/CocoaSharp", "id": "b32a46dfbaeb43a0b2aad000660434c3c371c29f", "size": "1023", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Headers/PrivateFrameworks/CoreMediaStream/MSImageScalingSpecification.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "259784" }, { "name": "C#", "bytes": "2789005" }, { "name": "C++", "bytes": "252504" }, { "name": "Objective-C", "bytes": "24301417" }, { "name": "Smalltalk", "bytes": "167909" } ], "symlink_target": "" }
package com.github.nikolaymakhonin.utils.serialization; import com.github.nikolaymakhonin.logger.Log; import com.github.nikolaymakhonin.utils.RefParam; import com.github.nikolaymakhonin.utils.strings.CharsetUtils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; public class StreamSerializerUtils { private static final int currentVersion = 3; // MAX_COMPRESSION_LEVEL public static boolean SaveToByteArray(final IStreamSerializable obj, final RefParam<byte[]> buffer) { return SaveToByteArray(obj, buffer, CompressMethod.None, 0, null, null, null); } public static boolean SaveToByteArray(final IStreamSerializable obj, final RefParam<byte[]> buffer, final CompressMethod compressMethod, final int compressionLevel, final String cryptKey, final String cryptIV, final Charset cryptEncoding) { try { final ByteArrayOutputStream memStream = new ByteArrayOutputStream(); if (SaveToStream(obj, memStream, compressMethod, compressionLevel, cryptKey, cryptIV, cryptEncoding)) { buffer.value = memStream.toByteArray(); memStream.close(); return true; } buffer.value = null; memStream.close(); return false; } catch (final IOException e) { Log.e("StreamSerializerUtils", "", e); buffer.value = null; return false; } } // public static boolean SaveToFile(final IStreamSerializable obj, final String filePath, final CompressMethod // compressMethod = CompressMethod.None, int compressionLevel = mika.utils.Serialization.MAX_COMPRESSION_LEVEL, // String cryptKey = null, String cryptIV = null, Charset cryptEncoding = null) // { // using (final Stream fileStream = FileUtils.FileOpenWrite(filePath)) // { // return SaveToStream(obj, fileStream, compressMethod, compressionLevel, cryptKey, cryptIV, cryptEncoding); // } // } // CompressionUtils.MAX_COMPRESSION_LEVEL public static boolean SaveToStream(final IStreamSerializable obj, final OutputStream stream, final CompressMethod compressMethod, final int compressionLevel, final String cryptKey , final String cryptIV, final Charset cryptEncoding) { try { final BinaryWriter writer = new BinaryWriter(stream); writer.write(currentVersion); switch (currentVersion) { case 3: writer.write(compressMethod.ordinal()); writer.write(compressionLevel); final boolean encrypt = cryptKey != null && cryptIV != null; writer.write(encrypt); if (compressMethod == CompressMethod.None && !encrypt) { obj.Serialize(writer); writer.flush(); } else { writer.flush(); final ByteArrayOutputStream bufferOutputStream = new ByteArrayOutputStream(); final BinaryWriter writer2 = new BinaryWriter(bufferOutputStream); obj.Serialize(writer2); writer2.flush(); ByteArrayInputStream bufferInputStream = new ByteArrayInputStream(bufferOutputStream.toByteArray()); if (compressMethod != CompressMethod.None) { if (encrypt) { final ByteArrayOutputStream packStream = new ByteArrayOutputStream(); final long result = CompressionUtils.Pack(bufferInputStream, packStream, compressMethod, compressionLevel); if (result < 0) { return false; } bufferInputStream = new ByteArrayInputStream(packStream.toByteArray()); } else { final long result = CompressionUtils.Pack(bufferInputStream, stream, compressMethod, compressionLevel); if (result < 0) { return false; } } } if (encrypt) { final boolean result = CryptUtils.Crypt(CryptMode.Encrypt, bufferInputStream, stream, cryptEncoding != null ? cryptEncoding : CharsetUtils.UTF8, cryptKey, cryptIV, false); if (!result) { return false; } } } break; } } catch (final Exception exception) { Log.e("UnknownLogTag", "", exception); return false; } return true; } public static boolean LoadFromByteArray(final IStreamSerializable obj, final byte[] buffer) { return LoadFromByteArray(obj, buffer, null, null); } /** @param cryptKey * - maxUsedLength = 24 bytes * @param cryptIV * - maxUsedLength = 8 bytes */ public static boolean LoadFromByteArray(final IStreamSerializable obj, final byte[] buffer, final String cryptKey, final String cryptIV) { try { if (buffer == null) { Log.e("UnknownLogTag", "buffer == null"); return false; } final ByteArrayInputStream memStream = new ByteArrayInputStream(buffer); final boolean result = loadFromStream(obj, memStream, cryptKey, cryptIV, null); memStream.close(); return result; } catch (final IOException e) { Log.e("StreamSerializerUtils", "", e); return false; } } // public static boolean LoadFromFile(final IStreamSerializable obj, final String filePath) // { // return LoadFromFile(obj, filePath, null, null); // } // // public static boolean LoadFromFile(final IStreamSerializable obj, final String filePath, final String cryptKey = // null, String cryptIV = null) // { // using (final Stream fileStream = FileUtils.FileOpenRead(filePath)) // { // return loadFromStream( obj, fileStream, null); // } // } public static boolean LoadFromStream(final IStreamSerializable obj, final ByteArrayInputStream stream, final String cryptKey, final String cryptIV, final Charset cryptEncoding) { return loadFromStream(obj, stream, cryptKey, cryptIV, cryptEncoding); } public static boolean LoadFromStream(final IStreamSerializable obj, final ByteArrayInputStream stream) { return loadFromStream(obj, stream, null, null, null); } private static boolean loadFromStream( final IStreamSerializable obj, InputStream stream, final String cryptKey, final String cryptIV, final Charset cryptEncoding) { try { BinaryReader reader = new BinaryReader(stream); final int version = reader.readInt(); CompressMethod compressMethod; switch (version) { case 3: compressMethod = CompressMethod.values()[reader.readInt()]; final int compressionLevel = reader.readInt(); final boolean encrypt = reader.readBoolean(); if (compressMethod != CompressMethod.None || encrypt) { if (encrypt) { final ByteArrayOutputStream decryptStream = new ByteArrayOutputStream(); final boolean result = CryptUtils.Crypt(CryptMode.Decrypt, stream, decryptStream, cryptEncoding != null ? cryptEncoding : CharsetUtils.UTF8, cryptKey, cryptIV, false); if (!result) { return false; } stream = new ByteArrayInputStream(decryptStream.toByteArray()); } if (compressMethod != CompressMethod.None) { final ByteArrayOutputStream unPackStream = new ByteArrayOutputStream(); final long result = CompressionUtils.UnPack(stream, unPackStream, compressMethod, compressionLevel); if (result < 0) { return false; } stream = new ByteArrayInputStream(unPackStream.toByteArray()); } reader = new BinaryReader(stream); } obj.DeSerialize(reader); break; default: Log.e("UnknownLogTag", "DeSerialize unavailable version: " + version); return false; } } catch (final Exception exception) { Log.e("UnknownLogTag", "", exception); return false; } return true; } }
{ "content_hash": "278761e6e5a49649ae3ddf4516f8f486", "timestamp": "", "source": "github", "line_count": 217, "max_line_length": 237, "avg_line_length": 44.382488479262676, "alnum_prop": 0.5476066867407331, "repo_name": "NikolayMakhonin/AndroidAppExample", "id": "f700307f4fd4085abe48b6ff30d650d152f93ce1", "size": "9631", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AndroidAppExample/Utils/src/main/java/com/github/nikolaymakhonin/utils/serialization/StreamSerializerUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "118" }, { "name": "Java", "bytes": "352580" } ], "symlink_target": "" }
#include "stdinc.hpp" #include "terrain_map.hpp" #include "resources/terrain_library.hpp" #include "utility/interpolate.hpp" #include "utility/triangle_utilities.hpp" #include "utility/math_utilities.hpp" namespace ts { namespace world { namespace map_components { IntRect bounding_box(const Pattern& pattern) { const auto& rect = pattern.rect; auto width = std::abs(rect.width * pattern.transformation[0]) + std::abs(rect.height * pattern.transformation[1]); auto height = std::abs(rect.width * pattern.transformation[1]) + std::abs(rect.height * pattern.transformation[0]); width >>= 16; height >>= 16; auto top_left = pattern.position - make_vector2(width >> 1, height >> 1); return IntRect(top_left, make_vector2(width, height)); } IntRect bounding_box(const Face& face) { auto min = face.vertices[0], max = min; for (int i = 1; i < 3; ++i) { auto p = face.vertices[i]; if (p.x < min.x) min.x = p.x; if (p.x > max.x) max.x = p.x; if (p.y < min.y) min.y = p.y; if (p.y > max.y) max.y = p.y; } return IntRect(min.x, min.y, max.x - min.x, max.y - min.y); } Vector2i calculate_local_coords(const Pattern& pattern, Vector2i position) { auto coords = (position - pattern.position); const auto& t = pattern.transformation; auto result = make_vector2( (coords.x * t[1] + coords.y * t[0]) >> 16, (coords.y * t[1] - coords.x * t[0]) >> 16 ); result.x += pattern.rect.width >> 1; result.y += pattern.rect.height >> 1; return result; } bool region_contains(IntRect region, const Face& face) { return region_contains_triangle(region, face.vertices[0], face.vertices[1], face.vertices[2]); } bool region_contains(IntRect region, const Pattern& pattern) { auto top_left = calculate_local_coords(pattern, { region.left, region.top }); auto bottom_left = calculate_local_coords(pattern, { region.left, region.bottom() }); auto bottom_right = calculate_local_coords(pattern, { region.right(), region.bottom() }); auto top_right = calculate_local_coords(pattern, { region.right(), region.top }); auto x_limits = std::minmax({ top_left.x, bottom_left.x, bottom_right.x, top_right.x }); auto y_limits = std::minmax({ top_left.y, bottom_left.y, bottom_right.y, top_right.y }); auto rect = IntRect(x_limits.first, y_limits.first, x_limits.second - x_limits.first, y_limits.second - y_limits.first); return intersects(IntRect(0, 0, pattern.rect.width, pattern.rect.height), rect); } TerrainDescriptor terrain_at(const Pattern& pattern, Vector2i position) { const auto& pat_rect = pattern.rect; auto coords = calculate_local_coords(pattern, position); if (coords.x >= 0 && coords.y >= 0 && coords.x < pat_rect.width && coords.y < pat_rect.height) { auto terrain_id = (*pattern.pattern)(coords.x + pat_rect.left, coords.y + pat_rect.top); return { static_cast<resources::TerrainId>(terrain_id), static_cast<std::uint32_t>(terrain_id == 0 ? 0 : 255) }; } return {}; } TerrainDescriptor terrain_at(const Face& face, Vector2i position) { auto sign = [](auto a, auto b, auto p) { return cross_product(b - a, p - a) <= 0; }; const auto& v = face.vertices; if (sign(v[0], v[1], position) && sign(v[1], v[2], position) && sign(v[2], v[0], position)) { return{ face.terrain_id, face.alpha }; } return{}; } TerrainDescriptor terrain_at(const Base& base, Vector2i position) { if (contains(base.rect, position)) { return{ base.terrain_id, base.alpha }; } return{}; } } namespace detail { TerrainDescriptor terrain_at(const TerrainMapComponent& component, Vector2i position) { return boost::apply_visitor([=](const auto& data) { return map_components::terrain_at(data, position); }, component.data); } resources::TerrainDefinition interpolate_terrain(const resources::TerrainDefinition& first, const resources::TerrainDefinition& second, std::uint8_t alpha) { if (alpha == 255) { return second; } const auto real_alpha = alpha / 255.0; resources::TerrainDefinition result; result.acceleration = interpolate_linearly(first.acceleration, second.acceleration, real_alpha); result.braking = interpolate_linearly(first.braking, second.braking, real_alpha); result.cornering = interpolate_linearly(first.cornering, second.cornering, real_alpha); result.jump = interpolate_linearly(first.jump, second.jump, real_alpha); result.rolling_resistance = interpolate_linearly(first.rolling_resistance, second.rolling_resistance, real_alpha); result.roughness = interpolate_linearly(first.roughness, second.roughness, real_alpha); result.traction = interpolate_linearly(first.traction, second.traction, real_alpha); result.sliding_traction = interpolate_linearly(first.sliding_traction, second.sliding_traction, real_alpha); result.id = first.id; auto interpolate_color = [](std::int32_t a, std::int32_t b, std::int32_t t) { return a + (((b - a) * (t + 1)) >> 8); }; result.color.r = interpolate_color(first.color.r, second.color.r, alpha); result.color.g = interpolate_color(first.color.g, second.color.g, alpha); result.color.b = interpolate_color(first.color.b, second.color.b, alpha); result.color.a = interpolate_color(first.color.a, second.color.a, alpha); return result; } } TerrainMap::TerrainMap(std::vector<TerrainMapComponent> components, resources::PatternStore pattern_store, Vector2i track_size, resources::TerrainId base_terrain) : terrain_components_(std::move(components)), pattern_store_(std::move(pattern_store)), track_size_(track_size), base_terrain_(base_terrain) { while (cell_bits_ > 3 && ((track_size_.x * track_size_.y) >> (cell_bits_ * 2)) < 4096) { --cell_bits_; } auto cell_size = (1 << cell_bits_); num_cells_.x = (track_size_.x + cell_size - 1) >> cell_bits_; num_cells_.y = (track_size_.y + cell_size - 1) >> cell_bits_; std::uint32_t max_level = 0; struct CellComponent { std::int32_t cell_x; std::int32_t cell_y; std::uint32_t component_idx; std::uint32_t level; }; std::vector<CellComponent> cell_components; for (std::uint32_t idx = 0; idx < terrain_components_.size(); ++idx) { auto& component = terrain_components_[idx]; if (component.level > max_level) max_level = component.level; IntRect bounding_box = boost::apply_visitor([this](const auto& v) { return intersection(map_components::bounding_box(v), IntRect(Vector2i(), track_size_)); }, component.data); auto min_cell_x = bounding_box.left >> cell_bits_; auto min_cell_y = bounding_box.top >> cell_bits_; auto max_cell_x = bounding_box.right() >> cell_bits_; auto max_cell_y = bounding_box.bottom() >> cell_bits_; for (auto y = min_cell_y; y <= max_cell_y; ++y) { IntRect region(min_cell_x << cell_bits_, y << cell_bits_, cell_size, cell_size); for (auto x = min_cell_x; x <= max_cell_x; ++x, region.left += cell_size) { bool contained = boost::apply_visitor([=](const auto& v) { return region_contains(region, v); }, component.data); if (contained) { cell_components.push_back({ x, y, idx, component.level }); } } } } auto num_levels = max_level + 1; terrain_cells_.resize(num_levels * num_cells_.x * num_cells_.y); std::sort(cell_components.begin(), cell_components.end(), [](const CellComponent& a, const CellComponent& b) { return std::tie(a.level, a.cell_y, a.cell_x, b.component_idx) < std::tie(b.level, b.cell_y, b.cell_x, a.component_idx); }); for (auto it = cell_components.begin(); it != cell_components.end(); ) { auto& cc = *it; auto range_end = std::find_if(it, cell_components.end(), [cc](const CellComponent& v) { return cc.cell_x != v.cell_x || cc.cell_y != v.cell_y; }); auto level = terrain_components_[cc.component_idx].level; auto cell_idx = level * num_cells_.x * num_cells_.y + cc.cell_y * num_cells_.x + cc.cell_x; terrain_cells_[cell_idx].first = static_cast<std::uint32_t>(component_mapping_.size()); std::transform(it, range_end, std::back_inserter(component_mapping_), [](const CellComponent& v) { return v.component_idx; }); terrain_cells_[cell_idx].second = static_cast<std::uint32_t>(component_mapping_.size()); it = range_end; } } resources::TerrainDefinition TerrainMap::terrain_at(Vector2i position, std::int32_t level, const resources::TerrainLibrary& terrain_lib) const { position.x = clamp(position.x, 0, track_size_.x - 1); position.y = clamp(position.y, 0, track_size_.y - 1); resources::TerrainDefinition result; auto cell = make_vector2(position.x >> cell_bits_, position.y >> cell_bits_); auto cell_idx = level *num_cells_.x * num_cells_.y + cell.y * num_cells_.x + cell.x; auto range = terrain_cells_[cell_idx]; auto begin = component_mapping_.data() + range.first; auto end = component_mapping_.data() + range.second; std::int32_t alpha = 0; for (auto ptr = begin; ptr != end && alpha < 255; ++ptr) { auto& component = terrain_components_[*ptr]; auto terrain_desc = detail::terrain_at(component, position); if (terrain_desc.terrain_id != 0 && terrain_desc.alpha != 0) { const auto& terrain = terrain_lib.terrain(terrain_desc.terrain_id); auto a = ((256 - alpha) * 255) >> 8; result = detail::interpolate_terrain(result, terrain, a); alpha += a; } } if (alpha < 255 && base_terrain_ != 0) { const auto& base_terrain = terrain_lib.terrain(base_terrain_); result = detail::interpolate_terrain(result, base_terrain, 255 - alpha); } return result; } } }
{ "content_hash": "52f056cce78494cd82b557e70e5be6d3", "timestamp": "", "source": "github", "line_count": 313, "max_line_length": 122, "avg_line_length": 35.78274760383387, "alnum_prop": 0.5679464285714285, "repo_name": "mnewhouse/tselements", "id": "cb62817679105a5e63dc62f1916d6c1ec830e7ed", "size": "11287", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/world/terrain_map.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "193555" }, { "name": "C++", "bytes": "1780008" }, { "name": "CMake", "bytes": "18346" } ], "symlink_target": "" }
layout: default disqus: false archive: false post_class: post-template --- <header class="main-header post-head {% if page.cover %}" style="background-image: url({{ page.cover }}) {%else%}no-cover{% endif %}"> <nav class="main-nav {% if page.cover %} overlay {% endif %} clearfix"> <a class="back-button icon-arrow-left" href="{{ site.baseurl }}/">Home</a> <!--<a class="subscribe-button icon-feed" href="{{ site.baseurl }}feed.xml">Subscribe</a>--> </nav> </header> <main class="content" role="main"> <article class="post"> <header class="post-header"> <h1 class="post-title">{{ page.title }}</h1> <section class="post-meta"> <time class="post-date" datetime="{{ page.date | date:"%Y-%m-%d" }}">{{ page.date | date_to_string }}</time> {% if page.categories.size > 0 %} {{ page.categories | array_to_sentence_string | prepend: 'on ' }} {% endif %} </section> </header> <!-- <header class="post-header"> <a id="blog-logo" href="{{site.url}}"> {% if site.logo %} <img src="{{site.logo}}" alt="{{ site.name }}" /> {% else %} <span class="blog-title">{{ site.name }}</span> {%endif%} </a> </header> --> <!-- <span class="post-meta"> <time datetime="{{ page.date | date:"%Y-%m-%d" }}">{{ page.date | date_to_string }}</time> {% if page.categories.size > 0 %} {{ page.categories | array_to_sentence_string | prepend: 'on ' }} {% endif %} </span> --> <!-- <h1 class="post-title">{{ page.title }}</h1> --> <section class="post-content"> {{content}} </section> {% if page.archive %} <section class="archive"> <h5>Archive</h5> <ul> {% for post in site.posts %} <li><span>{{ post.date | date_to_string }}</span> <a href="{{ post.url }}">{{ post.title }}</a></li> {% endfor %} </ul> </section> {% endif %} </article> </main>
{ "content_hash": "71a077a8506ad6dd0438c362320d65d3", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 134, "avg_line_length": 34.828125, "alnum_prop": 0.4679228353521759, "repo_name": "he11ow0rld/he11ow0rld.github.io", "id": "daf75bc0312e71cdbd452ab699e8025a5324891c", "size": "2233", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_layouts/post.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "40651" }, { "name": "HTML", "bytes": "9598" }, { "name": "JavaScript", "bytes": "5773" }, { "name": "Ruby", "bytes": "2281" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- This file is part of the Sylius package. (c) Paweł Jędrzejewski For the full copyright and license information, please view the LICENSE file that was distributed with this source code. --> <container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <parameters> <parameter key="sylius.context.channel.composite.class">Sylius\Component\Channel\Context\CompositeChannelContext</parameter> <parameter key="sylius.context.channel.request_based.class">Sylius\Component\Channel\Context\RequestBased\ChannelContext</parameter> <parameter key="sylius.context.channel.single_channel.class">Sylius\Component\Channel\Context\SingleChannelContext</parameter> <parameter key="sylius.context.channel.request_based.resolver.composite.class">Sylius\Component\Channel\Context\RequestBased\CompositeRequestResolver</parameter> <parameter key="sylius.context.channel.request_based.resolver.hostname_based.class">Sylius\Component\Channel\Context\RequestBased\HostnameBasedRequestResolver</parameter> <parameter key="sylius.collector.channel.class">Sylius\Bundle\ChannelBundle\Collector\ChannelCollector</parameter> </parameters> <services> <service id="sylius.context.channel.composite" class="%sylius.context.channel.composite.class%" public="false" /> <service id="sylius.context.channel.request_based" class="%sylius.context.channel.request_based.class%" public="false"> <argument type="service" id="sylius.context.channel.request_based.resolver" /> <argument type="service" id="request_stack" /> <tag name="sylius.context.channel" /> </service> <service id="sylius.context.channel.single_channel" class="%sylius.context.channel.single_channel.class%" public="false"> <argument type="service" id="sylius.repository.channel" /> <tag name="sylius.context.channel" priority="-128"/> </service> <service id="sylius.context.channel.request_based.resolver.composite" class="%sylius.context.channel.request_based.resolver.composite.class%" public="false"/> <service id="sylius.context.channel.request_based.resolver.hostname_based" class="%sylius.context.channel.request_based.resolver.hostname_based.class%" public="false"> <argument type="service" id="sylius.repository.channel" /> <tag name="sylius.context.channel.request_based.resolver" /> </service> <service id="sylius.collector.channel" class="%sylius.collector.channel.class%" public="false"> <argument type="service" id="sylius.repository.channel" /> <argument type="service" id="sylius.context.channel" /> <argument>false</argument> <tag name="data_collector" template="SyliusChannelBundle:Collector:channel.html.twig" id="sylius.collector.channel" /> </service> </services> </container>
{ "content_hash": "16e983ed22abc0deac166a46e8a61119", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 228, "avg_line_length": 56.96363636363636, "alnum_prop": 0.7181615065432493, "repo_name": "tuka217/Sylius", "id": "ce57ce80ed1845497b4866552430bf4cb01629fd", "size": "3135", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/Sylius/Bundle/ChannelBundle/Resources/config/services.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "519" }, { "name": "CSS", "bytes": "78975" }, { "name": "Cucumber", "bytes": "335352" }, { "name": "HTML", "bytes": "644588" }, { "name": "JavaScript", "bytes": "158221" }, { "name": "PHP", "bytes": "6847146" }, { "name": "Puppet", "bytes": "3165" }, { "name": "Ruby", "bytes": "1210" }, { "name": "Shell", "bytes": "27928" } ], "symlink_target": "" }
title: axz4 type: products image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png heading: z4 description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj main: heading: Foo Bar BAz description: |- ***This is i a thing***kjh hjk kj # Blah Blah ## Blah![undefined](undefined) ### Baah image1: alt: kkkk ---
{ "content_hash": "8bf4c5840c707c0b730edcfcb2704fee", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 61, "avg_line_length": 22.2, "alnum_prop": 0.6636636636636637, "repo_name": "pblack/kaldi-hugo-cms-template", "id": "0982ed85ac8294c028def7b7d42a6676ddc26b15", "size": "337", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "site/content/pages2/axz4.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "94394" }, { "name": "HTML", "bytes": "18889" }, { "name": "JavaScript", "bytes": "10014" } ], "symlink_target": "" }
using System; using System.Collections; using NUnit.Framework; public delegate void MethodThatThrows(); public static class NUnitSpecificationExtensions { public static void ShouldBeFalse(this bool condition, string message) { Assert.IsFalse(condition, message); } public static void ShouldBeFalse(this bool condition) { ShouldBeFalse(condition, string.Empty); } public static void ShouldBeTrue(this bool condition, string message) { Assert.IsTrue(condition, message); } public static void ShouldBeTrue(this bool condition) { ShouldBeTrue(condition, string.Empty); } public static T ShouldEqual<T>(this T actual, T expected) { return ShouldEqual(actual, expected, string.Empty); } public static T ShouldEqual<T>(this T actual, T expected, string message) { Assert.AreEqual(expected, actual, message); return actual; } public static T ShouldNotEqual<T>(this T actual, T expected) { Assert.AreNotEqual(expected, actual); return actual; } public static void ShouldBeNull(this object anObject) { Assert.IsNull(anObject); } public static T ShouldNotBeNull<T>(this T anObject) { Assert.IsNotNull(anObject); return anObject; } public static T ShouldNotBeNull<T>(this T anObject, string message) { Assert.IsNotNull(anObject, message); return anObject; } public static object ShouldBeTheSameAs(this object actual, object expected) { Assert.AreSame(expected, actual); return expected; } public static object ShouldNotBeTheSameAs(this object actual, object expected) { Assert.AreNotSame(expected, actual); return expected; } public static void ShouldBeOfType<T>(this object actual) { ShouldBeOfType(actual, typeof (T)); } public static void ShouldBeOfType(this object actual, Type expected) { Assert.IsInstanceOf(expected, actual); } public static void ShouldNotBeOfType(this object actual, Type expected) { Assert.IsNotInstanceOf(expected, actual); } public static void ShouldContain(this IList actual, object expected) { Assert.Contains(expected, actual); } public static void ShouldNotContain(this IList collection, object expected) { CollectionAssert.DoesNotContain(collection, expected); } public static IComparable ShouldBeGreaterThan(this IComparable arg1, IComparable arg2) { Assert.Greater(arg1, arg2); return arg2; } public static IComparable ShouldBeLessThan(this IComparable arg1, IComparable arg2) { Assert.Less(arg1, arg2); return arg2; } public static void ShouldBeEmpty(this ICollection collection) { Assert.IsEmpty(collection); } public static void ShouldBeEmpty(this string aString) { Assert.IsEmpty(aString); } public static void ShouldNotBeEmpty(this ICollection collection) { Assert.IsNotEmpty(collection); } public static void ShouldNotBeEmpty(this string aString) { Assert.IsNotEmpty(aString); } public static string ShouldContain(this string actual, string expected) { StringAssert.Contains(expected, actual); return actual; } public static void ShouldNotContain(this string actual, string expected) { try { StringAssert.Contains(expected, actual); } catch (AssertionException) { return; } throw new AssertionException(String.Format("\"{0}\" should not contain \"{1}\".", actual, expected)); } public static string ShouldBeEqualIgnoringCase(this string actual, string expected) { StringAssert.AreEqualIgnoringCase(expected, actual); return expected; } public static void ShouldStartWith(this string actual, string expected) { StringAssert.StartsWith(expected, actual); } public static void ShouldEndWith(this string actual, string expected) { StringAssert.EndsWith(expected, actual); } public static void ShouldBeSurroundedWith(this string actual, string expectedStartDelimiter, string expectedEndDelimiter) { StringAssert.StartsWith(expectedStartDelimiter, actual); StringAssert.EndsWith(expectedEndDelimiter, actual); } public static void ShouldBeSurroundedWith(this string actual, string expectedDelimiter) { StringAssert.StartsWith(expectedDelimiter, actual); StringAssert.EndsWith(expectedDelimiter, actual); } public static void ShouldContainErrorMessage(this Exception exception, string expected) { StringAssert.Contains(expected, exception.Message); } public static Exception ShouldBeThrownBy(this Type exceptionType, MethodThatThrows method) { Exception exception = method.GetException(); if (exception == null) Assert.Fail("Method " + method.Method.Name + " failed to throw expected exception [" + exceptionType.Name + "]."); Assert.AreEqual(exceptionType, exception.GetType()); return exception; } public static Exception GetException(this MethodThatThrows method) { Exception exception = null; try { method(); } catch (Exception e) { exception = e; } return exception; } }
{ "content_hash": "55f24d6119c25a780699daf5f210f5e9", "timestamp": "", "source": "github", "line_count": 211, "max_line_length": 126, "avg_line_length": 26.46919431279621, "alnum_prop": 0.660161145926589, "repo_name": "evicertia/HermaFx", "id": "bcb1dc9f08071bbf377714fbd8f7ca83e0dd3bff", "size": "5587", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HermaFx.Foundation.Tests/NUnitSpecificationExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "99" }, { "name": "C#", "bytes": "901229" }, { "name": "HTML", "bytes": "2734" }, { "name": "JavaScript", "bytes": "426" } ], "symlink_target": "" }
export const FETCH_RENTALS = "fetch_rents" export const FETCH_RENTAL = "fetch_rent" import axios from 'axios' const ROOT_URL = 'http://localhost:4741' export function fetchRentals(values){ const request = axios.get(`${ROOT_URL}/rentals?city=${values}`) return{ type: FETCH_RENTALS, payload: request } } export function fetchRental(id){ const request = axios.get(`${ROOT_URL}/rentals/${id}`) return{ type: FETCH_RENTAL, payload: request } }
{ "content_hash": "69c17839f078efba1dd9118266e5a4f3", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 65, "avg_line_length": 20.565217391304348, "alnum_prop": 0.6828752642706131, "repo_name": "wilsonkaya/roomy-react", "id": "112a222a28cee962843819db347a8ede6e5c8a70", "size": "473", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/actions/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "90" }, { "name": "HTML", "bytes": "474" }, { "name": "JavaScript", "bytes": "6537" } ], "symlink_target": "" }
/*Package client for interacting with bitcoin client Author: Mathieu Mailhos Filename: client_curl.go */ package client import ( "bytes" "encoding/json" "errors" "net/http" ) //TransactionTemplate Missing: depends[] type TransactionTemplate struct { Hash string `json:"hash"` Fee uint `json:"fee"` Data string `json:"data"` SigOps uint `json:"sigops"` } //ResultTemplate Missing: capabilities, mutable type ResultTemplate struct { PreviousBlockHash string `json:"previousblockhash"` Target string `json:"target"` NonceRange string `json:"noncerange"` Bits string `json:"bits"` LongPollID string `json:"longpollid"` MinTime uint `json:"mintime"` SigOpLimit uint `json:"sigoplimit"` CurTime uint `json:"curtime"` Height uint `json:"height"` Version uint `json:"version"` CoinBaseValue uint `json:"coinbasevalue"` SizeLimit uint `json:"sizelimit"` Transactions []TransactionTemplate `json:"transactions"` } type blockTemplate struct { Error string `json:"error"` Result ResultTemplate `json:"result"` } type difficultyTemplate struct { Error string `json:"error"` Difficulty float64 `json:"result"` ID string `json:"id"` } // btcClientParamsCaps define a list of capabilities to be ingested in some methods in HTTP requests to the Bitcoin client type btcClientParamsCaps struct { Capabilities []string `json:"capabilities"` } // btcClientPayload is a HTTP Payload for the Bitcoin client type btcClientPayload struct { Jsonrpc string `json:"jsonrpc"` ID string `json:"id"` Method string `json:"method"` Parameters []btcClientParamsCaps `json:"params",omitempty` } // VERY Temporary work-around for GetBlockTemplate() from BP023 ;) //GetResultTemplate(user, password, host) //Get and parse data received from Bitcoin client on a getblocktemplate request func getResultTemplate(user, password, host string) (rtp ResultTemplate, err error) { var btp blockTemplate caps := []string{"coinbasetxn", "workid", "coinbase/append"} params := btcClientParamsCaps{Capabilities: caps} data := btcClientPayload{ Jsonrpc: "1.1", ID: "0", Method: "getblocktemplate", Parameters: []btcClientParamsCaps{params}, } payloadBytes, err := json.Marshal(data) if err != nil { return btp.Result, err } body := bytes.NewReader(payloadBytes) req, err := http.NewRequest("POST", "http://"+host, body) if err != nil { return btp.Result, err } req.SetBasicAuth(user, password) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { return btp.Result, err } defer resp.Body.Close() decoder := json.NewDecoder(resp.Body) err = decoder.Decode(&btp) if err != nil { return btp.Result, err } if btp.Error == "" { return btp.Result, nil } return btp.Result, errors.New(btp.Error) } //GetDifficulty function that retrieves current difficulty from bitcoin client func GetDifficulty(user, password, host string) (difficulty float64, err error) { var dif difficultyTemplate data := btcClientPayload{ Jsonrpc: "1.1", ID: "0", Method: "getdifficulty", } payloadBytes, err := json.Marshal(data) if err != nil { return dif.Difficulty, err } body := bytes.NewReader(payloadBytes) req, err := http.NewRequest("GET", "http://"+host, body) if err != nil { return dif.Difficulty, err } req.SetBasicAuth(user, password) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { return dif.Difficulty, err } defer resp.Body.Close() decoder := json.NewDecoder(resp.Body) err = decoder.Decode(&dif) if err != nil { return dif.Difficulty, err } if dif.Error == "" { return dif.Difficulty, nil } return dif.Difficulty, errors.New(dif.Error) }
{ "content_hash": "a600221ea2ccbe0b7ae98530a418e970", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 122, "avg_line_length": 28.666666666666668, "alnum_prop": 0.6494670542635659, "repo_name": "MathieuMailhos/GoBtcMiner", "id": "ceceb2ba148114838cd32472f5102a40fd68b9ca", "size": "4128", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/gobtcminer/client/client.go", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9056" }, { "name": "Go", "bytes": "19527" }, { "name": "HTML", "bytes": "4464" }, { "name": "JavaScript", "bytes": "536" } ], "symlink_target": "" }
namespace Nancy.ViewEngines.Razor { /// <summary> /// Helpers for url related functions. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> public class UrlHelpers<TModel> { /// <summary> /// Initializes a new instance of the <see cref="UrlHelpers&lt;TModel&gt;"/> class. /// </summary> /// <param name="razorViewEngine">The razor view engine.</param> /// <param name="renderContext">The render context.</param> public UrlHelpers(RazorViewEngine razorViewEngine, IRenderContext renderContext) { this.RazorViewEngine = razorViewEngine; this.RenderContext = renderContext; } /// <summary> /// The engine that is currently rendering the view. /// </summary> /// <value>A <see cref="RazorViewEngine"/> instance.</value> public RazorViewEngine RazorViewEngine { get; set; } /// <summary> /// The context of the current render operation. /// </summary> /// <value>An <see cref="IRenderContext"/> intance.</value> public IRenderContext RenderContext { get; set; } /// <summary> /// Retrieves the absolute url of the specified path. /// </summary> /// <param name="path">The path.</param> public string Content(string path) { return this.RenderContext.ParsePath(path); } } }
{ "content_hash": "5515e70fa15a87e92ad0d7300857a6f2", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 91, "avg_line_length": 36.609756097560975, "alnum_prop": 0.5716189207195204, "repo_name": "Crisfole/Nancy", "id": "5db11d7deca5d174bf233450e7e64de82418b9d3", "size": "1501", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/Nancy.ViewEngines.Razor/UrlHelpers.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "107" }, { "name": "C#", "bytes": "3671217" }, { "name": "CSS", "bytes": "16121" }, { "name": "JavaScript", "bytes": "94382" }, { "name": "PowerShell", "bytes": "6365" }, { "name": "Ruby", "bytes": "14090" }, { "name": "Visual Basic", "bytes": "381" } ], "symlink_target": "" }
package org.jfree.chart.renderer.category; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.CategoryDataset; import org.jfree.data.statistics.StatisticalCategoryDataset; import org.jfree.io.SerialUtilities; import org.jfree.ui.GradientPaintTransformer; import org.jfree.ui.RectangleEdge; import org.jfree.util.ObjectUtilities; import org.jfree.util.PaintUtilities; import org.jfree.util.PublicCloneable; /** * A renderer that handles the drawing a bar plot where * each bar has a mean value and a standard deviation line. */ public class StatisticalBarRenderer extends BarRenderer implements CategoryItemRenderer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -4986038395414039117L; /** The paint used to show the error indicator. */ private transient Paint errorIndicatorPaint; /** * The stroke used to draw the error indicators. * * @since 1.0.8 */ private transient Stroke errorIndicatorStroke; /** * Default constructor. */ public StatisticalBarRenderer() { super(); this.errorIndicatorPaint = Color.gray; this.errorIndicatorStroke = new BasicStroke(1.0f); } /** * Returns the paint used for the error indicators. * * @return The paint used for the error indicators (possibly * <code>null</code>). * * @see #setErrorIndicatorPaint(Paint) */ public Paint getErrorIndicatorPaint() { return this.errorIndicatorPaint; } /** * Sets the paint used for the error indicators (if <code>null</code>, * the item outline paint is used instead) and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> permitted). * * @see #getErrorIndicatorPaint() */ public void setErrorIndicatorPaint(Paint paint) { this.errorIndicatorPaint = paint; fireChangeEvent(); } /** * Returns the stroke used to draw the error indicators. If this is * <code>null</code>, the renderer will use the item outline stroke). * * @return The stroke (possibly <code>null</code>). * * @see #setErrorIndicatorStroke(Stroke) * * @since 1.0.8 */ public Stroke getErrorIndicatorStroke() { return this.errorIndicatorStroke; } /** * Sets the stroke used to draw the error indicators, and sends a * {@link RendererChangeEvent} to all registered listeners. If you set * this to <code>null</code>, the renderer will use the item outline * stroke. * * @param stroke the stroke (<code>null</code> permitted). * * @see #getErrorIndicatorStroke() * * @since 1.0.8 */ public void setErrorIndicatorStroke(Stroke stroke) { this.errorIndicatorStroke = stroke; fireChangeEvent(); } /** * Draws the bar with its standard deviation line range for a single * (series, category) data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param data the data. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset data, int row, int column, int pass) { // defensive check if (!(data instanceof StatisticalCategoryDataset)) { throw new IllegalArgumentException( "Requires StatisticalCategoryDataset."); } StatisticalCategoryDataset statData = (StatisticalCategoryDataset) data; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { drawHorizontalItem(g2, state, dataArea, plot, domainAxis, rangeAxis, statData, row, column); } else if (orientation == PlotOrientation.VERTICAL) { drawVerticalItem(g2, state, dataArea, plot, domainAxis, rangeAxis, statData, row, column); } } /** * Draws an item for a plot with a horizontal orientation. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the data. * @param row the row index (zero-based). * @param column the column index (zero-based). */ protected void drawHorizontalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, StatisticalCategoryDataset dataset, int row, int column) { RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); // BAR Y double rectY = domainAxis.getCategoryStart(column, getColumnCount(), dataArea, xAxisLocation); int seriesCount = getRowCount(); int categoryCount = getColumnCount(); if (seriesCount > 1) { double seriesGap = dataArea.getHeight() * getItemMargin() / (categoryCount * (seriesCount - 1)); rectY = rectY + row * (state.getBarWidth() + seriesGap); } else { rectY = rectY + row * state.getBarWidth(); } // BAR X Number meanValue = dataset.getMeanValue(row, column); if (meanValue == null) { return; } double value = meanValue.doubleValue(); double base = 0.0; double lclip = getLowerClip(); double uclip = getUpperClip(); if (uclip <= 0.0) { // cases 1, 2, 3 and 4 if (value >= uclip) { return; // bar is not visible } base = uclip; if (value <= lclip) { value = lclip; } } else if (lclip <= 0.0) { // cases 5, 6, 7 and 8 if (value >= uclip) { value = uclip; } else { if (value <= lclip) { value = lclip; } } } else { // cases 9, 10, 11 and 12 if (value <= lclip) { return; // bar is not visible } base = getLowerClip(); if (value >= uclip) { value = uclip; } } RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transY1 = rangeAxis.valueToJava2D(base, dataArea, yAxisLocation); double transY2 = rangeAxis.valueToJava2D(value, dataArea, yAxisLocation); double rectX = Math.min(transY2, transY1); double rectHeight = state.getBarWidth(); double rectWidth = Math.abs(transY2 - transY1); Rectangle2D bar = new Rectangle2D.Double(rectX, rectY, rectWidth, rectHeight); Paint itemPaint = getItemPaint(row, column); GradientPaintTransformer t = getGradientPaintTransformer(); if (t != null && itemPaint instanceof GradientPaint) { itemPaint = t.transform((GradientPaint) itemPaint, bar); } g2.setPaint(itemPaint); g2.fill(bar); // draw the outline... if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) { Stroke stroke = getItemOutlineStroke(row, column); Paint paint = getItemOutlinePaint(row, column); if (stroke != null && paint != null) { g2.setStroke(stroke); g2.setPaint(paint); g2.draw(bar); } } // standard deviation lines Number n = dataset.getStdDevValue(row, column); if (n != null) { double valueDelta = n.doubleValue(); double highVal = rangeAxis.valueToJava2D(meanValue.doubleValue() + valueDelta, dataArea, yAxisLocation); double lowVal = rangeAxis.valueToJava2D(meanValue.doubleValue() - valueDelta, dataArea, yAxisLocation); if (this.errorIndicatorPaint != null) { g2.setPaint(this.errorIndicatorPaint); } else { g2.setPaint(getItemOutlinePaint(row, column)); } if (this.errorIndicatorStroke != null) { g2.setStroke(this.errorIndicatorStroke); } else { g2.setStroke(getItemOutlineStroke(row, column)); } Line2D line = null; line = new Line2D.Double(lowVal, rectY + rectHeight / 2.0d, highVal, rectY + rectHeight / 2.0d); g2.draw(line); line = new Line2D.Double(highVal, rectY + rectHeight * 0.25, highVal, rectY + rectHeight * 0.75); g2.draw(line); line = new Line2D.Double(lowVal, rectY + rectHeight * 0.25, lowVal, rectY + rectHeight * 0.75); g2.draw(line); } CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, dataset, row, column, plot, generator, bar, (value < 0.0)); } // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, bar); } } /** * Draws an item for a plot with a vertical orientation. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the data. * @param row the row index (zero-based). * @param column the column index (zero-based). */ protected void drawVerticalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, StatisticalCategoryDataset dataset, int row, int column) { RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); // BAR X double rectX = domainAxis.getCategoryStart(column, getColumnCount(), dataArea, xAxisLocation); int seriesCount = getRowCount(); int categoryCount = getColumnCount(); if (seriesCount > 1) { double seriesGap = dataArea.getWidth() * getItemMargin() / (categoryCount * (seriesCount - 1)); rectX = rectX + row * (state.getBarWidth() + seriesGap); } else { rectX = rectX + row * state.getBarWidth(); } // BAR Y Number meanValue = dataset.getMeanValue(row, column); if (meanValue == null) { return; } double value = meanValue.doubleValue(); double base = 0.0; double lclip = getLowerClip(); double uclip = getUpperClip(); if (uclip <= 0.0) { // cases 1, 2, 3 and 4 if (value >= uclip) { return; // bar is not visible } base = uclip; if (value <= lclip) { value = lclip; } } else if (lclip <= 0.0) { // cases 5, 6, 7 and 8 if (value >= uclip) { value = uclip; } else { if (value <= lclip) { value = lclip; } } } else { // cases 9, 10, 11 and 12 if (value <= lclip) { return; // bar is not visible } base = getLowerClip(); if (value >= uclip) { value = uclip; } } RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transY1 = rangeAxis.valueToJava2D(base, dataArea, yAxisLocation); double transY2 = rangeAxis.valueToJava2D(value, dataArea, yAxisLocation); double rectY = Math.min(transY2, transY1); double rectWidth = state.getBarWidth(); double rectHeight = Math.abs(transY2 - transY1); Rectangle2D bar = new Rectangle2D.Double(rectX, rectY, rectWidth, rectHeight); Paint itemPaint = getItemPaint(row, column); GradientPaintTransformer t = getGradientPaintTransformer(); if (t != null && itemPaint instanceof GradientPaint) { itemPaint = t.transform((GradientPaint) itemPaint, bar); } g2.setPaint(itemPaint); g2.fill(bar); // draw the outline... if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) { Stroke stroke = getItemOutlineStroke(row, column); Paint paint = getItemOutlinePaint(row, column); if (stroke != null && paint != null) { g2.setStroke(stroke); g2.setPaint(paint); g2.draw(bar); } } // standard deviation lines Number n = dataset.getStdDevValue(row, column); if (n != null) { double valueDelta = n.doubleValue(); double highVal = rangeAxis.valueToJava2D(meanValue.doubleValue() + valueDelta, dataArea, yAxisLocation); double lowVal = rangeAxis.valueToJava2D(meanValue.doubleValue() - valueDelta, dataArea, yAxisLocation); if (this.errorIndicatorPaint != null) { g2.setPaint(this.errorIndicatorPaint); } else { g2.setPaint(getItemOutlinePaint(row, column)); } if (this.errorIndicatorStroke != null) { g2.setStroke(this.errorIndicatorStroke); } else { g2.setStroke(getItemOutlineStroke(row, column)); } Line2D line = null; line = new Line2D.Double(rectX + rectWidth / 2.0d, lowVal, rectX + rectWidth / 2.0d, highVal); g2.draw(line); line = new Line2D.Double(rectX + rectWidth / 2.0d - 5.0d, highVal, rectX + rectWidth / 2.0d + 5.0d, highVal); g2.draw(line); line = new Line2D.Double(rectX + rectWidth / 2.0d - 5.0d, lowVal, rectX + rectWidth / 2.0d + 5.0d, lowVal); g2.draw(line); } CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, dataset, row, column, plot, generator, bar, (value < 0.0)); } // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, bar); } } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StatisticalBarRenderer)) { return false; } StatisticalBarRenderer that = (StatisticalBarRenderer) obj; if (!PaintUtilities.equal(this.errorIndicatorPaint, that.errorIndicatorPaint)) { return false; } if (!ObjectUtilities.equal(this.errorIndicatorStroke, that.errorIndicatorStroke)) { return false; } return super.equals(obj); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.errorIndicatorPaint, stream); SerialUtilities.writeStroke(this.errorIndicatorStroke, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.errorIndicatorPaint = SerialUtilities.readPaint(stream); this.errorIndicatorStroke = SerialUtilities.readStroke(stream); } }
{ "content_hash": "d662684bec5dbae940d4bca02e201911", "timestamp": "", "source": "github", "line_count": 536, "max_line_length": 80, "avg_line_length": 35.985074626865675, "alnum_prop": 0.5440170053919535, "repo_name": "ibestvina/multithread-centiscape", "id": "6f5e4eca07c3e0498e6e3678446626b28bc92bd9", "size": "21922", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CentiScaPe2.1/src/main/java/org/jfree/chart/renderer/category/StatisticalBarRenderer.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "13956" }, { "name": "Java", "bytes": "9360441" } ], "symlink_target": "" }
package com.obsidian.compiler.RawValues; /** * Created by Jonathon on 5/13/2017. */ public class RawBooleanValue extends RawValue { public boolean value; public RawBooleanValue(boolean value) { this.value = value; } @Override public RawValue copy() { return new RawBooleanValue(this.value); } }
{ "content_hash": "c3386ef9023d38058b3454d9528755f7", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 47, "avg_line_length": 14.952380952380953, "alnum_prop": 0.7197452229299363, "repo_name": "ObsidianLang/obsidian-grammar", "id": "bc232c1b991b559c74545fcf94a814c1062be6bc", "size": "916", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/obsidian/compiler/RawValues/RawBooleanValue.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "20816" }, { "name": "Java", "bytes": "595629" }, { "name": "Kotlin", "bytes": "16126" } ], "symlink_target": "" }
python /etc/init.d/notify_ip.py
{ "content_hash": "da2b2d1b51c816c10f9d1d84b07339af", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 31, "avg_line_length": 32, "alnum_prop": 0.75, "repo_name": "resolutedreamer/IR-Transmit-Receive", "id": "167658720cbbf4a12451aeeb3b9d8b7c3e3739fe", "size": "42", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/etc/init.d/report_ip.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "52916" }, { "name": "Makefile", "bytes": "345" }, { "name": "Python", "bytes": "19184" }, { "name": "Shell", "bytes": "3355" } ], "symlink_target": "" }
'use strict'; module.exports = (function () { var Collection = require('easy-collections'); var db = require('./db'); var utils = require('./utils'); var courses = new Collection(db, 'courses'); var classes = new Collection(db, 'classes'); var Validator = require('jsonschema').Validator; var v = new Validator(); var courseSchema = { id: '/Course', type: 'object', properties: { title: { type: 'string'}, teachers: { type: 'array', items: {type: 'string'} }, assistants: { type: 'array', items: {type: 'string'} } }, required: ['title'], additionalProperties: false }; v.addSchema(courseSchema, '/CourseSchema'); var participantsCourseSchema = { id: '/ParticipantsCourseSchema', type: 'object', properties: { teachers: { type: 'array', items: {type: 'string'} }, assistants: { type: 'array', items: {type: 'string'} } }, additionalProperties: false, minProperties: 1, maxProperties: 2 }; v.addSchema(participantsCourseSchema, '/ParticipantsCourseSchema'); courses.sort = { _id: -1 }; /** * Returns the courses */ courses.getCourses = function () { return courses.find(); }; /** * Creates a new course. * @Returns a promise with the course created */ courses.createCourse = function (username, course) { course.teachers = [username]; var validationObj = v.validate(course, courseSchema); if (validationObj.errors && validationObj.errors.length > 0) { throw { message: 'Course bad format: ' + validationObj.errors[0], status: 400 }; } return courses.insert(course); }; courses.modifyCourse = function (id, username, body, add) { var validationObj = v.validate(body, courseSchema); validationObj = validationObj.errors.length > 0 ? v.validate(body, participantsCourseSchema): validationObj; if (validationObj.errors && validationObj.errors.length > 0) { throw { message: 'Course bad format: ' + validationObj.errors[0], status: 400 }; } return courses.find(courses.toObjectID(id), true) .then(function (course) { if (!course) { throw { message: 'Course does not exist', status: 400 }; } if (!course.teachers || course.teachers.indexOf(username) === -1) { throw { message: 'You don\'t have permission to modify this course.', status: 401 }; } if (body._id) { delete body._id; } var update = {}; utils.addToArrayHandler(update, body, 'teachers', add); utils.addToArrayHandler(update, body, 'assistants', add); if (add && body.title) { update.$set = {}; update.$set.title = body.title; } return courses.findAndUpdate(id, update); }); }; courses.removeCourse = function (id, username) { return courses.findById(id) .then(function (courseRes) { if (!courseRes) { throw { message: 'Course does not exist', status: 404 }; } if (!courseRes.teachers || courseRes.teachers.indexOf(username) === -1) { throw { message: 'You don\'t have permission to delete this course.', status: 401 }; } return classes.find({courseId: id}) .then(function (classesRes) { if (classesRes.length > 0) { classesRes.forEach(function(classObj) { classes.findAndUpdate(classObj._id, { $set: {courseId: null} }); }); } return courses.removeById(id).then(function (result, err) { if (!err) { return { message: 'Success.' }; } }); }); }); }; return courses; })();
{ "content_hash": "95a3075422aac2c3799c06e8d7df2003", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 116, "avg_line_length": 31.49056603773585, "alnum_prop": 0.4353904533652886, "repo_name": "e-ucm/rage-analytics-backend", "id": "aac884bec02753680e5156bcbb1e78cf587eb948", "size": "5007", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/courses.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "3855" }, { "name": "HTML", "bytes": "58" }, { "name": "JavaScript", "bytes": "977493" }, { "name": "Shell", "bytes": "3461" } ], "symlink_target": "" }
'use strict'; var _ = require('lodash'); var Send = require('./send.model'); // Get list of sends exports.index = function(req, res) { Send.find(function (err, sends) { if(err) { return handleError(res, err); } return res.json(200, sends); }); }; // Get a single send exports.show = function(req, res) { Send.findById(req.params.id, function (err, send) { if(err) { return handleError(res, err); } if(!send) { return res.send(404); } return res.json(send); }); }; // Creates a new send in the DB. exports.create = function(req, res) { Send.create(req.body, function(err, send) { if(err) { return handleError(res, err); } return res.json(201, send); }); }; // Updates an existing send in the DB. exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } Send.findById(req.params.id, function (err, send) { if (err) { return handleError(res, err); } if(!send) { return res.send(404); } var updated = _.merge(send, req.body); updated.save(function (err) { if (err) { return handleError(res, err); } return res.json(200, send); }); }); }; // Deletes a send from the DB. exports.destroy = function(req, res) { Send.findById(req.params.id, function (err, send) { if(err) { return handleError(res, err); } if(!send) { return res.send(404); } send.remove(function(err) { if(err) { return handleError(res, err); } return res.send(204); }); }); }; function handleError(res, err) { return res.send(500, err); }
{ "content_hash": "2c93305ce2723a1752c91ff5241f31ca", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 53, "avg_line_length": 26.10169491525424, "alnum_prop": 0.6136363636363636, "repo_name": "josephmilla/llama", "id": "90581be7b105fea156a874dcc7a84963e93d975f", "size": "1540", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/api/send/send.controller.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "24139" }, { "name": "CSS", "bytes": "2577" }, { "name": "HTML", "bytes": "22680" }, { "name": "JavaScript", "bytes": "92306" } ], "symlink_target": "" }
<?xml version="1.0" encoding="ISO-8859-1"?> <!-- ~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ ~ WSO2 Inc. licenses this file to you under the Apache License, ~ Version 2.0 (the "License"); you may not use this file except ~ in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, ~ software distributed under the License is distributed on an ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ~ KIND, either express or implied. See the License for the ~ specific language governing permissions and limitations ~ under the License. --> <Server xmlns="http://wso2.org/projects/carbon/carbon.xml"> <JDBCPersistenceManager> <DataSource> <Name>jdbc/WSO2IdentityDB</Name> </DataSource> <SessionDataPersist> <Enable>true</Enable> <Temporary>true</Temporary> <PoolSize>0</PoolSize> <SessionDataCleanUp> <Enable>true</Enable> <CleanUpTimeout>20160</CleanUpTimeout> <CleanUpPeriod>1140</CleanUpPeriod> <DeleteChunkSize>50000</DeleteChunkSize> </SessionDataCleanUp> <OperationDataCleanUp> <Enable>true</Enable> </OperationDataCleanUp> </SessionDataPersist> </JDBCPersistenceManager> <TimeConfig> <SessionIdleTimeout>15</SessionIdleTimeout> <RememberMeTimeout>20160</RememberMeTimeout> </TimeConfig> <Security> <KeyStoresDir>${carbon.home}/conf/keystores</KeyStoresDir> <KeyManagerType>SunX509</KeyManagerType> <TrustManagerType>SunX509</TrustManagerType> </Security> <Identity> <IssuerPolicy>SelfAndManaged</IssuerPolicy> <TokenValidationPolicy>CertValidate</TokenValidationPolicy> <BlackList></BlackList> <WhiteList></WhiteList> <System> <KeyStore></KeyStore> <StorePass></StorePass> </System> </Identity> <OpenID> <OpenIDServerUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/openidserver</OpenIDServerUrl> <OpenIDUserPattern>${carbon.protocol}://${carbon.host}:${carbon.management.port}/openid</OpenIDUserPattern> <OpenIDLoginUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/openid_login.do</OpenIDLoginUrl> <OpenIDSkipUserConsent>false</OpenIDSkipUserConsent> <OpenIDRememberMeExpiry>7200</OpenIDRememberMeExpiry> <DisableOpenIDDumbMode>false</DisableOpenIDDumbMode> </OpenID> <OAuth> <OAuth1RequestTokenUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth/request-token</OAuth1RequestTokenUrl> <OAuth1AuthorizeUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth/authorize-url</OAuth1AuthorizeUrl> <OAuth1AccessTokenUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth/access-token</OAuth1AccessTokenUrl> <OAuth2AuthzEPUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/authorize</OAuth2AuthzEPUrl> <OAuth2TokenEPUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/token</OAuth2TokenEPUrl> <OAuth2RevokeEPUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/revoke</OAuth2RevokeEPUrl> <OAuth2IntrospectEPUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/introspect</OAuth2IntrospectEPUrl> <OAuth2UserInfoEPUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/userinfo</OAuth2UserInfoEPUrl> <OIDCCheckSessionEPUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/oidc/checksession</OIDCCheckSessionEPUrl> <OIDCLogoutEPUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/oidc/logout</OIDCLogoutEPUrl> <OAuth2ConsentPage>${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/oauth2_authz.do</OAuth2ConsentPage> <OAuth2ErrorPage>${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/oauth2_error.do</OAuth2ErrorPage> <OIDCConsentPage>${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/oauth2_consent.do</OIDCConsentPage> <OIDCLogoutConsentPage>${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/oauth2_logout_consent.do</OIDCLogoutConsentPage> <OIDCLogoutPage>${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/oauth2_logout.do</OIDCLogoutPage> <OIDCWebFingerEPUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/.well-known/webfinger</OIDCWebFingerEPUrl> <OAuth2DCREPUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/identity/connect/register</OAuth2DCREPUrl> <OAuth2JWKSPage>${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/jwks</OAuth2JWKSPage> <OIDCDiscoveryEPUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/oidcdiscovery</OIDCDiscoveryEPUrl> <AuthorizationCodeDefaultValidityPeriod>300</AuthorizationCodeDefaultValidityPeriod> <AccessTokenDefaultValidityPeriod>3600</AccessTokenDefaultValidityPeriod> <UserAccessTokenDefaultValidityPeriod>3600</UserAccessTokenDefaultValidityPeriod> <RefreshTokenValidityPeriod>84600</RefreshTokenValidityPeriod> <TimestampSkew>0</TimestampSkew> <RenewRefreshTokenForRefreshGrant>true</RenewRefreshTokenForRefreshGrant> <TokenPersistenceProcessor>org.wso2.carbon.identity.oauth.tokenprocessor.PlainTextPersistenceProcessor</TokenPersistenceProcessor> <MapFederatedUsersToLocal>false</MapFederatedUsersToLocal> <ClientAuthHandlers> <ClientAuthHandler Class="org.wso2.carbon.identity.oauth2.token.handlers.clientauth.BasicAuthClientAuthHandler"> <Property Name="StrictClientCredentialValidation">false</Property> </ClientAuthHandler> </ClientAuthHandlers> <SupportedResponseTypes> <SupportedResponseType> <ResponseTypeName>token</ResponseTypeName> <ResponseTypeHandlerImplClass>org.wso2.carbon.identity.oauth2.authz.handlers.AccessTokenResponseTypeHandler</ResponseTypeHandlerImplClass> </SupportedResponseType> <SupportedResponseType> <ResponseTypeName>code</ResponseTypeName> <ResponseTypeHandlerImplClass>org.wso2.carbon.identity.oauth2.authz.handlers.CodeResponseTypeHandler</ResponseTypeHandlerImplClass> </SupportedResponseType> <SupportedResponseType> <ResponseTypeName>id_token</ResponseTypeName> <ResponseTypeHandlerImplClass>org.wso2.carbon.identity.oauth2.authz.handlers.IDTokenResponseTypeHandler</ResponseTypeHandlerImplClass> </SupportedResponseType> <SupportedResponseType> <ResponseTypeName>id_token token</ResponseTypeName> <ResponseTypeHandlerImplClass>org.wso2.carbon.identity.oauth2.authz.handlers.IDTokenTokenResponseTypeHandler</ResponseTypeHandlerImplClass> </SupportedResponseType> </SupportedResponseTypes> <SupportedGrantTypes> <SupportedGrantType> <GrantTypeName>authorization_code</GrantTypeName> <GrantTypeHandlerImplClass>org.wso2.carbon.identity.oauth2.token.handlers.grant.AuthorizationCodeGrantHandler</GrantTypeHandlerImplClass> </SupportedGrantType> <SupportedGrantType> <GrantTypeName>password</GrantTypeName> <GrantTypeHandlerImplClass>org.wso2.carbon.identity.oauth2.token.handlers.grant.PasswordGrantHandler</GrantTypeHandlerImplClass> </SupportedGrantType> <SupportedGrantType> <GrantTypeName>refresh_token</GrantTypeName> <GrantTypeHandlerImplClass>org.wso2.carbon.identity.oauth2.token.handlers.grant.RefreshGrantHandler</GrantTypeHandlerImplClass> </SupportedGrantType> <SupportedGrantType> <GrantTypeName>client_credentials</GrantTypeName> <GrantTypeHandlerImplClass>org.wso2.carbon.identity.oauth2.token.handlers.grant.ClientCredentialsGrantHandler</GrantTypeHandlerImplClass> <IsRefreshTokenAllowed>false</IsRefreshTokenAllowed> <IdTokenAllowed>false</IdTokenAllowed> </SupportedGrantType> </SupportedGrantTypes> <OAuthCallbackHandlers> <OAuthCallbackHandler Class="org.wso2.carbon.identity.oauth.callback.DefaultCallbackHandler"/> </OAuthCallbackHandlers> <ScopeValidators> <ScopeValidator class="org.wso2.carbon.identity.oauth2.validators.JDBCScopeValidator" /> <ScopeValidator class="org.wso2.carbon.identity.oauth2.validators.xacml.XACMLScopeValidator"/> </ScopeValidators> <ScopeHandlers> <ScopeHandler class="org.wso2.carbon.identity.oauth2.validators.OIDCScopeHandler" /> </ScopeHandlers> <EnableAssertions> <UserName>false</UserName> </EnableAssertions> <EnableAccessTokenPartitioning>false</EnableAccessTokenPartitioning> <AccessTokenPartitioningDomains><!-- A:foo.com, B:bar.com --></AccessTokenPartitioningDomains> <AuthorizationContextTokenGeneration> <Enabled>false</Enabled> <TokenGeneratorImplClass>org.wso2.carbon.identity.oauth2.authcontext.JWTTokenGenerator</TokenGeneratorImplClass> <ClaimsRetrieverImplClass>org.wso2.carbon.identity.oauth2.authcontext.DefaultClaimsRetriever</ClaimsRetrieverImplClass> <ConsumerDialectURI>http://wso2.org/claims</ConsumerDialectURI> <SignatureAlgorithm>SHA256withRSA</SignatureAlgorithm> <AuthorizationContextTTL>15</AuthorizationContextTTL> </AuthorizationContextTokenGeneration> <SAML2Grant> <UserType>LOCAL</UserType> </SAML2Grant> <OpenIDConnect> <IDTokenBuilder>org.wso2.carbon.identity.openidconnect.DefaultIDTokenBuilder</IDTokenBuilder> <SignatureAlgorithm>SHA256withRSA</SignatureAlgorithm> <IDTokenIssuerID>${carbon.protocol}://${carbon.host}:${carbon.management.port}/oauth2/token</IDTokenIssuerID> <IDTokenCustomClaimsCallBackHandler>org.wso2.carbon.identity.openidconnect.SAMLAssertionClaimsCallback</IDTokenCustomClaimsCallBackHandler> <IDTokenExpiration>3600</IDTokenExpiration> <UserInfoJWTSignatureAlgorithm>SHA256withRSA</UserInfoJWTSignatureAlgorithm> <UserInfoEndpointClaimRetriever>org.wso2.carbon.identity.oauth.endpoint.user.impl.UserInfoUserStoreClaimRetriever</UserInfoEndpointClaimRetriever> <UserInfoEndpointRequestValidator>org.wso2.carbon.identity.oauth.endpoint.user.impl.UserInforRequestDefaultValidator</UserInfoEndpointRequestValidator> <UserInfoEndpointAccessTokenValidator>org.wso2.carbon.identity.oauth.endpoint.user.impl.UserInfoISAccessTokenValidator</UserInfoEndpointAccessTokenValidator> <UserInfoEndpointResponseBuilder>org.wso2.carbon.identity.oauth.endpoint.user.impl.UserInfoJSONResponseBuilder</UserInfoEndpointResponseBuilder> <SkipUserConsent>false</SkipUserConsent> <SignJWTWithSPKey>false</SignJWTWithSPKey> </OpenIDConnect> <!-- This property controls whether the display name of an OAuth app(if available) should be shown instead of SP name in the consent screen. Introduced for IDENTITY-6791--> <ShowDisplayNameInConsentPage>false</ShowDisplayNameInConsentPage> <TokenPersistence> <Enable>true</Enable> <PoolSize>0</PoolSize> <RetryCount>5</RetryCount> </TokenPersistence> </OAuth> <MultifactorAuthentication> <XMPPSettings> <XMPPConfig> <XMPPProvider>gtalk</XMPPProvider> <XMPPServer>talk.google.com</XMPPServer> <XMPPPort>5222</XMPPPort> <XMPPExt>gmail.com</XMPPExt> <XMPPUserName>multifactor1@gmail.com</XMPPUserName> <XMPPPassword>wso2carbon</XMPPPassword> </XMPPConfig> </XMPPSettings> </MultifactorAuthentication> <SSOService> <EntityId>${carbon.host}</EntityId> <IdentityProviderURL>${carbon.protocol}://${carbon.host}:${carbon.management.port}/samlsso</IdentityProviderURL> <DefaultLogoutEndpoint>${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/samlsso_logout.do</DefaultLogoutEndpoint> <NotificationEndpoint>${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/samlsso_notification.do</NotificationEndpoint> <SingleLogoutRetryCount>5</SingleLogoutRetryCount> <SingleLogoutRetryInterval>60000</SingleLogoutRetryInterval> <TenantPartitioningEnabled>false</TenantPartitioningEnabled> <AttributesClaimDialect>http://wso2.org/claims</AttributesClaimDialect> <SAMLSSOAssertionBuilder>org.wso2.carbon.identity.sso.saml.builders.assertion.DefaultSAMLAssertionBuilder</SAMLSSOAssertionBuilder> <SAMLSSOEncrypter>org.wso2.carbon.identity.sso.saml.builders.encryption.DefaultSSOEncrypter</SAMLSSOEncrypter> <SAMLSSOSigner>org.wso2.carbon.identity.sso.saml.builders.signature.DefaultSSOSigner</SAMLSSOSigner> <SAML2HTTPRedirectSignatureValidator>org.wso2.carbon.identity.sso.saml.validators.SAML2HTTPRedirectDeflateSignatureValidator</SAML2HTTPRedirectSignatureValidator> <SAMLResponseValidityPeriod>5</SAMLResponseValidityPeriod> <UseAuthenticatedUserDomainCrypto>false</UseAuthenticatedUserDomainCrypto> <SAMLDefaultSigningAlgorithmURI>http://www.w3.org/2000/09/xmldsig#rsa-sha1</SAMLDefaultSigningAlgorithmURI> <SAMLDefaultDigestAlgorithmURI>http://www.w3.org/2000/09/xmldsig#sha1</SAMLDefaultDigestAlgorithmURI> <SAMLDefaultAssertionEncryptionAlgorithmURI>http://www.w3.org/2001/04/xmlenc#aes256-cbc</SAMLDefaultAssertionEncryptionAlgorithmURI> <SAMLDefaultKeyEncryptionAlgorithmURI>http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p</SAMLDefaultKeyEncryptionAlgorithmURI> <SLOHostNameVerificationEnabled>true</SLOHostNameVerificationEnabled> <!-- SAML metadata validity period in minutes --> <SAMLMetadataValidityPeriod>60</SAMLMetadataValidityPeriod> <SAMLMetadataSigningEnabled>false</SAMLMetadataSigningEnabled> </SSOService> <SecurityTokenService> <IdentityProviderURL>${carbon.protocol}://${carbon.host}:${carbon.management.port}/services/wso2carbon-sts</IdentityProviderURL> </SecurityTokenService> <PassiveSTS> <IdentityProviderURL>${carbon.protocol}://${carbon.host}:${carbon.management.port}/passivests</IdentityProviderURL> <RetryURL>${carbon.protocol}://${carbon.host}:${carbon.management.port}/authenticationendpoint/retry.do</RetryURL> <TokenStoreClassName>org.wso2.carbon.identity.sts.passive.utils.NoPersistenceTokenStore</TokenStoreClassName> <SLOHostNameVerificationEnabled>true</SLOHostNameVerificationEnabled> </PassiveSTS> <EntitlementSettings> <ThirftBasedEntitlementConfig> <EnableThriftService>false</EnableThriftService> <ReceivePort>${Ports.ThriftEntitlementReceivePort}</ReceivePort> <ClientTimeout>10000</ClientTimeout> <KeyStore> <Location>${carbon.home}/repository/resources/security/wso2carbon.jks</Location> <Password>wso2carbon</Password> </KeyStore> <ThriftHostName>${carbon.host}</ThriftHostName> </ThirftBasedEntitlementConfig> </EntitlementSettings> <SCIM> <UserEPUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/wso2/scim/Users</UserEPUrl> <GroupEPUrl>${carbon.protocol}://${carbon.host}:${carbon.management.port}/wso2/scim/Groups</GroupEPUrl> <SCIMAuthenticators> <Authenticator class="org.wso2.carbon.identity.scim.provider.auth.BasicAuthHandler"> <Property name="Priority">5</Property> </Authenticator> <Authenticator class="org.wso2.carbon.identity.scim.provider.auth.OAuthHandler"> <Property name="Priority">10</Property> <Property name="AuthorizationServer">local://services</Property> </Authenticator> </SCIMAuthenticators> </SCIM> <EnableAskPasswordAdminUI>false</EnableAskPasswordAdminUI> <AuthenticationPolicy> <CheckAccountExist>true</CheckAccountExist> </AuthenticationPolicy> <EventListeners> <EventListener type="org.wso2.carbon.user.core.listener.UserOperationEventListener" name="org.wso2.carbon.user.mgt.workflow.userstore.UserStoreActionListener" orderId="10" enable="true"/> <EventListener type="org.wso2.carbon.user.core.listener.UserOperationEventListener" name="org.wso2.carbon.identity.mgt.IdentityMgtEventListener" orderId="50" enable="false"/> <EventListener type="dummyType" name="dummyName" orderId="50" enable="false"> <Property name="dummyProperty">dummyPropertyValue</Property> </EventListener> </EventListeners> <CacheConfig> <CacheManager name="IdentityApplicationManagementCacheManager"> <Cache name="AppAuthFrameworkSessionContextCache" enable="true" timeout="300" capacity="5000" isDistributed="false"/> <Cache name="AuthenticationContextCache" enable="true" timeout="300" capacity="5000" isDistributed="false"/> <Cache name="AuthenticationRequestCache"/> </CacheManager> </CacheConfig> <Cookies> <Cookie name="commonAuthId" domain="localhost" httpOnly="true" secure="true" /> <Cookie name="dummy" domain="localhost" httpOnly="true" secure="true" path="/" comment="comment" /> <Cookie name="dummy" path="/" comment="comment" version="1" maxAge="100"/> </Cookies> <ResourceAccessControl default-access="deny"> <Resource context="(.*)" secured="false" http-method="OPTIONS"/> <Resource context="(.*)/api/identity/user/v1.0/validate-code(.*)" secured="true" http-method="all"> <Permissions>/permission/admin/manage/identity/identitymgt</Permissions> </Resource> <Resource context="(.*)/api/identity/user/v1.0/resend-code(.*)" secured="true" http-method="all"/> <Resource context="(.*)/api/identity/user/v1.0/me(.*)" secured="true" http-method="POST"/> <Resource context="(.*)/api/identity/user/v1.0/me(.*)" secured="true" http-method="GET"/> <Resource context="(.*)/api/identity/user/v1.0/pi-info" secured="true" http-method="all"> <Permissions>/permission/admin/manage/identity/usermgt/view</Permissions> </Resource> <Resource context="(.*)/api/identity/user/v1.0/pi-info/(.*)" secured="true" http-method="all"> <Permissions>/permission/admin/manage/identity/usermgt/view</Permissions> </Resource> <Resource context="(.*)/api/identity/config-mgt/v1.0/search(.*)" secured="true" http-method="GET"> <Permissions>/permission/admin/manage/identity/configmgt/list</Permissions> </Resource> <Resource context="(.*)/api/identity/config-mgt/v1.0/resource-type" secured="true" http-method="POST"> <Permissions>/permission/admin/manage/identity/configmgt/add</Permissions> </Resource> <Resource context="(.*)/api/identity/config-mgt/v1.0/resource-type" secured="true" http-method="PUT"> <Permissions>/permission/admin/manage/identity/configmgt/update</Permissions> </Resource> <Resource context="(.*)/api/identity/config-mgt/v1.0/resource-type/(.*)" secured="true" http-method="GET"/> <Resource context="(.*)/api/identity/config-mgt/v1.0/resource-type/(.*)" secured="true" http-method="DELETE"> <Permissions>/permission/admin/manage/identity/configmgt/delete</Permissions> </Resource> <Resource context="(.*)/api/identity/config-mgt/v1.0/resource/(.*)" secured="true" http-method="POST"> <Permissions>/permission/admin/manage/identity/configmgt/add</Permissions> </Resource> <Resource context="(.*)/api/identity/config-mgt/v1.0/resource/(.*)" secured="true" http-method="PUT"> <Permissions>/permission/admin/manage/identity/configmgt/update</Permissions> </Resource> <Resource context="(.*)/api/identity/config-mgt/v1.0/resource/(.*)/(.*)" secured="true" http-method="GET"/> <Resource context="(.*)/api/identity/config-mgt/v1.0/resource/(.*)/(.*)" secured="true" http-method="DELETE"> <Permissions>/permission/admin/manage/identity/configmgt/delete</Permissions> </Resource> <Resource context="(.*)/api/identity/config-mgt/v1.0/resource/(.*)/(.*)" secured="true" http-method="POST"> <Permissions>/permission/admin/manage/identity/configmgt/add</Permissions> </Resource> <Resource context="(.*)/api/identity/config-mgt/v1.0/resource/(.*)/(.*)" secured="true" http-method="PUT"> <Permissions>/permission/admin/manage/identity/configmgt/update</Permissions> </Resource> <Resource context="(.*)/api/identity/config-mgt/v1.0/resource/(.*)/(.*)/(.*)" secured="true" http-method="GET"/> <Resource context="(.*)/api/identity/config-mgt/v1.0/resource/(.*)/(.*)/(.*)" secured="true" http-method="DELETE"> <Permissions>/permission/admin/manage/identity/configmgt/delete</Permissions> </Resource> <Resource context="(.*)/api/identity/consent-mgt/v1.0/consents" secured="true" http-method="all"/> <Resource context="(.*)/api/identity/consent-mgt/v1.0/consents/receipts/(.*)" secured="true" http-method="all"/> <Resource context="(.*)/api/identity/consent-mgt/v1.0/consents/purposes(.*)" secured="true" http-method="POST"> <Permissions>/permission/admin/manage/identity/consentmgt/add</Permissions> </Resource> <Resource context="(.*)/api/identity/consent-mgt/v1.0/consents/purposes(.*)" secured="true" http-method="GET"/> <Resource context="(.*)/api/identity/consent-mgt/v1.0/consents/purposes(.+)" secured="true" http-method="DELETE"> <Permissions>/permission/admin/manage/identity/consentmgt/delete</Permissions> </Resource> <Resource context="(.*)/api/identity/consent-mgt/v1.0/consents/pii-categories(.*)" secured="true" http-method="POST"> <Permissions>/permission/admin/manage/identity/consentmgt/add</Permissions> </Resource> <Resource context="(.*)/api/identity/consent-mgt/v1.0/consents/pii-categories(.*)" secured="true" http-method="GET"/> <Resource context="(.*)/api/identity/consent-mgt/v1.0/consents/pii-categories(.+)" secured="true" http-method="DELETE"> <Permissions>/permission/admin/manage/identity/consentmgt/delete</Permissions> </Resource> <Resource context="(.*)/api/identity/consent-mgt/v1.0/consents/purpose-categories(.*)" secured="true" http-method="POST"> <Permissions>/permission/admin/manage/identity/consentmgt/add</Permissions> </Resource> <Resource context="(.*)/api/identity/consent-mgt/v1.0/consents/purpose-categories(.*)" secured="true" http-method="GET"/> <Resource context="(.*)/api/identity/consent-mgt/v1.0/consents/purpose-categories(.+)" secured="true" http-method="DELETE"> <Permissions>/permission/admin/manage/identity/consentmgt/delete</Permissions> </Resource> <Resource context="(.*)/api/identity/recovery/(.*)" secured="true" http-method="all"> <Permissions>/permission/admin/manage/identity/identitymgt</Permissions> </Resource> <Resource context="(.*)/.well-known(.*)" secured="false" http-method="all"/> <Resource context="(.*)/api/identity/oauth2/dcr/v1.1/register(.*)" secured="true" http-method="POST"> <Permissions>/permission/admin/manage/identity/applicationmgt/create</Permissions> </Resource> <Resource context="(.*)/api/identity/oauth2/dcr/v1.1/register(.*)" secured="true" http-method="DELETE"> <Permissions>/permission/admin/manage/identity/applicationmgt/delete</Permissions> </Resource> <Resource context="(.*)/api/identity/oauth2/dcr/v1.1/register(.*)" secured="true" http-method="PUT"> <Permissions>/permission/admin/manage/identity/applicationmgt/update</Permissions> </Resource> <Resource context="(.*)/api/identity/oauth2/dcr/v1.1/register(.*)" secured="true" http-method="GET"> <Permissions>/permission/admin/manage/identity/applicationmgt/view</Permissions> </Resource> <Resource context="(.*)/identity/register(.*)" secured="true" http-method="all"> <Permissions>/permission/admin/manage/identity/applicationmgt/delete</Permissions> </Resource> <Resource context="(.*)/identity/connect/register(.*)" secured="true" http-method="all"> <Permissions>/permission/admin/manage/identity/applicationmgt/create</Permissions> </Resource> <Resource context="(.*)/oauth2/introspect(.*)" secured="true" http-method="all"> <Permissions>/permission/admin/manage/identity/applicationmgt/view</Permissions> </Resource> <Resource context="(.*)/api/identity/entitlement/(.*)" secured="true" http-method="all"> <Permissions>/permission/admin/manage/identity/pep</Permissions> </Resource> <Resource context="(.*)/scim2/Users(.*)" secured="true" http-method="POST"> <Permissions>/permission/admin/manage/identity/usermgt/create</Permissions> </Resource> <Resource context="(.*)/scim2/Users" secured="true" http-method="GET"> <Permissions>/permission/admin/manage/identity/usermgt/list</Permissions> </Resource> <Resource context="(.*)/scim2/Groups(.*)" secured="true" http-method="POST"> <Permissions>/permission/admin/manage/identity/rolemgt/create</Permissions> </Resource> <Resource context="(.*)/scim2/Groups" secured="true" http-method="GET"> <Permissions>/permission/admin/manage/identity/rolemgt/view</Permissions> </Resource> <Resource context="(.*)/scim2/Users/(.*)" secured="true" http-method="GET"> <Permissions>/permission/admin/manage/identity/usermgt/view</Permissions> </Resource> <Resource context="(.*)/scim2/Users/(.*)" secured="true" http-method="PUT"> <Permissions>/permission/admin/manage/identity/usermgt/update</Permissions> </Resource> <Resource context="(.*)/scim2/Users/(.*)" secured="true" http-method="PATCH"> <Permissions>/permission/admin/manage/identity/usermgt/update</Permissions> </Resource> <Resource context="(.*)/scim2/Users/(.*)" secured="true" http-method="DELETE"> <Permissions>/permission/admin/manage/identity/usermgt/delete</Permissions> </Resource> <Resource context="(.*)/scim2/Groups/(.*)" secured="true" http-method="GET"> <Permissions>/permission/admin/manage/identity/rolemgt/view</Permissions> </Resource> <Resource context="(.*)/scim2/Groups/(.*)" secured="true" http-method="PUT"> <Permissions>/permission/admin/manage/identity/rolemgt/update</Permissions> </Resource> <Resource context="(.*)/scim2/Groups/(.*)" secured="true" http-method="PATCH"> <Permissions>/permission/admin/manage/identity/rolemgt/update</Permissions> </Resource> <Resource context="(.*)/scim2/Groups/(.*)" secured="true" http-method="DELETE"> <Permissions>/permission/admin/manage/identity/rolemgt/delete</Permissions> </Resource> <Resource context="(.*)/scim2/Me" secured="true" http-method="GET"> <Permissions>/permission/admin/login</Permissions> </Resource> <Resource context="(.*)/scim2/Me" secured="true" http-method="DELETE"> <Permissions>/permission/admin/manage/identity/usermgt/delete</Permissions> </Resource> <Resource context="(.*)/scim2/Me" secured="true" http-method="PUT"> <Permissions>/permission/admin/login</Permissions> </Resource> <Resource context="(.*)/scim2/Me" secured="true" http-method="PATCH"> <Permissions>/permission/admin/login</Permissions> </Resource> <Resource context="(.*)/scim2/Me" secured="true" http-method="POST"> <Permissions>/permission/admin/manage/identity/usermgt/create</Permissions> </Resource> <Resource context="/scim2/ServiceProviderConfig" secured="false" http-method="all"> <Permissions></Permissions> </Resource> <Resource context="/scim2/ResourceTypes" secured="false" http-method="all"> <Permissions></Permissions> </Resource> <Resource context="/scim2/Bulk(.*)" secured="true" http-method="all"> <Permissions>/permission/admin/manage/identity/usermgt</Permissions> </Resource> <Resource context="(.*)/api/identity/oauth2/dcr/(.*)" secured="true" http-method="all"> <Permissions>/permission/admin/manage/identity/applicationmgt</Permissions> </Resource> <Resource context="(.*)/api/identity/auth/v1.2/data(.*)" secured="true" http-method="all"/> <Resource context="(.*)/api/identity/auth/v1.2/context(.*)" secured="true" http-method="all"/> <Resource context="(.*)/api/identity/user/v1.0/update-username(.*)" secured="true" http-method="PUT"> <Permissions>/permission/admin/manage/identity/usermgt/update</Permissions> </Resource> <Resource context="(.*)/api/identity/oauth2/v1.0/(.*)" secured="true" http-method="all"/> <Resource context="(.*)/api/users/v1/me/approval-tasks(.*)" secured="true" http-method="all"> <Permissions>/permission/admin/manage/humantask/viewtasks</Permissions> </Resource> <Resource context="(.*)/api/users/v1/me(.*)" secured="true" http-method="all"> <Permissions>/permission/admin/login</Permissions> </Resource> <Resource context="(.*)/api/users/v1/(.*)" secured="true" http-method="all"> <Permissions>/permission/admin/manage/identity/usermgt</Permissions> </Resource> <Resource context="(.*)/api/server/v1/(.*)" secured="true" http-method="all"> <Permissions>/permission/admin/manage/identity/</Permissions> </Resource> <Resource context="/carbon(.*)" secured="false" http-method="all"/> <Resource context="/portal(.*)" secured="false" http-method="all"/> <Resource context="/commonauth(.*)" secured="false" http-method="all"/> <Resource context="/t/(.*)/carbon(.*)" secured="false" http-method="all"/> <Resource context="/services(.*)" secured="false" http-method="all"/> <Resource context="/t/(.*)/services(.*)" secured="false" http-method="all"/> <Resource context="/samlsso(.*)" secured="false" http-method="all"/> <Resource context="/openidserver(.*)" secured="false" http-method="all"/> <Resource context="/passivests(.*)" secured="false" http-method="all"/> <Resource context="/samlartresolve(.*)" secured="false" http-method="all"/> <Resource context="/oauth/request-token(.*)" secured="false" http-method="all"/> <Resource context="/oauth/authorize-url(.*)" secured="false" http-method="all"/> <Resource context="/oauth/access-token(.*)" secured="false" http-method="all"/> <Resource context="/oauth2/token(.*)" secured="false" http-method="all"/> <Resource context="/oauth2/authorize(.*)" secured="false" http-method="all"/> <Resource context="/oauth2/revoke(.*)" secured="false" http-method="all"/> <Resource context="/oauth2/userinfo(.*)" secured="false" http-method="all"/> <Resource context="/oauth2/jwks(.*)" secured="false" http-method="all"/> <Resource context="/oidc/checksession(.*)" secured="false" http-method="all"/> <Resource context="/oidc/logout(.*)" secured="false" http-method="all"/> <Resource context="/oauth2/oidcdiscovery(.*)" secured="false" http-method="all"/> <Resource context="/wso2/scim/Users(.*)" secured="false" http-method="all"/> <Resource context="/wso2/scim/Groups(.*)" secured="false" http-method="all"/> <Resource context="/authenticationendpoint(.*)" secured="false" http-method="all"/> <Resource context="/accountrecoveryendpoint(.*)" secured="false" http-method="all"/> <Resource context="/api/health-check/v1(.*)" secured="false" http-method="all"/> <Resource context="/emailotpauthenticationendpoint(.*)" secured="false" http-method="all"/> <Resource context="/mex(.*)" secured="false" http-method="all"/> <Resource context="/mexut(.*)" secured="false" http-method="all"/> <Resource context="/smsotpauthenticationendpoint(.*)" secured="false" http-method="all"/> <Resource context="/totpauthenticationendpoint(.*)" secured="false" http-method="all"/> <Resource context="/x509certificateauthenticationendpoint(.*)" secured="false" http-method="all"/> <Resource context="/userandrolemgtservice(.*)" secured="false" http-method="all"/> </ResourceAccessControl> <ClientAppAuthentication> <Application name="dashboard" hash="66cd9688a2ae068244ea01e70f0e230f5623b7fa4cdecb65070a09ec06452262"/> </ClientAppAuthentication> <TenantContextsToRewrite> <WebApp> <Context>/api/identity/user/v1.0</Context> <Context>/api/identity/recovery/v0.9</Context> <Context>/oauth2</Context> </WebApp> <Servlet> <Context>/identity/(.*)</Context> </Servlet> </TenantContextsToRewrite> <ClockSkew>300</ClockSkew> <ReverseProxyConfig> <ReverseProxy> <DefaultContext>/oauth2/authorize</DefaultContext> <ProxyContext>/authorize</ProxyContext> </ReverseProxy> <ReverseProxy> <DefaultContext>/oidc/logout</DefaultContext> <ProxyContext>/logout</ProxyContext> </ReverseProxy> </ReverseProxyConfig> <CookiesToInvalidate> <Cookie name="commonAuthId"/> <Cookie name="opbs"/> <Cookie name="pastr"/> <Cookie name="sessionNonceCookie"/> <Cookie name="ALOR"/> </CookiesToInvalidate> </Server>
{ "content_hash": "8ce8a48e8a41490d7f1d09471fcc0c2d", "timestamp": "", "source": "github", "line_count": 585, "max_line_length": 180, "avg_line_length": 60.48205128205128, "alnum_prop": 0.6758521282007801, "repo_name": "wso2/carbon-identity-framework", "id": "86bf64ffb059613cc832c21ce01cef4fe9c8577a", "size": "35382", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/identity-core/org.wso2.carbon.identity.core/src/test/resources/identity.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "132102" }, { "name": "HTML", "bytes": "10775" }, { "name": "Java", "bytes": "16415770" }, { "name": "JavaScript", "bytes": "547683" }, { "name": "Jinja", "bytes": "225118" }, { "name": "PLSQL", "bytes": "210726" }, { "name": "PLpgSQL", "bytes": "126494" }, { "name": "SQLPL", "bytes": "65672" }, { "name": "Shell", "bytes": "11996" }, { "name": "TSQL", "bytes": "115317" }, { "name": "Thrift", "bytes": "1513" }, { "name": "XSLT", "bytes": "1030" } ], "symlink_target": "" }
#ifndef TRIGGER_H #define TRIGGER_H #include "nodes/execnodes.h" #include "nodes/parsenodes.h" /* * TriggerData is the node type that is passed as fmgr "context" info * when a function is called by the trigger manager. */ #define CALLED_AS_TRIGGER(fcinfo) \ ((fcinfo)->context != NULL && IsA((fcinfo)->context, TriggerData)) typedef uint32 TriggerEvent; typedef struct TriggerData { NodeTag type; TriggerEvent tg_event; Relation tg_relation; HeapTuple tg_trigtuple; HeapTuple tg_newtuple; Trigger *tg_trigger; Buffer tg_trigtuplebuf; Buffer tg_newtuplebuf; } TriggerData; /* * TriggerEvent bit flags * * Note that we assume different event types (INSERT/DELETE/UPDATE/TRUNCATE) * can't be OR'd together in a single TriggerEvent. This is unlike the * situation for pg_trigger rows, so pg_trigger.tgtype uses a different * representation! */ #define TRIGGER_EVENT_INSERT 0x00000000 #define TRIGGER_EVENT_DELETE 0x00000001 #define TRIGGER_EVENT_UPDATE 0x00000002 #define TRIGGER_EVENT_TRUNCATE 0x00000003 #define TRIGGER_EVENT_OPMASK 0x00000003 #define TRIGGER_EVENT_ROW 0x00000004 #define TRIGGER_EVENT_BEFORE 0x00000008 #define TRIGGER_EVENT_AFTER 0x00000000 #define TRIGGER_EVENT_INSTEAD 0x00000010 #define TRIGGER_EVENT_TIMINGMASK 0x00000018 /* More TriggerEvent flags, used only within trigger.c */ #define AFTER_TRIGGER_DEFERRABLE 0x00000020 #define AFTER_TRIGGER_INITDEFERRED 0x00000040 #define TRIGGER_FIRED_BY_INSERT(event) \ (((event) & TRIGGER_EVENT_OPMASK) == TRIGGER_EVENT_INSERT) #define TRIGGER_FIRED_BY_DELETE(event) \ (((event) & TRIGGER_EVENT_OPMASK) == TRIGGER_EVENT_DELETE) #define TRIGGER_FIRED_BY_UPDATE(event) \ (((event) & TRIGGER_EVENT_OPMASK) == TRIGGER_EVENT_UPDATE) #define TRIGGER_FIRED_BY_TRUNCATE(event) \ (((event) & TRIGGER_EVENT_OPMASK) == TRIGGER_EVENT_TRUNCATE) #define TRIGGER_FIRED_FOR_ROW(event) \ ((event) & TRIGGER_EVENT_ROW) #define TRIGGER_FIRED_FOR_STATEMENT(event) \ (!TRIGGER_FIRED_FOR_ROW(event)) #define TRIGGER_FIRED_BEFORE(event) \ (((event) & TRIGGER_EVENT_TIMINGMASK) == TRIGGER_EVENT_BEFORE) #define TRIGGER_FIRED_AFTER(event) \ (((event) & TRIGGER_EVENT_TIMINGMASK) == TRIGGER_EVENT_AFTER) #define TRIGGER_FIRED_INSTEAD(event) \ (((event) & TRIGGER_EVENT_TIMINGMASK) == TRIGGER_EVENT_INSTEAD) /* * Definitions for replication role based firing. */ #define SESSION_REPLICATION_ROLE_ORIGIN 0 #define SESSION_REPLICATION_ROLE_REPLICA 1 #define SESSION_REPLICATION_ROLE_LOCAL 2 extern PGDLLIMPORT int SessionReplicationRole; /* * States at which a trigger can be fired. These are the * possible values for pg_trigger.tgenabled. */ #define TRIGGER_FIRES_ON_ORIGIN 'O' #define TRIGGER_FIRES_ALWAYS 'A' #define TRIGGER_FIRES_ON_REPLICA 'R' #define TRIGGER_DISABLED 'D' extern Oid CreateTrigger(CreateTrigStmt *stmt, const char *queryString, Oid constraintOid, Oid indexOid, bool isInternal); extern void DropTrigger(Oid relid, const char *trigname, DropBehavior behavior, bool missing_ok); extern void RemoveTriggerById(Oid trigOid); extern Oid get_trigger_oid(Oid relid, const char *name, bool missing_ok); extern void renametrig(Oid relid, const char *oldname, const char *newname); extern void EnableDisableTrigger(Relation rel, const char *tgname, char fires_when, bool skip_system); extern void RelationBuildTriggers(Relation relation); extern TriggerDesc *CopyTriggerDesc(TriggerDesc *trigdesc); extern void FreeTriggerDesc(TriggerDesc *trigdesc); extern void ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo); extern void ExecASInsertTriggers(EState *estate, ResultRelInfo *relinfo); extern TupleTableSlot *ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot); extern void ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, List *recheckIndexes); extern TupleTableSlot *ExecIRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot); extern void ExecBSDeleteTriggers(EState *estate, ResultRelInfo *relinfo); extern void ExecASDeleteTriggers(EState *estate, ResultRelInfo *relinfo); extern bool ExecBRDeleteTriggers(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid); extern void ExecARDeleteTriggers(EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid); extern bool ExecIRDeleteTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple); extern void ExecBSUpdateTriggers(EState *estate, ResultRelInfo *relinfo); extern void ExecASUpdateTriggers(EState *estate, ResultRelInfo *relinfo); extern TupleTableSlot *ExecBRUpdateTriggers(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, TupleTableSlot *slot); extern void ExecARUpdateTriggers(EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple newtuple, List *recheckIndexes); extern TupleTableSlot *ExecIRUpdateTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, TupleTableSlot *slot); extern void ExecBSTruncateTriggers(EState *estate, ResultRelInfo *relinfo); extern void ExecASTruncateTriggers(EState *estate, ResultRelInfo *relinfo); extern void AfterTriggerBeginXact(void); extern void AfterTriggerBeginQuery(void); extern void AfterTriggerEndQuery(EState *estate); extern void AfterTriggerFireDeferred(void); extern void AfterTriggerEndXact(bool isCommit); extern void AfterTriggerBeginSubXact(void); extern void AfterTriggerEndSubXact(bool isCommit); extern void AfterTriggerSetState(ConstraintsSetStmt *stmt); extern bool AfterTriggerPendingOnRel(Oid relid); /* * in utils/adt/ri_triggers.c */ extern bool RI_FKey_keyequal_upd_pk(Trigger *trigger, Relation pk_rel, HeapTuple old_row, HeapTuple new_row); extern bool RI_FKey_keyequal_upd_fk(Trigger *trigger, Relation fk_rel, HeapTuple old_row, HeapTuple new_row); extern bool RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel); /* result values for RI_FKey_trigger_type: */ #define RI_TRIGGER_PK 1 /* is a trigger on the PK relation */ #define RI_TRIGGER_FK 2 /* is a trigger on the FK relation */ #define RI_TRIGGER_NONE 0 /* is not an RI trigger function */ extern int RI_FKey_trigger_type(Oid tgfoid); #endif /* TRIGGER_H */
{ "content_hash": "fc079b8b47ba0932503c1892515ddf99", "timestamp": "", "source": "github", "line_count": 199, "max_line_length": 76, "avg_line_length": 33.49748743718593, "alnum_prop": 0.7302730273027302, "repo_name": "caidongyun/nginx-openresty-windows", "id": "ce4e971973fd0398f3aab2adcf4929351509bb80", "size": "7076", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ngx_postgres-1.0rc3/include/server/commands/trigger.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ada", "bytes": "91920" }, { "name": "Assembly", "bytes": "489540" }, { "name": "C", "bytes": "30380579" }, { "name": "C#", "bytes": "55626" }, { "name": "C++", "bytes": "1684694" }, { "name": "CLIPS", "bytes": "5401" }, { "name": "CMake", "bytes": "43091" }, { "name": "CSS", "bytes": "13575" }, { "name": "DTrace", "bytes": "4418" }, { "name": "Emacs Lisp", "bytes": "1684" }, { "name": "Erlang", "bytes": "1083" }, { "name": "Groff", "bytes": "558936" }, { "name": "HTML", "bytes": "1199590" }, { "name": "JavaScript", "bytes": "48992" }, { "name": "Lua", "bytes": "773954" }, { "name": "Makefile", "bytes": "1387244" }, { "name": "Nginx", "bytes": "8553" }, { "name": "Objective-C", "bytes": "53002" }, { "name": "Pascal", "bytes": "69925" }, { "name": "Perl", "bytes": "7201823" }, { "name": "Perl6", "bytes": "62749" }, { "name": "Prolog", "bytes": "30361" }, { "name": "Protocol Buffer", "bytes": "2825" }, { "name": "Ragel in Ruby Host", "bytes": "27817" }, { "name": "Ruby", "bytes": "1118705" }, { "name": "SAS", "bytes": "1915" }, { "name": "Scheme", "bytes": "4332" }, { "name": "Shell", "bytes": "635575" }, { "name": "VimL", "bytes": "32807" }, { "name": "XS", "bytes": "26931" }, { "name": "XSLT", "bytes": "12505" }, { "name": "eC", "bytes": "5223" } ], "symlink_target": "" }
<?php namespace DAErp\Controller\Order\Production; use DACore\Controller\AbstractCrudRestController; class ProductionsRestController extends AbstractCrudRestController { protected $aclResource = 'productions'; }
{ "content_hash": "eb62c46ff027414d79e2417fe194c882", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 66, "avg_line_length": 24.11111111111111, "alnum_prop": 0.8341013824884793, "repo_name": "dnaloco/digitala", "id": "2259fb406c08f96564c1f4faaf82ed8d0f7ff01c", "size": "217", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "module/DAErp/src/DAErp/Controller/Order/Production/ProductionsRestController.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2254" }, { "name": "CSS", "bytes": "2667357" }, { "name": "HTML", "bytes": "1125189" }, { "name": "JavaScript", "bytes": "268641" }, { "name": "PHP", "bytes": "1042971" }, { "name": "Ruby", "bytes": "1102" } ], "symlink_target": "" }
/* * 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.facebook.presto.execution.resourceGroups.db; import com.facebook.airlift.json.JsonCodec; import com.facebook.presto.Session; import com.facebook.presto.execution.QueryManager; import com.facebook.presto.execution.QueryState; import com.facebook.presto.resourceGroups.ResourceGroupSelector; import com.facebook.presto.resourceGroups.db.DbResourceGroupConfig; import com.facebook.presto.resourceGroups.db.H2DaoProvider; import com.facebook.presto.resourceGroups.db.H2ResourceGroupsDao; import com.facebook.presto.resourceGroups.reloading.ReloadingResourceGroupConfigurationManager; import com.facebook.presto.spi.Plugin; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.resourceGroups.SchedulingPolicy; import com.facebook.presto.spi.security.Identity; import com.facebook.presto.tests.DistributedQueryRunner; import com.facebook.presto.tpch.TpchPlugin; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import static com.facebook.airlift.json.JsonCodec.listJsonCodec; import static com.facebook.presto.common.resourceGroups.QueryType.EXPLAIN; import static com.facebook.presto.execution.QueryState.RUNNING; import static com.facebook.presto.execution.QueryState.TERMINAL_QUERY_STATES; import static com.facebook.presto.spi.StandardErrorCode.CONFIGURATION_INVALID; import static com.facebook.presto.testing.TestingSession.testSessionBuilder; import static com.google.common.base.Preconditions.checkState; import static java.util.concurrent.TimeUnit.MILLISECONDS; class H2TestUtil { private static final String CONFIGURATION_MANAGER_TYPE = "h2"; public static final String TEST_ENVIRONMENT = "test_environment"; public static final String TEST_ENVIRONMENT_2 = "test_environment_2"; public static final JsonCodec<List<String>> CLIENT_TAGS_CODEC = listJsonCodec(String.class); private H2TestUtil() {} public static Session adhocSession() { return testSessionBuilder() .setCatalog("tpch") .setSchema("sf100000") .setSource("adhoc") .build(); } public static Session testSession(Identity identity) { return testSessionBuilder() .setCatalog("tpch") .setSchema("sf100000") .setSource("abc") .setIdentity(identity) .build(); } public static Session dashboardSession() { return testSessionBuilder() .setCatalog("tpch") .setSchema("sf100000") .setSource("dashboard") .build(); } public static Session rejectingSession() { return testSessionBuilder() .setCatalog("tpch") .setSchema("sf100000") .setSource("reject") .build(); } public static void waitForCompleteQueryCount(DistributedQueryRunner queryRunner, int expectedCount) throws InterruptedException { waitForQueryCount(queryRunner, TERMINAL_QUERY_STATES, expectedCount); } public static void waitForRunningQueryCount(DistributedQueryRunner queryRunner, int expectedCount) throws InterruptedException { waitForQueryCount(queryRunner, ImmutableSet.of(RUNNING), expectedCount); } public static void waitForQueryCount(DistributedQueryRunner queryRunner, Set<QueryState> countingStates, int expectedCount) throws InterruptedException { QueryManager queryManager = queryRunner.getCoordinator().getQueryManager(); while (queryManager.getQueries().stream() .filter(q -> countingStates.contains(q.getState())).count() != expectedCount) { MILLISECONDS.sleep(500); } } public static String getDbConfigUrl() { return "jdbc:h2:mem:test_" + System.nanoTime() + "_" + ThreadLocalRandom.current().nextInt(); } public static H2ResourceGroupsDao getDao(String url) { DbResourceGroupConfig dbResourceGroupConfig = new DbResourceGroupConfig() .setConfigDbUrl(url); H2ResourceGroupsDao dao = new H2DaoProvider(dbResourceGroupConfig).get(); dao.createResourceGroupsTable(); dao.createSelectorsTable(); dao.createResourceGroupsGlobalPropertiesTable(); return dao; } public static DistributedQueryRunner createQueryRunner(String dbConfigUrl, H2ResourceGroupsDao dao) throws Exception { return createQueryRunner(dbConfigUrl, dao, TEST_ENVIRONMENT, ImmutableMap.of(), 1, false, false); } public static DistributedQueryRunner createQueryRunner(String dbConfigUrl, H2ResourceGroupsDao dao, int coordinatorCount) throws Exception { return createQueryRunner(dbConfigUrl, dao, TEST_ENVIRONMENT, ImmutableMap.of(), coordinatorCount, false, false); } public static DistributedQueryRunner createQueryRunner(String dbConfigUrl, H2ResourceGroupsDao dao, Map<String, String> coordinatorProperties, int coordinatorCount) throws Exception { return createQueryRunner(dbConfigUrl, dao, TEST_ENVIRONMENT, coordinatorProperties, coordinatorCount, false, false); } public static DistributedQueryRunner createQueryRunner(String dbConfigUrl, H2ResourceGroupsDao dao, Map<String, String> coordinatorProperties, int coordinatorCount, boolean weightedFairSchedulingEnabled, boolean weightedSchedulingEnabled) throws Exception { return createQueryRunner(dbConfigUrl, dao, TEST_ENVIRONMENT, coordinatorProperties, coordinatorCount, weightedFairSchedulingEnabled, weightedSchedulingEnabled); } public static DistributedQueryRunner createQueryRunner(String dbConfigUrl, H2ResourceGroupsDao dao, String environment, Map<String, String> coordinatorProperties, int coordinatorCount, boolean weightedFairSchedulingEnabled, boolean weightedSchedulingEnabled) throws Exception { DistributedQueryRunner queryRunner = DistributedQueryRunner .builder(testSessionBuilder().setCatalog("tpch").setSchema("tiny").build()) .setNodeCount(2) .setCoordinatorCount(coordinatorCount) .setEnvironment(environment) .setResourceManagerEnabled(true) .setCoordinatorProperties(coordinatorProperties) .build(); try { Plugin h2ResourceGroupManagerPlugin = new H2ResourceGroupManagerPlugin(); queryRunner.installPlugin(h2ResourceGroupManagerPlugin); for (int coordinator = 0; coordinator < coordinatorCount; coordinator++) { queryRunner.getCoordinator(coordinator).getResourceGroupManager().get() .setConfigurationManager(CONFIGURATION_MANAGER_TYPE, ImmutableMap.of("resource-groups.config-db-url", dbConfigUrl, "node.environment", environment)); } queryRunner.installPlugin(new TpchPlugin()); queryRunner.createCatalog("tpch", "tpch"); setup(queryRunner, dao, environment, weightedFairSchedulingEnabled, weightedSchedulingEnabled); queryRunner.waitForClusterToGetReady(); return queryRunner; } catch (Exception e) { queryRunner.close(); throw e; } } public static DistributedQueryRunner getSimpleQueryRunner() throws Exception { String dbConfigUrl = getDbConfigUrl(); H2ResourceGroupsDao dao = getDao(dbConfigUrl); return createQueryRunner(dbConfigUrl, dao); } private static void resourceGroupSetup(H2ResourceGroupsDao dao) { dao.insertResourceGroupsGlobalProperties("cpu_quota_period", "1h"); dao.insertResourceGroup(1, "global", "1MB", 100, 1000, 1000, null, null, null, null, null, null, null, null, null, TEST_ENVIRONMENT); dao.insertResourceGroup(2, "bi-${USER}", "1MB", 3, 2, 2, null, null, null, null, null, null, null, null, 1L, TEST_ENVIRONMENT); dao.insertResourceGroup(3, "user-${USER}", "1MB", 3, 3, 3, null, null, null, null, null, null, null, null, 1L, TEST_ENVIRONMENT); dao.insertResourceGroup(4, "adhoc-${USER}", "1MB", 3, 3, 3, null, null, null, null, null, null, null, null, 3L, TEST_ENVIRONMENT); dao.insertResourceGroup(5, "dashboard-${USER}", "1MB", 1, 1, 1, null, null, null, null, null, null, null, null, 3L, TEST_ENVIRONMENT); dao.insertResourceGroup(6, "no-queueing", "1MB", 0, 1, 1, null, null, null, null, null, null, null, null, null, TEST_ENVIRONMENT_2); dao.insertResourceGroup(7, "explain", "1MB", 0, 1, 1, null, null, null, null, null, null, null, null, null, TEST_ENVIRONMENT); dao.insertResourceGroup(8, "test", "1MB", 3, 3, 3, null, null, null, null, null, null, null, null, 1L, TEST_ENVIRONMENT); dao.insertResourceGroup(9, "test-${USER}", "1MB", 3, 3, 3, null, null, null, null, null, null, null, null, 8L, TEST_ENVIRONMENT); dao.insertSelector(2, 10_000, "user.*", "test", null, null, null, null); dao.insertSelector(4, 1_000, "user.*", "(?i).*adhoc.*", null, null, null, null); dao.insertSelector(5, 100, "user.*", "(?i).*dashboard.*", null, null, null, null); dao.insertSelector(4, 10, "user.*", null, null, CLIENT_TAGS_CODEC.toJson(ImmutableList.of("tag1", "tag2")), null, null); dao.insertSelector(2, 1, "user.*", null, null, CLIENT_TAGS_CODEC.toJson(ImmutableList.of("tag1")), null, null); dao.insertSelector(6, 6, ".*", ".*", null, null, null, null); dao.insertSelector(7, 100_000, null, null, EXPLAIN.name(), null, null, null); dao.insertSelector(9, 10_000, "user.*", "abc", null, null, null, null); } private static void resourceGroupSetupWithWeightedFairPolicy(H2ResourceGroupsDao dao) { dao.insertResourceGroupsGlobalProperties("cpu_quota_period", "1h"); dao.insertResourceGroup(1, "global", "1MB", 100, 1000, 1000, null, null, null, null, null, null, null, null, null, TEST_ENVIRONMENT); dao.insertResourceGroup(2, "bi-${USER}", "1MB", 3, 2, 2, null, null, null, null, null, null, null, null, 1L, TEST_ENVIRONMENT); dao.insertResourceGroup(3, "user-${USER}", "1MB", 3, 4, 4, SchedulingPolicy.WEIGHTED_FAIR.toString(), null, null, null, null, null, null, null, 1L, TEST_ENVIRONMENT); dao.insertResourceGroup(4, "adhoc-${USER}", "1MB", 3, 3, 3, null, 1000, null, null, null, null, null, null, 3L, TEST_ENVIRONMENT); dao.insertResourceGroup(5, "dashboard-${USER}", "1MB", 1, 2, 2, null, 10, null, null, null, null, null, null, 3L, TEST_ENVIRONMENT); dao.insertResourceGroup(6, "no-queueing", "1MB", 0, 1, 1, null, null, null, null, null, null, null, null, null, TEST_ENVIRONMENT_2); dao.insertResourceGroup(7, "explain", "1MB", 0, 1, 1, null, null, null, null, null, null, null, null, null, TEST_ENVIRONMENT); dao.insertResourceGroup(8, "test", "1MB", 3, 3, 3, null, null, null, null, null, null, null, null, 1L, TEST_ENVIRONMENT); dao.insertResourceGroup(9, "test-${USER}", "1MB", 3, 3, 3, null, null, null, null, null, null, null, null, 8L, TEST_ENVIRONMENT); dao.insertSelector(2, 10_000, "user.*", "test", null, null, null, null); dao.insertSelector(4, 1_000, "user.*", "(?i).*adhoc.*", null, null, null, null); dao.insertSelector(5, 100, "user.*", "(?i).*dashboard.*", null, null, null, null); dao.insertSelector(4, 10, "user.*", null, null, CLIENT_TAGS_CODEC.toJson(ImmutableList.of("tag1", "tag2")), null, null); dao.insertSelector(2, 1, "user.*", null, null, CLIENT_TAGS_CODEC.toJson(ImmutableList.of("tag1")), null, null); dao.insertSelector(6, 6, ".*", ".*", null, null, null, null); dao.insertSelector(7, 100_000, null, null, EXPLAIN.name(), null, null, null); dao.insertSelector(9, 10_000, "user.*", "abc", null, null, null, null); } private static void resourceGroupSetupWithWeightedPolicy(H2ResourceGroupsDao dao) { dao.insertResourceGroupsGlobalProperties("cpu_quota_period", "1h"); dao.insertResourceGroup(1, "global", "1MB", 100, 1000, 1000, null, null, null, null, null, null, null, null, null, TEST_ENVIRONMENT); dao.insertResourceGroup(2, "bi-${USER}", "1MB", 3, 2, 2, null, null, null, null, null, null, null, null, 1L, TEST_ENVIRONMENT); dao.insertResourceGroup(3, "user-${USER}", "1MB", 3, 4, 4, SchedulingPolicy.WEIGHTED.toString(), null, null, null, null, null, null, null, 1L, TEST_ENVIRONMENT); dao.insertResourceGroup(4, "adhoc-${USER}", "1MB", 3, 3, 3, null, 10, null, null, null, null, null, null, 3L, TEST_ENVIRONMENT); dao.insertResourceGroup(5, "dashboard-${USER}", "1MB", 1, 1, 2, null, 1000, null, null, null, null, null, null, 3L, TEST_ENVIRONMENT); dao.insertResourceGroup(6, "no-queueing", "1MB", 0, 1, 1, null, null, null, null, null, null, null, null, null, TEST_ENVIRONMENT_2); dao.insertResourceGroup(7, "explain", "1MB", 0, 1, 1, null, null, null, null, null, null, null, null, null, TEST_ENVIRONMENT); dao.insertResourceGroup(8, "test", "1MB", 3, 3, 3, null, null, null, null, null, null, null, null, 1L, TEST_ENVIRONMENT); dao.insertResourceGroup(9, "test-${USER}", "1MB", 3, 3, 3, null, null, null, null, null, null, null, null, 8L, TEST_ENVIRONMENT); dao.insertSelector(2, 10_000, "user.*", "test", null, null, null, null); dao.insertSelector(4, 1_000, "user.*", "(?i).*adhoc.*", null, null, null, null); dao.insertSelector(5, 100, "user.*", "(?i).*dashboard.*", null, null, null, null); dao.insertSelector(4, 10, "user.*", null, null, CLIENT_TAGS_CODEC.toJson(ImmutableList.of("tag1", "tag2")), null, null); dao.insertSelector(2, 1, "user.*", null, null, CLIENT_TAGS_CODEC.toJson(ImmutableList.of("tag1")), null, null); dao.insertSelector(6, 6, ".*", ".*", null, null, null, null); dao.insertSelector(7, 100_000, null, null, EXPLAIN.name(), null, null, null); dao.insertSelector(9, 10_000, "user.*", "abc", null, null, null, null); } private static void setup(DistributedQueryRunner queryRunner, H2ResourceGroupsDao dao, String environment, boolean weightedFairSchedulingEnabled, boolean weightedSchedulingEnabled) throws InterruptedException { if (weightedFairSchedulingEnabled) { resourceGroupSetupWithWeightedFairPolicy(dao); } else if (weightedSchedulingEnabled) { resourceGroupSetupWithWeightedPolicy(dao); } else { resourceGroupSetup(dao); } int expectedSelectors = 7; if (environment.equals(TEST_ENVIRONMENT_2)) { expectedSelectors = 1; } // Selectors are loaded last for (int coordinator = 0; coordinator < queryRunner.getCoordinators().size(); coordinator++) { while (getSelectors(queryRunner, coordinator).size() != expectedSelectors) { MILLISECONDS.sleep(500); } } } public static List<ResourceGroupSelector> getSelectors(DistributedQueryRunner queryRunner) { checkState(queryRunner.getCoordinators().size() == 1, "Expected a single coordinator"); return getSelectors(queryRunner, 0); } public static List<ResourceGroupSelector> getSelectors(DistributedQueryRunner queryRunner, int coordinator) { try { return ((ReloadingResourceGroupConfigurationManager) queryRunner.getCoordinator(coordinator).getResourceGroupManager().get().getConfigurationManager()).getSelectors(); } catch (PrestoException e) { if (e.getErrorCode() == CONFIGURATION_INVALID.toErrorCode()) { return ImmutableList.of(); } throw e; } } }
{ "content_hash": "a26685867b97c3cc96d25dd0aca43379", "timestamp": "", "source": "github", "line_count": 306, "max_line_length": 262, "avg_line_length": 54.450980392156865, "alnum_prop": 0.6745288680830632, "repo_name": "prestodb/presto", "id": "2397e1c686d2415437906ae85ba367ce0f85d869", "size": "16662", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "presto-tests/src/test/java/com/facebook/presto/execution/resourceGroups/db/H2TestUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "33331" }, { "name": "Batchfile", "bytes": "795" }, { "name": "C++", "bytes": "640275" }, { "name": "CMake", "bytes": "31361" }, { "name": "CSS", "bytes": "28319" }, { "name": "Dockerfile", "bytes": "1266" }, { "name": "HTML", "bytes": "29601" }, { "name": "Java", "bytes": "52940440" }, { "name": "JavaScript", "bytes": "286864" }, { "name": "Makefile", "bytes": "16617" }, { "name": "Mustache", "bytes": "17803" }, { "name": "NASL", "bytes": "11965" }, { "name": "PLSQL", "bytes": "85" }, { "name": "Python", "bytes": "39357" }, { "name": "Roff", "bytes": "52281" }, { "name": "Shell", "bytes": "38937" }, { "name": "Thrift", "bytes": "14675" } ], "symlink_target": "" }
package domain //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. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" ) // SaveBatchTaskForTransferProhibitionLock invokes the domain.SaveBatchTaskForTransferProhibitionLock API synchronously // api document: https://help.aliyun.com/api/domain/savebatchtaskfortransferprohibitionlock.html func (client *Client) SaveBatchTaskForTransferProhibitionLock(request *SaveBatchTaskForTransferProhibitionLockRequest) (response *SaveBatchTaskForTransferProhibitionLockResponse, err error) { response = CreateSaveBatchTaskForTransferProhibitionLockResponse() err = client.DoAction(request, response) return } // SaveBatchTaskForTransferProhibitionLockWithChan invokes the domain.SaveBatchTaskForTransferProhibitionLock API asynchronously // api document: https://help.aliyun.com/api/domain/savebatchtaskfortransferprohibitionlock.html // asynchronous document: https://help.aliyun.com/document_detail/66220.html func (client *Client) SaveBatchTaskForTransferProhibitionLockWithChan(request *SaveBatchTaskForTransferProhibitionLockRequest) (<-chan *SaveBatchTaskForTransferProhibitionLockResponse, <-chan error) { responseChan := make(chan *SaveBatchTaskForTransferProhibitionLockResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.SaveBatchTaskForTransferProhibitionLock(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan } // SaveBatchTaskForTransferProhibitionLockWithCallback invokes the domain.SaveBatchTaskForTransferProhibitionLock API asynchronously // api document: https://help.aliyun.com/api/domain/savebatchtaskfortransferprohibitionlock.html // asynchronous document: https://help.aliyun.com/document_detail/66220.html func (client *Client) SaveBatchTaskForTransferProhibitionLockWithCallback(request *SaveBatchTaskForTransferProhibitionLockRequest, callback func(response *SaveBatchTaskForTransferProhibitionLockResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *SaveBatchTaskForTransferProhibitionLockResponse var err error defer close(result) response, err = client.SaveBatchTaskForTransferProhibitionLock(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result } // SaveBatchTaskForTransferProhibitionLockRequest is the request struct for api SaveBatchTaskForTransferProhibitionLock type SaveBatchTaskForTransferProhibitionLockRequest struct { *requests.RpcRequest UserClientIp string `position:"Query" name:"UserClientIp"` Lang string `position:"Query" name:"Lang"` DomainName *[]string `position:"Query" name:"DomainName" type:"Repeated"` Status requests.Boolean `position:"Query" name:"Status"` } // SaveBatchTaskForTransferProhibitionLockResponse is the response struct for api SaveBatchTaskForTransferProhibitionLock type SaveBatchTaskForTransferProhibitionLockResponse struct { *responses.BaseResponse RequestId string `json:"RequestId" xml:"RequestId"` TaskNo string `json:"TaskNo" xml:"TaskNo"` } // CreateSaveBatchTaskForTransferProhibitionLockRequest creates a request to invoke SaveBatchTaskForTransferProhibitionLock API func CreateSaveBatchTaskForTransferProhibitionLockRequest() (request *SaveBatchTaskForTransferProhibitionLockRequest) { request = &SaveBatchTaskForTransferProhibitionLockRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("Domain", "2018-01-29", "SaveBatchTaskForTransferProhibitionLock", "", "") return } // CreateSaveBatchTaskForTransferProhibitionLockResponse creates a response to parse from SaveBatchTaskForTransferProhibitionLock response func CreateSaveBatchTaskForTransferProhibitionLockResponse() (response *SaveBatchTaskForTransferProhibitionLockResponse) { response = &SaveBatchTaskForTransferProhibitionLockResponse{ BaseResponse: &responses.BaseResponse{}, } return }
{ "content_hash": "2e8ccdc76f3f79f9b6627415d126b387", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 228, "avg_line_length": 45.626168224299064, "alnum_prop": 0.8074559606718558, "repo_name": "xiaozhu36/terraform-provider", "id": "62e709e55ac224dd922913942f4718f8bf973df0", "size": "4882", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/domain/save_batch_task_for_transfer_prohibition_lock.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "2195403" }, { "name": "HCL", "bytes": "818" }, { "name": "HTML", "bytes": "40750" }, { "name": "Makefile", "bytes": "1899" }, { "name": "Shell", "bytes": "1341" } ], "symlink_target": "" }
import { Component, OnInit, ChangeDetectorRef } from '@angular/core'; import { StepsService } from '../../services/steps/steps.service'; @Component({ selector: 'ra-navigation', providers: [ StepsService ], styles: [` :host { position: fixed; bottom: 1rem; right: 1rem; z-index: 100; background: rgba(0,0,0,.4); padding: 1rem; border-radius: 3px; font-size: 1.125rem; } .icon { color: #fff; font-size: 1.563rem; line-height: 1.563rem; height: 1.563rem; width: .938rem; background: transparent; border: 0; padding: 0; margin: 0; outline: none; cursor: pointer; transition: transform 0.5s ease; } .icon:hover { transform: scale(1.3); } .icon-left { float: left; } .icon-right { float: right; } .step-number { display: inline-block; margin: 0 1rem; } `], template: ` <button class="icon icon-left" (click)="prevStep()"></button> <span class="step-number"><strong>{{activeStep + 1}}</strong> / <strong>4</strong></span> <button class="icon icon-right" (click)="nextStep()"></button> ` }) export class NavigationComponent { activeStep:number = 1; constructor( private steps:StepsService, private ref:ChangeDetectorRef ) {} ngOnInit() { this.steps.getActiveStep(snapshot => { this.activeStep = this.steps.getStep(snapshot.val()); this.ref.detectChanges(); }); }; nextStep() { if (this.activeStep < 3) { this.steps.activeStep = ++this.activeStep; } } prevStep() { if (this.activeStep > 0) { this.steps.activeStep = --this.activeStep; } } }
{ "content_hash": "c8e38b8628a8ad403ad410fb1f27e1d8", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 93, "avg_line_length": 21.949367088607595, "alnum_prop": 0.5749711649365629, "repo_name": "eskypl/retroanywhere", "id": "6a9d70c4356a009f681609f7f150abc84f3ff54e", "size": "1734", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/app/retro/components/navigation/navigation.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5923" }, { "name": "HTML", "bytes": "11041" }, { "name": "JavaScript", "bytes": "4897" }, { "name": "TypeScript", "bytes": "39229" } ], "symlink_target": "" }
layout: page title: Personal Blog excerpt: "An archive of blog posts sorted by date." search_omit: true --- <ul class="post-list"> {% for post in site.categories.blog %} <li><article><a href="{{ site.url }}{{ post.url }}">{{ post.title }} <span class="entry-date"><time datetime="{{ post.date | date_to_xmlschema }}">{{ post.date | date: "%B %d, %Y" }}</time></span>{% if post.excerpt %} <span class="excerpt">{{ post.excerpt }}</span>{% endif %}</a></article></li> {% endfor %} </ul>
{ "content_hash": "84938509565d1f0e9d692e9d4cb05e70", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 297, "avg_line_length": 44.45454545454545, "alnum_prop": 0.6175869120654397, "repo_name": "ericjansen/ericjansen.github.io", "id": "00aefd99032025c67eefd1ce6ef14cd314d794ec", "size": "493", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "blog/index.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "50103" }, { "name": "HTML", "bytes": "18863" }, { "name": "JavaScript", "bytes": "78237" }, { "name": "Ruby", "bytes": "3858" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in Bot. Mag. 114: t. 7022. 1888 #### Original name null ### Remarks null
{ "content_hash": "bd0cc0e435efe5d647cfb246b1077d0a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 11.538461538461538, "alnum_prop": 0.6866666666666666, "repo_name": "mdoering/backbone", "id": "ad64c3442a7c51059afe793d2a32b50e7ff49c3b", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Piperales/Aristolochiaceae/Asarum/Asarum macranthum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.hackerrank.java.datastructures; class Printer { public void printArray(Object[] array) { for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } } }
{ "content_hash": "7e17dc9222237cf2dd91ad7fab980653", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 43, "avg_line_length": 20.77777777777778, "alnum_prop": 0.6631016042780749, "repo_name": "FireClawGames/School", "id": "dc4d5abcb38e618441c802befcfef5ffb042998e", "size": "187", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Independent-Study/src/com/hackerrank/java/datastructures/Generics.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "8065" } ], "symlink_target": "" }
"""Microsoft SQLServer hook module""" from __future__ import annotations from typing import Any import pymssql from airflow.providers.common.sql.hooks.sql import DbApiHook class MsSqlHook(DbApiHook): """Interact with Microsoft SQL Server.""" conn_name_attr = 'mssql_conn_id' default_conn_name = 'mssql_default' conn_type = 'mssql' hook_name = 'Microsoft SQL Server' supports_autocommit = True DEFAULT_SQLALCHEMY_SCHEME = 'mssql+pymssql' def __init__( self, *args, sqlalchemy_scheme: str | None = None, **kwargs, ) -> None: """ :param args: passed to DBApiHook :param sqlalchemy_scheme: Scheme sqlalchemy connection. Default is ``mssql+pymssql`` Only used for ``get_sqlalchemy_engine`` and ``get_sqlalchemy_connection`` methods. :param kwargs: passed to DbApiHook """ super().__init__(*args, **kwargs) self.schema = kwargs.pop("schema", None) self._sqlalchemy_scheme = sqlalchemy_scheme @property def connection_extra_lower(self) -> dict: """ ``connection.extra_dejson`` but where keys are converted to lower case. This is used internally for case-insensitive access of mssql params. """ conn = self.get_connection(self.mssql_conn_id) # type: ignore[attr-defined] return {k.lower(): v for k, v in conn.extra_dejson.items()} @property def sqlalchemy_scheme(self) -> str: """Sqlalchemy scheme either from constructor, connection extras or default.""" return ( self._sqlalchemy_scheme or self.connection_extra_lower.get('sqlalchemy_scheme') or self.DEFAULT_SQLALCHEMY_SCHEME ) def get_uri(self) -> str: from urllib.parse import parse_qs, urlencode, urlsplit, urlunsplit r = list(urlsplit(super().get_uri())) # change pymssql driver: r[0] = self.sqlalchemy_scheme # remove query string 'sqlalchemy_scheme' like parameters: qs = parse_qs(r[3], keep_blank_values=True) for k in list(qs.keys()): if k.lower() == 'sqlalchemy_scheme': qs.pop(k, None) r[3] = urlencode(qs, doseq=True) return urlunsplit(r) def get_sqlalchemy_connection( self, connect_kwargs: dict | None = None, engine_kwargs: dict | None = None ) -> Any: """Sqlalchemy connection object""" engine = self.get_sqlalchemy_engine(engine_kwargs=engine_kwargs) return engine.connect(**(connect_kwargs or {})) def get_conn( self, ) -> pymssql.connect: """Returns a mssql connection object""" conn = self.get_connection(self.mssql_conn_id) # type: ignore[attr-defined] conn = pymssql.connect( server=conn.host, user=conn.login, password=conn.password, database=self.schema or conn.schema, port=conn.port, ) return conn def set_autocommit( self, conn: pymssql.connect, autocommit: bool, ) -> None: conn.autocommit(autocommit) def get_autocommit(self, conn: pymssql.connect): return conn.autocommit_state
{ "content_hash": "44d450d343a516b3b61b09224e3be1e6", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 107, "avg_line_length": 32.81818181818182, "alnum_prop": 0.6078793474915358, "repo_name": "cfei18/incubator-airflow", "id": "20c1d4a4530138ff597e4ee914cc45f59d838215", "size": "4036", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "airflow/providers/microsoft/mssql/hooks/mssql.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "25980" }, { "name": "Dockerfile", "bytes": "72003" }, { "name": "HCL", "bytes": "3786" }, { "name": "HTML", "bytes": "173434" }, { "name": "JavaScript", "bytes": "143068" }, { "name": "Jinja", "bytes": "38808" }, { "name": "Jupyter Notebook", "bytes": "5482" }, { "name": "Mako", "bytes": "1339" }, { "name": "Python", "bytes": "22660683" }, { "name": "R", "bytes": "313" }, { "name": "Shell", "bytes": "312715" }, { "name": "TypeScript", "bytes": "472379" } ], "symlink_target": "" }