text:
layout: post
title: AngularJS Form
category: AngularJS
tags: [angularjs]
---

AngularJS provides a small and well-defined set of constructs that make standard form-based operations easier. For a form, we should consider three points:

1. Allowing user input
2. Validating those inputs against business rules
3. Submitting the data to the backend server

`form` in AngularJS is extend from html `form`. Now it's a directive. When Angular encounters the `form` tag, it executes the `form` directive. This directive creates an instance of a special Angular class `FormController` that is made available to us on the current scope. It's this controller which provides an API to check and manipulate the state of the form. The same as `ng-model` which creates an instance of `NgModelController`.

## Validation

It already has **built-in support for validating**. Validations are automatically setup by AngularJS according to:

* Input type - text, numbers, e-mails, URLs, radios, checkboxes, and a few others. (such as `<intput type='email'/>`).
* Validation attributes - `required`, `min`, `max`, and custom attributes such as `ng-pattern`, `ng-minlength`, and `ng-maxlength`.

{% highlight html %}

<form name="form" novalidate>
    Name:
    <input name="formName" id="form-name" class="form-control" type="text" ng-model="user.name" required/>
    Name is required
</form>
{% endhighlight %}

So AngularJS will check `required` attribute. When input is empty, the error label will be shown.

More details, `from` directive creates an instace of `FormController` and published into the scope using the name attribute. Then the inside `ng-model` create `NgModelController` and published as a property of the form instance using the name attribute. `$error` and $dirty is of `NgModelController`.

### $error

It contains a list of all errors for the specific ng-model directive. From above example, `required` is validation attribute. So to check the validation, we need to follow this format:

{% highlight html %}
formName.inputName.$error.validation
{% endhighlight %}

For example:

{% highlight html %}
formName.inputName.$error.required // For required
formName.inputName.$error.number   // For type="number"
formName.inputName.$error.pattern  // For ng-pattern
{% endhighlight %}

**When validation is failing, `$error.validation` will be true**. We could use it to decide whether to show error messages.

### States by ng-model

Besides `$error`, every element that uses ng-model — including input, textarea, and select — has states defined on the associated model controller:

* $pristine: True if user does not interact with the input. Any updates to the input field and $pristine is set to false. **Once false, it never flips, unless we call the `$setPristine()` function on the model controller**.
* $dirty: Reverse of $pristine. This is true when the input data has been updated. **This gets reset to false if `$setPristine()` is called.**
* $touched: True if the control ever had focus.
* $untouched: True if the control has never lost focus.
* $valid: True if there are validations defined on the input element and none of them are failing.
* $invalid: True if any of the validations defined on the element are failing.

So from above example:

{% highlight html %}
Name is required
{% endhighlight %}

If there is no `form.formName.$dirty`, the validation message is shown as soon as we load the form. When user never interacts with the input, `$pristine` is true and `$pristine` is false. So here, the error message will never be shown until user begins to interact with the input.

### CSS to an input element

Based on the model state, Angular also adds some CSS classes automatically to an input element.

* `ng-valid/ng-invalid`: This is used if the model is valid or not
* `ng-pristine/ng-dirty`: This is used if the model is pristine or ng-dirty.
* `ng-untouched/ng-touched`:  This is used when the input is never visited or not.
* `ng-invalid-<errorkey>/ng-valid-<errorkey>`: This is used for a specific failed/sucessed validation.
* `ng-empty/ng-not-empty`:  This is used if the model is empty or not

For example, when we check the page by Inspect of browser (not your own code), we could find a list of class already added in input:

{% highlight html %}
<input type="text" name="test" class="ng-pristine ng-untouched ng-invalid ng-invalid-required" ...>
{% endhighlight %}

When we type something, it could change to:

{% highlight html %}
<input type="text" name="test" class="ng-dirty ng-touched ng-valid ng-valid-required" ...>
{% endhighlight %}

So we could customize input element by these classes according to different state. For example:

{% highlight css %}
input.ng-invalid {
	border:1px solid blue;
}
{% endhighlight %}

### Points to be careful

**If data in the model is invalid, it does not show up in the view and the view element is empty.**

For example, we set age value as "2" in controller in init method. But on the view, we set a "min='5'" validation. So the input is empty when we load page.

### Error messages by ng-messages

`ng-messages` and `ng-message` that allow us to show/hide error messages with a less verbose syntax. It's better to use them to show validation errors instead of `ng-show/ng-hide`.

> To use them, we need to add angular-messages.js and add ngMessages module.

Think about a lot of validation in one input:

{% highlight html %}
<form name="form" novalidate>
    Demo:
    <input type="number" name="test" id="test" ng-model="user.demo" min="1" ng-pattern="/^-?\d+$/" required>
    Required
    Must be number
    Min 1
    Must in right format
</form>
{% endhighlight %}

We could change it to:

{% highlight html %}
<form name="form" novalidate>
    Demo:
    <input type="number" name="test" id="test" ng-model="user.demo" min="1" ng-pattern="/^-?\d+$/" required>

        Required
        Must be number
        Min 1
        Must in right format

</form>
{% endhighlight %}

### ng-messages-multiple

With above example, each time, only one message will be shown. (Always the upper one has higher priority). When user typed "-1", both `$error.min` and `$error.pattern` will be true. But only error message for `min` will be shown. To avoid this problem:

{% highlight html %}

{% endhighlight %}

### Message reuse and override

#### Reuse

Because many messages are the same in a big and complex form, we could reuse them by defining all messages in a sepereted file:

{% highlight html %}

This field is required

This field is too short

This field is too long

This field is required

This needs to be a valid email

{% endhighlight %}

And include it by `ng-messages-include`:

{% highlight html %}

{% endhighlight %}

#### Override

If generic messages are not enough to match all input fields, we could override messages defined in the remote template by redefining them within the directive container.

{% highlight html %}

Override the required message

{% endhighlight %}

### Custom validation

There two ways to create a custom validation:

