text:
=========
CHANGELOG
=========

1.15.1
======

* bugfix:packaging:Fix setup.py dependencies where the wheel package was not being installed (#1435)

1.15.0
======

* feature:blueprints:Mark blueprints as an accepted API (#1250)
* feature:package:Add ability to generate and merge yaml CloudFormation templates (#1425)
* enhancement:terraform:Allow generated terraform template to be used as a terraform module (#1300)
* feature:logs:Add support for tailing logs (#4).

1.14.1
======

* enhancement:pip:Update pip version range to 20.1.

1.14.0
======

* bugfix:packaging:Fix pandas packaging regression (#1398)
* feature:CLI:Add ``dev plan/appgraph`` commands (#1396)
* enhancement:SQS:Validate queue name is used and not queue URL or ARN (#1388)

1.13.1
======

* enhancement:local:Add support for multiValueHeaders in local mode (#1381).
* bugfix:local:Make ``current_request`` thread safe in local mode (#759)
* enhancement:local:Add support for cognito in local mode (#1377).
* bugfix:packaging:Fix terraform generation when injecting custom domains (#1237)
* enhancement:packaging:Ensure repeatable zip file generation (#1114).
* bugfix:CORS:Fix CORS request when returning compressed binary types (#1336)

1.13.0
======

* bugfix:logs:Fix error for ``chalice logs`` when a Lambda function
  has not been invoked
  (`#1252 <https://github.com/aws/chalice/issues/1252>`__)
* feature:CORS:Add global CORS configuration
  (`#70 <https://github.com/aws/chalice/pull/70>`__)
* bugfix:packaging:Fix packaging simplejson
  (`#1304 <https://github.com/aws/chalice/pull/1304>`__)
* feature:python:Add support for Python 3.8
  (`#1315 <https://github.com/aws/chalice/pull/1315>`__)
* feature:authorizer:Add support for invocation role in custom authorizer
  (`#1303 <https://github.com/aws/chalice/pull/1303>`__)
* bugfix:packaging:Fix packaging on case-sensitive filesystems
  (`#1356 <https://github.com/aws/chalice/pull/1356>`__)

1.12.0
======

* feature:CLI:Add ``generate-models`` command
  (`#1245 <https://github.com/aws/chalice/pull/1245>`__)
* enhancement:websocket:Add ``close`` and ``info`` commands to websocket api
  (`#1259 <https://github.com/aws/chalice/pull/1259>`__)
* enhancement:dependencies:Bump upper bound on PIP to ``<19.4``
  (`#1273 <https://github.com/aws/chalice/pull/1273>`__)
  (`#1272 <https://github.com/aws/chalice/pull/1272>`__)

1.11.1
======

* bugfix:blueprint:Fix mouting blueprints with root routes
  (`#1230 <https://github.com/aws/chalice/pull/1230>`__)
* feature:rest-api:Add support for multi-value headers responses
  (`#1205 <https://github.com/aws/chalice/pull/1205>`__)

1.11.0
======

* feature:config:Add support for stage independent lambda configuration
  (`#1162 <https://github.com/aws/chalice/pull/1162>`__)
* feature:event-source:Add support for subscribing to CloudWatch Events
  (`#1126 <https://github.com/aws/chalice/pull/1126>`__)
* feature:event-source:Add a ``description`` argument to CloudWatch schedule events
  (`#1155 <https://github.com/aws/chalice/pull/1155>`__)
* bugfix:rest-api:Fix deployment of API Gateway resource policies
  (`#1220 <https://github.com/aws/chalice/pull/1220>`__)

1.10.0
======

* feature:websocket:Add experimental support for websockets
  (`#1017 <https://github.com/aws/chalice/issues/1017>`__)
* feature:rest-api:API Gateway Endpoint Type Configuration
  (`#1160 <https://github.com/aws/chalice/pull/1160>`__)
* feature:rest-api:API Gateway Resource Policy Configuration
  (`#1160 <https://github.com/aws/chalice/pull/1160>`__)
* feature:packaging:Add --merge-template option to package command
  (`#1195 <https://github.com/aws/chalice/pull/1195>`__)
* feature:packaging:Add support for packaging via terraform
  (`#1129 <https://github.com/aws/chalice/pull/1129>`__)

1.9.1
=====

* enhancement:rest-api:Make MultiDict mutable
  (`#1158 <https://github.com/aws/chalice/issues/1158>`__)

1.9.0
=====

* enhancement:dependencies:Update PIP to support up to 19.1.x
  (`#1104 <https://github.com/aws/chalice/issues/1104>`__)
* bugfix:rest-api:Fix handling of more complex Accept headers for binary
  content types
  (`#1078 <https://github.com/aws/chalice/issues/1078>`__)
* enhancement:rest-api:Raise TypeError when trying to serialize an unserializable
  type
  (`#1100 <https://github.com/aws/chalice/issues/1100>`__)
* enhancement:policy:Update ``policies.json`` file
  (`#1110 <https://github.com/aws/chalice/issues/1110>`__)
* feature:rest-api:Support repeating values in the query string
  (`#1131 <https://github.com/aws/chalice/issues/1131>`__)
* feature:packaging:Add layer support to chalice package
  (`#1130 <https://github.com/aws/chalice/issues/1130>`__)
* bugfix:rest-api:Fix bug with route ``name`` kwarg raising a ``TypeError``
  (`#1112 <https://github.com/aws/chalice/issues/1112>`__)
* enhancement:logging:Change exceptions to always be logged at the ERROR level
  (`#969 <https://github.com/aws/chalice/issues/969>`__)
* bugfix:CLI:Fix bug handling exceptions during ``chalice invoke`` on
  Python 3.7
  (`#1139 <https://github.com/aws/chalice/issues/1139>`__)
* bugfix:rest-api:Add support for API Gateway compression
  (`#672 <https://github.com/aws/chalice/issues/672>`__)
* enhancement:packaging:Add support for both relative and absolute paths for
  ``--package-dir``
  (`#940 <https://github.com/aws/chalice/issues/940>`__)

1.8.0
=====

* bugfix:packaging:Fall back to pure python version of yaml parser
  when unable to compile C bindings for PyYAML
  (`#1074 <https://github.com/aws/chalice/issues/1074>`__)
* feature:packaging:Add support for Lambda layers.
  (`#1001 <https://github.com/aws/chalice/issues/1001>`__)

1.7.0
=====

* bugfix:packaging:Fix packaging multiple local directories as dependencies
  (`#1047 <https://github.com/aws/chalice/pull/1047>`__)
* feature:event-source:Add support for passing SNS ARNs to ``on_sns_message``
  (`#1048 <https://github.com/aws/chalice/pull/1048>`__)
* feature:blueprint:Add support for Blueprints
  (`#1023 <https://github.com/aws/chalice/pull/1023>`__)
* feature:config:Add support for opting-in to experimental features
  (`#1053 <https://github.com/aws/chalice/pull/1053>`__)
* feature:event-source:Provide Lambda context in event object
  (`#856 <https://github.com/aws/chalice/issues/856>`__)

1.6.2
=====

* enhancement:dependencies:Add support for pip 18.2
  (`#991 <https://github.com/aws/chalice/pull/991>`__)
* enhancement:logging:Add more detailed debug logs to the packager.
  (`#934 <https://github.com/aws/chalice/pull/934>`__)
* feature:python:Add support for python3.7
  (`#992 <https://github.com/aws/chalice/pull/992>`__)
* feature:rest-api:Support bytes for the application/json binary type
  (`#988 <https://github.com/aws/chalice/issues/988>`__)
* enhancement:rest-api:Use more compact JSON representation by default for dicts
  (`#958 <https://github.com/aws/chalice/pull/958>`__)
* enhancement:logging:Log internal exceptions as errors
  (`#254 <https://github.com/aws/chalice/issues/254>`__)
* feature:rest-api:Generate swagger documentation from docstrings
  (`#574 <https://github.com/aws/chalice/issues/574>`__)

1.6.1
=====

* bugfix:local:Fix local mode issue with unicode responses and Content-Length
  (`#910 <https://github.com/aws/chalice/pull/910>`__)
* enhancement:dev:Fix issue with ``requirements-dev.txt`` not setting up a working
  dev environment
  (`#920 <https://github.com/aws/chalice/pull/920>`__)
* enhancement:dependencies:Add support for pip 18
  (`#910 <https://github.com/aws/chalice/pull/908>`__)

1.6.0
=====

* feature:CLI:Add ``chalice invoke`` command
  (`#900 <https://github.com/aws/chalice/issues/900>`__)

1.5.0
=====

* feature:policy:Add support for S3 upload_file/download_file in
  policy generator
  (`#889 <https://github.com/aws/chalice/pull/889>`__)

1.4.0
=====

* enhancement:CI-CD:Add support for generating python 3.6 pipelines
  (`#858 <https://github.com/aws/chalice/pull/858>`__)
* feature:event-source:Add support for connecting lambda functions to S3 events
  (`#855 <https://github.com/aws/chalice/issues/855>`__)
* feature:event-source:Add support for connecting lambda functions to SNS message
  (`#488 <https://github.com/aws/chalice/issues/488>`__)
* enhancement:local:Make ``watchdog`` an optional dependency and add a built in
  ``stat()`` based file poller
  (`#867 <https://github.com/aws/chalice/issues/867>`__)
* feature:event-source:Add support for connecting lambda functions to an SQS queue
  (`#884 <https://github.com/aws/chalice/issues/884>`__)

1.3.0
=====

* feature:config:Add support for Lambdas in a VPC
  (`#413 <https://github.com/aws/chalice/issues/413>`__,
  `#837 <https://github.com/aws/chalice/pull/837>`__,
  `#673 <https://github.com/aws/chalice/pull/673>`__)
* feature:packaging:Add support for packaging local directories
  (`#653 <https://github.com/aws/chalice/pull/653>`__)
* enhancement:local:Add support for automatically reloading the local
  dev server when files are modified
  (`#316 <https://github.com/aws/chalice/issues/316>`__,
  `#846 <https://github.com/aws/chalice/pull/846>`__,
  `#706 <https://github.com/aws/chalice/pull/706>`__)
* enhancement:logging:Add support for viewing cloudwatch logs of all
  lambda functions
  (`#841 <https://github.com/aws/chalice/issues/841>`__,
  `#849 <https://github.com/aws/chalice/pull/849>`__)

1.2.3
=====

* enhancement:dependency:Add support for pip 10
  (`#808 <https://github.com/aws/chalice/issues/808>`__)
* enhancement:policy:Update ``policies.json`` file
  (`#817 <https://github.com/aws/chalice/issues/817>`__)

1.2.2
=====

* bugfix:packaging:Fix package command not correctly setting environment variables
  (`#795 <https://github.com/aws/chalice/issues/795>`__)

1.2.1
=====

* enhancement:rest-api:Add CORS headers to error response
  (`#715 <https://github.com/aws/chalice/pull/715>`__)
* bugfix:local:Fix parsing empty query strings in local mode
  (`#767 <https://github.com/aws/chalice/pull/767>`__)
* bugfix:packaging:Fix regression in ``chalice package`` when using role arns
  (`#793 <https://github.com/aws/chalice/issues/793>`__)

1.2.0
=====

This release features a rewrite of the core deployment
code used in Chalice.  This is a backwards compatible change
for users, but you may see changes to the autogenerated
files Chalice creates.
Please read the `upgrade notes for 1.2.0
<http://aws.github.io/chalice/upgrading.html#v1-2-0>`__
for more detailed information about upgrading to this release.

* enhancement:rest-api:Print out full stack trace when an error occurs
  (`#711 <https://github.com/aws/chalice/issues/711>`__)
* enhancement:rest-api:Add ``image/jpeg`` as a default binary content type
  (`#707 <https://github.com/aws/chalice/pull/707>`__)
* feature:event-source:Add support for AWS Lambda only projects
  (`#162 <https://github.com/aws/chalice/issues/162>`__,
  `#640 <https://github.com/aws/chalice/issues/640>`__)
* bugfix:policy:Fix inconsistent IAM role generation with pure lambdas
  (`#685 <https://github.com/aws/chalice/issues/685>`__)
* enhancement:deployment:Rewrite Chalice deployer to more easily support additional AWS resources
  (`#604 <https://github.com/aws/chalice/issues/604>`__)
* feature:packaging:Update the ``chalice package`` command to support
  pure lambda functions and scheduled events.
  (`#772 <https://github.com/aws/chalice/issues/772>`__)
* bugfix:packaging:Fix packager edge case normalizing sdist names
  (`#778 <https://github.com/aws/chalice/issues/778>`__)
* bugfix:packaging:Fix SQLAlchemy packaging
  (`#778 <https://github.com/aws/chalice/issues/778>`__)
* bugfix:packaging:Fix packaging abi3, wheels this fixes cryptography 2.2.x packaging
  (`#764 <https://github.com/aws/chalice/issues/764>`__)

1.1.1
=====

* feature:CLI:Add ``--connection-timeout`` to the ``deploy`` command
  (`#344 <https://github.com/aws/chalice/issues/344>`__)
* bugfix:policy:Fix IAM role creation issue
  (`#565 <https://github.com/aws/chalice/issues/565>`__)
* bugfix:local:Fix `chalice local` handling of browser requests
  (`#565 <https://github.com/aws/chalice/issues/628>`__)
* enhancement:policy:Support async/await syntax in automatic policy generation
  (`#565 <https://github.com/aws/chalice/issues/646>`__)
* enhancement:packaging:Support additional PyPi package formats (.tar.bz2)
  (`#720 <https://github.com/aws/chalice/issues/720>`__)

1.1.0
=====

* enhancement:rest-api:Default to ``None`` in local mode when no query parameters
  are provided
  (`#593 <https://github.com/aws/chalice/issues/593>`__)
* enhancement:local:Add support for binding a custom address for local dev server
  (`#596 <https://github.com/aws/chalice/issues/596>`__)
* bugfix:rest-api:Fix local mode handling of routes with trailing slashes
  (`#582 <https://github.com/aws/chalice/issues/582>`__)
* bugfix:config:Scale ``lambda_timeout`` parameter correctly in local mode
  (`#579 <https://github.com/aws/chalice/pull/579>`__)
* feature:CI-CD:Add ``--codebuild-image`` to the ``generate-pipeline`` command
  (`#609 <https://github.com/aws/chalice/issues/609>`__)
* feature:CI-CD:Add ``--source`` and ``--buildspec-file`` to the
  ``generate-pipeline`` command
  (`#609 <https://github.com/aws/chalice/issues/619>`__)

1.0.4
=====

* bugfix:packaging:Fix issue deploying some packages in Windows with utf-8 characters
  (`#560 <https://github.com/aws/chalice/pull/560>`__)
* feature:packaging:Add support for custom authorizers with ``chalice package``
  (`#580 <https://github.com/aws/chalice/pull/580>`__)

1.0.3
=====

* bugfix:packaging:Fix issue with some packages with `-` or `.` in their distribution name
  (`#555 <https://github.com/aws/chalice/pull/555>`__)
* bugfix:rest-api:Fix issue where chalice local returned a 403 for successful OPTIONS requests
  (`#554 <https://github.com/aws/chalice/pull/554>`__)
* bugfix:local:Fix issue with chalice local mode causing http clients to hang on responses
  with no body
  (`#525 <https://github.com/aws/chalice/issues/525>`__)
* enhancement:local:Add ``--stage`` parameter to ``chalice local``
  (`#545 <https://github.com/aws/chalice/issues/545>`__)
* bugfix:policy:Fix issue with analyzer that followed recursive functions infinitely
  (`#531 <https://github.com/aws/chalice/issues/531>`__)

1.0.2
=====

* bugfix:rest-api:Fix issue where requestParameters were not being mapped
  correctly resulting in invalid generated javascript SDKs
  (`#498 <https://github.com/aws/chalice/issues/498>`__)
* bugfix:rest-api:Fix issue where ``api_gateway_stage`` was being
  ignored when set in the ``config.json`` file
  (`#495 <https://github.com/aws/chalice/issues/495>`__)
* bugfix:rest-api:Fix bug where ``raw_body`` would raise an exception if no HTTP
  body was provided
  (`#503 <https://github.com/aws/chalice/issues/503>`__)
* bugfix:CLI:Fix bug where exit codes were not properly being propagated during packaging
  (`#500 <https://github.com/aws/chalice/issues/500>`__)
* feature:local:Add support for Builtin Authorizers in local mode
  (`#404 <https://github.com/aws/chalice/issues/404>`__)
* bugfix:packaging:Fix environment variables being passed to subprocess while packaging
  (`#501 <https://github.com/aws/chalice/issues/501>`__)
* enhancement:rest-api:Allow view to require API keys as well as authorization
  (`#473 <https://github.com/aws/chalice/pull/473/>`__)

1.0.1
=====

* bugfix:packaging:Only use alphanumeric characters for event names in SAM template
  (`#450 <https://github.com/aws/chalice/issues/450>`__)
* enhancement:config:Print useful error message when config.json is invalid
  (`#458 <https://github.com/aws/chalice/pull/458>`__)
* bugfix:rest-api:Fix api gateway stage being set incorrectly in non-default chalice stage
  (`#$70 <https://github.com/aws/chalice/issues/470>`__)

1.0.0
=====

* enhancement:rest-api:Change default API Gateway stage name to ``api``
  (`#431 <https://github.com/awslabs/chalice/pull/431>`__)
* enhancement:local:Add support for ``CORSConfig`` in ``chalice local``
  (`#436 <https://github.com/awslabs/chalice/issues/436>`__)
* enhancement:logging:Propagate ``DEBUG`` log level when setting ``app.debug``
  (`#386 <https://github.com/awslabs/chalice/issues/386>`__)
* feature:rest-api:Add support for wildcard routes and HTTP methods in ``AuthResponse``
  (`#403 <https://github.com/awslabs/chalice/issues/403>`__)
* bugfix:policy:Fix bug when analyzing list comprehensions
  (`#412 <https://github.com/awslabs/chalice/issues/412>`__)
* enhancement:local:Update ``chalice local`` to use HTTP 1.1
  (`#448 <https://github.com/awslabs/chalice/pull/448>`__)

1.0.0b2
=======

Please read the `upgrade notes for 1.0.0b2
<http://aws.github.io/chalice/upgrading.html#v1-0-0b2>`__
for more detailed information about upgrading to this release.

Note: to install this beta version of chalice you must specify
``pip install 'chalice>=1.0.0b2,<2.0.0'`` or
use the ``--pre`` flag for pip: ``pip install --pre chalice``.

* enhancement:local:Set env vars from config in ``chalice local``
  (`#396 <https://github.com/awslabs/chalice/issues/396>`__)
* bugfix:packaging:Fix edge case when building packages with optional c extensions
  (`#421 <https://github.com/awslabs/chalice/pull/421>`__)
* enhancement:policy:Remove legacy ``policy.json`` file support. Policy files must
  use the stage name, e.g. ``policy-dev.json``
  (`#430 <https://github.com/awslabs/chalice/pull/540>`__)
* bugfix:deployment:Fix issue where IAM role policies were updated twice on redeploys
  (`#428 <https://github.com/awslabs/chalice/pull/428>`__)
* enhancement:rest-api:Validate route path is not an empty string
  (`#432 <https://github.com/awslabs/chalice/pull/432>`__)
* enhancement:rest-api:Change route code to invoke view function with kwargs instead of
  positional args
  (`#429 <https://github.com/awslabs/chalice/issues/429>`__)

1.0.0b1
=======

Please read the `upgrade notes for 1.0.0b1
<http://aws.github.io/chalice/upgrading.html#v1-0-0b1>`__
for more detailed information about upgrading to this release.

Note: to install this beta version of chalice you must specify
``pip install 'chalice>=1.0.0b1,<2.0.0'`` or
use the ``--pre`` flag for pip: ``pip install --pre chalice``.

* bugfix:rest-api:Fix unicode responses being quoted in python 2.7
  (`#262 <https://github.com/awslabs/chalice/issues/262>`__)
* feature:event-source:Add support for scheduled events
  (`#390 <https://github.com/awslabs/chalice/issues/390>`__)
* feature:event-source:Add support for pure lambda functions
  (`#390 <https://github.com/awslabs/chalice/issues/400>`__)
* feature:packaging:Add support for wheel packaging.
  (`#249 <https://github.com/awslabs/chalice/issues/249>`__)

0.10.1
======

* bugfix:deployment:Fix deployment issue for projects deployed with versions
  prior to 0.10.0
  (`#387 <https://github.com/awslabs/chalice/issues/387>`__)
* bugfix:policy:Fix crash in analyzer when encountering genexprs and listcomps
  (`#263 <https://github.com/awslabs/chalice/issues/263>`__)

0.10.0
======

* bugfix:deployment:Fix issue where provided ``iam_role_arn`` was not respected on
  redeployments of chalice applications and in the CloudFormation template
  generated by ``chalice package``
  (`#339 <https://github.com/awslabs/chalice/issues/339>`__)
* bugfix:config:Fix ``autogen_policy`` in config being ignored
  (`#367 <https://github.com/awslabs/chalice/pull/367>`__)
* feature:rest-api:Add support for view functions that share the same view url but
  differ by HTTP method
  (`#81 <https://github.com/awslabs/chalice/issues/81>`__)
* enhancement:deployment:Improve deployment error messages for deployment packages that are
  too large
  (`#246 <https://github.com/awslabs/chalice/issues/246>`__,
  `#330 <https://github.com/awslabs/chalice/issues/330>`__,
  `#380 <https://github.com/awslabs/chalice/pull/380>`__)
* feature:rest-api:Add support for built-in authorizers
  (`#356 <https://github.com/awslabs/chalice/issues/356>`__)

0.9.0
=====

* feature:rest-api:Add support for ``IAM`` authorizer
  (`#334 <https://github.com/awslabs/chalice/pull/334>`__)
* feature:config:Add support for configuring ``lambda_timeout``, ``lambda_memory_size``,
  and ``tags`` in your AWS Lambda function
  (`#347 <https://github.com/awslabs/chalice/issues/347>`__)
* bugfix:packaging:Fix vendor directory contents not being importable locally
  (`#350 <https://github.com/awslabs/chalice/pull/350>`__)
* feature:rest-api:Add support for binary payloads
  (`#348 <https://github.com/awslabs/chalice/issues/348>`__)

0.8.2
=====

* bugfix:CLI:Fix issue where ``--api-gateway-stage`` was being
  ignored (`#325 <https://github.com/awslabs/chalice/pull/325>`__)
* feature:CLI:Add ``chalice delete`` command
  (`#40 <https://github.com/awslabs/chalice/issues/40>`__)

0.8.1
=====

* enhancement:deployment:Alway overwrite existing API Gateway Rest API on updates
  (`#305 <https://github.com/awslabs/chalice/issues/305>`__)
* enhancement:CORS:Added more granular support for CORS
  (`#311 <https://github.com/awslabs/chalice/pull/311>`__)
* bugfix:local:Fix duplicate content type header in local model
  (`#311 <https://github.com/awslabs/chalice/issues/310>`__)
* bugfix:rest-api:Fix content type validation when charset is provided
  (`#306 <https://github.com/awslabs/chalice/issues/306>`__)
* enhancement:rest-api:Add back custom authorizer support
  (`#322 <https://github.com/awslabs/chalice/pull/322>`__)

0.8.0
=====

* feature:python:Add support for python3!
  (`#296 <https://github.com/awslabs/chalice/pull/296>`__)
* bugfix:packaging:Fix swagger generation when using ``api_key_required=True``
  (`#279 <https://github.com/awslabs/chalice/issues/279>`__)
* bugfix:CI-CD:Fix ``generate-pipeline`` to install requirements file before packaging
  (`#295 <https://github.com/awslabs/chalice/pull/295>`__)

0.7.0
=====

* feature:CLI:Add ``chalice package`` command.  This will
  create a SAM template and Lambda deployment package that
  can be subsequently deployed by AWS CloudFormation.
  (`#258 <https://github.com/awslabs/chalice/pull/258>`__)
* feature:CLI:Add a ``--stage-name`` argument for creating chalice stages.
  A chalice stage is a completely separate set of AWS resources.
  As a result, most configuration values can also be specified
  per chalice stage.
  (`#264 <https://github.com/awslabs/chalice/pull/264>`__,
  `#270 <https://github.com/awslabs/chalice/pull/270>`__)
* feature:policy:Add support for ``iam_role_file``, which allows you to
  specify the file location of an IAM policy to use for your app
  (`#272 <https://github.com/awslabs/chalice/pull/272>`__)
* feature:config:Add support for setting environment variables in your app
  (`#273 <https://github.com/awslabs/chalice/pull/273>`__)
* feature:CI-CD:Add a ``generate-pipeline`` command
  (`#277 <https://github.com/awslabs/chalice/pull/277>`__)

0.6.0
=====

Check out the `upgrade notes for 0.6.0
<http://aws.github.io/chalice/upgrading.html#v0-6-0>`__
for more detailed information about changes in this release.

* feature:local:Add port parameter to local command
  (`#220 <https://github.com/awslabs/chalice/pull/220>`__)
* feature:packaging:Add support for binary vendored packages
  (`#182 <https://github.com/awslabs/chalice/pull/182>`__,
  `#106 <https://github.com/awslabs/chalice/issues/106>`__,
  `#42 <https://github.com/awslabs/chalice/issues/42>`__)
* feature:rest-api:Add support for customizing the returned HTTP response
  (`#240 <https://github.com/awslabs/chalice/pull/240>`__,
  `#218 <https://github.com/awslabs/chalice/issues/218>`__,
  `#110 <https://github.com/awslabs/chalice/issues/110>`__,
  `#30 <https://github.com/awslabs/chalice/issues/30>`__,
  `#226 <https://github.com/awslabs/chalice/issues/226>`__)
* enhancement:packaging:Always inject latest runtime to allow for chalice upgrades
  (`#245 <https://github.com/awslabs/chalice/pull/245>`__)

0.5.1
=====

* enhancement:local:Add support for serializing decimals in ``chalice local``
  (`#187 <https://github.com/awslabs/chalice/pull/187>`__)
* enhancement:local:Add stdout handler for root logger when using ``chalice local``
  (`#186 <https://github.com/awslabs/chalice/pull/186>`__)
* enhancement:local:Map query string parameters when using ``chalice local``
  (`#184 <https://github.com/awslabs/chalice/pull/184>`__)
* enhancement:rest-api:Support Content-Type with a charset
  (`#180 <https://github.com/awslabs/chalice/issues/180>`__)
* bugfix:deployment:Fix not all resources being retrieved due to pagination
  (`#188 <https://github.com/awslabs/chalice/pull/188>`__)
* bugfix:deployment:Fix issue where root resource was not being correctly retrieved
  (`#205 <https://github.com/awslabs/chalice/pull/205>`__)
* bugfix:deployment:Handle case where local policy does not exist
  (`29 <https://github.com/awslabs/chalice/issues/29>`__)

0.5.0
=====

* enhancement:logging:Add default application logger
  (`#149 <https://github.com/awslabs/chalice/issues/149>`__)
* enhancement:local:Return 405 when method is not supported when running
  ``chalice local``
  (`#159 <https://github.com/awslabs/chalice/issues/159>`__)
* enhancement:SDK:Add path params as requestParameters so they can be used
  in generated SDKs as well as cache keys
  (`#163 <https://github.com/awslabs/chalice/issues/163>`__)
* enhancement:rest-api:Map cognito user pool claims as part of request context
  (`#165 <https://github.com/awslabs/chalice/issues/165>`__)
* feature:CLI:Add ``chalice url`` command to print the deployed URL
  (`#169 <https://github.com/awslabs/chalice/pull/169>`__)
* enhancement:deployment:Bump up retry limit on initial function creation to 30 seconds
  (`#172 <https://github.com/awslabs/chalice/pull/172>`__)
* feature:local:Add support for ``DELETE`` and ``PATCH`` in ``chalice local``
  (`#167 <https://github.com/awslabs/chalice/issues/167>`__)
* feature:CLI:Add ``chalice generate-sdk`` command
  (`#178 <https://github.com/awslabs/chalice/pull/178>`__)

0.4.0
=====

* bugfix:deployment:Fix issue where role name to arn lookup was failing due to lack of pagination
  (`#139 <https://github.com/awslabs/chalice/issues/139>`__)
* enhancement:rest-api:Raise errors when unknown kwargs are provided to ``app.route(...)``
  (`#144 <https://github.com/awslabs/chalice/pull/144>`__)
* enhancement:config:Raise validation error when configuring CORS and an OPTIONS method
  (`#142 <https://github.com/awslabs/chalice/issues/142>`__)
* feature:rest-api:Add support for multi-file applications
  (`#21 <https://github.com/awslabs/chalice/issues/21>`__)
* feature:local:Add support for ``chalice local``, which runs a local HTTP server for testing
  (`#22 <https://github.com/awslabs/chalice/issues/22>`__)

0.3.0
=====

* bugfix:rest-api:Fix bug with case insensitive headers
  (`#129 <https://github.com/awslabs/chalice/issues/129>`__)
* feature:CORS:Add initial support for CORS
  (`#133 <https://github.com/awslabs/chalice/pull/133>`__)
* enhancement:deployment:Only add API gateway permissions if needed
  (`#48 <https://github.com/awslabs/chalice/issues/48>`__)
* bugfix:policy:Fix error when dict comprehension is encountered during policy generation
  (`#131 <https://github.com/awslabs/chalice/issues/131>`__)
* enhancement:CLI:Add ``--version`` and ``--debug`` options to the chalice CLI

0.2.0
=====

* enhancement:rest-api:Add support for input content types besides ``application/json``
  (`#96 <https://github.com/awslabs/chalice/issues/96>`__)
* enhancement:rest-api:Allow ``ChaliceViewErrors`` to propagate, so that API Gateway
  can properly map HTTP status codes in non debug mode
  (`#113 <https://github.com/awslabs/chalice/issues/113>`__)
* enhancement:deployment:Add windows compatibility
  (`#31 <https://github.com/awslabs/chalice/issues/31>`__,
  `#124 <https://github.com/awslabs/chalice/pull/124>`__,
  `#103 <https://github.com/awslabs/chalice/issues/103>`__)

0.1.0
=====

* enhancement:packaging:Require ``virtualenv`` as a package dependency.
  (`#33 <https://github.com/awslabs/chalice/issues/33>`__)
* enhancement:CLI:Add ``--profile`` option when creating a new project
  (`#28 <https://github.com/awslabs/chalice/issues/28>`__)
* enhancement:rest-api:Add support for more error codes exceptions
  (`#34 <https://github.com/awslabs/chalice/issues/34>`__)
* enhancement:rest-api:Improve error validation when routes containing a
  trailing ``/`` char
  (`#65 <https://github.com/awslabs/chalice/issues/65>`__)
* enhancement:rest-api:Validate duplicate route entries
  (`#79 <https://github.com/awslabs/chalice/issues/79>`__)
* enhancement:policy:Ignore lambda expressions in policy analyzer
  (`#74 <https://github.com/awslabs/chalice/issues/74>`__)
* enhancement:rest-api:Print original error traceback in debug mode
  (`#50 <https://github.com/awslabs/chalice/issues/50>`__)
* feature:rest-api:Add support for authenticate routes
  (`#14 <https://github.com/awslabs/chalice/issues/14>`__)
* feature:policy:Add ability to disable IAM role management
  (`#61 <https://github.com/awslabs/chalice/issues/61>`__)


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Garage extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public $css_files;
	public $js_files;

	public function __construct()
	{
		parent::__construct();

		$this->load->helper('cookie');

		$this->load->database();
		$this->load->helper('url');

		$this->load->library('grocery_CRUD');

		$this->css_files = array();
		$this->js_files = array();
	}

	public function security() {
		return $this->_render('security');
	}

	public function disconnect() {
		$cookie = array(
		    'name'   => 'lmpa',
		    'value'  => '',
		    'expire' => '86500',
		    'domain' => $this->config->item('domain'),
		    'path'   => '/',
		    'secure' => false
		);
		$this->input->set_cookie($cookie);

		return redirect('/');
	}

	public function testSecurity() {
		$input = $this->input->get('password');
		if ($input) {
			$cookie = array(
			    'name'   => 'lmpa',
			    'value'  => md5($input),
			    'expire' => '86500',
			    'domain' => $this->config->item('domain'),
			    'path'   => '/',
			    'secure' => false
			);
			$this->input->set_cookie($cookie);
			redirect(current_url());
		}
		$securityCheck = $this->config->item('security');
		$security = $this->input->cookie('lmpa');
		return md5($securityCheck) == $security;
	}

	public function marques()
	{
		if (!$this->testSecurity()) {
			return $this->security();
		}
		$crud = new grocery_CRUD();
		$crud->set_subject('une marque');
		$output = $crud->render();
		$this->_crud_output($output);
	}

	public function pieces()
	{
		if (!$this->testSecurity()) {
			return $this->security();
		}
		$crud = new grocery_CRUD();
		$crud->set_table('pieces');
		$crud->set_subject('une pièce');
		$crud->set_relation('marque','marques','label');
		$crud->set_field_upload('image1','assets/uploads/files');
		$crud->set_field_upload('image2','assets/uploads/files');
		$crud->set_field_upload('image3','assets/uploads/files');
		$crud->order_by('annee_fin', 'ASC');
		$crud->order_by('annee_debut', 'ASC');

		$crud->callback_after_upload(function($uploader_response,$field_info, $files_to_upload) {

			//Is only one file uploaded so it ok to use it with $uploader_response[0].
			$fileUploaded = $field_info->upload_path.'/'.$uploader_response[0]->name;
			$thumbnail 	  = $field_info->upload_path.'/thumbnails/'.$uploader_response[0]->name;

			$config['image_library'] = 'gd2';
			$config['source_image'] = $fileUploaded;
			$config['maintain_ratio'] = TRUE;
			$config['width']         = 800;
			$config['height']       = 600;
			// $config['new_image'] = $thumbnail;

			$this->load->library('image_lib', $config);
			$this->image_lib->resize();

			return true;
		});

		$output = $crud->render();

		$this->_crud_output($output);
	}

/*	function example_callback_after_upload($uploader_response,$field_info, $files_to_upload)
{
    $this->load->library('image_moo');

    //Is only one file uploaded so it ok to use it with $uploader_response[0].
    $file_uploaded = $field_info->upload_path.'/'.$uploader_response[0]->name;

    $this->image_moo->load($file_uploaded)->resize(800,600)->save($file_uploaded,true);

    return true;
}*/

	protected function _crud_output($crud, $view = 'crud.php')
	{
		$this->css_files = array_merge($this->css_files, $crud->css_files);
		$this->js_files  = array_merge($this->js_files, $crud->js_files);

		$data = array(
			'css_files' => $this->css_files,
			'js_files'  => $this->js_files,
			'crud_view' => $crud->output,
			'title' => false
		);

		$this->load->view('header', $data);
		$this->load->view($view, $data);
		$this->load->view('footer', $data);
	}

	protected function _render($view, $data = array())
	{
		$data = array_merge($data, array(
			'css_files' => $this->css_files,
			'js_files'  => $this->js_files,
			'title' => false
		));

		$this->load->view('header', $data);
		$this->load->view($view, $data);
		$this->load->view('footer', $data);

	}

	public function index()
	{
		if (!$this->testSecurity()) {
			return $this->security();
		}
		$this->pieces();
		// $this->load->view('welcome_message');
	}
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

// Create viewer.
var viewer = new Marzipano.Viewer(document.getElementById('pano'));

// Create asset and source.
var asset = new VideoAsset();
var source = new Marzipano.SingleAssetSource(asset);

// Create geometry.
// This is a trivial equirectangular geometry with a single level.
// The level size need not match the actual video dimensions because it is
// only used to determine the most appropriate level to render, and no such
// choice has to be made in this case.
var geometry = new Marzipano.EquirectGeometry([ { width: 1 } ]);

// Create view.
// We display the video at a fixed vertical fov.
var limiter = Marzipano.RectilinearView.limit.vfov(90*Math.PI/180, 90*Math.PI/180);
var view = new Marzipano.RectilinearView({ fov: Math.PI/2 }, limiter);

// Create scene.
var scene = viewer.createScene({
  source: source,
  geometry: geometry,
  view: view
});

// Display scene.
scene.switchTo();

// Start playback on click.
// Playback cannot start automatically because most browsers require the play()
// method on the video element to be called in the context of a user action.
document.body.addEventListener('click', tryStart);
document.body.addEventListener('touchstart', tryStart);

// Whether playback has started.
var started = false;

// Try to start playback.
function tryStart() {
  if (started) {
    return;
  }
  started = true;

  var video = document.createElement('video');
  video.src = '//www.marzipano.net/media/video/mercedes-f1-1280x640.mp4';
  video.crossOrigin = 'anonymous';

  video.autoplay = true;
  video.loop = true;

  // Prevent the video from going full screen on iOS.
  video.playsInline = true;
  video.webkitPlaysInline = true;

  video.play();

  waitForReadyState(video, video.HAVE_METADATA, 100, function() {
    waitForReadyState(video, video.HAVE_ENOUGH_DATA, 100, function() {
      asset.setVideo(video);
    });
  });
}

// Wait for an element to reach the given readyState by polling.
// The HTML5 video element exposes a `readystatechange` event that could be
// listened for instead, but it seems to be unreliable on some browsers.
function waitForReadyState(element, readyState, interval, done) {
  var timer = setInterval(function() {
    if (element.readyState >= readyState) {
      clearInterval(timer);
      done(null, true);
    }
  }, interval);
}


text:
/*
 * MinIO Cloud Storage, (C) 2015-2020 MinIO, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cmd

// DO NOT EDIT THIS FILE DIRECTLY. These are build-time constants
// set through 'buildscripts/gen-ldflags.go'.
var (
	// GOPATH - GOPATH value at the time of build.
	GOPATH = ""

	// GOROOT - GOROOT value at the time of build.
	GOROOT = ""

	// Version - version time.RFC3339.
	Version = "DEVELOPMENT.GOGET"

	// ReleaseTag - release tag in TAG.%Y-%m-%dT%H-%M-%SZ.
	ReleaseTag = "DEVELOPMENT.GOGET"

	// CommitID - latest commit id.
	CommitID = "DEVELOPMENT.GOGET"

	// ShortCommitID - first 12 characters from CommitID.
	ShortCommitID = "DEVELOPMENT.GOGET"
)


text:
package io.neba.core.logviewer;

import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * Bridges non-websocket servlets with websockets. Handles all requests using the {@link TailSocket}.
 *
 * @author Olaf Otto
 */
@Component(service = TailServlet.class)
public class TailServlet extends WebSocketServlet {
    private static final long serialVersionUID = 1326193543519605309L;

    @Reference
    private LogFiles logFiles;

    @Override
    public void configure(WebSocketServletFactory factory) {
        factory.getPolicy().setIdleTimeout(SECONDS.toMillis(30));
        factory.setCreator((servletUpgradeRequest, servletUpgradeResponse) -> new TailSocket(logFiles));
    }
}


text:
class SearchController < ApplicationController
  STOP_WORDS = /season/i

  def search_database(type, query, page, perpage = 20)
    return [] if query.length < 3
    model = case type
      when "anime" then Anime.page(page).per(perpage).sfw_filter(current_user)
      when "manga" then Manga.page(page).per(perpage)
      when "character" then Character.page(page).per(perpage)
    end
    list = model.simple_search_by_title(query)
    list = model.fuzzy_search_by_title(query) if list.length == 0
    list
  end

  def basic

    @stype = params[:type] || "anime"
    @query = params[:query] || ""
    @page  = params[:page]

    case @stype
      when "anime"
        query = (@query || "").gsub(STOP_WORDS, '')
        found = search_database 'anime', query, @page

        # TODO: Re-write broken watchlist stuff here
        @results = found.map {|x| [x.title, x.alt_title] }.flatten.compact

      when "manga"
        query = (query || "").gsub(STOP_WORDS, '')
        @results = search_database 'manga', query, @page

      when "users"
        @results = User.search(@query).page(@page).per(20)

      when "users_to_follow"
        @results = User.search(@query).page(@page).per(20)

      when "character"
        @results = search_database 'character', @query, @page

      # Mixed search provides search results for the instant
      # search field in the page header.
      when "mixed"
        anime = search_database 'anime', @query, @page
        manga = search_database 'manga', @query, @page
        users = User.match(@query)
        users = User.search(@query).page(1).per(20) if users.length == 0

        formattedAnime = anime.map { |x|
          {:type => 'anime', :title => x.title, :image => x.poster_image_thumb, :link => "/anime/#{x.slug}" }
        }.flatten
        formattedManga = manga.map { |x|
          {:type => 'manga', :title => x.romaji_title, :image => x.poster_image_thumb, :link => "/manga/#{x.slug}" }
        }.flatten
        formattedUsers = users.map { |x|
          {:type => 'user', :title => x.name, :image => x.avatar_template, :link => "/users/#{x.name}" }
        }.flatten

        @results = [formattedAnime.take(3), formattedManga.take(3), formattedUsers.take(2)].flatten

      # Full search provides search results for the search page
      # with more detailed information about anime, manga and users
      # as well as a direct library / following widget (<- not yet)
      when "full"
        anime = search_database 'anime', @query, @page, 30
        manga = search_database 'manga', @query, @page, 30
        users = User.search(@query).page(1).per(20)

        formattedAnime = anime.map do |x| {
          :type => 'anime',
          :title => x.title,
          :desc => "#{x.synopsis[0..300].split(" ").to_a[0..-2].join(" ")}...",
          :image => x.poster_image_thumb,
          :link => x.slug,
          :badges => [
            {:class => 'anime', :content => "Anime"},
            {:class => 'episodes', :content => "#{x.episode_count}ep • #{x.episode_length}min"},
            {:class => 'episodes', :content => "#{x.show_type} • #{x.age_rating}"}
          ]}
        end
        formattedManga = manga.map do |x| {
          :type => 'manga',
          :title => x.romaji_title,
          :desc => "#{x.synopsis[0..300].split(" ").to_a[0..-2].join(" ")}...",
          :image => x.poster_image_thumb,
          :link => x.slug,
          :badges => [
            {:class => 'manga', :content => "Manga"},
            {:class => 'episodes', :content => "#{x.volume_count || "?"}vol • #{x.chapter_count || "?"}chap"}
          ]}
        end
        formattedUsers = users.map do |x| {
          :type => 'user',
          :title => x.name,
          :desc => x.bio,
          :image => x.avatar_url,
          :link => x.name,
          :badges => [
            {:class => 'user', :content => "User"}
          ]}
        end

        @results = [formattedAnime, formattedManga, formattedUsers].flatten

      else
        not_found!
    end

    respond_to do |format|
      format.html { render_ember }
      format.json { render :json => @results }
    end
  end
end


text:
import React, { useState } from 'react'
import { action } from '@storybook/addon-actions'
import { DropdownMenu } from './index'
import {
  pxToRem,
  COLORS,
  EllipsisIcon,
  AvatarWithTextAndBadge,
  Text,
  ArrowIcon,
  LinkIconNext,
  FacebookIconNext,
  TwitterIconNext,
  InstagramIconNext,
  MessengerIconNext,
  WhatsappIconNext,
  LinkedinIconNext,
  EmbedIconNext,
  Button,
  AirplaneIconNext,
} from 'kitten'
import styled from 'styled-components'
import { DocsPage } from 'storybook/docs-page'

export default {
  title: 'Structure/Expand/DropdownMenu',
  component: DropdownMenu,
  parameters: {
    docs: {
      page: () => (
        <DocsPage filepath={__filename} importString="DropdownMenu" />
      ),
    },
  },
  argTypes: {
    open: {
      name: 'open',
      control: 'boolean',
    },
    menuPosition: {
      name: 'menuPosition',
      options: ['left', 'center', 'right'],
      control: 'inline-radio',
    },
    button: {
      name: 'button',
      control: null,
    },
    menuprops: {
      name: 'menuprops',
      control: 'object',
    },
    onToggle: {
      name: 'onToggle',
      control: null,
    },
    positionedButton: {
      name: 'positionedButton',
      control: 'boolean',
    },
  },
  args: {
    open: false,
    menuPosition: null,
    button: ({ open }) => (
      <>
        <EllipsisIcon color={COLORS.font1} />

          {open ? 'Click to close menu' : 'Click to open menu'}

      </>
    ),
    onToggle: action('on Toggle'),
    positionedButton: false,
  },
}

const StyledWrapper = styled.div`
  div {
    height: 5rem;
    display: flex;
    align-items: stretch;
    justify-content: stretch;
  }

  details {
    width: 5em;
    border: 1px solid red;
  }
`

export const Default = ({ menuPosition, ...args }) => {
  return (

  )
}

Default.decorators = [story =>
{story()}
]

export const Controlled = ({ ...args }) => {
  const [isOpen, setOpen] = useState(false)

  return (
    <>

      <Button
        onClick={() => {
          setOpen(current => !current)
        }}
        active={isOpen}
      >
        {isOpen ? 'Fermer le menu' : 'Ouvrir le menu'}
      </Button>
    </>
  )
}

Controlled.decorators = [
  story =>
{story()}
,
]

export const WithAvatar = args => (
  <>

      <DropdownMenu
        {...args}
        menuPosition="center"
        button={({ open }) => (
          <AvatarWithTextAndBadge>
            <AvatarWithTextAndBadge.Image alt="" src="/kitten-0.jpg" />

            <AvatarWithTextAndBadge.Text>
              <Text
                weight="500"
                className="k-u-block k-u-link k-u-link-primary1"
              >
                Kitten Kitty
              </Text>
              <Text className="k-u-block">Cat City</Text>
            </AvatarWithTextAndBadge.Text>
            <ArrowIcon
              className="k-u-flex-shrink-none"
              direction={open ? 'top' : 'bottom'}
            />
          </AvatarWithTextAndBadge>
        )}
      >
        <DropdownMenu.Link href="">A link</DropdownMenu.Link>
        <DropdownMenu.Button>Click this button</DropdownMenu.Button>
        <DropdownMenu.Link href="">
          Another last very very very very very very very very very very long
          link
        </DropdownMenu.Link>
      </DropdownMenu>

  </>
)

WithAvatar.decorators = [
  story =>
{story()}
,
]

export const WithButton = args => (
  <>

      <DropdownMenu
        {...args}
        menuPosition="center"
        open
        button={({ open }) => (
          <Button active={open} rounded fit="content" as="span">
            <AirplaneIconNext />
            Partager
          </Button>
        )}
        top={pxToRem(10)}
      >
        <DropdownMenu.Link href="#" icon={<LinkIconNext />}>
          Copier le lien
        </DropdownMenu.Link>
        <DropdownMenu.Separator />
        <DropdownMenu.Button icon={<FacebookIconNext />}>
          Facebook
        </DropdownMenu.Button>
        <DropdownMenu.Button icon={<TwitterIconNext />}>
          Twitter
        </DropdownMenu.Button>
        <DropdownMenu.Button icon={<InstagramIconNext />}>
          Instagram
        </DropdownMenu.Button>
        <DropdownMenu.Button icon={<MessengerIconNext />}>
          Messenger
        </DropdownMenu.Button>
        <DropdownMenu.Button icon={<WhatsappIconNext />}>
          WhatsApp
        </DropdownMenu.Button>
        <DropdownMenu.Button icon={<LinkedinIconNext width={13} heigh={13} />}>
          LinkedIn
        </DropdownMenu.Button>
        <DropdownMenu.Separator />
        <DropdownMenu.Button icon={<EmbedIconNext />}>
          Widget
        </DropdownMenu.Button>
      </DropdownMenu>

  </>
)

WithButton.decorators = [
  story =>
{story()}
,
]

const StyledImageWrapper = styled.div`
  position: relative;
  display: inline-block;

  img {
    display: inline;
    max-width: ${pxToRem(600)};
    max-height: ${pxToRem(400)};
  }

  .image-menu {
    position: absolute;
    left: 0;
    width: 100%;
    top: 0;
    height: 100%;
  }
`

export const WithImage = args => (
  <>

  </>
)

WithImage.decorators = [
  story =>
{story()}
,
]


text:
<?php

declare(strict_types=1);

namespace SerendipityHQ\Bundle\CommandsQueuesBundle\Service;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use RuntimeException;
use Safe\Exceptions\StringsException;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Entity\Daemon;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Entity\Job;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Repository\JobRepository;
use SerendipityHQ\Bundle\CommandsQueuesBundle\Util\InputParser;

/**
 * Manages the commands_queues.
 */
final class QueuesManager
{
    /** @var EntityManager */
    private $entityManager;

    /**
     * @param EntityManagerInterface $entityManager
     */
    public function __construct(EntityManagerInterface $entityManager)
    {
        // This is to make static analysis pass
        if ( ! $entityManager instanceof EntityManager) {
            throw new RuntimeException('You need to pass an EntityManager instance.');
        }

        $this->entityManager = $entityManager;
    }

    /**
     * Checks if a Job is scheduled given a Job instance.
     *
     * It uses the given Job's parameters to find one already scheduled.
     *
     * It uses command, arguments and queue and searches only for Jobs not already executed.
     *
     * Returns (bool) false if it doesn't exist or the scheduled Job if it exists.
     *
     * @param Job  $job
     * @param bool $fullSearch If false, searches only not yet started jobs
     *
     * @throws StringsException
     *
     * @return bool
     */
    public function jobExists(Job $job, bool $fullSearch = false): bool
    {
        return $this->exists($job->getCommand(), $job->getInput(), $job->getQueue(), $fullSearch);
    }

    /**
     * Finds a Job given a Job instance.
     *
     * It uses the given Job's parameters to find one already scheduled.
     *
     * It uses command, arguments and queue and searches only for Jobs not already executed.
     *
     * Returns null if it doesn't exist or the scheduled Job if it exists.
     *
     * @param Job  $job
     * @param bool $fullSearch If false, searches only not yet started jobs
     *
     * @throws StringsException
     *
     * @return array|null
     */
    public function findByJob(Job $job, bool $fullSearch = false): ?array
    {
        return $this->find($job->getCommand(), $job->getInput(), $job->getQueue(), $fullSearch);
    }

    /**
     * Given Job parameters, checks if it exists or not.
     *
     * Returns (bool) false if it doesn't exist or the scheduled Job if it exists.
     *
     * @param string            $command
     * @param array|string|null $input
     * @param string            $queue
     * @param bool              $fullSearch If false, searches only not yet started jobs
     *
     * @throws StringsException
     *
     * @return bool
     */
    public function exists(string $command, $input = null, string $queue = Daemon::DEFAULT_QUEUE_NAME, bool $fullSearch = false): bool
    {
        $exists = $this->find($command, $input, $queue, $fullSearch);

        return ! empty($exists);
    }

    /**
     * Finds a Job given its parameters.
     *
     * Returns null if it doesn't exist or the scheduled Job if it exists.
     *
     * @param string|null       $command
     * @param array|string|null $input
     * @param string|null       $queue
     * @param bool              $fullSearch If false, searches only not yet started jobs
     *
     * @throws StringsException
     *
     * @return array|null
     */
    public function find(string $command = null, $input = null, ?string $queue = Daemon::DEFAULT_QUEUE_NAME, bool $fullSearch = false): ?array
    {
        /** @var JobRepository $jobsRepo */
        $jobsRepo = $this->entityManager->getRepository(Job::class);

        // Check and prepare arguments of the command
        if (null !== $input) {
            $input = InputParser::parseInput($input);
        }

        return $jobsRepo->findBySearch($command, $input, $queue, $fullSearch);
    }

    /**
     * persists a job and flushes it to the database.
     *
     * @param Job $job
     *
     * @throws OptimisticLockException
     * @throws ORMException
     */
    public function schedule(Job $job): void
    {
        $this->entityManager->persist($job);
        $this->entityManager->flush($job);
    }
}


text:
import { Component, ViewEncapsulation, OnInit } from '@angular/core';

import { AuthService } from './core';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class AppComponent implements OnInit {
  constructor(private authService: AuthService) { }

  ngOnInit() {
    this.authService.syncWithFirebase();
  }
}


text:
export type StaticRouterContextType = {
    url?: string,
};

export type LocationType = {
    pathname: string,
    search: string,
    hash: string,
    state?: {},
    key?: string,
};

export type LocationShapeType = {
    pathname?: string,
    search?: string,
    hash?: string,
    state?: {},
};

export type HistoryActionType = 'PUSH' | 'REPLACE' | 'POP';

export type RouterHistoryType = {
    length: number,
    location: LocationType,
    action: HistoryActionType,
    listen(callback: (location: LocationType, action: HistoryActionType) => void): () => void,
    push(path: string | LocationShapeType, state?: {}): void,
    replace(path: string | LocationShapeType, state?: {}): void,
    go(n: number): void,
    goBack(): void,
    goForward(): void,
    canGo?: (n: number) => boolean,
    block(callback: (location: LocationType, action: HistoryActionType) => boolean): void,
    // createMemoryHistory
    index?: number,
    entries?: Array<LocationType>,
};

export type MatchType = {
    params: {[key: string]: ?string},
    isExact: boolean,
    path: string,
    url: string,
};

export type ContextRouterType = {|
    history: RouterHistoryType,
    location: LocationType,
    match: MatchType,
    staticContext?: StaticRouterContextType,
|};

declare type ContextRouterVoidType = {
    history: RouterHistoryType | void,
    location: LocationType | void,
    match: MatchType | void,
    staticContext?: StaticRouterContextType | void,
};

export type GetUserConfirmationType = (message: string, callback: (confirmed: boolean) => void) => void;

export type MatchPathOptionsType = {
    path?: string,
    exact?: boolean,
    sensitive?: boolean,
    strict?: boolean,
};


text:
package net.hillsdon.reviki.wiki.plugin;

public class InvalidPluginException extends Exception {

  private static final long serialVersionUID = 1L;

  public InvalidPluginException(final Throwable t) {
    super(t);
  }

  public InvalidPluginException(final String message) {
    super(message);
  }

}


text:
Dummy::Application.routes.draw do
  resources :articles, only: [:create]
  resources :widgets, only: %i[create update destroy]
end


text:
package git

import (
	"bytes"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"cloud.google.com/go/internal/gapicgen/execv"
	"gopkg.in/src-d/go-git.v4"
)

// ChangeInfo represents a change and its associated metadata.
type ChangeInfo struct {
	Body           string
	Title          string
	Package        string
	PackageDir     string
	GoogleapisHash string
}

// FormatChanges turns a slice of changes into formatted string that will match
// the conventional commit footer pattern. This will allow these changes to be
// parsed into the changelog.
func FormatChanges(changes []*ChangeInfo, onlyGapicChanges bool) string {
	if len(changes) == 0 {
		return ""
	}
	var sb strings.Builder
	sb.WriteString("\nChanges:\n\n")
	for _, c := range changes {
		if onlyGapicChanges && c.Package == "" {
			continue
		}

		title := c.Title
		if c.Package != "" {
			// Try to add in pkg affected into conventional commit scope.
			titleParts := strings.SplitN(c.Title, ":", 2)
			if len(titleParts) == 2 {
				// If a scope is already provided, remove it.
				if i := strings.Index(titleParts[0], "("); i > 0 {
					titleParts[0] = titleParts[0][:i]
				}

				var breakChangeIndicator string
				if strings.HasSuffix(titleParts[0], "!") {
					// If the change is marked as breaking we need to move the
					// bang to after the added scope.
					titleParts[0] = titleParts[0][:len(titleParts[0])-1]
					breakChangeIndicator = "!"
				}
				titleParts[0] = fmt.Sprintf("%s(%s)%s", titleParts[0], c.Package, breakChangeIndicator)
			}
			title = strings.Join(titleParts, ":")
		}
		sb.WriteString(fmt.Sprintf("%s\n", title))

		// Format the commit body to conventional commit footer standards.
		splitBody := strings.Split(c.Body, "\n")
		for i := range splitBody {
			splitBody[i] = fmt.Sprintf("  %s", splitBody[i])
		}
		body := strings.Join(splitBody, "\n")
		sb.WriteString(fmt.Sprintf("%s\n\n", body))
	}
	// If the buffer is empty except for the "Changes:" text return an empty
	// string.
	if sb.Len() == 11 {
		return ""
	}
	return sb.String()
}

// ParseChangeInfo gets the ChangeInfo for a given googleapis hash.
func ParseChangeInfo(googleapisDir string, hashes []string, gapicPkgs map[string]string) ([]*ChangeInfo, error) {
	var changes []*ChangeInfo
	for _, hash := range hashes {
		// Get commit title and body
		c := execv.Command("git", "show", "--pretty=format:%s~~%b", "-s", hash)
		c.Dir = googleapisDir
		b, err := c.Output()
		if err != nil {
			return nil, err
		}

		ss := strings.Split(string(b), "~~")
		if len(ss) != 2 {
			return nil, fmt.Errorf("expected two segments for commit, got %d: %s", len(ss), b)
		}
		title, body := strings.TrimSpace(ss[0]), strings.TrimSpace(ss[1])

		// Add link so corresponding googleapis commit.
		body = fmt.Sprintf("%s\nSource-Link: https://github.com/googleapis/googleapis/commit/%s", body, hash)

		// Try to map files updated to a package in google-cloud-go. Assumes only
		// one servies protos are updated per commit. Multile versions are okay.
		files, err := filesChanged(googleapisDir, hash)
		if err != nil {
			return nil, err
		}
		var pkg, pkgDir string
		for _, file := range files {
			if file == "" {
				continue
			}
			importPath := gapicPkgs[filepath.Dir(file)]
			if importPath != "" {
				pkg = parseConventionalCommitPkg(importPath)
				pkgDir = strings.TrimPrefix(importPath, "cloud.google.com/go/")
				break
			}
		}

		changes = append(changes, &ChangeInfo{
			Title:          title,
			Body:           body,
			Package:        pkg,
			PackageDir:     pkgDir,
			GoogleapisHash: hash,
		})
	}
	return changes, nil
}

// parseConventionalCommitPkg parses the package context for conventional commit
// messages.
func parseConventionalCommitPkg(importPath string) string {
	s := strings.TrimPrefix(importPath, "cloud.google.com/go/")
	ss := strings.Split(s, "/")
	// remove the version, i.e /apiv1
	return strings.Join(ss[:len(ss)-1], "/")
}

// CommitsSinceHash gathers all of the commits since the provided hash for the
// given gitDir. The inclusive parameter tells if the provided hash should also
// be returned in the slice.
func CommitsSinceHash(gitDir, hash string, inclusive bool) ([]string, error) {
	var commitRange string
	if inclusive {
		commitRange = fmt.Sprintf("%s^..", hash)
	} else {
		commitRange = fmt.Sprintf("%s..", hash)
	}

	c := execv.Command("git", "rev-list", commitRange)
	c.Dir = gitDir
	b, err := c.Output()
	if err != nil {
		return nil, err
	}
	return strings.Split(strings.TrimSpace(string(b)), "\n"), nil
}

// UpdateFilesSinceHash returns a listed of files updated since the provided
// hash for the given gitDir.
func UpdateFilesSinceHash(gitDir, hash string) ([]string, error) {
	// The provided diff-filter flags restricts to files that have been:
	// - (A) Added
	// - (C) Copied
	// - (M) Modified
	// - (R) Renamed
	c := execv.Command("git", "diff-tree", "--no-commit-id", "--name-only", "--diff-filter=ACMR", "-r", fmt.Sprintf("%s..HEAD", hash))
	c.Dir = gitDir
	b, err := c.Output()
	if err != nil {
		return nil, err
	}
	return strings.Split(string(b), "\n"), nil
}

// HasChanges reports whether the given directory has uncommitted git changes.
func HasChanges(dir string) (bool, error) {
	c := execv.Command("bash", "-c", "git status --short")
	c.Dir = dir
	b, err := c.Output()
	return len(b) > 0, err
}

// DeepClone clones a repository in the given directory.
func DeepClone(repo, dir string) error {
	log.Printf("cloning %s\n", repo)

	_, err := git.PlainClone(dir, false, &git.CloneOptions{
		URL:      repo,
		Progress: os.Stdout,
	})
	return err
}

// FindModifiedFiles locates modified files in the git directory provided.
func FindModifiedFiles(dir string) ([]string, error) {
	return findModifiedFiles(dir, "-m")
}

// FindModifiedAndUntrackedFiles locates modified and untracked files in the git
// directory provided.
func FindModifiedAndUntrackedFiles(dir string) ([]string, error) {
	return findModifiedFiles(dir, "-mo")
}

func findModifiedFiles(dir string, filter string) ([]string, error) {
	c := execv.Command("git", "ls-files", filter)
	c.Dir = dir
	out, err := c.Output()
	if err != nil {
		return nil, err
	}
	return strings.Split(string(bytes.TrimSpace(out)), "\n"), nil
}

// ResetFile reverts all changes made to a file in the provided directory.
func ResetFile(dir, filename string) error {
	c := exec.Command("git", "checkout", "HEAD", "--", filename)
	c.Dir = dir
	return c.Run()
}

// FileDiff returns the git diff for the specified file.
func FileDiff(dir, filename string) (string, error) {
	c := exec.Command("git", "diff", "--unified=0", filename)
	c.Dir = dir
	out, err := c.Output()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(out)), nil
}

// CheckoutRef checks out the ref in the provided git project directory.
func CheckoutRef(dir, ref string) error {
	cmd := execv.Command("git", "checkout", ref)
	cmd.Dir = dir
	return cmd.Run()
}

// filesChanged returns a list of files changed in a commit for the provdied
// hash in the given gitDir.
func filesChanged(gitDir, hash string) ([]string, error) {
	c := execv.Command("git", "show", "--pretty=format:", "--name-only", hash)
	c.Dir = gitDir
	b, err := c.Output()
	if err != nil {
		return nil, err
	}
	return strings.Split(string(b), "\n"), nil
}


text:
const net = require('net');
const server = net.createServer((c) => {
  // 'connection' listener
  console.log('client connected');

  c.on('data', (data) => {
    console.log('Buffer length: ', data.length);
    console.log(data.toString('utf8'));
  });

  c.on('end', () => {
    console.log('client disconnected');
  });
  c.write('hello\r\n');
  c.pipe(c);
});
server.on('error', (err) => {
  throw err;
});
server.listen(8080, () => {
  console.log('server bound');
});


text:
using System;
using System.Collections.Generic;
using BoardTracker.Model;

namespace BoardTracker.Repository
{
    public interface ITrackingRepository
    {
        #region Add models
        /// <summary>
        /// Add posts of a specific author to the database
        /// </summary>
        /// <param name="posts"></param>
        /// <param name="profile"></param>
        void AddPosts(IEnumerable<Post> posts);

        /// <summary>
        /// Insert a post if it does not already exist, update it if it does
        /// </summary>
        /// <param name="post"></param>
        void UpsertPost(Post post);

        /// <summary>
        /// Add a new website to the database
        /// </summary>
        /// <param name="website"></param>
        void UpsertWebsite(Website website);

        /// <summary>
        /// Add a new author's profile of a website to the database
        /// </summary>
        /// <param name="website"></param>
        /// <param name="profile"></param>
        void UpsertProfile(Profile profile);

        /// <summary>
        /// Add a new author to the database
        /// </summary>
        /// <param name="author"></param>
        void UpsertAuthor(Author author);

        #endregion Add Models

        /// <summary>
        /// Get the date of the last post of a profile
        /// </summary>
        /// <param name="website"></param>
        /// <param name="profile"></param>
        /// <returns></returns>
        DateTime? GetDateOfLastPost(Profile profile);

        /// <summary>
        ///
        /// </summary>
        /// <param name="authorId"></param>
        /// <returns></returns>
        Author GetAuthor(int authorId);

        /// <summary>
        /// Get a saved website by name
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        Website GetWebsite(string name);

        /// <summary>
        /// Get the profile with a specific template key
        /// </summary>
        /// <param name="templateKey"></param>
        /// <returns></returns>
        Profile GetProfile(string templateKey);
    }
}


text:
#include <cstddef>
#include <string>
#include <map>
#include <iostream>
#include <fstream>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/smart_ptr/make_shared_object.hpp>
#include <boost/log/sinks.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/attributes/scoped_attribute.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/utility/value_ref.hpp>
#include <boost/log/utility/manipulators/add_value.hpp>

namespace logging = boost::log;
namespace src = boost::log::sources;
namespace expr = boost::log::expressions;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;

//[ example_expressions_has_attr_stat_accumulator
// Declare attribute keywords
BOOST_LOG_ATTRIBUTE_KEYWORD(stat_stream, "StatisticStream", std::string)
BOOST_LOG_ATTRIBUTE_KEYWORD(change, "Change", int)

// A simple sink backend to accumulate statistic information
class my_stat_accumulator :
    public sinks::basic_sink_backend< sinks::synchronized_feeding >
{
    // A map of accumulated statistic values,
    // ordered by the statistic information stream name
    typedef std::map< std::string, int > stat_info_map;
    stat_info_map m_stat_info;

public:
    // Destructor
    ~my_stat_accumulator()
    {
        // Display the accumulated data
        stat_info_map::const_iterator it = m_stat_info.begin(), end = m_stat_info.end();
        for (; it != end; ++it)
        {
            std::cout << "Statistic stream: " << it->first
                << ", accumulated value: " << it->second << "\n";
        }
        std::cout.flush();
    }

    // The method is called for every log record being put into the sink backend
    void consume(logging::record_view const& rec)
    {
        // First, acquire statistic information stream name
        logging::value_ref< std::string, tag::stat_stream > name = rec[stat_stream];
        if (name)
        {
            // Next, get the statistic value change
            logging::value_ref< int, tag::change > change_amount = rec[change];
            if (change_amount)
            {
                // Accumulate the statistic data
                m_stat_info[name.get()] += change_amount.get();
            }
        }
    }
};

// The function registers two sinks - one for statistic information,
// and another one for other records
void init()
{
    boost::shared_ptr< logging::core > core = logging::core::get();

    // Create a backend and attach a stream to it
    boost::shared_ptr< sinks::text_ostream_backend > backend =
        boost::make_shared< sinks::text_ostream_backend >();
    backend->add_stream(
        boost::shared_ptr< std::ostream >(new std::ofstream("test.log")));

    // Create a frontend and setup filtering
    typedef sinks::synchronous_sink< sinks::text_ostream_backend > log_sink_type;
    boost::shared_ptr< log_sink_type > log_sink(new log_sink_type(backend));
    // All records that don't have a "StatisticStream" attribute attached
    // will go to the "test.log" file
    log_sink->set_filter(!expr::has_attr(stat_stream));

    core->add_sink(log_sink);

    // Create another sink that will receive all statistic data
    typedef sinks::synchronous_sink< my_stat_accumulator > stat_sink_type;
    boost::shared_ptr< stat_sink_type > stat_sink(new stat_sink_type());
    // All records with a "StatisticStream" string attribute attached
    // will go to the my_stat_accumulator sink
    stat_sink->set_filter(expr::has_attr(stat_stream));

    core->add_sink(stat_sink);
}

// This simple macro will simplify putting statistic data into a logger
#define PUT_STAT(lg, stat_stream_name, change)\
    if (true) {\
        BOOST_LOG_SCOPED_LOGGER_TAG(lg, "StatisticStream", stat_stream_name);\
        BOOST_LOG(lg) << logging::add_value("Change", (int)(change));\
    } else ((void)0)

void logging_function()
{
    src::logger lg;

    // Put a regular log record, it will go to the "test.log" file
    BOOST_LOG(lg) << "A regular log record";

    // Put some statistic data
    PUT_STAT(lg, "StreamOne", 10);
    PUT_STAT(lg, "StreamTwo", 20);
    PUT_STAT(lg, "StreamOne", -5);
}
//]

int main(int, char*[])
{
    init();
    logging_function();

    return 0;
}


text:
@interface NSMutableArray (WeaverQueue)

- (id) dequeue;
- (void) enqueue:(id)obj;

@end


text:
using System;
using System.IO;
using System.Security;
using System.Security.Permissions;
using System.Collections;
using System.Reflection;
using MS.Internal;
using MS.Win32;
using System.Diagnostics;
using System.Windows.Media;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Microsoft.Win32.SafeHandles;

using UnsafeNativeMethods=MS.Win32.PresentationCore.UnsafeNativeMethods;

namespace System.Windows.Media
{
    internal class SafeMediaHandle : SafeMILHandle
    {
        /// <summary>
        /// </summary>
        internal SafeMediaHandle()
        {
        }

        /// <summary>
        /// </summary>
        ///<SecurityNote>
        ///     Critical: calls SafeHandle.SetHandle which LinkDemands
        ///               also takes arbitrary IntPtr as a handle
        ///</SecurityNote>
        [SecurityCritical]
        internal SafeMediaHandle(IntPtr handle)
        {
            SetHandle(handle);
        }

        /// <SecurityNote>
        /// Critical - calls unmanaged code, not treat as safe because you must
        ///            validate that handle is a valid COM object.
        /// </SecurityNote>
        [SecurityCritical]
        protected override bool ReleaseHandle()
        {
            HRESULT.Check(MILMedia.Shutdown(handle));
            UnsafeNativeMethods.MILUnknown.ReleaseInterface(ref handle);

            return true;
        }
    }
}


text:
define(function () {

    var archiveSessionStorageToLocalStorage = function() {
        var backup = {};

        for (var i = 0; i < sessionStorage.length; i++) {
            backup[sessionStorage.key(i)] = sessionStorage[sessionStorage.key(i)];
        }

        localStorage["sessionStorageBackup"] = JSON.stringify(backup);
        sessionStorage.clear();
    };

    var restoreSessionStorageFromLocalStorage = function () {
        var backupText = localStorage["sessionStorageBackup"];
        var backup;

        if (backupText) {
            backup = JSON.parse(backupText);

            for (var key in backup) {
                sessionStorage[key] = backup[key];
            }

            localStorage.removeItem("sessionStorageBackup");
        }
    };

    var getFragment = function () {
        if (window.location.hash.indexOf("#") === 0) {
            return parseQueryString(window.location.hash.substr(1));
        } else {
            return {};
        }
    };

    var parseQueryString = function (queryString) {
        var data = {},
            pairs, pair, separatorIndex, escapedKey, escapedValue, key, value;

        if (queryString === null) {
            return data;
        }

        pairs = queryString.split("&");

        for (var i = 0; i < pairs.length; i++) {
            pair = pairs[i];
            separatorIndex = pair.indexOf("=");

            if (separatorIndex === -1) {
                escapedKey = pair;
                escapedValue = null;
            } else {
                escapedKey = pair.substr(0, separatorIndex);
                escapedValue = pair.substr(separatorIndex + 1);
            }

            key = decodeURIComponent(escapedKey);
            value = decodeURIComponent(escapedValue);

            data[key] = value;
        }

        return data;
    };

    var verifyStateMatch = function (fragment) {
        var state;

        if (typeof (fragment.access_token) !== "undefined") {
            state = sessionStorage["state"];
            sessionStorage.removeItem("state");

            if (state === null || fragment.state !== state) {
                fragment.error = "invalid_state";
            }
        }
    };

    return {
        archiveSessionStorageToLocalStorage: archiveSessionStorageToLocalStorage,
        restoreSessionStorageFromLocalStorage: restoreSessionStorageFromLocalStorage,
        verifyStateMatch: verifyStateMatch,
        parseQueryString: parseQueryString,
        getFragment: getFragment
    };
});


text:
exports.name = 'version';
exports.hidden = false;
exports.enabled = true;
exports.matchStart = false;
exports.handler = function(data) {
    request('http://registry.npmjs.org/sparklebot/latest',
        function (error, response, body) {
            var currentversion = JSON.parse(body).version;
            var response;
            if (package.version != currentversion) {
                setTimeout(function() {
                    output({text: 'Your version of sparklebot is out of date! Update through npm or at http://git.io/meow', destination: data.source, userid: data.userid});
                }, 1000);
            }
            response = '[Sparkle] ' + package.version + ' (Latest version: ' + currentversion + ')';
            output({text: response, destination: data.source, userid: data.userid});
        });
}


text:
// =============================================================================
//
//  app/components/ap-header/ap-header-controller.js
//
// =============================================================================

/**
 * ApHeaderController class handles our interaction with the Header component
 *
 * @class ApHeaderController
 */
class ApHeaderController {

  /**
   * Constructor for the ApHeaderController class
   *
   * @constructor
   * @param {Object} $rootScope - The root scope provider of our angular application
   */
  constructor($rootScope) {
    'ngInject';

    this.$rootScope = $rootScope;
    this.user = $rootScope.currentUser.userName;
  }
}

export default ApHeaderController;


text:
enum GameState
{
    INITIALIZED,
    PLAYING,
    GAME_OVER
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="UsuariosController GET show" tests="1" time="0.016208" failures="0" errors="0" skipped="0">
  <testcase name="UsuariosController GET show assigns the requested usuario as @usuario" time="0.015514">
  </testcase>
  <system-out>
  </system-out>
  <system-err>
  </system-err>
</testsuite>


text:
package edu.uci.python.nodes.literal;

import com.oracle.truffle.api.frame.*;

import edu.uci.python.runtime.datatype.*;

public final class ComplexLiteralNode extends LiteralNode {

    private final PComplex value;

    public ComplexLiteralNode(PComplex value) {
        this.value = value;
    }

    public PComplex getValue() {
        return value;
    }

    @Override
    public PComplex executePComplex(VirtualFrame frame) {
        return value;
    }

    @Override
    public Object execute(VirtualFrame frame) {
        return value;
    }

}


text:
"""Tests for subpopl_utils."""

import collections

import tensorflow as tf

import subpopl_utils  # local file import from baselines.jft
from google3.testing.pybase import googletest

class SubpoplUtilsTest(googletest.TestCase):

  def test_eval_subpopl_metrics(self):

    def addition_map_fn_builder(increment):

      def addition_map_fn(element):
        return element + increment

      return addition_map_fn

    def dict_map_fn(element):
      return collections.OrderedDict(
          image=element, labels=element, batch=element, mask=element)

    # Construct simple but slightly different datasets for 10 subpopulations.
    splits = {
        i: tf.data.Dataset.range(5).map(
            addition_map_fn_builder(i)).batch(3).map(dict_map_fn)
        for i in range(10)
    }

    # Create a predictable evaluation function that treats examples above "10"
    # correct.
    def evaluation_fn(dummy_params, image, labels, mask):
      del dummy_params, labels, mask
      n_correct = tf.reduce_sum(tf.cast(tf.greater(image, 10), tf.int32))
      n = tf.size(image)
      return [n_correct], None, [n], None

    measurements = subpopl_utils.eval_subpopl_metrics(splits, evaluation_fn,
                                                      None, 0)

    # Subpops 0-6 will have 0 correct, Subpops 7, 8, 9 will have 1, 2, 3,
    # respectively. There are 50 examples total. Percentiles are calculated
    # via interpolation.
    expected_measurements = {}
    expected_measurements['subpopl_avg_prec@1'] = 0.12
    expected_measurements['subpopl_med_prec@1'] = 0.0
    expected_measurements['subpopl_var_prec@1'] = 0.0416
    expected_measurements['subpopl_p95_prec@1'] = 0.51
    expected_measurements['subpopl_p75_prec@1'] = 0.15
    expected_measurements['subpopl_p25_prec@1'] = 0.0
    expected_measurements['subpopl_p05_prec@1'] = 0.0

    self.assertCountEqual(expected_measurements.keys(), measurements.keys())
    for key in expected_measurements:
      self.assertAlmostEqual(expected_measurements[key], measurements[key])

if __name__ == '__main__':
  googletest.main()


text:
const NCAPModel = require('~/models/ncap');

const ctx = NCAPModel.getEmptyPlaceholder();

const colorRecallContainer = (page, recalls) => {
    recalls = recalls || 0;
    const view = page.getViewById('recallCard');
    if (recalls > 0) {
        view.className = view.className + ' color-warning';
    }
};

exports.onNavigatingTo = args => {
    const page = args.object;

    const {vehicle} = page.navigationContext;
    ctx.set('vehicle', vehicle);

    colorRecallContainer(page, vehicle.RecallsCount);
    page.bindingContext = ctx;
};


text:
package org.apache.camel.component.smpp;

import java.util.HashMap;
import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.ExchangePattern;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.SimpleRegistry;
import org.jsmpp.extra.SessionState;
import org.jsmpp.session.Session;
import org.jsmpp.session.SessionStateListener;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

/**
 * JUnit test class for org.apache.camel.component.smpp.SmppComponent
 */
public class SmppComponentTest {

    private SmppComponent component;
    private DefaultCamelContext context;

    @Before
    public void setUp() {
        context = new DefaultCamelContext();
        component = new SmppComponent(context);
    }

    @Test
    public void constructorSmppConfigurationShouldSetTheConfiguration() {
        SmppConfiguration configuration = new SmppConfiguration();
        component = new SmppComponent(configuration);

        assertSame(configuration, component.getConfiguration());
    }

    @Test
    public void constructorCamelContextShouldSetTheContext() {
        CamelContext context = new DefaultCamelContext();
        component = new SmppComponent(context);

        assertSame(context, component.getCamelContext());
    }

    @Test
    public void createEndpointStringStringMapShouldReturnASmppEndpoint() throws Exception {
        CamelContext context = new DefaultCamelContext();
        component = new SmppComponent(context);
        Map<String, String> parameters = new HashMap<>();
        parameters.put("password", "secret");
        Endpoint endpoint = component.createEndpoint("smpp://smppclient@localhost:2775", "?password=secret", parameters);
        SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;

        assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointUri());
        assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
        assertSame(component, smppEndpoint.getComponent());
        assertNotNull(smppEndpoint.getConfiguration());
        assertEquals("secret", smppEndpoint.getConfiguration().getPassword());
        assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getConnectionString());
        assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
        assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
        assertNotNull(smppEndpoint.getCamelContext());
    }

    @Test
    public void createEndpointStringStringMapShouldReturnASmppsEndpoint() throws Exception {
        CamelContext context = new DefaultCamelContext();
        component = new SmppComponent(context);
        Map<String, String> parameters = new HashMap<>();
        parameters.put("password", "secret");
        Endpoint endpoint = component.createEndpoint("smpps://smppclient@localhost:2775", "?password=secret", parameters);
        SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;

        assertEquals("smpps://smppclient@localhost:2775", smppEndpoint.getEndpointUri());
        assertEquals("smpps://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
        assertSame(component, smppEndpoint.getComponent());
        assertNotNull(smppEndpoint.getConfiguration());
        assertEquals("secret", smppEndpoint.getConfiguration().getPassword());
        assertEquals("smpps://smppclient@localhost:2775", smppEndpoint.getConnectionString());
        assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
        assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
        assertNotNull(smppEndpoint.getCamelContext());
    }

    @Test
    public void createEndpointStringStringMapWithoutACamelContextShouldReturnASmppEndpoint() throws Exception {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("password", "secret");
        Endpoint endpoint = component.createEndpoint("smpp://smppclient@localhost:2775", "?password=secret", parameters);
        SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;

        assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointUri());
        assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
        assertSame(component, smppEndpoint.getComponent());
        assertNotNull(smppEndpoint.getConfiguration());
        assertEquals("secret", smppEndpoint.getConfiguration().getPassword());
        assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getConnectionString());
        assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
        assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
        assertNotNull(smppEndpoint.getCamelContext());
    }

    @Test
    public void allowEmptySystemTypeAndServiceTypeOption() throws Exception {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("systemType", null);
        parameters.put("serviceType", null);
        Endpoint endpoint = component.createEndpoint("smpp://smppclient@localhost:2775", "?systemType=&serviceType=", parameters);
        SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;

        assertEquals(null, smppEndpoint.getConfiguration().getSystemType());
        assertEquals(null, smppEndpoint.getConfiguration().getServiceType());
    }

    @Test
    public void createEndpointSmppConfigurationShouldReturnASmppEndpoint() throws Exception {
        SmppConfiguration configuration = new SmppConfiguration();
        Endpoint endpoint = component.createEndpoint(configuration);
        SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;

        assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointUri());
        assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
        assertSame(component, smppEndpoint.getComponent());
        assertSame(configuration, smppEndpoint.getConfiguration());
        assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getConnectionString());
        assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
        assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
        assertNotNull(smppEndpoint.getCamelContext());
    }

    @Test
    public void createEndpointStringSmppConfigurationShouldReturnASmppEndpoint() throws Exception {
        SmppConfiguration configuration = new SmppConfiguration();
        Endpoint endpoint = component.createEndpoint("smpp://smppclient@localhost:2775?password=password", configuration);
        SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;

        assertEquals("smpp://smppclient@localhost:2775?password=password", smppEndpoint.getEndpointUri());
        assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
        assertSame(component, smppEndpoint.getComponent());
        assertSame(configuration, smppEndpoint.getConfiguration());
        assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getConnectionString());
        assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
        assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
        assertNotNull(smppEndpoint.getCamelContext());
    }

    @Test
    public void getterShouldReturnTheSetValues() {
        SmppConfiguration configuration = new SmppConfiguration();
        component.setConfiguration(configuration);

        assertSame(configuration, component.getConfiguration());
    }

    @Test
    public void createEndpointWithSessionStateListener() throws Exception {
        SimpleRegistry registry = new SimpleRegistry();
        registry.put("sessionStateListener", new SessionStateListener() {
            @Override
            public void onStateChange(SessionState arg0, SessionState arg1, Session arg2) {
            }
        });
        context.setRegistry(registry);
        component = new SmppComponent(context);
        SmppEndpoint endpoint = (SmppEndpoint) component.createEndpoint("smpp://smppclient@localhost:2775?password=password&sessionStateListener=#sessionStateListener");

        assertNotNull(endpoint.getConfiguration().getSessionStateListener());
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Hywel-Jones, Mycol. Res. 98(8): 940 (1994)

#### Original name
Cordyceps pseudomilitaris Hywel-Jones & Sivichai

### Remarks
null


text:
void ThomasEngine::Collider::attachedRigidbody::set(Rigidbody^ value)
{
	m_attachedRigidbody = value;
	if (m_attachedRigidbody)
	{
		((thomas::object::component::Collider*)nativePtr)->SetAttachedRigidbody((thomas::object::component::Rigidbody*)value->nativePtr);
	}
	else
	{
		((thomas::object::component::Collider*)nativePtr)->SetAttachedRigidbody(nullptr);
	}
}


text:
package org.apache.flink.runtime.shuffle;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.io.network.ConnectionID;
import org.apache.flink.runtime.io.network.partition.ResultPartitionID;

import java.io.Serializable;
import java.net.InetSocketAddress;
import java.util.Optional;

/**
 * Default implementation of {@link ShuffleDescriptor} for {@link NettyShuffleMaster}.
 */
public class NettyShuffleDescriptor implements ShuffleDescriptor {

	private static final long serialVersionUID = 852181945034989215L;

	private final ResourceID producerLocation;

	private final PartitionConnectionInfo partitionConnectionInfo;

	private final ResultPartitionID resultPartitionID;

	public NettyShuffleDescriptor(
			ResourceID producerLocation,
			PartitionConnectionInfo partitionConnectionInfo,
			ResultPartitionID resultPartitionID) {
		this.producerLocation = producerLocation;
		this.partitionConnectionInfo = partitionConnectionInfo;
		this.resultPartitionID = resultPartitionID;
	}

	public ConnectionID getConnectionId() {
		return partitionConnectionInfo.getConnectionId();
	}

	@Override
	public ResultPartitionID getResultPartitionID() {
		return resultPartitionID;
	}

	@Override
	public Optional<ResourceID> storesLocalResourcesOn() {
		return Optional.of(producerLocation);
	}

	public boolean isLocalTo(ResourceID consumerLocation) {
		return producerLocation.equals(consumerLocation);
	}

	/**
	 * Information for connection to partition producer for shuffle exchange.
	 */
	@FunctionalInterface
	public interface PartitionConnectionInfo extends Serializable {
		ConnectionID getConnectionId();
	}

	/**
	 * Remote partition connection information with index to query partition.
	 *
	 *
Normal connection information with network address and port for connection in case of distributed execution.
	 */
	public static class NetworkPartitionConnectionInfo implements PartitionConnectionInfo {

		private static final long serialVersionUID = 5992534320110743746L;

		private final ConnectionID connectionID;

		@VisibleForTesting
		public NetworkPartitionConnectionInfo(ConnectionID connectionID) {
			this.connectionID = connectionID;
		}

		@Override
		public ConnectionID getConnectionId() {
			return connectionID;
		}

		static NetworkPartitionConnectionInfo fromProducerDescriptor(
				ProducerDescriptor producerDescriptor,
				int connectionIndex) {
			InetSocketAddress address =
				new InetSocketAddress(producerDescriptor.getAddress(), producerDescriptor.getDataPort());
			return new NetworkPartitionConnectionInfo(new ConnectionID(address, connectionIndex));
		}
	}

	/**
	 * Local partition connection information.
	 *
	 *
Does not have any network connection information in case of local execution.
	 */
	public enum LocalExecutionPartitionConnectionInfo implements PartitionConnectionInfo {
		INSTANCE;

		@Override
		public ConnectionID getConnectionId() {
			throw new UnsupportedOperationException("Local execution does not support shuffle connection.");
		}
	}
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Potentilla galantha Soják

### Remarks
null


text:
import { PopupComponent } from "../../widgets/popupComponent";
import { ICellEditorComp, ICellEditorParams } from "../../interfaces/iCellEditor";
import { AgInputTextField } from "../../widgets/agInputTextField";
import { RefSelector } from "../../widgets/componentAnnotations";
import { exists } from "../../utils/generic";
import { isBrowserSafari, isBrowserIE } from "../../utils/browser";
import { KeyCode } from '../../constants/keyCode';

/**
 * useFormatter: used when the cell value needs formatting prior to editing, such as when using reference data and you
 *               want to display text rather than code.
*/
export interface ITextCellEditorParams extends ICellEditorParams {
    useFormatter: boolean;
}

export class TextCellEditor extends PopupComponent implements ICellEditorComp {

    private static TEMPLATE = '
<ag-input-text-field class="ag-cell-editor" ref="eInput"></ag-input-text-field>
';

    private highlightAllOnFocus: boolean;
    private focusAfterAttached: boolean;
    protected params: ICellEditorParams;
    @RefSelector('eInput') protected eInput: AgInputTextField;

    constructor() {
        super(TextCellEditor.TEMPLATE);
    }

    public init(params: ITextCellEditorParams): void {
        this.params = params;

        const eInput = this.eInput;
        let startValue: string;

        // cellStartedEdit is only false if we are doing fullRow editing
        if (params.cellStartedEdit) {
            this.focusAfterAttached = true;

            if (params.keyPress === KeyCode.BACKSPACE || params.keyPress === KeyCode.DELETE) {
                startValue = '';
            } else if (params.charPress) {
                startValue = params.charPress;
            } else {
                startValue = this.getStartValue(params);

                if (params.keyPress !== KeyCode.F2) {
                    this.highlightAllOnFocus = true;
                }
            }

        } else {
            this.focusAfterAttached = false;
            startValue = this.getStartValue(params);
        }

        if (exists(startValue)) {
            eInput.setValue(startValue, true);
        }

        this.addManagedListener(eInput.getGui(), 'keydown', (event: KeyboardEvent) => {
            const { keyCode } = event;

            if (keyCode === KeyCode.PAGE_UP || keyCode === KeyCode.PAGE_DOWN) {
                event.preventDefault();
            }
        });
    }

    public afterGuiAttached(): void {
        const translate = this.gridOptionsWrapper.getLocaleTextFunc();
        const eInput = this.eInput;

        eInput.setInputAriaLabel(translate('ariaInputEditor', 'Input Editor'));

        if (!this.focusAfterAttached) { return; }
        // Added for AG-3238. We can't remove this explicit focus() because Chrome requires an input
        // to be focused before setSelectionRange will work. But it triggers a bug in Safari where
        // explicitly focusing then blurring an empty field will cause the parent container to scroll.
        if (!isBrowserSafari()) {
            eInput.getFocusableElement().focus();
        }

        const inputEl = eInput.getInputElement();

        if (this.highlightAllOnFocus) {
            inputEl.select();
        } else {
            // when we started editing, we want the caret at the end, not the start.
            // this comes into play in two scenarios: a) when user hits F2 and b)
            // when user hits a printable character, then on IE (and only IE) the caret
            // was placed after the first character, thus 'apply' would end up as 'pplea'
            const value = eInput.getValue();
            const len = (exists(value) && value.length) || 0;

            if (len) {
                inputEl.setSelectionRange(len, len);
            }
        }
    }

    // gets called when tabbing trough cells and in full row edit mode
    public focusIn(): void {
        const eInput = this.eInput;
        const focusEl = eInput.getFocusableElement();
        const inputEl = eInput.getInputElement();

        focusEl.focus();
        inputEl.select();
    }

    public focusOut(): void {
        const inputEl = this.eInput.getInputElement();
        if (isBrowserIE()) {
            inputEl.setSelectionRange(0, 0);
        }
    }

    public getValue(): any {
        const eInput = this.eInput;
        return this.params.parseValue(eInput.getValue());
    }

    private getStartValue(params: ITextCellEditorParams) {
        const formatValue = params.useFormatter || params.column.getColDef().refData;
        return formatValue ? params.formatValue(params.value) : params.value;
    }
    public isPopup() {
        return false;
    }
}