1. By [AngularJS-UI](https://htmlpreview.github.io/?https://github.com/angular-ui/ui-validate/master/demo/index.html)
2. By our own directive

#### By AngularJS-UI

Check [AngularJS-UI](https://htmlpreview.github.io/?https://github.com/angular-ui/ui-validate/master/demo/index.html)

#### By our onw directive

Define a directive:

{% highlight javascript %}
// A validation works like a blacklist, user input can not be in this list
app.directive('blacklist', function(){
    return {
        require: 'ngModel',
        link: function(scope, elem, attr, ngModel) {

            var blacklist = attr.blacklist.split(',');

            //For DOM -> model validation
            ngModel.$parsers.unshift(function(value) {
                var valid = blacklist.indexOf(value) === -1;
                ngModel.$setValidity('blacklist', valid);
                return valid ? value : undefined;
            });

            //For model -> DOM validation
            ngModel.$formatters.unshift(function(value) {
                ngModel.$setValidity('blacklist', blacklist.indexOf(value) === -1);
                return value;
            });
        }
    };
});
{% endhighlight %}

Add it in input element:

{% highlight html %}
<form name="form">
   <input type="text" name="type" ng-model="data.fruitName" blacklist="coconuts,bananas,pears" required/>
    The phrase "{{data.fruitName}}" is blacklisted
   required
</form>
{% endhighlight %}

## Submit

Form in Angular has a different role to play as compared to traditional html form that posts data to the server. We could not find `action` attribute. So how to submit data?!

The standard form behavior of posting data to the server using full-page post-back does not make sense with a SPA framework such as AngularJS. In Angular, **all server requests are made through AJAX** invocations originating from controllers, directives, or services. While the traditional one will refresh the whole page.

So two ways to do it:

1. By `ng-submit`

{% highlight html %}
<form name="form" ng-submit="submit()">
   <button type="submit" ng-disabled="form.$invalid">Submit</button>
</form>
{% endhighlight %}

2. By binding function to the button directly

{% highlight html %}
<form name="form">
    <button ng-click="submit()" ng-disabled="form.$invalid">Submit</button>
</form>
{% endhighlight %}

Then, we need to know that from controller also has some APIs and properties as model controller:

* `$setValidity(validationKey, status, childController)`: This is similar to the `$setValidity` API of `NgModelController` but is used to set the validation state of the model controller inside form controller.
* `$setDirty()`: This is used to mark the form dirty.
* `$setPristine()`: This is used to make the form pristine. This is often used to mark the form pristine after persisting the data to server. The $setPristine call propagates to all model controllers registered with the form, so **all child inputs are also set back to the pristine state**.
* `$setUntouched()`: This is used to mark the form untouched. This is mostly called in sync with `$setPristine`, after data is submitted.

Other than the state manipulation API, there are some handy properties:

* $pristine
* $dirty
* $valid
* $invalid
* $error

They are similar to model controller properties except for the $error property. It's in fact a bit more complex. **It aggregates all failures across all contained inputs**. The `$error`'s property corresponds to the failing error condition and the value is an array of controllers that are invalid. For example, If there are three `required` errors, `$error.required` should be an array with three controllers with this kind of error.

Any way, we **use the $invalid property of the form controller to verify if there are validation errors before we perform a submit**.

{% highlight html %}
<button ng-class="{'btn-default':formName.$valid,'btn-warning':formName.$invalid}" ng-click="submit()" ng-disabled="formName.$invalid">Submit</button>
{% endhighlight %}

So submit button will only be available when no validation errors of its elements. We also use `$valid/$invalid` to set css :D.

### Points to be careful

In general, instead of disabling a submit button, we prefer to inform user all validation errors when user clicks submit button.
If we remove `ng-disabled`, when user loads the page and clicks submit button directly without touching others. Nothing is submitted as the form is invalid, but validation errors on its child elements like input do not show up at all. Look at one label:

{% highlight html %}
Name is required
{% endhighlight %}

`form.formName.$dirty` disables validation messages until user has touched the element. It's why here.

So in `submit()`, we could set a flag to fix this problem.

{% highlight javascript %}
$scope.submit = function () {

    $scope.submitted = true; // Will force validations
    if ($scope.form.$invalid) return; // Nothing will be submitted if invalid!

    $scope.form.$setPristine();
    $scope.submitted = false;

    // Other operations
}
{% endhighlight %}

So now update label:

{% highlight html %}
Name is required
{% endhighlight %}

When user clicks submit button, we force validation to be true!. But still a problem here, we need to repeat this fix on all labels and a little complex to read. So why not create a function because all validations need to check `submitted`

{% highlight javascript %}
$scope.hasError = function (modelController, error) {
  return (modelController.$dirty || $scope.submitted) && error;
}
{% endhighlight %}

So now update label again:

{% highlight html %}
Name is required
{% endhighlight %}

For the moment, we only need to pass model controller and its validation without caring the conditions!

## Reset

The standard way to reset a form is to call the reset method on the form object such as `document.forms["formName"].reset()` or to use `type="reset"` for a button.

But we could also define a function by ourselves to add on the reset button

{% highlight javascript %}
$scope.reset = function () {
	$scope.formName.$setPristine();
	// Restore other parameters
	// Other things to do
};
{% endhighlight %}

## Ref
- [AngularJS Form](https://docs.angularjs.org/guide/forms)
- [AngularJS by Example](https://www.packtpub.com/web-development/angularjs-example)
- [AngularJS ngMessage](https://docs.angularjs.org/api/ngMessages)
- [Stackover Custom validation](http://stackoverflow.com/questions/12581439/how-to-add-custom-validation-to-an-angularjs-form)


text:
#include "BulletXmlImportDemo.h"
#include "GlutStuff.h"

#include "btBulletDynamicsCommon.h"
#include "LinearMath/btHashMap.h"

#ifdef USE_AMD_OPENCL

#include "btOpenCLUtils.h"

#include <LinearMath/btScalar.h>

cl_context        g_cxMainContext;
cl_device_id      g_cdDevice;
cl_command_queue  g_cqCommandQue;

// Returns true if OpenCL is initialized properly, false otherwise.
bool initCL( void* glCtx, void* glDC )
{
	const char* vendorSDK = btOpenCLUtils::getSdkVendorName();
	printf("This program was compiled using the %s OpenCL SDK\n",vendorSDK);

    int ciErrNum = 0;

#ifdef BT_USE_CLEW
    ciErrNum = clewInit( "OpenCL.dll" );
    if ( ciErrNum != CLEW_SUCCESS ) {
        return false;
    }
#endif

#if defined(CL_PLATFORM_MINI_CL)
    cl_device_type deviceType = CL_DEVICE_TYPE_CPU;
#elif defined(CL_PLATFORM_AMD)
    cl_device_type deviceType = CL_DEVICE_TYPE_GPU;
#elif defined(CL_PLATFORM_NVIDIA)
    cl_device_type deviceType = CL_DEVICE_TYPE_GPU;
#else
    cl_device_type deviceType = CL_DEVICE_TYPE_CPU;
#endif

	g_cxMainContext = btOpenCLUtils::createContextFromType(deviceType, &ciErrNum, glCtx, glDC);
    oclCHECKERROR(ciErrNum, CL_SUCCESS);

	int numDev = btOpenCLUtils::getNumDevices(g_cxMainContext);
	if (!numDev)
		return false;

    g_cdDevice =  btOpenCLUtils::getDevice(g_cxMainContext,0);

    btOpenCLDeviceInfo clInfo;
	btOpenCLUtils::getDeviceInfo(g_cdDevice,clInfo);
	btOpenCLUtils::printDeviceInfo(g_cdDevice);

    // create a command-queue
    g_cqCommandQue = clCreateCommandQueue(g_cxMainContext, g_cdDevice, 0, &ciErrNum);
    oclCHECKERROR(ciErrNum, CL_SUCCESS);

    return true;
}

#endif //#ifdef USE_AMD_OPENCL

int main(int argc,char** argv)
{

#ifdef USE_AMD_OPENCL

	bool initialized = initCL(0,0);
	btAssert(initialized);
#endif //USE_AMD_OPENCL

	BulletXmlImportDemo serializeDemo;
	serializeDemo.initPhysics();

#ifdef CHECK_MEMORY_LEAKS
	serializeDemo.exitPhysics();
#else
	return glutmain(argc, argv,640,480,"Bullet Physics Demo. http://bulletphysics.org",&serializeDemo);
#endif

	//default glut doesn't return from mainloop
	return 0;
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Teapotio\Base\ForumBundle\Service;

interface PathServiceInterface
{
}


text:
<?php

declare(strict_types=1);

namespace DiContainerBenchmarks\Fixture\C;

class FixtureC442
{
    public function __construct(FixtureC441 $dependency)
    {
    }
}


text:
<!-- ======================================================
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      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.
====================================================== -->

<mujoco model='dclaw3xh_valve3'>
    <include file='../../../env_models/scenes/basic_scene.xml' />
    <include file='../../../env_models/dclaw/assets/dependencies3xh.xml' />
    <include file='../../../env_models/dclaw/dclaw_stations/dependencies.xml' />
    <compiler meshdir='../../../env_models/dclaw' texturedir="../../../env_models/dclaw"/>

    <worldbody>

        <!-- camera -->
		<camera name='targeting' pos='1 1 2' mode='targetbodycom' target='dClaw'/>

        <!-- dclaw mount + overlay -->
		<body name='mount' pos='0 0 .335' euler='0 0 0'>
            <geom name='mount' type="cylinder" size='0.03 0.005' rgba='.7 .7 .7 1'/>
	        <include file='../../../env_models/dclaw/assets/chain3xh.xml'/>
	        <include file='../../../env_models/dclaw/assets/chain3xh_overlay.xml'/>
	    </body>

        <!-- the valve -->
        <body name="object" pos="0 0 0.0001">
            <include file='../../../env_models/dclaw/assets/valve3.xml'/>
        </body>

        <!-- green mark for the target -->
        <body name="target" pos="0 0 0" >
            <site name="tmark" type='capsule' size='.003 0.04' pos='.04 0 0' rgba='0 1 0 1' euler='0 1.57 0'/>
        </body>

    </worldbody>

</mujoco>


text:
//===--- ArgumentCompletion.cpp ---------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/IDE/ArgumentCompletion.h"
#include "swift/IDE/CodeCompletion.h"
#include "swift/IDE/CompletionLookup.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/IDETypeChecking.h"

using namespace swift;
using namespace swift::ide;
using namespace swift::constraints;

bool ArgumentTypeCheckCompletionCallback::addPossibleParams(
    const ArgumentTypeCheckCompletionCallback::Result &Res,
    SmallVectorImpl<PossibleParamInfo> &Params, SmallVectorImpl<Type> &Types) {
  if (!Res.ParamIdx) {
    // We don't really know much here. Suggest global results without a specific
    // expected type.
    return true;
  }

  if (Res.HasLabel) {
    // We already have a parameter label, suggest types
    Types.push_back(Res.ExpectedType);
    return true;
  }

  ArrayRef<AnyFunctionType::Param> ParamsToPass =
      Res.FuncTy->getAs<AnyFunctionType>()->getParams();

  ParameterList *PL = nullptr;
  if (Res.FuncD) {
    PL = swift::getParameterList(Res.FuncD);
  }
  assert(!PL || PL->size() == ParamsToPass.size());

  bool ShowGlobalCompletions = false;
  for (auto Idx : range(*Res.ParamIdx, ParamsToPass.size())) {
    bool IsCompletion = (Idx == Res.ParamIdx);

    // Stop at the first param claimed by other arguments.
    if (!IsCompletion && Res.ClaimedParamIndices.count(Idx) > 0) {
      break;
    }

    const AnyFunctionType::Param *P = &ParamsToPass[Idx];
    bool Required =
        !(PL && PL->get(Idx)->isDefaultArgument()) && !P->isVariadic();

    if (P->hasLabel() && !(IsCompletion && Res.IsNoninitialVariadic)) {
      // Suggest parameter label if parameter has label, we are completing in it
      // and it is not a variadic parameter that already has arguments
      PossibleParamInfo PP(P, Required);
      if (!llvm::is_contained(Params, PP)) {
        Params.push_back(std::move(PP));
      }
    } else {
      // We have a parameter that doesn't require a label. Suggest global
      // results for that type.
      ShowGlobalCompletions = true;
      Types.push_back(P->getPlainType());
    }
    if (Required) {
      // The user should only be suggested the first required param. Stop.
      break;
    }
  }
  return ShowGlobalCompletions;
}

void ArgumentTypeCheckCompletionCallback::sawSolutionImpl(const Solution &S) {
  Type ExpectedTy = getTypeForCompletion(S, CompletionExpr);

  auto &CS = S.getConstraintSystem();

  Expr *ParentCall = CompletionExpr;
  while (ParentCall && ParentCall->getArgs() == nullptr) {
    ParentCall = CS.getParentExpr(ParentCall);
  }

  if (!ParentCall || ParentCall == CompletionExpr) {
    // We might not have a call that contains the code completion expression if
    // we type-checked the fallback code completion expression that only
    // contains the code completion token, but not the surrounding call.
    return;
  }

  auto ArgInfo = getCompletionArgInfo(ParentCall, CS);
  if (!ArgInfo) {
    assert(false && "bad parent call match?");
    return;
  }
  auto ArgIdx = ArgInfo->completionIdx;

  auto *CallLocator = CS.getConstraintLocator(ParentCall);
  auto *CalleeLocator = S.getCalleeLocator(CallLocator);
  ValueDecl *FuncD = nullptr;
  Type FuncTy;
  Type CallBaseTy;
  // If we are calling a closure in-place there is no overload choice, but we
  // still have all the other required information (like the argument's
  // expected type) to provide useful code completion results.
  if (auto SelectedOverload = S.getOverloadChoiceIfAvailable(CalleeLocator)) {

    CallBaseTy = SelectedOverload->choice.getBaseType();
    if (CallBaseTy) {
      CallBaseTy = S.simplifyType(CallBaseTy)->getRValueType();
    }

    FuncD = SelectedOverload->choice.getDeclOrNull();
    FuncTy = S.simplifyTypeForCodeCompletion(SelectedOverload->openedType);

    // For completion as the arg in a call to the implicit [keypath: _]
    // subscript the solver can't know what kind of keypath is expected without
    // an actual argument (e.g. a KeyPath vs WritableKeyPath) so it ends up as a
    // hole. Just assume KeyPath so we show the expected keypath's root type to
    // users rather than '_'.
    if (SelectedOverload->choice.getKind() ==
        OverloadChoiceKind::KeyPathApplication) {
      auto Params = FuncTy->getAs<AnyFunctionType>()->getParams();
      if (Params.size() == 1 &&
          Params[0].getPlainType()->is<UnresolvedType>()) {
        auto *KPDecl = CS.getASTContext().getKeyPathDecl();
        Type KPTy =
            KPDecl->mapTypeIntoContext(KPDecl->getDeclaredInterfaceType());
        Type KPValueTy = KPTy->castTo<BoundGenericType>()->getGenericArgs()[1];
        KPTy = BoundGenericType::get(KPDecl, Type(), {CallBaseTy, KPValueTy});
        FuncTy = FunctionType::get({Params[0].withType(KPTy)}, KPValueTy);
      }
    }
  }

  // Find the parameter the completion was bound to (if any), as well as which
  // parameters are already bound (so we don't suggest them even when the args
  // are out of order).
  Optional<unsigned> ParamIdx;
  std::set<unsigned> ClaimedParams;
  bool IsNoninitialVariadic = false;

  ConstraintLocator *ArgumentLocator;
  ArgumentLocator =
      CS.getConstraintLocator(CallLocator, ConstraintLocator::ApplyArgument);
  auto ArgMatchChoices = S.argumentMatchingChoices.find(ArgumentLocator);
  if (ArgMatchChoices != S.argumentMatchingChoices.end()) {
    // We might not have argument matching choices when applying a subscript
    // found via @dynamicMemberLookup.
    auto Bindings = ArgMatchChoices->second.parameterBindings;

    for (auto i : indices(Bindings)) {
      bool Claimed = false;
      for (auto j : Bindings[i]) {
        if (j == ArgIdx) {
          assert(!ParamIdx);
          ParamIdx = i;
          IsNoninitialVariadic = llvm::any_of(
              Bindings[i], [j](unsigned other) { return other < j; });
        }
        // Synthesized args don't count.
        if (j < ArgInfo->argCount) {
          Claimed = true;
        }
      }
      if (Claimed) {
        ClaimedParams.insert(i);
      }
    }
  } else {
    // FIXME: We currently don't look through @dynamicMemberLookup applications
    // for subscripts (rdar://90363138)
  }

  bool HasLabel = false;
  if (auto PE = CS.getParentExpr(CompletionExpr)) {
    if (auto Args = PE->getArgs()) {
      HasLabel = !Args->getLabel(ArgIdx).empty();
    }
  }

  bool IsAsync = isContextAsync(S, DC);

  // If this is a duplicate of any other result, ignore this solution.
  if (llvm::any_of(Results, [&](const Result &R) {
        return R.FuncD == FuncD && nullableTypesEqual(R.FuncTy, FuncTy) &&
               nullableTypesEqual(R.BaseType, CallBaseTy) &&
               R.ParamIdx == ParamIdx &&
               R.IsNoninitialVariadic == IsNoninitialVariadic;
      })) {
    return;
  }

  llvm::SmallDenseMap<const VarDecl *, Type> SolutionSpecificVarTypes;
  getSolutionSpecificVarTypes(S, SolutionSpecificVarTypes);

  Results.push_back({ExpectedTy, isa<SubscriptExpr>(ParentCall), FuncD, FuncTy,
                     ArgIdx, ParamIdx, std::move(ClaimedParams),
                     IsNoninitialVariadic, CallBaseTy, HasLabel, IsAsync,
                     SolutionSpecificVarTypes});
}

void ArgumentTypeCheckCompletionCallback::deliverResults(
    bool IncludeSignature, SourceLoc Loc, DeclContext *DC,
    ide::CodeCompletionContext &CompletionCtx,
    CodeCompletionConsumer &Consumer) {
  ASTContext &Ctx = DC->getASTContext();
  CompletionLookup Lookup(CompletionCtx.getResultSink(), Ctx, DC,
                          &CompletionCtx);

  // Perform global completion as a fallback if we don't have any results.
  bool shouldPerformGlobalCompletion = Results.empty();
  SmallVector<Type, 8> ExpectedTypes;

  if (IncludeSignature && !Results.empty()) {
    Lookup.setHaveLParen(true);
    for (auto &Result : Results) {
      auto SemanticContext = SemanticContextKind::None;
      NominalTypeDecl *BaseNominal = nullptr;
      if (Result.BaseType) {
        Type BaseTy = Result.BaseType;
        if (auto InstanceTy = BaseTy->getMetatypeInstanceType()) {
          BaseTy = InstanceTy;
        }
        if ((BaseNominal = BaseTy->getAnyNominal())) {
          SemanticContext = SemanticContextKind::CurrentNominal;
          if (Result.FuncD &&
              Result.FuncD->getDeclContext()->getSelfNominalTypeDecl() !=
                  BaseNominal) {
            SemanticContext = SemanticContextKind::Super;
          }
        } else if (BaseTy->is<TupleType>() || BaseTy->is<SubstitutableType>()) {
          SemanticContext = SemanticContextKind::CurrentNominal;
        }
      }
      if (SemanticContext == SemanticContextKind::None && Result.FuncD) {
        if (Result.FuncD->getDeclContext()->isTypeContext()) {
          SemanticContext = SemanticContextKind::CurrentNominal;
        } else if (Result.FuncD->getDeclContext()->isLocalContext()) {
          SemanticContext = SemanticContextKind::Local;
        } else if (Result.FuncD->getModuleContext() == DC->getParentModule()) {
          SemanticContext = SemanticContextKind::CurrentModule;
        }
      }
      if (Result.FuncTy) {
        if (auto FuncTy = Result.FuncTy->lookThroughAllOptionalTypes()
                              ->getAs<AnyFunctionType>()) {
          if (Result.IsSubscript) {
            assert(SemanticContext != SemanticContextKind::None);
            auto *SD = dyn_cast_or_null<SubscriptDecl>(Result.FuncD);
            Lookup.addSubscriptCallPattern(FuncTy, SD, SemanticContext);
          } else {
            auto *FD = dyn_cast_or_null<AbstractFunctionDecl>(Result.FuncD);
            Lookup.addFunctionCallPattern(FuncTy, FD, SemanticContext);
          }
        }
      }
    }
    Lookup.setHaveLParen(false);

    shouldPerformGlobalCompletion |=
        !Lookup.FoundFunctionCalls || Lookup.FoundFunctionsWithoutFirstKeyword;
  } else if (!Results.empty()) {
    SmallVector<PossibleParamInfo, 8> Params;
    for (auto &Ret : Results) {
      shouldPerformGlobalCompletion |=
          addPossibleParams(Ret, Params, ExpectedTypes);
    }
    Lookup.addCallArgumentCompletionResults(Params);
  }

  if (shouldPerformGlobalCompletion) {
    for (auto &Result : Results) {
      ExpectedTypes.push_back(Result.ExpectedType);
      Lookup.setSolutionSpecificVarTypes(Result.SolutionSpecificVarTypes);
    }
    Lookup.setExpectedTypes(ExpectedTypes, false);
    bool IsInAsyncContext = llvm::any_of(
        Results, [](const Result &Res) { return Res.IsInAsyncContext; });
    Lookup.setCanCurrDeclContextHandleAsync(IsInAsyncContext);
    Lookup.getValueCompletionsInDeclContext(Loc);
    Lookup.getSelfTypeCompletionInDeclContext(Loc, /*isForDeclResult=*/false);

    // Add any keywords that can be used in an argument expr position.
    addSuperKeyword(CompletionCtx.getResultSink(), DC);
    addExprKeywords(CompletionCtx.getResultSink(), DC);
  }

  deliverCompletionResults(CompletionCtx, Lookup, DC, Consumer);
}


text:
"""Create a series of reports.

All reports have the same user, which would not be possible when using the web
front end because reports are user plans and you can have only one plan per
user. But programatically it is possible and doesn't disturb.

"""

from lino.api import rt, dd

def objects():
    # dd.logger.info(
    #     "sheets %s %s",
    #     dd.plugins.ledger.start_year, dd.today().year+1)
    from datetime import date
    Report = rt.models.sheets.Report
    AccountingPeriod = rt.models.ledger.AccountingPeriod
    ses = rt.login("robin")
    for year in range(dd.plugins.ledger.start_year, dd.today().year+1):
        sp = AccountingPeriod.get_default_for_date(date(year, 1, 1))
        ep = AccountingPeriod.get_default_for_date(date(year, 12, 31))
        obj = Report(start_period=sp, end_period=ep, user=ses.get_user())
        yield obj
        obj.run_update_plan(ses)
        # dd.logger.info("20180907 %s", year)


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\ThemeBundle\Context;

use Sylius\Bundle\ThemeBundle\Model\ThemeInterface;

final class SettableThemeContext implements ThemeContextInterface
{
    /** @var ThemeInterface */
    private $theme;

    /**
     * {@inheritdoc}
     */
    public function setTheme(ThemeInterface $theme): void
    {
        $this->theme = $theme;
    }

    /**
     * {@inheritdoc}
     */
    public function getTheme(): ?ThemeInterface
    {
        return $this->theme;
    }
}


text:
package org.gradoop.flink.model.impl.operators.neighborhood.functions;

import org.gradoop.flink.model.api.functions.EdgeAggregateFunction;

/**
 * Super class for all neighbor edge functions.
 */
public abstract class NeighborEdgeFunction implements NeighborFunction {

  /**
   * EPGMEdge aggregation function.
   */
  private EdgeAggregateFunction function;

  /**
   * Valued constructor.
   *
   * @param function edge aggregation function
   */
  public NeighborEdgeFunction(EdgeAggregateFunction function) {
    this.function = function;
  }

  @Override
  public EdgeAggregateFunction getFunction() {
    return function;
  }
}


text:
"""Handler that integrates with Stackdriver"""
import logging
from typing import Collection, Dict, List, Optional, Tuple, Type, Union
from urllib.parse import urlencode

from google.auth.credentials import Credentials
from google.cloud import logging as gcp_logging
from google.cloud.logging import Resource
from google.cloud.logging.handlers.transports import BackgroundThreadTransport, Transport
from google.cloud.logging_v2.services.logging_service_v2 import LoggingServiceV2Client
from google.cloud.logging_v2.types import ListLogEntriesRequest, ListLogEntriesResponse

from airflow.compat.functools import cached_property
from airflow.models import TaskInstance
from airflow.providers.google.cloud.utils.credentials_provider import get_credentials_and_project_id
from airflow.providers.google.common.consts import CLIENT_INFO

DEFAULT_LOGGER_NAME = "airflow"
_GLOBAL_RESOURCE = Resource(type="global", labels={})

_DEFAULT_SCOPESS = frozenset(
    ["https://www.googleapis.com/auth/logging.read", "https://www.googleapis.com/auth/logging.write"]
)

class StackdriverTaskHandler(logging.Handler):
    """Handler that directly makes Stackdriver logging API calls.

    This is a Python standard ``logging`` handler using that can be used to
    route Python standard logging messages directly to the Stackdriver
    Logging API.

    It can also be used to save logs for executing tasks. To do this, you should set as a handler with
    the name "tasks". In this case, it will also be used to read the log for display in Web UI.

    This handler supports both an asynchronous and synchronous transport.

    :param gcp_key_path: Path to Google Cloud Credential JSON file.
        If omitted, authorization based on `the Application Default Credentials
        <https://cloud.google.com/docs/authentication/production#finding_credentials_automatically>`__ will
        be used.
    :param scopes: OAuth scopes for the credentials,
    :param name: the name of the custom log in Stackdriver Logging. Defaults
        to 'airflow'. The name of the Python logger will be represented
        in the ``python_logger`` field.
    :param transport: Class for creating new transport objects. It should
        extend from the base :class:`google.cloud.logging.handlers.Transport` type and
        implement :meth`google.cloud.logging.handlers.Transport.send`. Defaults to
        :class:`google.cloud.logging.handlers.BackgroundThreadTransport`. The other
        option is :class:`google.cloud.logging.handlers.SyncTransport`.
    :param resource: (Optional) Monitored resource of the entry, defaults
                     to the global resource type.
    :param labels: (Optional) Mapping of labels for the entry.
    """

    LABEL_TASK_ID = "task_id"
    LABEL_DAG_ID = "dag_id"
    LABEL_EXECUTION_DATE = "execution_date"
    LABEL_TRY_NUMBER = "try_number"
    LOG_VIEWER_BASE_URL = "https://console.cloud.google.com/logs/viewer"
    LOG_NAME = 'Google Stackdriver'

    def __init__(
        self,
        gcp_key_path: Optional[str] = None,
        scopes: Optional[Collection[str]] = _DEFAULT_SCOPESS,
        name: str = DEFAULT_LOGGER_NAME,
        transport: Type[Transport] = BackgroundThreadTransport,
        resource: Resource = _GLOBAL_RESOURCE,
        labels: Optional[Dict[str, str]] = None,
    ):
        super().__init__()
        self.gcp_key_path: Optional[str] = gcp_key_path
        self.scopes: Optional[Collection[str]] = scopes
        self.name: str = name
        self.transport_type: Type[Transport] = transport
        self.resource: Resource = resource
        self.labels: Optional[Dict[str, str]] = labels
        self.task_instance_labels: Optional[Dict[str, str]] = {}
        self.task_instance_hostname = 'default-hostname'

    @cached_property
    def _credentials_and_project(self) -> Tuple[Credentials, str]:
        credentials, project = get_credentials_and_project_id(
            key_path=self.gcp_key_path, scopes=self.scopes, disable_logging=True
        )
        return credentials, project

    @property
    def _client(self) -> gcp_logging.Client:
        """The Cloud Library API client"""
        credentials, project = self._credentials_and_project
        client = gcp_logging.Client(
            credentials=credentials,
            project=project,
            client_info=CLIENT_INFO,
        )
        return client

    @property
    def _logging_service_client(self) -> LoggingServiceV2Client:
        """The Cloud logging service v2 client."""
        credentials, _ = self._credentials_and_project
        client = LoggingServiceV2Client(
            credentials=credentials,
            client_info=CLIENT_INFO,
        )
        return client

    @cached_property
    def _transport(self) -> Transport:
        """Object responsible for sending data to Stackdriver"""
        # The Transport object is badly defined (no init) but in the docs client/name as constructor
        # arguments are a requirement for any class that derives from Transport class, hence ignore:
        return self.transport_type(self._client, self.name)  # type: ignore[call-arg]

    def emit(self, record: logging.LogRecord) -> None:
        """Actually log the specified logging record.

        :param record: The record to be logged.
        """
        message = self.format(record)
        labels: Optional[Dict[str, str]]
        if self.labels and self.task_instance_labels:
            labels = {}
            labels.update(self.labels)
            labels.update(self.task_instance_labels)
        elif self.labels:
            labels = self.labels
        elif self.task_instance_labels:
            labels = self.task_instance_labels
        else:
            labels = None
        self._transport.send(record, message, resource=self.resource, labels=labels)

    def set_context(self, task_instance: TaskInstance) -> None:
        """
        Configures the logger to add information with information about the current task

        :param task_instance: Currently executed task
        """
        self.task_instance_labels = self._task_instance_to_labels(task_instance)
        self.task_instance_hostname = task_instance.hostname

    def read(
        self, task_instance: TaskInstance, try_number: Optional[int] = None, metadata: Optional[Dict] = None
    ) -> Tuple[List[Tuple[Tuple[str, str]]], List[Dict[str, Union[str, bool]]]]:
        """
        Read logs of given task instance from Stackdriver logging.

        :param task_instance: task instance object
        :param try_number: task instance try_number to read logs from. If None
           it returns all logs
        :param metadata: log metadata. It is used for steaming log reading and auto-tailing.
        :return: a tuple of (
            list of (one element tuple with two element tuple - hostname and logs)
            and list of metadata)
        :rtype: Tuple[List[Tuple[Tuple[str, str]]], List[Dict[str, str]]]
        """
        if try_number is not None and try_number < 1:
            logs = f"Error fetching the logs. Try number {try_number} is invalid."
            return [((self.task_instance_hostname, logs),)], [{"end_of_log": "true"}]

        if not metadata:
            metadata = {}

        ti_labels = self._task_instance_to_labels(task_instance)

        if try_number is not None:
            ti_labels[self.LABEL_TRY_NUMBER] = str(try_number)
        else:
            del ti_labels[self.LABEL_TRY_NUMBER]

        log_filter = self._prepare_log_filter(ti_labels)
        next_page_token = metadata.get("next_page_token", None)
        all_pages = 'download_logs' in metadata and metadata['download_logs']

        messages, end_of_log, next_page_token = self._read_logs(log_filter, next_page_token, all_pages)

        new_metadata: Dict[str, Union[str, bool]] = {"end_of_log": end_of_log}

        if next_page_token:
            new_metadata['next_page_token'] = next_page_token

        return [((self.task_instance_hostname, messages),)], [new_metadata]

    def _prepare_log_filter(self, ti_labels: Dict[str, str]) -> str:
        """
        Prepares the filter that chooses which log entries to fetch.

        More information:
        https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list#body.request_body.FIELDS.filter
        https://cloud.google.com/logging/docs/view/advanced-queries

        :param ti_labels: Task Instance's labels that will be used to search for logs
        :return: logs filter
        """

        def escape_label_key(key: str) -> str:
            return f'"{key}"' if "." in key else key

        def escale_label_value(value: str) -> str:
            escaped_value = value.replace("\\", "\\\\").replace('"', '\\"')
            return f'"{escaped_value}"'

        _, project = self._credentials_and_project
        log_filters = [
            f'resource.type={escale_label_value(self.resource.type)}',
            f'logName="projects/{project}/logs/{self.name}"',
        ]

        for key, value in self.resource.labels.items():
            log_filters.append(f'resource.labels.{escape_label_key(key)}={escale_label_value(value)}')

        for key, value in ti_labels.items():
            log_filters.append(f'labels.{escape_label_key(key)}={escale_label_value(value)}')
        return "\n".join(log_filters)

    def _read_logs(
        self, log_filter: str, next_page_token: Optional[str], all_pages: bool
    ) -> Tuple[str, bool, Optional[str]]:
        """
        Sends requests to the Stackdriver service and downloads logs.

        :param log_filter: Filter specifying the logs to be downloaded.
        :param next_page_token: The token of the page from which the log download will start.
            If None is passed, it will start from the first page.
        :param all_pages: If True is passed, all subpages will be downloaded. Otherwise, only the first
            page will be downloaded
        :return: A token that contains the following items:
            * string with logs
            * Boolean value describing whether there are more logs,
            * token of the next page
        :rtype: Tuple[str, bool, str]
        """
        messages = []
        new_messages, next_page_token = self._read_single_logs_page(
            log_filter=log_filter,
            page_token=next_page_token,
        )
        messages.append(new_messages)
        if all_pages:
            while next_page_token:
                new_messages, next_page_token = self._read_single_logs_page(
                    log_filter=log_filter, page_token=next_page_token
                )
                messages.append(new_messages)
                if not messages:
                    break

            end_of_log = True
            next_page_token = None
        else:
            end_of_log = not bool(next_page_token)
        return "\n".join(messages), end_of_log, next_page_token

    def _read_single_logs_page(self, log_filter: str, page_token: Optional[str] = None) -> Tuple[str, str]:
        """
        Sends requests to the Stackdriver service and downloads single pages with logs.

        :param log_filter: Filter specifying the logs to be downloaded.
        :param page_token: The token of the page to be downloaded. If None is passed, the first page will be
            downloaded.
        :return: Downloaded logs and next page token
        :rtype: Tuple[str, str]
        """
        _, project = self._credentials_and_project
        request = ListLogEntriesRequest(
            resource_names=[f'projects/{project}'],
            filter=log_filter,
            page_token=page_token,
            order_by='timestamp asc',
            page_size=1000,
        )
        response = self._logging_service_client.list_log_entries(request=request)
        page: ListLogEntriesResponse = next(response.pages)
        messages = []
        for entry in page.entries:
            if "message" in entry.json_payload:
                messages.append(entry.json_payload["message"])
        return "\n".join(messages), page.next_page_token

    @classmethod
    def _task_instance_to_labels(cls, ti: TaskInstance) -> Dict[str, str]:
        return {
            cls.LABEL_TASK_ID: ti.task_id,
            cls.LABEL_DAG_ID: ti.dag_id,
            cls.LABEL_EXECUTION_DATE: str(ti.execution_date.isoformat()),
            cls.LABEL_TRY_NUMBER: str(ti.try_number),
        }

    @property
    def log_name(self):
        """Return log name."""
        return self.LOG_NAME

    @cached_property
    def _resource_path(self):
        segments = [self.resource.type]

        for key, value in self.resource.labels:
            segments += [key]
            segments += [value]

        return "/".join(segments)

    def get_external_log_url(self, task_instance: TaskInstance, try_number: int) -> str:
        """
        Creates an address for an external log collecting service.
        :param task_instance: task instance object
        :param try_number: task instance try_number to read logs from.
        :return: URL to the external log collection service
        :rtype: str
        """
        _, project_id = self._credentials_and_project

        ti_labels = self._task_instance_to_labels(task_instance)
        ti_labels[self.LABEL_TRY_NUMBER] = str(try_number)

        log_filter = self._prepare_log_filter(ti_labels)

        url_query_string = {
            'project': project_id,
            'interval': 'NO_LIMIT',
            'resource': self._resource_path,
            'advancedFilter': log_filter,
        }

        url = f"{self.LOG_VIEWER_BASE_URL}?{urlencode(url_query_string)}"
        return url

    def close(self) -> None:
        self._transport.flush()


text:
package com.youku.java.navi.engine.async;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.youku.java.navi.engine.core.INaviMQConsumeStrategy;
import com.youku.java.navi.server.module.INaviModuleContext;
import com.youku.java.navi.server.module.NaviAsyncModuleContextFactory;
import lombok.Getter;
import lombok.Setter;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

public class AsyncMethodConsumeStrategy implements INaviMQConsumeStrategy<String> {

    @Getter @Setter
    private ThreadPoolExecutor executor;

    private Logger log = Logger.getLogger(AsyncMethodConsumeStrategy.class);

    public Class<String> getClassNM() {
        return String.class;
    }

    public void afterPropertiesSet() throws Exception {

    }

    public void destroy() throws Exception {
        executor.shutdown();
    }

    public void consume(List<String> list) {
        Map<INaviAsynchronousMethod, List<String[]>> map = new HashMap<>();
        for (String node : list) {
            try {
                JSONObject obj = JSON.parseObject(node);
                String module = obj.getString("module");
                String method = obj.getString("method");
                JSONArray jsonParams = obj.getJSONArray("params");
                INaviModuleContext moduleCtx = NaviAsyncModuleContextFactory.getInstance().getNaviAsyncModuleContext(module);
                INaviAsynchronousMethod asynMethod = (INaviAsynchronousMethod) moduleCtx.getBean(method);
                String[] params = parseParams(jsonParams);
                if (map.containsKey(asynMethod)) {
                    map.get(asynMethod).add(params);
                } else {
                    if (!asynMethod.getBatch()) {
                        executor.execute(new AsyncRunner(asynMethod, params));
                    } else {
                        map.put(asynMethod, new ArrayList<String[]>());
                        map.get(asynMethod).add(params);
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }

        if (map.size() > 0) {
            for (INaviAsynchronousMethod method : map.keySet()) {
                executor.execute(new AsyncRunner(method, map.get(method)));
            }
        }
    }

    private String[] parseParams(JSONArray params) {
        String[] strs = new String[params.size()];
        for (int i = 0; i < params.size(); i++) {
            String str = params.get(i).toString();
            if ("null".equals(str)) {
                strs[i] = null;
            } else {
                strs[i] = str;
            }
        }
        return strs;
    }

    class AsyncRunner implements Runnable {

        private List<String[]> params;
        private INaviAsynchronousMethod method;

        public AsyncRunner(INaviAsynchronousMethod method, String[] param) {
            this.method = method;
            this.params = new ArrayList<>();
            this.params.add(param);
        }

        public AsyncRunner(INaviAsynchronousMethod method, List<String[]> params) {
            this.method = method;
            this.params = params;
        }

        public void run() {
            int tryTime = 0;
            int retry = 0;
            do {
                try {
                    method.invoke(params);
                } catch (NaviAsyncRetryException e) {
                    log.error(e.getCause().getMessage(), e);
                    retry = e.getTimes();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            } while (tryTime++ < retry);

        }
    }
}


text:
package water.rapids.ast.prims.mungers;

import water.fvec.Frame;
import water.fvec.Vec;
import water.rapids.Env;
import water.rapids.Val;
import water.rapids.ast.AstRoot;
import water.rapids.vals.ValFrame;
import water.rapids.ast.AstPrimitive;
import water.util.VecUtils;

/**
 * Convert to StringVec
 */
public class AstAsCharacter extends AstPrimitive {
  @Override
  public String[] args() {
    return new String[]{"ary"};
  }

  @Override
  public int nargs() {
    return 1 + 1;
  } // (as.character col)

  @Override
  public String str() {
    return "as.character";
  }

  @Override
  public ValFrame apply(Env env, Env.StackHelp stk, AstRoot asts[]) {
    Frame ary = stk.track(asts[1].exec(env)).getFrame();
    Vec[] nvecs = new Vec[ary.numCols()];
    Vec vv;
    for (int c = 0; c < nvecs.length; ++c) {
      vv = ary.vec(c);
      try {
        nvecs[c] = vv.toStringVec();
      } catch (Exception e) {
        VecUtils.deleteVecs(nvecs, c);
        throw e;
      }
    }
    return new ValFrame(new Frame(ary._names, nvecs));
  }
}


text:
/**
 * Extension for binding multiple instances in a collection; this extension requires {@code
 * guice-multibindings-2.0.jar}.
 */
package org.elasticsearch.common.inject.multibindings;


text:
using System.Diagnostics.Contracts;
using Cqrs.Messaging.Configuration.Amqp;
using EasyNetQ;

namespace Cqrs.Messaging.Rabbitmq
{
    internal sealed  class EasyNetQContainerAdapter : IContainer
    {
        private readonly ILocator _locator;

        public EasyNetQContainerAdapter(ILocator locator)
        {
            Contract.Requires(locator != null);
            _locator = locator;
        }

        public TService Resolve<TService>() where TService : class
        {
            return _locator.Resolve<TService>();
        }

        public IServiceRegister Register<TService>(System.Func<IServiceProvider, TService> serviceCreator) where TService : class
        {
            _locator.Register(() => serviceCreator(this));

            return this;
        }

        public IServiceRegister Register<TService, TImplementation>() where TService : class where TImplementation : class, TService
        {
            _locator.Register<TService, TImplementation>();

            return this;
        }
    }
}


text:
Deployment
==========

This page describes, how to deploy your own version of the measurement software.

Required Plugins
----------------

Since this is an e3 Plug-In deployed in an e4 environment all required `compatibility layer plugins`_ must be added.

.. _compatibility layer plugins: https://www.eclipse.org/community/eclipse_newsletter/2013/february/article3.php#compatibiliylayer_plugins

Export the RCP application
--------------------------

Open the ``fvf.product`` file in eclipse. On the `Overview` page there is the export section with a link to open the "Eclipse Product export wizard" (which is also available from the toolbar of this editor). Make sure to check "Export for multiple platforms" (which is only available if you followed the :ref:`setup-deltapack` instructions) and "Synchronize before exporting". Click "Next" which shows the available platforms to deploy to.


text:
package Paws::Snowball::DescribeJob;
  use Moose;
  has JobId => (is => 'ro', isa => 'Str', required => 1);

  use MooseX::ClassAttribute;

  class_has _api_call => (isa => 'Str', is => 'ro', default => 'DescribeJob');
  class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::Snowball::DescribeJobResult');
  class_has _result_key => (isa => 'Str', is => 'ro');
1;

### main pod documentation begin ###

=head1 NAME

Paws::Snowball::DescribeJob - Arguments for method DescribeJob on Paws::Snowball

=head1 DESCRIPTION

This class represents the parameters used for calling the method DescribeJob on the
Amazon Import/Export Snowball service. Use the attributes of this class
as arguments to method DescribeJob.

You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to DescribeJob.

As an example:

  $service_obj->DescribeJob(Att1 => $value1, Att2 => $value2, ...);

Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.

=head1 ATTRIBUTES

=head2 B<REQUIRED> JobId => Str

The automatically generated ID for a job, for example
C<JID123e4567-e89b-12d3-a456-426655440000>.

=head1 SEE ALSO

This class forms part of L<Paws>, documenting arguments for method DescribeJob in L<Paws::Snowball>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: https://github.com/pplu/aws-sdk-perl

Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues

=cut


text:
from django.db import models
from questionnaire.models.base import BaseModel

class QuestionTextHistory(BaseModel):
    text = models.TextField(blank=False, null=False)
    export_label = models.TextField(blank=True, null=False)
    questionnaire = models.ForeignKey("Questionnaire", blank=False, null=False)
    question = models.ForeignKey("Question", blank=False, null=False, related_name="history")


text:
<?php

namespace PhalconTest\Di;

use Phalcon\Di\Config;
use Phalcon\Di\Di;
use PHPUnit\Framework\TestCase;

/**
 * @covers \Phalcon\Di\Di
 */
class DiTest extends TestCase
{
    /**
     * @covers \Phalcon\Di\Di::configure
     */
    public function testPassesKnownServiceConfigKeysToServiceManagerWithConfigMethod()
    {
        $expected = [
            'services' => [
                'foo' => $this,
            ],
            'shared' => [
                __CLASS__     => true,
                __NAMESPACE__ => false,
            ],
        ];
        $config = $expected + [
                'foo' => 'bar',
                'baz' => 'bat',
            ];
        $services = $this->prophesize(Di::class);
        $services->configure($expected)->willReturn('CALLED');
        $configuration = new Config($config);
        $this->assertEquals('CALLED', $configuration->configureServiceManager($services->reveal()));
        return [
            'array'  => $expected,
            'config' => $configuration,
        ];
    }
}


text:
namespace CastGetter.Interfaces
{
    public interface IShell
    {
        void OpenDetailView();
    }
}


text:
package net.kebernet.skillz.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * An annotation for a method called when a skill is launched by the user for
 * continuous interactive mode.
 */
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Target(ElementType.METHOD)
public @interface Launched {
}


text:
@implementation BooksCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"b"]];
        //self.layer.borderWidth = 0;
        //self.layer.borderColor = [UIColor clearColor].CGColor;
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
    self.selectionStyle = UITableViewCellSelectionStyleNone;
}

@end


text:
import { getTimeOfDay } from './get-time-of-day';

export function greet(name = 'friend') {
  const timeOfDay = getTimeOfDay();

  return `Good ${timeOfDay}, ${name}!`;
}


text:
import getViewportSize from '../../utils/dom/getViewportSize';

import { BottomLeft } from './bottom-left';
import { BottomRight } from './bottom-right';
import { BottomCenter } from './bottom-center';
import { TopLeft } from './top-left';
import { TopRight } from './top-right';
import { TopCenter } from './top-center';
import { IPositionFunction } from '../position-function';

const positionMap: Record<string, IPositionFunction> = {
  BottomLeft,
  BottomRight,
  BottomCenter,
  TopLeft,
  TopRight,
  TopCenter,
};

export const AutoBottomCenter: IPositionFunction = props => {
  const { contentRect, cushion, anchorRect } = props;
  const viewport = getViewportSize();

  let horizontal;
  let vertical;

  const mid = (anchorRect.left + anchorRect.right) / 2;
  const halfWidth = contentRect.width / 2;

  // 只有当居中放不下,并且右边能够放下的时候才移动到右边,如果左边能放下就移动到左边
  if (
    mid + halfWidth > viewport.width &&
    anchorRect.right - contentRect.width > 0
  ) {
    horizontal = 'Right';
  } else if (
    mid - halfWidth < 0 &&
    anchorRect.left + contentRect.width < viewport.width
  ) {
    horizontal = 'Left';
  } else {
    horizontal = 'Center';
  }

  // 只有当下面放不下,并且上面能够放下时才移动到上面
  if (
    anchorRect.bottom + cushion + contentRect.height > viewport.height &&
    anchorRect.top - cushion - contentRect.height > 0
  ) {
    vertical = 'Top';
  } else {
    vertical = 'Bottom';
  }

  const key = `${vertical}${horizontal}`;

  return positionMap[key](props);
};


text:
package com.saasxx.framework.testcase.data.copier;

import java.util.Date;

public class Pojo1 {
	String name;
	String password;
	Date date;
	int interger;
	boolean bool;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public int getInterger() {
		return interger;
	}

	public void setInterger(int interger) {
		this.interger = interger;
	}

	public boolean isBool() {
		return bool;
	}

	public void setBool(boolean bool) {
		this.bool = bool;
	}

}


text:
package io.reactivex.internal.operators.observable;

import java.util.concurrent.atomic.*;

import io.reactivex.*;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.Function;
import io.reactivex.internal.disposables.DisposableHelper;
import io.reactivex.internal.functions.ObjectHelper;
import io.reactivex.internal.queue.*;
import io.reactivex.internal.util.AtomicThrowable;
import io.reactivex.plugins.RxJavaPlugins;

public final class ObservableSwitchMap<T, R> extends AbstractObservableWithUpstream<T, R> {
    final Function<? super T, ? extends ObservableSource<? extends R>> mapper;
    final int bufferSize;

    final boolean delayErrors;

    public ObservableSwitchMap(ObservableSource<T> source,
                               Function<? super T, ? extends ObservableSource<? extends R>> mapper, int bufferSize,
                                       boolean delayErrors) {
        super(source);
        this.mapper = mapper;
        this.bufferSize = bufferSize;
        this.delayErrors = delayErrors;
    }

    @Override
    public void subscribeActual(Observer<? super R> t) {

        if (ObservableScalarXMap.tryScalarXMapSubscribe(source, t, mapper)) {
            return;
        }

        source.subscribe(new SwitchMapObserver<T, R>(t, mapper, bufferSize, delayErrors));
    }

    static final class SwitchMapObserver<T, R> extends AtomicInteger implements Observer<T>, Disposable {

        private static final long serialVersionUID = -3491074160481096299L;
        final Observer<? super R> actual;
        final Function<? super T, ? extends ObservableSource<? extends R>> mapper;
        final int bufferSize;

        final boolean delayErrors;

        final AtomicThrowable errors;

        volatile boolean done;

        volatile boolean cancelled;

        Disposable s;

        final AtomicReference<SwitchMapInnerObserver<T, R>> active = new AtomicReference<SwitchMapInnerObserver<T, R>>();

        static final SwitchMapInnerObserver<Object, Object> CANCELLED;
        static {
            CANCELLED = new SwitchMapInnerObserver<Object, Object>(null, -1L, 1);
            CANCELLED.cancel();
        }

        volatile long unique;

        SwitchMapObserver(Observer<? super R> actual,
                Function<? super T, ? extends ObservableSource<? extends R>> mapper, int bufferSize,
                        boolean delayErrors) {
            this.actual = actual;
            this.mapper = mapper;
            this.bufferSize = bufferSize;
            this.delayErrors = delayErrors;
            this.errors = new AtomicThrowable();
        }

        @Override
        public void onSubscribe(Disposable s) {
            if (DisposableHelper.validate(this.s, s)) {
                this.s = s;
                actual.onSubscribe(this);
            }
        }

        @Override
        public void onNext(T t) {
            long c = unique + 1;
            unique = c;

            SwitchMapInnerObserver<T, R> inner = active.get();
            if (inner != null) {
                inner.cancel();
            }

            ObservableSource<? extends R> p;
            try {
                p = ObjectHelper.requireNonNull(mapper.apply(t), "The ObservableSource returned is null");
            } catch (Throwable e) {
                Exceptions.throwIfFatal(e);
                s.dispose();
                onError(e);
                return;
            }

            SwitchMapInnerObserver<T, R> nextInner = new SwitchMapInnerObserver<T, R>(this, c, bufferSize);

            for (;;) {
                inner = active.get();
                if (inner == CANCELLED) {
                    break;
                }
                if (active.compareAndSet(inner, nextInner)) {
                    p.subscribe(nextInner);
                    break;
                }
            }
        }

        @Override
        public void onError(Throwable t) {
            if (!done && errors.addThrowable(t)) {
                if (!delayErrors) {
                    disposeInner();
                }
                done = true;
                drain();
            } else {
                RxJavaPlugins.onError(t);
            }
        }

        @Override
        public void onComplete() {
            if (!done) {
                done = true;
                drain();
            }
        }

        @Override
        public void dispose() {
            if (!cancelled) {
                cancelled = true;
                s.dispose();
                disposeInner();
            }
        }

        @Override
        public boolean isDisposed() {
            return cancelled;
        }

        @SuppressWarnings("unchecked")
        void disposeInner() {
            SwitchMapInnerObserver<T, R> a = active.get();
            if (a != CANCELLED) {
                a = active.getAndSet((SwitchMapInnerObserver<T, R>)CANCELLED);
                if (a != CANCELLED && a != null) {
                    a.cancel();
                }
            }
        }

        void drain() {
            if (getAndIncrement() != 0) {
                return;
            }

            final Observer<? super R> a = actual;

            int missing = 1;

            for (;;) {

                if (cancelled) {
                    return;
                }

                if (done) {
                    boolean empty = active.get() == null;
                    if (delayErrors) {
                        if (empty) {
                            Throwable ex = errors.get();
                            if (ex != null) {
                                a.onError(ex);
                            } else {
                                a.onComplete();
                            }
                            return;
                        }
                    } else {
                        Throwable ex = errors.get();
                        if (ex != null) {
                            a.onError(errors.terminate());
                            return;
                        }
                        if (empty) {
                            a.onComplete();
                            return;
                        }
                    }
                }

                SwitchMapInnerObserver<T, R> inner = active.get();

                if (inner != null) {
                    SpscLinkedArrayQueue<R> q = inner.queue;

                    if (inner.done) {
                        boolean empty = q.isEmpty();
                        if (delayErrors) {
                            if (empty) {
                                active.compareAndSet(inner, null);
                                continue;
                            }
                        } else {
                            Throwable ex = errors.get();
                            if (ex != null) {
                                a.onError(errors.terminate());
                                return;
                            }
                            if (empty) {
                                active.compareAndSet(inner, null);
                                continue;
                            }
                        }
                    }

                    boolean retry = false;

                    for (;;) {
                        if (cancelled) {
                            return;
                        }
                        if (inner != active.get()) {
                            retry = true;
                            break;
                        }

                        if (!delayErrors) {
                            Throwable ex = errors.get();
                            if (ex != null) {
                                a.onError(errors.terminate());
                                return;
                            }
                        }

                        boolean d = inner.done;
                        R v = q.poll();
                        boolean empty = v == null;

                        if (d && empty) {
                            active.compareAndSet(inner, null);
                            retry = true;
                            break;
                        }

                        if (empty) {
                            break;
                        }

                        a.onNext(v);
                    }

                    if (retry) {
                        continue;
                    }
                }

                missing = addAndGet(-missing);
                if (missing == 0) {
                    break;
                }
            }
        }

        void innerError(SwitchMapInnerObserver<T, R> inner, Throwable ex) {
            if (inner.index == unique && errors.addThrowable(ex)) {
                if (!delayErrors) {
                    s.dispose();
                }
                inner.done = true;
                drain();
            } else {
                RxJavaPlugins.onError(ex);
            }
        }
    }

    static final class SwitchMapInnerObserver<T, R> extends AtomicReference<Disposable> implements Observer<R> {

        private static final long serialVersionUID = 3837284832786408377L;
        final SwitchMapObserver<T, R> parent;
        final long index;
        final SpscLinkedArrayQueue<R> queue;

        volatile boolean done;

        SwitchMapInnerObserver(SwitchMapObserver<T, R> parent, long index, int bufferSize) {
            this.parent = parent;
            this.index = index;
            this.queue = new SpscLinkedArrayQueue<R>(bufferSize);
        }

        @Override
        public void onSubscribe(Disposable s) {
            DisposableHelper.setOnce(this, s);
        }

        @Override
        public void onNext(R t) {
            if (index == parent.unique) {
                queue.offer(t);
                parent.drain();
            }
        }

        @Override
        public void onError(Throwable t) {
            parent.innerError(this, t);
        }

        @Override
        public void onComplete() {
            if (index == parent.unique) {
                done = true;
                parent.drain();
            }
        }

        public void cancel() {
            DisposableHelper.dispose(this);
        }
    }
}


text:
package org.apereo.cas.ticket.accesstoken;

import org.apereo.cas.authentication.Authentication;
import org.apereo.cas.authentication.principal.Service;
import org.apereo.cas.support.oauth.services.OAuthRegisteredService;
import org.apereo.cas.ticket.ExpirationPolicy;
import org.apereo.cas.ticket.Ticket;
import org.apereo.cas.ticket.TicketFactory;
import org.apereo.cas.ticket.TicketGrantingTicket;
import org.apereo.cas.ticket.UniqueTicketIdGenerator;
import org.apereo.cas.token.JWTBuilder;
import org.apereo.cas.util.DateTimeUtils;
import org.apereo.cas.util.DefaultUniqueTicketIdGenerator;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.val;

import java.time.ZonedDateTime;
import java.util.Collection;

/**
 * Default OAuth access token factory.
 *
 * @author Jerome Leleu
 * @since 5.0.0
 */
@RequiredArgsConstructor
@Getter
public class DefaultAccessTokenFactory implements AccessTokenFactory {

    /**
     * Default instance for the ticket id generator.
     */
    protected final UniqueTicketIdGenerator accessTokenIdGenerator;

    /**
     * ExpirationPolicy for refresh tokens.
     */
    protected final ExpirationPolicy expirationPolicy;

    /**
     * JWT builder instance.
     */
    protected final JWTBuilder jwtBuilder;

    public DefaultAccessTokenFactory(final ExpirationPolicy expirationPolicy, final JWTBuilder jwtBuilder) {
        this(new DefaultUniqueTicketIdGenerator(), expirationPolicy, jwtBuilder);
    }

    @Override
    public AccessToken create(final Service service, final Authentication authentication,
                              final TicketGrantingTicket ticketGrantingTicket,
                              final Collection<String> scopes, final String clientId) {
        var accessTokenId = this.accessTokenIdGenerator.getNewTicketId(AccessToken.PREFIX);

        val registeredService = (OAuthRegisteredService) this.jwtBuilder.getServicesManager().findServiceBy(service);
        if (registeredService != null && registeredService.isJwtAccessToken()) {
            val dt = ZonedDateTime.now().plusSeconds(this.expirationPolicy.getTimeToLive());
            val builder = JWTBuilder.JwtRequest.builder();
            val request = builder.serviceAudience(service.getId())
                .issueDate(DateTimeUtils.dateOf(authentication.getAuthenticationDate()))
                .jwtId(accessTokenId)
                .subject(authentication.getPrincipal().getId())
                .validUntilDate(DateTimeUtils.dateOf(dt))
                .attributes(authentication.getAttributes())
                .build();
            accessTokenId = jwtBuilder.build(request);
        }
        val at = new AccessTokenImpl(accessTokenId, service, authentication,
            this.expirationPolicy, ticketGrantingTicket, scopes, clientId);
        if (ticketGrantingTicket != null) {
            ticketGrantingTicket.getDescendantTickets().add(at.getId());
        }
        return at;
    }

    @Override
    public TicketFactory get(final Class<? extends Ticket> clazz) {
        return this;
    }
}


text:
namespace kepler {
namespace gl {

#define SAMPLES_BASE "../../../glTF-Sample-Models/2.0/"

static std::vector<const char*> g_paths{
    SAMPLES_BASE "CesiumMilkTruck/glTF/CesiumMilkTruck.gltf",
    SAMPLES_BASE "Lantern/glTF/Lantern.gltf",
    SAMPLES_BASE "Duck/glTF/Duck.gltf",
    SAMPLES_BASE "SciFiHelmet/glTF/SciFiHelmet.gltf",
    SAMPLES_BASE "Box/glTF/Box.gltf",
    SAMPLES_BASE "BoxAnimated/glTF/BoxAnimated.gltf",
    SAMPLES_BASE "AnimatedCube/glTF/AnimatedCube.gltf",
    SAMPLES_BASE "AnimatedMorphCube/glTF/AnimatedMorphCube.gltf",
    SAMPLES_BASE "AnimatedMorphSphere/glTF/AnimatedMorphSphere.gltf",
    SAMPLES_BASE "Avocado/glTF/Avocado.gltf",
    SAMPLES_BASE "BarramundiFish/glTF/BarramundiFish.gltf",
    SAMPLES_BASE "BoomBox/glTF/BoomBox.gltf",
    SAMPLES_BASE "BoxInterleaved/glTF/BoxInterleaved.gltf",
    SAMPLES_BASE "BoxTextured/glTF/BoxTextured.gltf",
    SAMPLES_BASE "BrainStem/glTF/BrainStem.gltf",
    SAMPLES_BASE "Buggy/glTF/Buggy.gltf",
    SAMPLES_BASE "Cameras/glTF/Cameras.gltf",
    SAMPLES_BASE "CesiumMan/glTF/CesiumMan.gltf",
    SAMPLES_BASE "Corset/glTF/Corset.gltf",
    SAMPLES_BASE "Cube/glTF/Cube.gltf",
    SAMPLES_BASE "GearboxAssy/glTF/GearboxAssy.gltf",
    SAMPLES_BASE "MetalRoughSpheres/glTF/MetalRoughSpheres.gltf",
    SAMPLES_BASE "Monster/glTF/Monster.gltf",
    SAMPLES_BASE "NormalTangentTest/glTF/NormalTangentTest.gltf",
    SAMPLES_BASE "ReciprocatingSaw/glTF/ReciprocatingSaw.gltf",
    SAMPLES_BASE "RiggedFigure/glTF/RiggedFigure.gltf",
    SAMPLES_BASE "RiggedSimple/glTF/RiggedSimple.gltf",
    SAMPLES_BASE "SimpleMeshes/glTF/SimpleMeshes.gltf",
    SAMPLES_BASE "Suzanne/glTF/Suzanne.gltf",
    SAMPLES_BASE "TextureSettingsTest/glTF/TextureSettingsTest.gltf",
    SAMPLES_BASE "Triangle/glTF/Triangle.gltf",
    SAMPLES_BASE "TriangleWithoutIndices/glTF/TriangleWithoutIndices.gltf",
    SAMPLES_BASE "AnimatedTriangle/glTF/AnimatedTriangle.gltf",
    SAMPLES_BASE "TwoSidedPlane/glTF/TwoSidedPlane.gltf",
    SAMPLES_BASE "2CylinderEngine/glTF/2CylinderEngine.gltf",
    SAMPLES_BASE "VC/glTF/VC.gltf",
};
static size_t g_pathIndex = 0;

static std::string g_text;

shared_ptr<Material> createBoxMaterial();

static const char* nextPath() {
    g_pathIndex = (g_pathIndex + 1) % g_paths.size();
    return g_paths[g_pathIndex];
}

static const char* prevPath() {
    if (g_pathIndex == 0) {
        g_pathIndex = g_paths.size() - 1;
    }
    else {
        g_pathIndex = (g_pathIndex - 1) % g_paths.size();
    }
    return g_paths[g_pathIndex];
}

static const char* getCurrentPath() {
    return g_paths[g_pathIndex];
}

Gltf2Test::Gltf2Test() : _moveCamera(false) {
}

void Gltf2Test::start() {
    g_pathIndex = 0;
    //glClearColor(0.16f, 0.3f, 0.5f, 1.0f);
    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    loadSceneFromFile(getCurrentPath());
    if (_scene) {
        if (auto node = _scene->findFirstNodeByName("pro12-18s")) {
            node->editLocalTransform().loadIdentity();
        }
    }
    _font = BmpFont::createFromFile("res/fonts/arial-32.fnt");
}

void Gltf2Test::update() {
}

void Gltf2Test::render() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    if (_scene) {
        _scene->visit([](Node* node) {
            if (auto renderer = node->drawable()) {
                renderer->draw();
            }
        });
    }

    if (_font) {
        _font->drawText(g_text.c_str(), 0.f, 0.f);
    }
}

void Gltf2Test::keyEvent(int key, int scancode, int action, int mods) {
    if (key == KEY_ESCAPE && action == PRESS) {
        MainMenu::gotoMainMenu();
    }
    if (action == PRESS) {
        switch (key) {
		case KEY_UP:
			_scene->childAt(0)->translateY(0.1f);
			break;
		case KEY_DOWN:
			_scene->childAt(0)->translateY(-0.1f);
			break;
        case KEY_F:
            focus();
            break;
        case KEY_N:
            loadNextPath();
            break;
        case KEY_P:
            loadPrevPath();
            break;
        case KEY_F4:
            if (mods & MOD_CTRL) {
                MainMenu::gotoMainMenu();
            }
            break;
        default:
            break;
        }
    }
}

void Gltf2Test::mouseEvent(double xpos, double ypos) {
    if (_moveCamera && app()->getMouseButton(LEFT_MOUSE)) {
        _orbitCamera.move(static_cast<float>(xpos), static_cast<float>(ypos));
    }
}

void Gltf2Test::mouseButtonEvent(int button, int action, int mods) {
    if (action == PRESS) {
        if (button == LEFT_MOUSE) {
            double x, y;
            app()->cursorPosition(&x, &y);
            _orbitCamera.start(static_cast<float>(x), static_cast<float>(y));
            _moveCamera = true;
        }
        else if (button == FORWARD_MOUSE) {
            loadNextPath();
        }
        else if (button == BACK_MOUSE) {
            loadPrevPath();
        }
    }
}

void Gltf2Test::scrollEvent(double xoffset, double yoffset) {
    float offset = static_cast<float>(yoffset) * _zoomMag * -0.5f;
    offset = std::min(5.0f, offset);
    offset = std::max(-5.0f, offset);
    _orbitCamera.zoomOut(offset);
}

void Gltf2Test::dropEvent(int count, const char** paths) {
    // Load the first GLTF file found. Ignore directories.
    for (int i = 0; i < count; ++i) {
        const char* path = paths[i];
        if (endsWith(path, ".gltf") || endsWith(path, ".glb")) {
            std::clog << "Load: " << path << std::endl;
            loadSceneFromFile(paths[i]);
            return;
        }
    }
}

void Gltf2Test::focus() {
    // account for near plane
    float zoom = _zoomMag + 0.2f;
    _orbitCamera.setZoom(zoom);
}

void Gltf2Test::loadSceneFromFile(const char* path) {
    if (path == nullptr || *path == '\0') {
        std::clog << "Invalid path" << std::endl;
        return;
    }
    _orbitCamera.detach();
    _scene.reset();

    GLTF2Loader loader;
    loader.setCameraAspectRatio(app()->aspectRatio());
    _scene = loader.loadSceneFromFile(path);

    if (_scene) {
        calcBoundingBox(_scene.get());
        _orbitCamera.attach(_scene.get());
        _scene->addNode(_compass.node());
    }
    g_text.assign(path);
}

void Gltf2Test::loadNextPath() {
    loadSceneFromFile(nextPath());
}

void Gltf2Test::loadPrevPath() {
    loadSceneFromFile(prevPath());
}

void Gltf2Test::calcBoundingBox(Scene* scene) {
    _box = BoundingBox();
    if (scene) {
        for (size_t i = 0; i < scene->childCount(); ++i) {
            const auto& childBox = scene->childAt(i)->boundingBox();
            if (!childBox.empty()) {
                if (_box.empty()) {
                    _box = childBox;
                }
                else {
                    _box.merge(childBox);
                }
            }
        }
    }
    auto v1 = glm::abs(_box.max);
    auto v2 = glm::abs(_box.min);
    auto v = vec3(std::max(v1.x, v2.x), std::max(v1.y, v2.y), std::max(v1.z, v2.z));
    _zoomMag = std::sqrt(v.x*v.x + v.y*v.y + v.z*v.z);

    auto prim = createWireframeBoxPrimitive(_box);
    auto material = createBoxMaterial();
    if (prim && material) {
        prim->setMaterial(material);
        auto node = Node::create("box");
        node->addComponent(MeshRenderer::create(Mesh::create(prim)));
        scene->addNode(node);
    }
}

shared_ptr<Material> createBoxMaterial() {
    static constexpr char* VERT_PATH = "res/shaders/lamp.vert";
    static constexpr char* FRAG_PATH = "res/shaders/lamp.frag";
    auto effect = Effect::createFromFile(VERT_PATH, FRAG_PATH);
    if (effect) {
        auto tech = Technique::create(effect);
        tech->setAttribute("a_position", AttributeSemantic::POSITION);
        tech->setSemanticUniform("mvp", MaterialParameter::Semantic::MODELVIEWPROJECTION);
        auto f = [](Effect& effect, const Uniform* uniform) {effect.setValue(uniform, vec3(1, 0, 0)); };
        tech->setUniform("color", MaterialParameter::create("color", f));

        auto& state = tech->renderState();
        state.setDepthTest(true);
        state.setCulling(true);

        return Material::create(tech);
    }
    return nullptr;
}
}
}


text:
/**
 * Account management module - evidence for provisioning.
 *
 * @author Radek Tomiška
 *
 */
package eu.bcvsolutions.idm.acc;


text:
import argparse
import os
import sys
import zipfile

REPOSITORY_ROOT = os.path.abspath(
    os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))

sys.path.insert(0, os.path.join(REPOSITORY_ROOT, 'build/android/gyp'))
from util import build_utils  # pylint: disable=wrong-import-position

JAVA_PACKAGE_PREFIX = 'org/chromium/'

def main():
  parser = argparse.ArgumentParser()
  build_utils.AddDepfileOption(parser)
  parser.add_argument(
      '--excluded-classes',
      help='A list of .class file patterns to exclude from the jar.')
  parser.add_argument(
      '--src-search-dirs',
      action='append',
      help='A list of directories that should be searched'
      ' for the source files.')
  parser.add_argument(
      '--src-files', action='append', help='A list of source files to jar.')
  parser.add_argument(
      '--src-jars',
      action='append',
      help='A list of source jars to include in addition to source files.')
  parser.add_argument(
      '--src-list-files',
      action='append',
      help='A list of files that contain a list of sources,'
      ' e.g. a list of \'.sources\' files generated by GN.')
  parser.add_argument('--jar-path', help='Jar output path.', required=True)

  options = parser.parse_args()

  src_jars = []
  for gn_list in options.src_jars:
    src_jars.extend(build_utils.ParseGnList(gn_list))

  src_search_dirs = []
  for gn_src_search_dirs in options.src_search_dirs:
    src_search_dirs.extend(build_utils.ParseGnList(gn_src_search_dirs))

  src_list_files = []
  if options.src_list_files:
    for gn_src_list_file in options.src_list_files:
      src_list_files.extend(build_utils.ParseGnList(gn_src_list_file))

  src_files = []
  for gn_src_files in options.src_files:
    src_files.extend(build_utils.ParseGnList(gn_src_files))

  # Add files from --source_list_files
  for src_list_file in src_list_files:
    with open(src_list_file, 'r') as f:
      src_files.extend(f.read().splitlines())

  # Preprocess source files by removing any prefix that comes before
  # the Java package name.
  for i, s in enumerate(src_files):
    prefix_position = s.find(JAVA_PACKAGE_PREFIX)
    if prefix_position != -1:
      src_files[i] = s[prefix_position:]

  excluded_classes = []
  if options.excluded_classes:
    classes = build_utils.ParseGnList(options.excluded_classes)
    excluded_classes.extend(f.replace('.class', '.java') for f in classes)

  predicate = None
  if excluded_classes:
    predicate = lambda f: not build_utils.MatchesGlob(f, excluded_classes)

  # Create a dictionary that maps every source directory
  # to source files that it contains.
  dir_to_files_map = {}
  # Initialize the map.
  for src_search_dir in src_search_dirs:
    dir_to_files_map[src_search_dir] = []
  # Fill the map.
  for src_file in src_files:
    number_of_file_instances = 0
    for src_search_dir in src_search_dirs:
      target_path = os.path.join(src_search_dir, src_file)
      if os.path.isfile(target_path):
        number_of_file_instances += 1
        if not predicate or predicate(src_file):
          dir_to_files_map[src_search_dir].append(target_path)
    if (number_of_file_instances > 1):
      raise Exception(
          'There is more than one instance of file %s in %s'
          % (src_file, src_search_dirs))
    if (number_of_file_instances < 1):
      raise Exception(
          'Unable to find file %s in %s' % (src_file, src_search_dirs))

  # Jar the sources from every source search directory.
  with build_utils.AtomicOutput(options.jar_path) as o, \
      zipfile.ZipFile(o, 'w', zipfile.ZIP_DEFLATED) as z:
    for src_search_dir in src_search_dirs:
      subpaths = dir_to_files_map[src_search_dir]
      if subpaths:
        build_utils.DoZip(subpaths, z, base_dir=src_search_dir)
      else:
        raise Exception(
            'Directory %s does not contain any files and can be'
            ' removed from the list of directories to search' % src_search_dir)

    # Jar additional src jars
    if src_jars:
      build_utils.MergeZips(z, src_jars, compress=True)

  if options.depfile:
    deps = []
    for sources in dir_to_files_map.itervalues():
      deps.extend(sources)
    # Srcjar deps already captured in GN rules (no need to list them here).
    build_utils.WriteDepfile(options.depfile, options.jar_path, deps)

if __name__ == '__main__':
  sys.exit(main())


text:
<?php

use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Message\Response;
use GuzzleHttp\Subscriber\Mock;
use paslandau\GuzzleRotatingProxySubscriber\Exceptions\NoProxiesLeftException;
use paslandau\GuzzleRotatingProxySubscriber\Interval\RandomCounterInterval;
use paslandau\GuzzleRotatingProxySubscriber\Proxy\Identity;
use paslandau\GuzzleRotatingProxySubscriber\Proxy\RotatingIdentityProxy;
use paslandau\GuzzleRotatingProxySubscriber\Proxy\RotatingProxy;
use paslandau\GuzzleRotatingProxySubscriber\ProxyRotator;
use paslandau\GuzzleRotatingProxySubscriber\Random\SystemRandomizer;
use paslandau\GuzzleRotatingProxySubscriber\RotatingProxySubscriber;

require_once __DIR__ . '/bootstrap.php';

$userAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0"; // common user agent string for firefox
$defaultRequestHeaders = ["Accept-Language" => "de,en"]; // add a preferred language to each of our requests
$cookieSession = new CookieJar(); // enable cookies for this identity

$identity = new Identity($userAgent,$defaultRequestHeaders,$cookieSession);
$identities = [$identity];
$proxy1 = new RotatingIdentityProxy($identities, "[PROXY 1]");

$userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"; // common user agent string for chrome
$defaultRequestHeaders = ["Accept-Language" => "de"]; // add a preferred language to each of our requests
$cookieSession = null; // disable cookies for this identity

$identity1 = new Identity($userAgent,$defaultRequestHeaders,$cookieSession);

$userAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)"; // common user agent string for Internet Explorer
$defaultRequestHeaders = ["Pragma" => "no-cache"]; // add a no-cache directive to each request
$cookieSession = new CookieJar(); // enable cookies for this identity

$identity2 = new Identity($userAgent,$defaultRequestHeaders,$cookieSession);

$identities = [$identity1,$identity2];
$systemRandomizer = new SystemRandomizer();

// switch identities randomly after 2 to 5 requests
$minRequests = 2;
$maxRequests = 5;
$counter = new RandomCounterInterval($minRequests,$maxRequests);
$proxy2 = new RotatingIdentityProxy($identities, "[PROXY 2]",$systemRandomizer,$counter);

$proxies = [$proxy1,$proxy2];
$rotator = new ProxyRotator($proxies);
$sub = new RotatingProxySubscriber($rotator);
$client = new Client();
$client->getEmitter()->attach($sub);
// lets prepare 20 responses
$num = 20;
$responses = [];
for($i = 0; $i < $num; $i++){
    $responses[] = new Response(200);
}
$mock = new Mock($responses);
$client->getEmitter()->attach($mock);

// lets execute 20 requests
$requests = [];
$url = "http://localhost/";
for($i = 0; $i < $num; $i++){
    $requests[] = $client->createRequest("GET",$url);
}

for ($i = 0; $i < $num; $i++) {
    $request =  $client->createRequest("GET",$url);
    try {
        $response = $client->send($request);
        echo "Success with " . $request->getConfig()->get("proxy") . " using user agent " . $request->getHeader("user-agent"). " on $i. request\n";
    } catch (Exception $e) {
        if ($e->getPrevious() instanceof NoProxiesLeftException) {
            echo "All proxies are blocked, terminating...\n";
            break;
        }
        echo "Failed with " . $request->getConfig()->get("proxy") . " on $i. request: " . $e->getMessage() . "\n";
    }
}

/** @var \paslandau\GuzzleRotatingProxySubscriber\Proxy\RotatingProxy $proxy */
echo "\nProxy usage:\n";
foreach($proxies as $proxy){
    echo $proxy->getProxyString()."\t made ".$proxy->getTotalRequests()." requests in total\n";
}

/** Example ouput
Success with [PROXY 2] using user agent Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0) on 0. request
Success with [PROXY 2] using user agent Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0) on 1. request
Success with [PROXY 2] using user agent Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0) on 2. request
Success with [PROXY 1] using user agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0 on 3. request
Success with [PROXY 1] using user agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0 on 4. request
Success with [PROXY 2] using user agent Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0) on 5. request
Success with [PROXY 2] using user agent Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0) on 6. request
Success with [PROXY 2] using user agent Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36 on 7. request
Success with [PROXY 2] using user agent Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36 on 8. request
Success with [PROXY 1] using user agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0 on 9. request
Success with [PROXY 1] using user agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0 on 10. request
Success with [PROXY 2] using user agent Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36 on 11. request
Success with [PROXY 1] using user agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0 on 12. request
Success with [PROXY 1] using user agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0 on 13. request
Success with [PROXY 1] using user agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0 on 14. request
Success with [PROXY 1] using user agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0 on 15. request
Success with [PROXY 2] using user agent Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36 on 16. request
Success with [PROXY 1] using user agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0 on 17. request
Success with [PROXY 1] using user agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0 on 18. request
Success with [PROXY 2] using user agent Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36 on 19. request
[PROXY 1]	 made 10 requests in total
[PROXY 2]	 made 10 requests in total
 */


text:
This module includes a few examples of how to use jimu Mirror's Sandbox features.

Preview with Mirror that includes Java hot-swapping support. For more information see [this blog post](http://jimulabs.com/2015/01/building-android-animations-mirror-sandbox-piecewise/).


text:
@implementation ABI42_0_0AIRMapCalloutSubviewManager
ABI42_0_0RCT_EXPORT_MODULE()

- (UIView *)view
{
  ABI42_0_0AIRMapCalloutSubview *calloutSubview = [ABI42_0_0AIRMapCalloutSubview new];
  return calloutSubview;
}

ABI42_0_0RCT_EXPORT_VIEW_PROPERTY(onPress, ABI42_0_0RCTBubblingEventBlock)

@end


text:
package org.dcm4chee.web.common.secure;

import java.io.Serializable;

import org.apache.wicket.MetaDataKey;

/**
 * @author Robert David <robert.david@agfa.com>
 * @version $Revision$ $Date$
 * @since 23.09.2010
 */
public class ComponentHiveKey extends MetaDataKey<Serializable> {

    private static final long serialVersionUID = 1L;

    public ComponentHiveKey(Class<?> type) {
        super();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class macaca.client.common.ElementSelector</title>
<meta name="date" content="2016-11-08">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
macaca.client.common.ElementSelector

Packages that use ElementSelector

Package
Description

macaca.client

Uses of ElementSelector in macaca.client

Methods in macaca.client that return ElementSelector

Modifier and Type
Method and Description

ElementSelector
MacacaClient.elementsByClassName(java.lang.String className)

Search for multiple elements on the page, starting from the document
 root.

ElementSelector
MacacaClient.elementsByCss(java.lang.String css)

Search for multiple elements on the page, starting from the document
 root.

ElementSelector
MacacaClient.elementsById(java.lang.String elementId)

Search for multiple elements on the page, starting from the document
 root.

ElementSelector
MacacaClient.elementsByLinkText(java.lang.String linkText)

Search for multiple elements on the page, starting from the document
 root.

ElementSelector
MacacaClient.elementsByName(java.lang.String name)

Search for multiple elements on the page, starting from the document
 root.

ElementSelector
MacacaClient.elementsByPartialLinkText(java.lang.String partialLinkText)

Search for multiple elements on the page, starting from the document
 root.

ElementSelector
MacacaClient.elementsByTagName(java.lang.String tagName)

Search for multiple elements on the page, starting from the document
 root.

ElementSelector
MacacaClient.elementsByXPath(java.lang.String xpath)

Search for multiple elements on the page, starting from the document
 root.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes