text:
import uuid

from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging as messaging
from oslo_messaging.notify import dispatcher as oslo_dispatcher
from oslo_messaging import target
from oslo_utils import timeutils
from sqlalchemy import desc

from murano.common.helpers import token_sanitizer
from murano.db import models
from murano.db.services import environments
from murano.db.services import instances
from murano.db import session
from murano.common.i18n import _LI, _LW
from murano.services import states

CONF = cfg.CONF

RPC_SERVICE = None
NOTIFICATION_SERVICE = None

LOG = logging.getLogger(__name__)

class ResultEndpoint(object):
    @staticmethod
    def process_result(context, result, environment_id):
        secure_result = token_sanitizer.TokenSanitizer().sanitize(result)
        LOG.debug('Got result from orchestration '
                  'engine:\n{result}'.format(result=secure_result))

        model = result['model']
        action_result = result.get('action', {})

        unit = session.get_session()
        environment = unit.query(models.Environment).get(environment_id)

        if not environment:
            LOG.warning(_LW('Environment result could not be handled, '
                            'specified environment not found in database'))
            return

        if model['Objects'] is None and model.get('ObjectsCopy', {}) is None:
            environments.EnvironmentServices.remove(environment_id)
            return

        environment.description = model
        if environment.description['Objects'] is not None:
            environment.description['Objects']['services'] = \
                environment.description['Objects'].pop('applications', [])
            action_name = 'Deployment'
            deleted = False
        else:
            action_name = 'Deletion'
            deleted = True
        environment.version += 1
        environment.save(unit)

        # close deployment
        deployment = get_last_deployment(unit, environment.id)
        deployment.finished = timeutils.utcnow()
        deployment.result = action_result

        num_errors = unit.query(models.Status)\
            .filter_by(level='error', task_id=deployment.id).count()
        num_warnings = unit.query(models.Status)\
            .filter_by(level='warning', task_id=deployment.id).count()

        final_status_text = action_name + ' finished'
        if num_errors:
            final_status_text += " with errors"

        elif num_warnings:
            final_status_text += " with warnings"

        status = models.Status()
        status.task_id = deployment.id
        status.text = final_status_text
        status.level = 'info'
        deployment.statuses.append(status)
        deployment.save(unit)

        # close session
        conf_session = unit.query(models.Session).filter_by(
            **{'environment_id': environment.id,
               'state': states.SessionState.DEPLOYING if not deleted
               else states.SessionState.DELETING}).first()
        if num_errors > 0 or result['action'].get('isException'):
            conf_session.state = \
                states.SessionState.DELETE_FAILURE if deleted else \
                states.SessionState.DEPLOY_FAILURE
        else:
            conf_session.state = states.SessionState.DEPLOYED
        conf_session.save(unit)

        # output application tracking information
        services = []
        objects = model['Objects']
        if objects:
            services = objects.get('services')
        if num_errors + num_warnings > 0:
            LOG.warning(_LW('EnvId: {env_id} TenantId: {tenant_id} Status: '
                            'Failed Apps: {services}')
                        .format(env_id=environment.id,
                                tenant_id=environment.tenant_id,
                                services=services))
        else:
            LOG.info(_LI('EnvId: {env_id} TenantId: {tenant_id} Status: '
                         'Successful Apps: {services}')
                     .format(env_id=environment.id,
                             tenant_id=environment.tenant_id,
                             services=services))

def notification_endpoint_wrapper(priority='info'):
    def wrapper(func):
        class NotificationEndpoint(object):
            def __init__(self):
                setattr(self, priority, self._handler)

            def _handler(self, ctxt, publisher_id, event_type,
                         payload, metadata):
                if event_type == ('murano.%s' % func.__name__):
                    func(payload)

            def __call__(self, payload):
                return func(payload)
        return NotificationEndpoint()
    return wrapper

@notification_endpoint_wrapper()
def track_instance(payload):
    LOG.debug('Got track instance request from orchestration '
              'engine:\n{payload}'.format(payload=payload))
    instance_id = payload['instance']
    instance_type = payload.get('instance_type', 0)
    environment_id = payload['environment']
    unit_count = payload.get('unit_count')
    type_name = payload['type_name']
    type_title = payload.get('type_title')

    instances.InstanceStatsServices.track_instance(
        instance_id, environment_id, instance_type,
        type_name, type_title, unit_count)

@notification_endpoint_wrapper()
def untrack_instance(payload):
    LOG.debug('Got untrack instance request from orchestration '
              'engine:\n{payload}'.format(payload=payload))
    instance_id = payload['instance']
    environment_id = payload['environment']
    instances.InstanceStatsServices.destroy_instance(
        instance_id, environment_id)

@notification_endpoint_wrapper()
def report_notification(report):
    LOG.debug('Got report from orchestration '
              'engine:\n{report}'.format(report=report))

    report['entity_id'] = report['id']
    del report['id']

    status = models.Status()
    status.update(report)

    unit = session.get_session()
    # connect with deployment
    with unit.begin():
        running_deployment = get_last_deployment(unit,
                                                 status.environment_id)
        status.task_id = running_deployment.id
        unit.add(status)

def get_last_deployment(unit, env_id):
    query = unit.query(models.Task) \
        .filter_by(environment_id=env_id) \
        .order_by(desc(models.Task.started))
    return query.first()

def _prepare_rpc_service(server_id):
    endpoints = [ResultEndpoint()]

    transport = messaging.get_transport(CONF)
    s_target = target.Target('murano', 'results', server=server_id)
    return messaging.get_rpc_server(transport, s_target, endpoints, 'eventlet')

def _prepare_notification_service(server_id):
    endpoints = [report_notification, track_instance, untrack_instance]

    transport = messaging.get_transport(CONF)
    s_target = target.Target(topic='murano', server=server_id)
    dispatcher = oslo_dispatcher.NotificationDispatcher(
        [s_target], endpoints, None, True)
    return messaging.MessageHandlingServer(transport, dispatcher, 'eventlet')

def get_rpc_service():
    global RPC_SERVICE

    if RPC_SERVICE is None:
        RPC_SERVICE = _prepare_rpc_service(str(uuid.uuid4()))
    return RPC_SERVICE

def get_notification_service():
    global NOTIFICATION_SERVICE

    if NOTIFICATION_SERVICE is None:
        NOTIFICATION_SERVICE = _prepare_notification_service(str(uuid.uuid4()))
    return NOTIFICATION_SERVICE


text:
date: 2008-12-22 13:47:00+00:00

slug: 9-year-old-cracks-mcse
title: 9 year old cracks MCSE
wordpress_id: 66
categories:
- mcse
- rant
- redhat
---

> A fourth standard girl from rural Tamil Nadu has become the youngest to qualify the Microsoft certified professional examination.</blockquote>

I think it's high time they changed the course material for MCSE. A quick google search will show that the youngest was 10 years old (A Pakistani girl) and many more 10-15 year olds had probably had a go at it too.

[9-year-old TN girl cracks Microsoft exam](http://www.ndtv.com/convergence/ndtv/story.aspx?id=NEWEN20080077337&ch=12/22/2008%209%3A28%3A00%20AM)

On the other hand, the youngest person to crack the RHCE is 12 years old, which makes you think. Also the little boy in question did flunk the first time, which leads me to believe that RHCE is slightly more challenging.

[Twelve Year Old qualifies to wear the Red Hat !](http://www.iosn.net/south-asia/countries/india/news/twelve-year-old-qualifies-to-wear-the-red-hat/)

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<link href="style.css" type="text/css" rel="stylesheet">
<title>RDTSCP—Read Time-Stamp Counter and Processor ID </title>

RDTSCP—Read Time-Stamp Counter and Processor ID

Opcode*
Instruction
Op/En
64-Bit Mode
Compat/Leg Mode
Description

0F 01 F9
RDTSCP
NP
Valid
Valid
Read 64-bit time-stamp counter and IA32_TSC_AUX value into EDX:EAX and ECX.

Instruction Operand Encoding

Op/En
Operand 1
Operand 2
Operand 3
Operand 4

NP
NA
NA
NA
NA

Description

Reads the current value of the processor's time-stamp counter (a 64-bit MSR) into the EDX:EAX registers and also reads the value of the IA32_TSC_AUX MSR (address C0000103H) into the ECX register. The EDX register is loaded with the high-order 32 bits of the IA32_TSC MSR; the EAX register is loaded with the low-order 32 bits of the IA32_TSC MSR; and the ECX register is loaded with the low-order 32-bits of IA32_TSC_AUX MSR. On processors that support the Intel 64 architecture, the high-order 32 bits of each of RAX, RDX, and RCX are cleared.

The processor monotonically increments the time-stamp counter MSR every clock cycle and resets it to 0 whenever the processor is reset. See "Time Stamp Counter" in Chapter 17 of the Intel® 64 and IA-32 Architectures Software Developer's Manual, Volume 3B, for specific details of the time stamp counter behavior.

The time stamp disable (TSD) flag in register CR4 restricts the use of the RDTSCP instruction as follows. When the flag is clear, the RDTSCP instruction can be executed at any privilege level; when the flag is set, the instruction can only be executed at privilege level 0.

The RDTSCP instruction waits until all previous instructions have been executed before reading the counter. However, subsequent instructions may begin execution before the read operation is performed.

See "Changes to Instruction Behavior in VMX Non-Root Operation" in Chapter 25 of the Intel® 64 and IA-32 Archi-tectures Software Developer's Manual, Volume 3C, for more information about the behavior of this instruction in VMX non-root operation.

Operation

IF (CR4.TSD = 0) or (CPL = 0) or (CR0.PE = 0)
    THEN
         EDX:EAX ← TimeStampCounter;
         ECX ← IA32_TSC_AUX[31:0];
    ELSE (* CR4.TSD = 1 and (CPL = 1, 2, or 3) and CR0.PE = 1 *)
         #GP(0);
FI;

Flags Affected

None.

Protected Mode Exceptions

#GP(0)
If the TSD flag in register CR4 is set and the CPL is greater than 0.

#UD

If the LOCK prefix is used.

If CPUID.80000001H:EDX.RDTSCP[bit 27] = 0.

Real-Address Mode Exceptions

#UD

If the LOCK prefix is used.

If CPUID.80000001H:EDX.RDTSCP[bit 27] = 0.

Virtual-8086 Mode Exceptions

#GP(0)
If the TSD flag in register CR4 is set.

#UD

If the LOCK prefix is used.

If CPUID.80000001H:EDX.RDTSCP[bit 27] = 0.

Compatibility Mode Exceptions

Same exceptions as in protected mode.

64-Bit Mode Exceptions

Same exceptions as in protected mode.


text:
class UsersController < ApplicationController
  before_filter :prepare_user

  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:user])

    if @user.save
      redirect_to :action => :index
    else
      render :new
    end
  end

  def edit

  end

  def update
    if @user.update_attributes(params[:user])
      redirect_to :action => :index

    else
      render :edit
    end
  end

  def destroy
    @user.destroy
    redirect_to :action => :index
  end

  private

  def prepare_user
    case action_name
    when "index"
      @users = User.all
    when "new"
      @user = User.create
    when "update", "edit", "destroy"
      @user = User.find(params[:id])
    end
  end
end


text:
const roleFilter = acceptedRoles => (req, res, next) => {
  const roles = [];
  if (!Array.isArray(acceptedRoles)) {
    roles.push(...acceptedRoles.split(' '));
  } else {
    roles.push(...acceptedRoles.join(' ').split(' '));
  }
  if (req.user && req.user.role && roles.length) {
    if (roles.includes(req.user.role)) {
      next();
    } else if (roles.includes('all')) {
      next();
    } else {
      res.status(403).json({ status: 'error', message: 'Forbidden access to user' });
    }
  } else {
    next();
  }
};

export default roleFilter;


text:
How to Unity3D – Configure Project for Android and Run it on Mobile Device
======

![alt text](screenshots/170601181253444.png)

In this tutorial, you start from scratch. You will install Unity3D, Android SDK, then configure a project for Android, and run it on a mobile device.

##

## Steps

* Choose Your Mobile Plateforme
* Install Unity3D and Android Plugin
* Install AndroidWorks
* Install Android Driver (optional)
* Activate Dev Debug mode
* Configure Project
* Build, Run and Play!

## 1. Choose Your Mobile Plateforme

Targeting a technology is always the same. Because it change over time, it's safer to choose the "largest lesser" version (and not the latest) at your product launch to allow you to reach most devices .

Examples:

* 2016: choose Android 4.4, you'll reach 80-90% of the devices.
* 2012: choose Android 2.3.3, you'll reach 70%…
* 2010: choose Android 2.1…

[https://en.wikipedia.org/wiki/Android_version_history](https://en.wikipedia.org/wiki/Android_version_history)
https://en.wikipedia.org/wiki/Android_version_history

![alt text](screenshots/170601181253618.png)

![alt text](screenshots/170601181253685.png)

## 2. Install Unity3D And Android Plugin (Windows)

Unity3D and his Android package is needed.

* download your installer (perso, pro, etc)
* run installer
* choose components Example Project Android Build Support
* Wait for download to complete (4 Go)

![alt text](screenshots/170601181253716.png)

![alt text](screenshots/170601181253758.png)

![alt text](screenshots/170601181253785.png)

![alt text](screenshots/170601181253817.png)

![alt text](screenshots/170601181253847.png)

![alt text](screenshots/170601181253878.png)

![alt text](screenshots/170601181253913.png)

![alt text](screenshots/170601181253944.png)

![alt text](screenshots/170601181253976.png)

## 3. Install AndroidWorks (Windows)

You need to install Android SDK for Unity3D compatibility (API 23/Android6.0 for Unity3D 5.6) and for your target devices (API 19/Android 4.4.2)

* got to https://developer.nvidia.com/codeworks-android Create and Nvidia account download codeworks for Windows 64
* install
* wait for manager popup after download stage check install Unity3D android target Version (6.0). check install your android target Version (4.4). uncheck NVidia stuff like Android NDK, Developer Tools check  auto resolve click next
* ignore warnings
* accepts licences
* wait for download to complete (12 Go)

![alt text](screenshots/170601181254212.png)

![alt text](screenshots/170601181254247.png)

![alt text](screenshots/170601181254279.png)

![alt text](screenshots/170601181254353.png)

![alt text](screenshots/170601181254398.png)

![alt text](screenshots/170601181254427.png)

![alt text](screenshots/170601181254457.png)

![alt text](screenshots/170601181254486.png)

![alt text](screenshots/170601181254516.png)

![alt text](screenshots/170601181254545.png)

![alt text](screenshots/170601181254574.png)

![alt text](screenshots/170601181254604.png)

![alt text](screenshots/170601181254635.png)

![alt text](screenshots/170601181254686.png)

## 4. Install Android USB Driver (Windows)

Sometimes, to enable debug mode, you need to install a specific USB driver for your phone.

[https://developer.android.com/studio/run/win-usb.html](https://developer.android.com/studio/run/win-usb.html)
https://developer.android.com/studio/run/win-usb.html

![alt text](screenshots/170601181254745.png)

## 5. Activate Dev Debug Mode (Android)

Settings > About Phone > Build number > Tap it 7 times to become developer;

Settings > Developer Options > USB Debugging.

[https://www.kingoapp.com/root-tutorials/how-to-enable-usb-debugging-mode-on-android.htm](https://www.kingoapp.com/root-tutorials/how-to-enable-usb-debugging-mode-on-android.htm)
https://www.kingoapp.com/root-tutorials/how-to-enable-usb-debugging-mode-on-android.htm

![alt text](screenshots/170601181254779.png)

![alt text](screenshots/170601181254817.png)

## 6. Configure Project (Unity3d)

We will use the "Standard Assets Example Project", but limit to only ONE scene because of the load of the entire project during deployment to the mobile device (one scene is 30sec, all scenes is 10min).

* Open the Unity3d project Update Build Settings
Check only ONE project Choose Android, with dev build
* Update Player Settings Select Android Choose targets API (ex 4.4)
* Test it locally (Windows)
* Save

![alt text](screenshots/170601181254863.png)

![alt text](screenshots/170601181254892.png)

![alt text](screenshots/170601181254977.png)

![alt text](screenshots/170601181255014.png)

![alt text](screenshots/170601181255049.png)

![alt text](screenshots/170601181255078.png)

![alt text](screenshots/170601181255107.png)

![alt text](screenshots/170601181255137.png)

![alt text](screenshots/170601181255177.png)

![alt text](screenshots/170601181255263.png)

![alt text](screenshots/170601181255293.png)

![alt text](screenshots/170601181255394.png)

![alt text](screenshots/170601181255425.png)

![alt text](screenshots/170601181255526.png)

## 7. Build, Run and Play!

Project and device are ready.

* Build and Run
* Choose APK name, Save
* Autorise usb debug on for device from android
* Wait for deployment ('Hold On' popup)
* Play!
* Get APK from Project folder (on Windows, 'Example Project.apk')

![alt text](screenshots/170601181255560.png)

![alt text](screenshots/170601181255598.png)

![alt text](screenshots/170601181255636.png)

![alt text](screenshots/170601181255664.png)

![alt text](screenshots/170601181255703.png)

![alt text](screenshots/170601181255732.png)

![alt text](screenshots/170601181255761.png)

![alt text](screenshots/170601181255811.png)

![alt text](screenshots/170601181255877.png)

![alt text](screenshots/170601181255966.png)

![alt text](screenshots/170601181256066.png)

![alt text](screenshots/170601181256103.png)

##  Conclusion

AndroidWorks provide a simple way to install and manage android sdk installation.

Choosing Android version first is better, because latter it's harder to do that latter in the project: you can run into Unity3D API changes, or bugs in your game, and you don't want to do that just before your final release!

These example have been tested on multiple devices:

* LG G4 (2015) Android 6.x high specs
* Samsung Galaxy A5 (2016) Android 7.x low specs no gyro

If you change your mind about the Android Version, just relaunch AndroidWorks.

![alt text](screenshots/170601181256153.png)

## Source

[https://github.com/DamienFremont/blog/tree/master/20170601-unity3d-configure-project-for-android-and-run-it](https://github.com/DamienFremont/blog/tree/master/20170601-unity3d-configure-project-for-android-and-run-it)
https://github.com/DamienFremont/blog/tree/master/20170601-unity3d-configure-project-for-android-and-run-it

## References

[https://en.wikipedia.org/wiki/Android_version_history](https://en.wikipedia.org/wiki/Android_version_history)
https://en.wikipedia.org/wiki/Android_version_history

[https://store.unity.com](https://store.unity.com)
https://store.unity.com

[https://docs.nvidia.com/gameworks/content/developertools/mobile/androidworks/androidworks_install.htm](https://docs.nvidia.com/gameworks/content/developertools/mobile/androidworks/androidworks_install.htm)
https://docs.nvidia.com/gameworks/content/developertools/mobile/androidworks/androidworks_install.htm

[https://developer.android.com/studio/run/win-usb.html](https://developer.android.com/studio/run/win-usb.html)
https://developer.android.com/studio/run/win-usb.html

[https://www.kingoapp.com/root-tutorials/how-to-enable-usb-debugging-mode-on-android.htm](https://www.kingoapp.com/root-tutorials/how-to-enable-usb-debugging-mode-on-android.htm)
https://www.kingoapp.com/root-tutorials/how-to-enable-usb-debugging-mode-on-android.htm

## Origin
[https://damienfremont.com/2017/06/01/how-to-unity3d-configure-project-for-android-and-run-it-on-mobile-device/](https://damienfremont.com/2017/06/01/how-to-unity3d-configure-project-for-android-and-run-it-on-mobile-device/)


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

  <meta name="description" content="Javadoc API documentation for Urban Airship Android Library." />

<link rel="shortcut icon" type="image/x-icon" href="../../../favicon.ico" />
<title>

  com.urbanairship.actions

| Urban Airship Android Library

</title>
<link href="../../../../assets/doclava-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../../../../assets/customizations.css" rel="stylesheet" type="text/css" />

      Urban Airship Android Library

          <form accept-charset="utf-8" class="gsc-search-box"
                onsubmit="return submit_search()">

                    <input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
                      title="search developer docs" name="q"
                      value="search developer docs"
                      onFocus="search_focus_changed(this, true)"
                      onBlur="search_focus_changed(this, false)"
                      onkeydown="return search_changed(event, true, '../../../')"
                      onkeyup="return search_changed(event, false, '../../../')" />

                    <input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" />

          </form>

                Package Index |
                Class Index

  com.urbanairship

  com.urbanairship.actions

  com.urbanairship.actions.tags

  com.urbanairship.amazon

  com.urbanairship.analytics

  com.urbanairship.google

  com.urbanairship.js

  com.urbanairship.location

  com.urbanairship.preference

  com.urbanairship.push

  com.urbanairship.push.notifications

  com.urbanairship.richpush

  com.urbanairship.widget

Interfaces

ActionCompletionCallback

Classes

Action

Action.ActivityResult

ActionActivity

ActionArguments

ActionArguments.Builder

ActionRegistry

ActionRegistry.Entry

ActionResult

ActionRunner

ActionService

ActionUtils

AddCustomEventAction

DeepLinkAction

LandingPageAction

LandingPageActivity

OpenExternalUrlAction

ShareAction

Enums

ActionResult.Status

Situation

            Package Index |
            Class Index

  package

com.urbanairship.actions

    The Urban Airship Actions Framework.

Interfaces

              ActionCompletionCallback
              An interface for callbacks signaling the completion of an
 Action.

Classes

              Action
              The base action class that describes an operation to perform.

              Action.ActivityResult
              Wraps the result code and data from starting an activity
 for a result.

              ActionActivity
              An activity that is used by the Action framework to enable starting other activities
 for results.

              ActionArguments
              Container for the argument data passed to an Action.

              ActionArguments.Builder
              Action argument builder.

              ActionRegistry
              Class responsible for runtime-persisting actions and associating them
 with names and predicates.

              ActionRegistry.Entry
              An entry in the action registry.

              ActionResult
              Stores the results of running an Action.

              ActionRunner
              A helper class for running an Action.

              ActionService
              Service class for running actions via push payload.

              ActionUtils
              Utility methods related to actions.

              AddCustomEventAction
              An action that adds a custom event.

              DeepLinkAction
              Action for opening a deep link.

              LandingPageAction
              Action for launching a Landing Page.

              LandingPageActivity
              An activity that displays a landing page.

              OpenExternalUrlAction
              Action for opening a URL for viewing.

              ShareAction
              Shows a chooser activity to share text.

Enums

              ActionResult.Status
              The run status of the action.

              Situation
              An enum representing the possible situations for an Action.

Urban Airship Android Library v. 5.0.1


text:
<?php

namespace Mautic\SmsBundle\Entity;

use Doctrine\ORM\Query;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Mautic\CoreBundle\Entity\CommonRepository;

/**
 * Class SmsRepository
 *
 * @package Mautic\SmsBundle\Entity
 */
class SmsRepository extends CommonRepository
{
    /**
     * Get a list of entities
     *
     * @param array      $args
     * @return Paginator
     */
    public function getEntities($args = array())
    {
        $q = $this->_em
            ->createQueryBuilder()
            ->select('e')
            ->from('MauticSmsBundle:Sms', 'e', 'e.id');
        if (empty($args['iterator_mode'])) {
            $q->leftJoin('e.category', 'c');
        }

        $args['qb'] = $q;

        return parent::getEntities($args);
    }

    /**
     * Get amounts of sent and read emails
     *
     * @return array
     */
    public function getSentCount()
    {
        $q = $this->_em->createQueryBuilder();
        $q->select('SUM(e.sentCount) as sent_count')
            ->from('MauticSmsBundle:Sms', 'e');
        $results = $q->getQuery()->getSingleResult(Query::HYDRATE_ARRAY);

        if (!isset($results['sent_count'])) {
            $results['sent_count'] = 0;
        }

        return $results;
    }

    /**
     * @param QueryBuilder $q
     * @param              $filter
     * @return array
     */
    protected function addSearchCommandWhereClause(&$q, $filter)
    {
        $command         = $filter->command;
        $unique          = $this->generateRandomParameterName();
        $returnParameter = true; //returning a parameter that is not used will lead to a Doctrine error
        $expr            = false;
        switch ($command) {
            case $this->translator->trans('mautic.core.searchcommand.ispublished'):
                $expr = $q->expr()->eq("e.isPublished", ":$unique");
                $forceParameters = array($unique => true);
                break;
            case $this->translator->trans('mautic.core.searchcommand.isunpublished'):
                $expr = $q->expr()->eq("e.isPublished", ":$unique");
                $forceParameters = array($unique => true);
                break;
            case $this->translator->trans('mautic.core.searchcommand.isuncategorized'):
                $expr = $q->expr()->orX(
                    $q->expr()->isNull('e.category'),
                    $q->expr()->eq('e.category', $q->expr()->literal(''))
                );
                $returnParameter = false;
                break;
            case $this->translator->trans('mautic.core.searchcommand.ismine'):
                $expr = $q->expr()->eq("IDENTITY(e.createdBy)", $this->currentUser->getId());
                $returnParameter = false;
                break;
            case $this->translator->trans('mautic.core.searchcommand.category'):
                $expr = $q->expr()->like('e.alias', ":$unique");
                $filter->strict = true;
                break;
            case $this->translator->trans('mautic.core.searchcommand.lang'):
                $langUnique       = $this->generateRandomParameterName();
                $langValue        = $filter->string . "_%";
                $forceParameters = array(
                    $langUnique => $langValue,
                    $unique     => $filter->string
                );
                $expr = $q->expr()->orX(
                    $q->expr()->eq('e.language', ":$unique"),
                    $q->expr()->like('e.language', ":$langUnique")
                );
                break;
        }

        if ($expr && $filter->not) {
            $expr = $q->expr()->not($expr);
        }

        if (!empty($forceParameters)) {
            $parameters = $forceParameters;
        } elseif (!$returnParameter) {
            $parameters = array();
        } else {
            $string     = ($filter->strict) ? $filter->string : "%{$filter->string}%";
            $parameters = array("$unique" => $string);
        }

        return array( $expr, $parameters );
    }

    /**
     * @return array
     */
    public function getSearchCommands()
    {
        return array(
            'mautic.core.searchcommand.ispublished',
            'mautic.core.searchcommand.isunpublished',
            'mautic.core.searchcommand.isuncategorized',
            'mautic.core.searchcommand.ismine',
            'mautic.core.searchcommand.category',
            'mautic.core.searchcommand.lang'
        );
    }

    /**
     * @return string
     */
    protected function getDefaultOrder()
    {
        return array(
            array('e.name', 'ASC')
        );
    }

    /**
     * @return string
     */
    public function getTableAlias()
    {
        return 'e';
    }

    /**
     * Up the click/sent counts
     *
     * @param            $id
     * @param string     $type
     * @param int        $increaseBy
     */
    public function upCount($id, $type = 'sent', $increaseBy = 1)
    {
        try {
            $q = $this->_em->getConnection()->createQueryBuilder();

            $q->update(MAUTIC_TABLE_PREFIX.'sms_messages')
                ->set($type.'_count', $type.'_count + '.(int) $increaseBy)
                ->where('id = '.(int) $id);

            $q->execute();
        } catch (\Exception $exception) {
            // not important
        }
    }

    /**
     * @param string $search
     * @param int    $limit
     * @param int    $start
     * @param bool   $viewOther
     * @param string $smsType
     *
     * @return array
     */
    public function getSmsList($search = '', $limit = 10, $start = 0, $viewOther = false, $smsType = null)
    {
        $q = $this->createQueryBuilder('e');
        $q->select('partial e.{id, name, language}');

        if (!empty($search)) {
            $q->andWhere($q->expr()->like('e.name', ':search'))
                ->setParameter('search', "{$search}%");
        }

        if (!$viewOther) {
            $q->andWhere($q->expr()->eq('e.createdBy', ':id'))
                ->setParameter('id', $this->currentUser->getId());
        }

        if (!empty($smsType)) {
            $q->andWhere(
                $q->expr()->eq('e.smsType', $q->expr()->literal($smsType))
            );
        }

        $q->orderBy('e.name');

        if (!empty($limit)) {
            $q->setFirstResult($start)
                ->setMaxResults($limit);
        }

        return $q->getQuery()->getArrayResult();
    }
}


text:
import random

import requests
from lxml import etree
from fake_useragent import UserAgent

from spider.encrypt import gen_data
from config import PROXIES

TIMEOUT = 5

def choice_proxy():
    if PROXIES:
        return random.choice(PROXIES + [''])
    return ''

def get_user_agent():
    ua = UserAgent()
    return ua.random

def fetch(url, retry=0):
    s = requests.Session()
    proxies = {
        'http': choice_proxy()
    }
    s.headers.update({'user-agent': get_user_agent(),
                      'referer': 'http://music.163.com/'})
    try:
        return s.get(url, timeout=TIMEOUT, proxies=proxies)
    except requests.exceptions.RequestException:
        if retry < 3:
            return fetch(url, retry=retry + 1)
        raise

def post(url):
    headers = {
        'Cookie': 'appver=1.5.0.75771;',
        'Referer': 'http://music.163.com/'
    }

    return requests.post(url, headers=headers, data=gen_data())

def get_tree(url):
    r = fetch(url)
    return etree.HTML(r.text)


text:
/*
 * Exemplo swtich
 *
 * @author André Ferreira <andrehrf@gmail.com>
 */

var signo = "peixe";

switch(signo){
    case "aries":
        console.log("O Sol começa sua caminhada através de Câncer e se une a Vênus deixando você mais fechado e...");
    break;
    case "touro":
        console.log("O Sol começa sua caminhada através de Câncer e se une a Vênus, seu regente, beneficiando...");
    break;
    case "gemeos":
        console.log("O Sol começa sua caminhada através de Câncer e se une a Vênus indicando uma fase de maior...");
    break;
    default:
        console.log("Singo não encontrado");
    break;
}


text:
ALTER TABLE IDN_OAUTH2_SCOPE MODIFY SCOPE_ID INTEGER NOT NULL AUTO_INCREMENT;
ALTER TABLE IDN_OAUTH2_SCOPE CHANGE COLUMN `NAME` `DISPLAY_NAME` VARCHAR(255) NOT NULL;
ALTER TABLE IDN_OAUTH2_SCOPE CHANGE COLUMN `SCOPE_KEY` `NAME` VARCHAR(255) NOT NULL;
ALTER TABLE IDN_OAUTH2_SCOPE DROP COLUMN ROLES;
UPDATE IDN_OAUTH2_SCOPE SET TENANT_ID = -1 WHERE TENANT_ID = 0;
ALTER TABLE IDN_OAUTH2_SCOPE MODIFY TENANT_ID INTEGER NOT NULL DEFAULT -1;
-- CREATE UNIQUE INDEX SCOPE_INDEX ON IDN_OAUTH2_SCOPE (NAME, TENANT_ID);

SELECT CONCAT("ALTER TABLE IDN_OAUTH2_RESOURCE_SCOPE DROP FOREIGN KEY ",CONSTRAINT_NAME)
INTO @sqlst
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = "IDN_OAUTH2_RESOURCE_SCOPE"
AND REFERENCED_TABLE_NAME = "IDN_OAUTH2_SCOPE" AND REFERENCED_COLUMN_NAME = "SCOPE_ID" ;

PREPARE stmt FROM @sqlst;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @sqlstr = NULL;

ALTER TABLE IDN_OAUTH2_RESOURCE_SCOPE MODIFY SCOPE_ID INTEGER NOT NULL;
ALTER TABLE IDN_OAUTH2_RESOURCE_SCOPE ADD FOREIGN KEY (SCOPE_ID) REFERENCES IDN_OAUTH2_SCOPE(SCOPE_ID) ON DELETE CASCADE;


text: from .googleplus_comments import *


text:
import pkgutil
import os
from .driver import abstractDriver
__all__ = []
for loader, module_name, is_pkg in pkgutil.walk_packages(__path__):
    __all__.append(module_name)
    module = loader.find_module(module_name).load_module(module_name)
    exec('%s = module' % module_name)

driverList = []
path = os.path.dirname(os.path.abspath(__file__))
for py in [f[:-3] for f in os.listdir(path) if f.endswith('.py') and f != '__init__.py']:
    mod = __import__('.'.join([__name__, py]), fromlist=[py])
    classes = [getattr(mod, x) for x in dir(mod) if isinstance(getattr(mod, x), type)]
    for cls in classes:
        if issubclass(cls, abstractDriver):
            driverList.append(cls())


text:
namespace base
{
/// A cross-platform replacenemt of gmtime_r
std::tm GmTime(time_t const time);
}  // namespace base


text:
BEGIN_INANITY_GRAPHICS

/// Класс монитора Win32.
class Win32Monitor : public Monitor
{
private:
	DISPLAY_DEVICE info;
	String deviceName;
	String deviceString;
	MonitorModes modes;
	bool modesInitialized;

public:
	Win32Monitor(const DISPLAY_DEVICE& info);

	//*** методы Monitor
	String GetId() const;
	String GetName() const;
	const MonitorModes& GetModes();
	ptr<MonitorMode> TryCreateMode(int width, int height);
	ptr<Platform::Window> CreateDefaultWindow(const String& title, int width, int height);
	RECT GetRect() const;
};

END_INANITY_GRAPHICS

#endif


text:
require_relative './direction'
require_relative './position'

module MarsRover

  class RoverError < StandardError; end

	class Rover

    attr_accessor :x, :y, :direction, :plateau

    def initialize(x, y, direction, plateau)
      self.x = x
      self.y = y
      self.direction = direction
      self.plateau = plateau

      raise RoverError unless valid_position?
    end

    def turn_right
      MarsRover::Direction.turn_right(self)
    end

    def turn_left
      MarsRover::Direction.turn_left(self)
    end

    def move
      MarsRover::Position.move(self)
    end

    def run_command(command)
      case command
      when 'L'
        turn_left
      when 'R'
        turn_right
      when 'M'
        move
      end
    end

    private
    def valid_position?
      x <= plateau.x_upper_limit &&
      x >= plateau.x_lower_limit &&
      y <= plateau.y_upper_limit &&
      y >= plateau.y_lower_limit
    end
  end

end


text:
package com.google.tmch.util;

public class DateUtil {
	public static String getThaiCurrentTime(){
		java.text.SimpleDateFormat thaiCurrentTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss",new java.util.Locale("th","TH"));
	      System.out.println(thaiCurrentTime.format(new java.util.Date()));
		return thaiCurrentTime.format(new java.util.Date());
	}
}


text:
@interface ZXContentViewController ()<UITextViewDelegate,UIActionSheetDelegate>

@end

@implementation ZXContentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%s [LINE:%d]", __func__, __LINE__);
    [self createTextView];

}

# pragma mark ------注册观察者:改变字体
-(void)viewWillAppear:(BOOL)animated{
     NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(changeTextViewFontSize:) name:@"changeFontSize" object:nil];
}

-(void)changeTextViewFontSize:(NSNotification *)notification{

    NSDictionary *dic = notification.userInfo;

    UITextView *tv = (UITextView *)[self.view viewWithTag:300];

    tv.font = [UIFont systemFontOfSize:[dic[@"fontSize"] integerValue]];
    //[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)createTextView{
    UITextView *tv = [[UITextView alloc]init];
    tv.tag = 300;
    tv.frame = CGRectMake(10, 40, 300, 200);
    tv.backgroundColor = [UIColor colorWithRed:200./255. green:200./255. blue:200/255. alpha:0.5];
    [tv.layer setMasksToBounds:YES];
    [tv.layer setCornerRadius:10];
    tv.text = @"老码农冒死揭开行业黑幕:[如何编写无法维护的代码]为了造福大众,在编程领域创造就业机会,兄弟在此传授大师秘籍。这些大师写的代码极其难以维护,后继者就是想对它做最简单的修改都需要花上数年时间";
    [self.view addSubview:tv];

    //添加一个工具栏
    UIBarButtonItem *finish = [[UIBarButtonItem alloc]initWithTitle:@"done"
                                                              style:UIBarButtonItemStylePlain
                                                             target:self
                                                             action:@selector(clickedFinish:)];
    UIBarButtonItem *clean = [[UIBarButtonItem alloc]initWithTitle:@"clean"
                                                             style:UIBarButtonItemStylePlain
                                                            target:self
                                                            action:@selector(clickedClean:)];
    UIToolbar *toolBar = [[UIToolbar alloc]init];
    toolBar.frame = CGRectMake(0, 0, 320, 44);
    toolBar.items = @[finish,clean];

    tv.inputAccessoryView = toolBar;
    tv.delegate = self;//
    [self.view addSubview:tv];
}
-(void)clickedFinish:(UIBarButtonItem *)finish{
    UITextView *tv = (UITextView *)[self.view viewWithTag:300];
    [tv resignFirstResponder];
    [self shareButtonClicked];

}

-(void)shareButtonClicked{
    UIActionSheet *as = [[UIActionSheet alloc] initWithTitle:@"share"
                                                    delegate:nil
                                           cancelButtonTitle:@"cancle"
                         //                                      destructiveButtonTitle:@"error tips"
                                      destructiveButtonTitle:nil
                                           otherButtonTitles:@"sina",@"weixin",@"momo",nil];
    as.delegate = self;
    [as showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    UITextView *tv = (UITextView *)[self.view viewWithTag:300];
    NSLog(@"%s [LINE:%d] \n成功分享了内容:\n\t%@ \n到--->%@",
          __func__,
          __LINE__,
          tv.text,
          [actionSheet buttonTitleAtIndex:buttonIndex]);
}

-(void)clickedClean:(UIBarButtonItem *)clean{
    UITextView *tv = (UITextView *)[self.view viewWithTag:300];
    tv.text = @"";
}

@end


text:
[role=checkbox] {
    cursor: pointer;
    display: inline-block;
}

[role=checkbox] .icon:before {
    content: '\2610';
    display: inline-block;
    font-size: 2em;
    line-height: 1;
    vertical-align: middle;
    speak: none;
}

[role=checkbox].active .icon:before {
    content: '\2611';
}

pre {
    white-space: pre-wrap;
}


text:
package io.opentelemetry.exporter.internal.auth;

import io.opentelemetry.exporter.internal.grpc.GrpcExporterBuilder;
import io.opentelemetry.exporter.internal.okhttp.OkHttpExporterBuilder;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * This class is internal and is hence not for public use. Its APIs are unstable and can change at
 * any time.
 *
 * <p>Allow users of OTLP-OkHttp exporters to add support for authentication.
 */
public interface Authenticator {

  /**
   * Method called by the exporter to get headers to be used on a request that requires
   * authentication.
   *
   * @return Headers to add to the request
   */
  Map<String, String> getHeaders();

  /**
   * Reflectively access a {@link GrpcExporterBuilder}, or {@link OkHttpExporterBuilder} instance in
   * field called "delegate" of the instance, and set the {@link Authenticator}.
   *
   * @param builder export builder to modify
   * @param authenticator authenticator to set on builder
   * @throws IllegalArgumentException if the instance does not contain a field called "delegate" of
   *     a supported type.
   */
  static void setAuthenticatorOnDelegate(Object builder, Authenticator authenticator) {
    try {
      Field field = builder.getClass().getDeclaredField("delegate");
      field.setAccessible(true);
      Object value = field.get(builder);
      if (value instanceof GrpcExporterBuilder) {
        throw new IllegalArgumentException("GrpcExporterBuilder not supported yet.");
      } else if (value instanceof OkHttpExporterBuilder) {
        ((OkHttpExporterBuilder<?>) value).setAuthenticator(authenticator);
      } else {
        throw new IllegalArgumentException(
            "Delegate field is not type DefaultGrpcExporterBuilder or OkHttpGrpcExporterBuilder.");
      }
    } catch (NoSuchFieldException | IllegalAccessException e) {
      throw new IllegalArgumentException("Unable to access delegate reflectively.", e);
    }
  }
}


text:
(function () {
  'use strict';

  angular
    .module('nocbeo-ui')
    .factory('paginationHelper', paginationHelperService);

  /*
   * @ngInject
   */
  function paginationHelperService (PAGE_SIZE, $location, $q) {
    var defaults = function(total, page, pageSize) {
      return {
        total: total || 0,
        limit: pageSize || PAGE_SIZE,
        page: page || $location.search().page || 1
      };
    };

    function create(onChange, count, page, pageSize) {
      return $q(function(resolve, reject) {
        count().then(function(results) {
          var pagination = new defaults(results.data.count, page, pageSize);
          pagination.onChange = function() {
            $location.search('page', this.page);
            count().then(function(results) {
              pagination.total = results.data.count;
            });
            return onChange();
          };
          if (pagination.page > 1) {
            onChange(pagination.page, pagination.limit);
          }
          return resolve(pagination);
        }, reject);
      });

    }

    // Interface
    return {
      create: create
    };
  }

})();


text:
package com.hazelcast.ringbuffer.impl.operations;

import com.hazelcast.core.IFunction;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.impl.Versioned;
import com.hazelcast.ringbuffer.impl.ReadResultSetImpl;
import com.hazelcast.ringbuffer.impl.RingbufferContainer;
import com.hazelcast.spi.BlockingOperation;
import com.hazelcast.spi.ReadonlyOperation;
import com.hazelcast.spi.WaitNotifyKey;

import java.io.IOException;

import static com.hazelcast.ringbuffer.impl.RingbufferDataSerializerHook.READ_MANY_OPERATION;

public class ReadManyOperation<O> extends AbstractRingBufferOperation
        implements BlockingOperation, ReadonlyOperation, Versioned {
    transient long sequence;

    private int minSize;
    private int maxSize;
    private long startSequence;
    private IFunction<O, Boolean> filter;

    private transient ReadResultSetImpl<O, O> resultSet;

    public ReadManyOperation() {
    }

    public ReadManyOperation(String name, long startSequence, int minSize, int maxSize, IFunction<O, Boolean> filter) {
        super(name);
        this.minSize = minSize;
        this.maxSize = maxSize;
        this.startSequence = startSequence;
        this.filter = filter;
    }

    @Override
    public void beforeRun() {
        RingbufferContainer ringbuffer = getRingBufferContainer();
        ringbuffer.checkBlockableReadSequence(startSequence);
    }

    @Override
    public boolean shouldWait() {
        if (resultSet == null) {
            resultSet = new ReadResultSetImpl<O, O>(minSize, maxSize, getNodeEngine().getSerializationService(), filter);
            sequence = startSequence;
        }

        RingbufferContainer ringbuffer = getRingBufferContainer();
        if (minSize == 0) {
            if (!ringbuffer.shouldWait(sequence)) {
                sequence = ringbuffer.readMany(sequence, resultSet);
            }

            return false;
        }

        if (resultSet.isMinSizeReached()) {
            // enough items have been read, we are done.
            return false;
        }

        if (ringbuffer.isTooLargeSequence(sequence) || ringbuffer.isStaleSequence(sequence)) {
            //no need to wait, let the operation continue and fail in beforeRun
            return false;
        }
        if (sequence == ringbuffer.tailSequence() + 1) {
            // the sequence is not readable
            return true;
        }
        sequence = ringbuffer.readMany(sequence, resultSet);
        return !resultSet.isMinSizeReached();
    }

    @Override
    public void run() throws Exception {
        // no-op; we already did the work in the shouldWait method.
    }

    @Override
    public Object getResponse() {
        return resultSet;
    }

    @Override
    public WaitNotifyKey getWaitKey() {
        RingbufferContainer ringbuffer = getRingBufferContainer();
        return ringbuffer.getRingEmptyWaitNotifyKey();
    }

    @Override
    public void onWaitExpire() {
        //todo:
    }

    @Override
    public int getId() {
        return READ_MANY_OPERATION;
    }

    @Override
    protected void writeInternal(ObjectDataOutput out) throws IOException {
        super.writeInternal(out);
        out.writeLong(startSequence);
        out.writeInt(minSize);
        out.writeInt(maxSize);
        out.writeObject(filter);
    }

    @Override
    protected void readInternal(ObjectDataInput in) throws IOException {
        super.readInternal(in);
        startSequence = in.readLong();
        minSize = in.readInt();
        maxSize = in.readInt();
        filter = in.readObject();
    }
}


text:
using System;
using Android.OS;

namespace Repository.Internal.Threading
{
    internal static class ThreadingUtilities
    {
        /// <summary>
        /// A <see cref="Handler"/> associated with the UI thread.
        /// </summary>
        private static Handler UIThreadHandler { get; } = new Handler(Looper.MainLooper);

        /// <summary>
        /// Posts an action to the UI thread.
        /// </summary>
        /// <param name="action">The action.</param>
        public static bool PostToUIThread(Action action) => UIThreadHandler.Post(action);
    }
}


text:
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Linq;

using ICSharpCode.AvalonEdit.Document;

namespace ICSharpCode.AvalonEdit.Xml
{
	/// <summary>
	/// Represents any markup starting with "<" and (hopefully) ending with ">"
	/// </summary>
	public class AXmlTag: AXmlContainer
	{
		/// <summary> These identify the start of DTD elements </summary>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification="ReadOnlyCollection is immutable")]
		public static readonly ReadOnlyCollection<string> DtdNames = new ReadOnlyCollection<string>(
			new string[] {"<!DOCTYPE", "<!NOTATION", "<!ELEMENT", "<!ATTLIST", "<!ENTITY" } );

		/// <summary> Opening bracket - usually "<" </summary>
		public string OpeningBracket { get; internal set; }
		/// <summary> Name following the opening bracket </summary>
		public string Name { get; internal set; }
		/// <summary> Opening bracket - usually ">" </summary>
		public string ClosingBracket { get; internal set; }

		/// <summary> True if tag starts with "<" </summary>
		public bool IsStartOrEmptyTag       { get { return OpeningBracket == "<"; } }
		/// <summary> True if tag starts with "<" and ends with ">" </summary>
		public bool IsStartTag              { get { return OpeningBracket == "<" && ClosingBracket == ">"; } }
		/// <summary> True if tag starts with "<" and does not end with ">" </summary>
		public bool IsEmptyTag              { get { return OpeningBracket == "<" && ClosingBracket != ">" ; } }
		/// <summary> True if tag starts with "</" </summary>
		public bool IsEndTag                { get { return OpeningBracket == "</"; } }
		/// <summary> True if tag starts with "<?" </summary>
		public bool IsProcessingInstruction { get { return OpeningBracket == "<?"; } }
		/// <summary> True if tag starts with "<!--" </summary>
		public bool IsComment               { get { return OpeningBracket == "<!--"; } }
		/// <summary> True if tag starts with "<![CDATA[" </summary>
		public bool IsCData                 { get { return OpeningBracket == "<![CDATA["; } }
		/// <summary> True if tag starts with one of the DTD starts </summary>
		public bool IsDocumentType          { get { return DtdNames.Contains(OpeningBracket); } }
		/// <summary> True if tag starts with "<!" </summary>
		public bool IsUnknownBang           { get { return OpeningBracket == "<!"; } }

		#region Helpper methods

		AXmlAttributeCollection attributes;

		/// <summary> Gets attributes of the tag (if applicable) </summary>
		public AXmlAttributeCollection Attributes {
			get {
				if (attributes == null) {
					attributes = new AXmlAttributeCollection(this.Children);
				}
				return attributes;
			}
		}

		#endregion

		internal override void DebugCheckConsistency(bool checkParentPointers)
		{
			Assert(OpeningBracket != null, "Null OpeningBracket");
			Assert(Name != null, "Null Name");
			Assert(ClosingBracket != null, "Null ClosingBracket");
			base.DebugCheckConsistency(checkParentPointers);
		}

		/// <inheritdoc/>
		public override void AcceptVisitor(IAXmlVisitor visitor)
		{
			visitor.VisitTag(this);
		}

		/// <inheritdoc/>
		internal override bool UpdateDataFrom(AXmlObject source)
		{
			if (!base.UpdateDataFrom(source)) return false;
			AXmlTag src = (AXmlTag)source;
			if (this.OpeningBracket != src.OpeningBracket ||
				this.Name != src.Name ||
				this.ClosingBracket != src.ClosingBracket)
			{
				OnChanging();
				this.OpeningBracket = src.OpeningBracket;
				this.Name = src.Name;
				this.ClosingBracket = src.ClosingBracket;
				OnChanged();
				return true;
			} else {
				return false;
			}
		}

		/// <inheritdoc/>
		public override string ToString()
		{
			return string.Format(CultureInfo.InvariantCulture, "[{0} '{1}{2}{3}' Attr:{4}]", base.ToString(), this.OpeningBracket, this.Name, this.ClosingBracket, this.Children.Count);
		}
	}
}


text:
#include <aws/elasticbeanstalk/model/DescribeInstancesHealthRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::ElasticBeanstalk::Model;
using namespace Aws::Utils;

DescribeInstancesHealthRequest::DescribeInstancesHealthRequest() :
    m_environmentNameHasBeenSet(false),
    m_environmentIdHasBeenSet(false),
    m_attributeNamesHasBeenSet(false),
    m_nextTokenHasBeenSet(false)
{
}

Aws::String DescribeInstancesHealthRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=DescribeInstancesHealth&";
  if(m_environmentNameHasBeenSet)
  {
    ss << "EnvironmentName=" << StringUtils::URLEncode(m_environmentName.c_str()) << "&";
  }
  if(m_environmentIdHasBeenSet)
  {
    ss << "EnvironmentId=" << StringUtils::URLEncode(m_environmentId.c_str()) << "&";
  }
  if(m_attributeNamesHasBeenSet)
  {
    unsigned attributeNamesCount = 1;
    for(auto& item : m_attributeNames)
    {
      ss << "AttributeNames.member." << attributeNamesCount << "="
          << StringUtils::URLEncode(InstancesHealthAttributeMapper::GetNameForInstancesHealthAttribute(item).c_str()) << "&";
      attributeNamesCount++;
    }
  }
  if(m_nextTokenHasBeenSet)
  {
    ss << "NextToken=" << StringUtils::URLEncode(m_nextToken.c_str()) << "&";
  }
  ss << "Version=2010-12-01";
  return ss.str();
}


text:
var React = require('react');

var Hello = React.createClass({
  render: function() {

    return <Input
                  ref='inputElement'
                  value={ this.state.urlValue }
                  type={ 'text' }
                  label={ this.props.label }
                  placeholder={ 'Enter value' }
                  addonBefore={ 'URL:' }
                  onChange={ this._handleChangeUrlValue }
                  buttonAfter={ <Button
                                        onClick={ this._handleClearUrlValue }
                                        bsStyle={ 'default' }>

                                </Button> }>
             <Grid>
               <Row>
                 <Col/>
               </Row>
             </Grid>
           </Input>
  }
});

React.render(<Hello message="world" />, document.body);


text:
> Based on [https://downshiftology.com/recipes/perfect-soft-boiled-hard-boiled-eggs/](https://downshiftology.com/recipes/perfect-soft-boiled-hard-boiled-eggs/)

<!-- {cts} rating=2; (User can specify rating on scale of 1-5) -->

Personal rating: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-regular-star: :fontawesome-regular-star: :fontawesome-regular-star:

<!-- {cte} -->

<!-- {cts} name_image=hard_boiled_eggs.jpeg; (User can specify image name) -->

![hard_boiled_eggs.jpeg](./hard_boiled_eggs.jpeg){: .image-recipe loading=lazy }

<!-- {cte} -->

## Ingredients

* [ ] Eggs!

## Recipe

* Boil water in a saucepan deep enough for the eggs to sit in one layer
* Add eggs, cover, and reduce to a simmer. After 12 minutes, remove and place into room temp water (for variations on time, see source - egg shown in photo was put in for 6 min)

## Notes

* Fresher eggs will take slightly longer to peel. The eggs in this recipe should be cooked straight from the refrigerator; reduce cooking times by 1 minute if using room-temperature eggs
* Great for salads, with stir fry and rice, ramen (add in last minute of cooking to warm the egg),


text:
package org.lpw.tephra.office.excel;

import com.alibaba.fastjson.JSONObject;

import java.io.OutputStream;

/**
 * @author lpw
 */
public interface ExcelWriter {
    /**
     * 输出Excel。
     *
     * @param object       数据。
     * @param outputStream 输出流。
     * @return 成功则返回true;否则返回false。
     */
    boolean write(JSONObject object, OutputStream outputStream);
}


text:
from scriptcore.testing.testcase import TestCase
from scriptcore.console.asciimatics.widgets.label import Label
from asciimatics.widgets import Label as ALabel

class TestLabel(TestCase):

    def test_label(self):
        """
        Test the label
        :return:    void
        """

        label = Label(self.rand_str())

        self.assert_is_instance(label, ALabel)


text:
package com.github.dkharrat.nexusdata.metamodel;

import com.github.dkharrat.nexusdata.core.ManagedObject;

/**
 * A Relationship is a {@link ManagedObject} {@link Property} that represents a field that stores a to-one or to-many
 * relationship.
 */
public class Relationship extends Property {
    /**
     * Represents the type of the relationship
     */
    public enum Type {
        TO_ONE,
        TO_MANY,
    }

    private final Type relationshipType;
    private final Entity<?> destinationEntity;
    private Relationship inverse;

    //TODO: look into deducing the 'type' param based on relationshipType
    /**
     * Creates a new Attribute.
     *
     * @param entity            the associated entity
     * @param name              the name of the property
     * @param type              the relationship instance type. For to-one relationships, it must be the same as
     *                          {@code destinationEntity} (i.e. type of the related object. For to-many relationships,
     *                          it must be {@link java.util.Set}.
     * @param relationshipType  the relationship type (to-one or to-many)
     * @param destinationEntity the entity of the object(s) this relationship will store
     * @param inverse           the relationship in the other direction (from the destination entity to this
     *                          relationship's entity
     * @param isRequired        if true, property is required to have a value
     */
    public Relationship(Entity<?> entity, String name, Class<?> type, Type relationshipType, Entity<?> destinationEntity, Relationship inverse, boolean isRequired) {
        super(entity, name, type, isRequired);
        this.relationshipType = relationshipType;
        this.destinationEntity = destinationEntity;
        this.inverse = inverse;
    }

    /**
     * Returns the relationship type.
     *
     * @return the relationship type
     */
    public Type getRelationshipType() {
        return relationshipType;
    }

    /**
     * Indicates whether this relationship is a to-one relationship or not.
     *
     * @return true if this relationship is a to-one relationship, or false otherwise
     */
    public boolean isToOne() {
        return relationshipType == Type.TO_ONE;
    }

    /**
     * Indicates whether this relationship is a to-many relationship or not.
     *
     * @return true if this relationship is a to-many relationship, or false otherwise
     */
    public boolean isToMany() {
        return relationshipType == Type.TO_MANY;
    }

    /**
     * Returns the entity to which this relationship is related to.
     *
     * @return the entity to which this relationship is related to
     */
    public Entity<?> getDestinationEntity() {
        return destinationEntity;
    }

    /**
     * Returns the inverse relationship (i.e the relationship in the other direction).
     *
     * @return the inverse relationship
     */
    public Relationship getInverse() {
        return inverse;
    }

    void setInverse(Relationship inverse) {
        this.inverse = inverse;
    }

    @Override
    public boolean isRelationship() {
        return true;
    }

    @Override
    public String toString() {
        return super.toString() + "["
                +   "destinationEntity=" + (getDestinationEntity() == null ? "<null>" : getDestinationEntity().getName())
                + ", inverseRelationship=" + (getInverse() == null ? "<null>" : getInverse().getName())
                + "]";
    }
}


text:
namespace P03_StudentSystem
{
    using System;
    using System.Collections.Generic;

    public class StudentSystem
    {
        private Dictionary<string, Student> repo;

        public StudentSystem()
        {
            this.Repo = new Dictionary<string, Student>();
        }

        public Dictionary<string, Student> Repo
        {
            get { return repo; }
            private set { repo = value; }
        }

        public void ParseCommand()
        {
            string[] args = Console.ReadLine().Split();

            if (args[0] == "Create")
            {
                var name = args[1];
                var age = int.Parse(args[2]);
                var grade = double.Parse(args[3]);
                if (!repo.ContainsKey(name))
                {
                    var student = new Student(name, age, grade);
                    Repo[name] = student;
                }
            }
            else if (args[0] == "Show")
            {
                var name = args[1];
                if (Repo.ContainsKey(name))
                {
                    var student = Repo[name];
                    string view = $"{student.Name} is {student.Age} years old.";

                    if (student.Grade >= 5.00)
                    {
                        view += " Excellent student.";
                    }
                    else if (student.Grade < 5.00 && student.Grade >= 3.50)
                    {
                        view += " Average student.";
                    }
                    else
                    {
                        view += " Very nice person.";
                    }

                    Console.WriteLine(view);
                }

            }
            else if (args[0] == "Exit")
            {
                Environment.Exit(0);
            }
        }
    }

    public class Student
    {
        private string name;
        private int age;
        private double grade;

        public double Grade
        {
            get { return grade; }
            set { grade = value; }
        }

        public int Age
        {
            get { return age; }
            set { age = value; }
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public Student(string name, int age, double grade)
        {
            this.Name = name;
            this.Age = age;
            this.grade = grade;
        }
    }
}


text:
'use strict';
const addonBlueprint = require('../addon');
const getURLFor = require('ember-source-channel-url');

let emberCanaryVersion;
module.exports = Object.assign({}, addonBlueprint, {
  description: 'Generates an Ember addon with a module unification layout.',
  appBlueprintName: 'module-unification-app',

  fileMap: Object.assign({}, addonBlueprint.fileMap, {
    '^src.*': 'tests/dummy/:path',
    '^addon-src/.gitkeep': 'src/.gitkeep',
  }),

  beforeInstall() {
    return getURLFor('canary').then(url => {
      emberCanaryVersion = url;
    });
  },

  locals(options) {
    let result = addonBlueprint.locals(options);
    result.emberCanaryVersion = emberCanaryVersion;
    return result;
  },
});


text:
package http

import (
	"errors"
	"fmt"
	"net/http"
	"net/http/httputil"
	"net/url"

	"go-micro.dev/v4/api"
	"go-micro.dev/v4/api/handler"
	"go-micro.dev/v4/selector"
)

const (
	Handler = "http"
)

type httpHandler struct {
	options handler.Options

	// set with different initialiser
	s *api.Service
}

func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	service, err := h.getService(r)
	if err != nil {
		w.WriteHeader(500)
		return
	}

	if len(service) == 0 {
		w.WriteHeader(404)
		return
	}

	rp, err := url.Parse(service)
	if err != nil {
		w.WriteHeader(500)
		return
	}

	httputil.NewSingleHostReverseProxy(rp).ServeHTTP(w, r)
}

// getService returns the service for this request from the selector
func (h *httpHandler) getService(r *http.Request) (string, error) {
	var service *api.Service

	if h.s != nil {
		// we were given the service
		service = h.s
	} else if h.options.Router != nil {
		// try get service from router
		s, err := h.options.Router.Route(r)
		if err != nil {
			return "", err
		}
		service = s
	} else {
		// we have no way of routing the request
		return "", errors.New("no route found")
	}

	// create a random selector
	next := selector.Random(service.Services)

	// get the next node
	s, err := next()
	if err != nil {
		return "", nil
	}

	return fmt.Sprintf("http://%s", s.Address), nil
}

func (h *httpHandler) String() string {
	return "http"
}

// NewHandler returns a http proxy handler
func NewHandler(opts ...handler.Option) handler.Handler {
	options := handler.NewOptions(opts...)

	return &httpHandler{
		options: options,
	}
}

// WithService creates a handler with a service
func WithService(s *api.Service, opts ...handler.Option) handler.Handler {
	options := handler.NewOptions(opts...)

	return &httpHandler{
		options: options,
		s:       s,
	}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
    public partial class MethodDeclarationSyntax
    {
        public int Arity
        {
            get
            {
                return this.TypeParameterList == null ? 0 : this.TypeParameterList.Parameters.Count;
            }
        }
    }
}

namespace Microsoft.CodeAnalysis.CSharp
{
    public partial class SyntaxFactory
    {
        public static MethodDeclarationSyntax MethodDeclaration(
            SyntaxList<AttributeListSyntax> attributeLists,
            SyntaxTokenList modifiers,
            TypeSyntax returnType,
            ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier,
            SyntaxToken identifier,
            TypeParameterListSyntax typeParameterList,
            ParameterListSyntax parameterList,
            SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses,
            BlockSyntax body,
            SyntaxToken semicolonToken)
        {
            return SyntaxFactory.MethodDeclaration(
                attributeLists,
                modifiers,
                returnType,
                explicitInterfaceSpecifier,
                identifier,
                typeParameterList,
                parameterList,
                constraintClauses,
                body,
                null,
                semicolonToken);
        }
    }
}


text:
#include <aws/storagegateway/model/AddCacheRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::StorageGateway::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

AddCacheRequest::AddCacheRequest() :
    m_gatewayARNHasBeenSet(false),
    m_diskIdsHasBeenSet(false)
{
}

Aws::String AddCacheRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_gatewayARNHasBeenSet)
  {
   payload.WithString("GatewayARN", m_gatewayARN);

  }

  if(m_diskIdsHasBeenSet)
  {
   Array<JsonValue> diskIdsJsonList(m_diskIds.size());
   for(unsigned diskIdsIndex = 0; diskIdsIndex < diskIdsJsonList.GetLength(); ++diskIdsIndex)
   {
     diskIdsJsonList[diskIdsIndex].AsString(m_diskIds[diskIdsIndex]);
   }
   payload.WithArray("DiskIds", std::move(diskIdsJsonList));

  }

  return payload.WriteReadable();
}

Aws::Http::HeaderValueCollection AddCacheRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "StorageGateway_20130630.AddCache"));
  return headers;

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="aspect_ratio" format="float"/>

    <declare-styleable name="AspectRatioView">
        <attr name="aspect_ratio"/>
    </declare-styleable>

    <declare-styleable name="AspectRatioImageView">
        <attr name="aspect_ratio"/>
    </declare-styleable>

    <declare-styleable name="SpannedGridLayoutManager">
        <attr name="android:orientation"/>
        <attr name="spanCount"/>
        <attr name="aspectRatio"/>
    </declare-styleable>

    <declare-styleable name="BottomNavigation">
        <attr name="primaryEnable" format="boolean"/>
        <attr name="primaryIcon" format="reference"/>
        <attr name="primaryText" format="string|reference"/>
        <attr name="elevation" format="dimension"/>
    </declare-styleable>
</resources>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.edu.ifnmg.ifad.view;

import br.edu.ifnmg.ifad.entity.Usuario;
import br.edu.ifnmg.ifad.util.Context;
import br.edu.ifnmg.ifad.util.FileUtil;
import br.edu.ifnmg.ifad.util.StringHelper;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author danilo
 */
@WebServlet(name = "FileServlet", urlPatterns = {"/fileServlet"})
public class FileServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * GET and
     * POST methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         Object objLogin = request.getSession().getAttribute(Context.USUARIO_LOGADO);
         Usuario login = null;
         if(objLogin != null){
             login = (Usuario)objLogin;
         }
         if(login != null){
            try {
                String fileName = request.getParameter("fileName");
                String contentType = request.getParameter("contentType");
                File file = null;
                if(!StringHelper.isEmpty(fileName)){
                    file = new File(fileName);
                }
                if(file != null){
                    response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
                    response.setHeader("Cache-Control", "public");
                    response.setContentLength((int)file.length());
                    Calendar dataExpiracao = Calendar.getInstance();
                    dataExpiracao.add(Calendar.HOUR, 2);
                    response.setHeader("expires", new SimpleDateFormat().format(dataExpiracao.getTime()));
                    if(!StringHelper.isEmpty(contentType)){
                        response.setContentType(contentType);
                    } else {
                        response.setContentType("application/octet-stream");
                    }
                    byte[] img = null;
                    if(file.exists()){
                        img = FileUtil.fileToByteArray(file);
                        response.getOutputStream().write(img);
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(FileServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
         }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}


text:
"""A package to hold all the files for the form classification tests.
"""


text:
using base::android::ConvertJavaStringToUTF8;

static jlong Init(JNIEnv* env, jclass clazz, jobject profile) {
  NewTabPagePrefs* new_tab_page_prefs =
      new NewTabPagePrefs(ProfileAndroid::FromProfileAndroid(profile));
  return reinterpret_cast<intptr_t>(new_tab_page_prefs);
}

NewTabPagePrefs::NewTabPagePrefs(Profile* profile)
  : profile_(profile) {
}

void NewTabPagePrefs::Destroy(JNIEnv* env, jobject obj) {
  delete this;
}

NewTabPagePrefs::~NewTabPagePrefs() {
}

jboolean NewTabPagePrefs::GetSnapshotDocumentCollapsed(JNIEnv* env,
                                                       jobject obj) {
  return profile_->GetPrefs()->GetBoolean(prefs::kNtpCollapsedSnapshotDocument);
}

void NewTabPagePrefs::SetSnapshotDocumentCollapsed(JNIEnv* env,
                                                   jobject obj,
                                                   jboolean is_collapsed) {
  PrefService* prefs = profile_->GetPrefs();
  prefs->SetBoolean(prefs::kNtpCollapsedSnapshotDocument, is_collapsed);
}

jboolean NewTabPagePrefs::GetRecentlyClosedTabsCollapsed(JNIEnv* env,
                                                         jobject obj) {
  return profile_->GetPrefs()->GetBoolean(
      prefs::kNtpCollapsedRecentlyClosedTabs);
}

void NewTabPagePrefs::SetRecentlyClosedTabsCollapsed(JNIEnv* env,
                                                     jobject obj,
                                                     jboolean is_collapsed) {
  PrefService* prefs = profile_->GetPrefs();
  prefs->SetBoolean(prefs::kNtpCollapsedRecentlyClosedTabs, is_collapsed);
}

jboolean NewTabPagePrefs::GetSyncPromoCollapsed(JNIEnv* env,
                                                       jobject obj) {
  return profile_->GetPrefs()->GetBoolean(prefs::kNtpCollapsedSyncPromo);
}

void NewTabPagePrefs::SetSyncPromoCollapsed(JNIEnv* env,
                                            jobject obj,
                                            jboolean is_collapsed) {
  PrefService* prefs = profile_->GetPrefs();
  prefs->SetBoolean(prefs::kNtpCollapsedSyncPromo, is_collapsed);
}

jboolean NewTabPagePrefs::GetForeignSessionCollapsed(JNIEnv* env,
                                                     jobject obj,
                                                     jstring session_tag) {
  const DictionaryValue* dict = profile_->GetPrefs()->GetDictionary(
      prefs::kNtpCollapsedForeignSessions);
  return dict && dict->HasKey(ConvertJavaStringToUTF8(env, session_tag));
}

void NewTabPagePrefs::SetForeignSessionCollapsed(JNIEnv* env,
                                                 jobject obj,
                                                 jstring session_tag,
                                                 jboolean is_collapsed) {
  // Store session tags for collapsed sessions in a preference so that the
  // collapsed state persists.
  PrefService* prefs = profile_->GetPrefs();
  DictionaryPrefUpdate update(prefs, prefs::kNtpCollapsedForeignSessions);
  if (is_collapsed)
    update.Get()->SetBoolean(ConvertJavaStringToUTF8(env, session_tag), true);
  else
    update.Get()->Remove(ConvertJavaStringToUTF8(env, session_tag), NULL);
}

// static
void NewTabPagePrefs::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterBooleanPref(
      prefs::kNtpCollapsedSnapshotDocument,
      false,
      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
  registry->RegisterBooleanPref(
      prefs::kNtpCollapsedRecentlyClosedTabs,
      false,
      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
  registry->RegisterBooleanPref(
      prefs::kNtpCollapsedSyncPromo,
      false,
      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}

// static
bool NewTabPagePrefs::RegisterNewTabPagePrefs(JNIEnv* env) {
  return RegisterNativesImpl(env);
}


text:
package edu.wustl.xipHost.avt2ext;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.apache.log4j.Logger;
import com.pixelmed.dicom.AttributeList;
import edu.wustl.xipHost.dicom.AttributePanel;
import edu.wustl.xipHost.dicom.DicomUtil;
import edu.wustl.xipHost.gui.BasicSearchCriteriaVerifier;
import edu.wustl.xipHost.gui.SearchCriteriaVerifier;
import edu.wustl.xipHost.gui.UnderDevelopmentDialog;
import edu.wustl.xipHost.hostControl.HostConfigurator;

/**
 * @author Jaroslaw Krych
 *
 */
public class SearchCriteriaPanelAVT extends JPanel implements ActionListener{
	final static Logger logger = Logger.getLogger(SearchCriteriaPanelAVT.class);
	SearchCriteriaVerifier searchCriteriaVerifier;
	JPanel btnPanel = new JPanel();
	JButton btnSearch = new JButton("Search");
	JButton btnCancel = new JButton("Cancel");
	AttributePanelAIM panelAVT;
	AttributePanel panelDICOM;
	AttributePanelPrivateTag panelPrivateTag;
	JScrollPane attEntryPanel;
	Color xipColor = new Color(51, 51, 102);
	Color xipBtn = new Color(56, 73, 150);
	GridBagLayout layout = new GridBagLayout();
	JPanel panel = new JPanel();

	public SearchCriteriaPanelAVT(){
		panelAVT = new AttributePanelAIM();
		AttributeList list = DicomUtil.constructEmptyAttributeList();
		panelDICOM = new AttributePanel(list);
		panelPrivateTag = new AttributePanelPrivateTag();
		// default criteria verifier is basic one unless different one is set.
		searchCriteriaVerifier = new BasicSearchCriteriaVerifier();
		panelAVT.setBackground(new Color(156, 162, 189));
		panelAVT.setForeground(Color.WHITE);
		panelDICOM.setBackground(new Color(156, 162, 189));
		panelDICOM.setForeground(Color.WHITE);
		panelPrivateTag.setBackground(new Color(156, 162, 189));
		panelPrivateTag.setForeground(Color.WHITE);
		buildAttributePanelLayout();
		panel.setLayout(layout);
		panel.add(panelAVT);
		panel.add(panelDICOM);
		panel.add(panelPrivateTag);
		panel.setBackground(new Color(156, 162, 189));
		attEntryPanel = new JScrollPane(panel);
		attEntryPanel.setPreferredSize(new Dimension(500, HostConfigurator.adjustForResolution()));
		add(attEntryPanel);
		btnSearch.setPreferredSize(new Dimension(120, 25));
		btnSearch.setBackground(xipBtn);
		btnSearch.setForeground(Color.BLACK);
		btnCancel.setPreferredSize(new Dimension(100, 25));
		btnCancel.setBackground(xipBtn);
		btnCancel.setForeground(Color.BLACK);
		btnSearch.addActionListener(this);
		btnCancel.addActionListener(this);
		btnPanel.add(btnSearch);
		btnPanel.add(btnCancel);
		btnPanel.setBackground(xipColor);
		add(btnPanel);
		this.setBackground(xipColor);
		buildLayout();
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension windowSize = this.getPreferredSize();
        setBounds((screenSize.width - windowSize.width) / 2, (screenSize.height - windowSize.height) /2,  windowSize.width, windowSize.height);
		setVisible(true);
	}

	void buildLayout(){
		GridBagLayout layout = new GridBagLayout();
        GridBagConstraints constraints = new GridBagConstraints();
        setLayout(layout);

		constraints.fill = GridBagConstraints.NONE;
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.insets.top = 10;
        constraints.insets.left = 10;
        constraints.insets.right = 10;
        constraints.insets.bottom = 0;
        //constraints.anchor = GridBagConstraints.NORTH;
        layout.setConstraints(attEntryPanel, constraints);

        constraints.fill = GridBagConstraints.NONE;
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.insets.top = 10;
        constraints.insets.bottom = 10;
        //constraints.anchor = GridBagConstraints.NORTH;
        layout.setConstraints(btnPanel, constraints);
	}

	void buildAttributePanelLayout(){
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.gridy = 1;
		constraints.gridx = 1;
		constraints.anchor = GridBagConstraints.EAST;
		constraints.insets.left = 10;
        constraints.insets.right = 10;
        constraints.insets.top = 2;
        constraints.insets.bottom = 2;
		layout.setConstraints(panelAVT, constraints);
		constraints.gridy = 2;
		constraints.gridx = 1;
		layout.setConstraints(panelDICOM, constraints);
		constraints.gridy = 3;
		constraints.gridx = 1;
		layout.setConstraints(panelPrivateTag, constraints);
	}

	public static void main(String args[]){
		SearchCriteriaPanelAVT panel = new SearchCriteriaPanelAVT();
		JDialog dialog = new JDialog(new JFrame(), "Criteria", true);
		dialog.getContentPane().add(panel);
		dialog.setPreferredSize(new Dimension(550, 900));
		dialog.pack();
		dialog.setVisible(true);
		dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

	}

	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == btnCancel){
			new UnderDevelopmentDialog(btnCancel.getLocationOnScreen());
		}
	}

	public boolean verifyCriteria(AttributeList list, Map<String, Object> aimCriteria){
		boolean blnAimCriteria = false;
		Set<String> keys = aimCriteria.keySet();
		Iterator<String> iter = keys.iterator();
		boolean isAimCriteriaEmpty = true;
		while(iter.hasNext()){
			String key = iter.next();
			String value = (String) aimCriteria.get(key);
			if(value.equalsIgnoreCase("null")){
				logger.warn("Verification result - NULL query criteria - INVALID.");
				return false;
			} else if (isAimCriteriaEmpty == true && !value.isEmpty()){
				logger.debug(key + ": " + aimCriteria.get(key));
				isAimCriteriaEmpty = false;
			}
		}
		if(isAimCriteriaEmpty == false){
			logger.debug("Verification result - AIM query criteria - VALID.");
			blnAimCriteria = true;
		}
		boolean blnDicomCriteria = searchCriteriaVerifier.verifyCriteria(list);
		boolean criteria = false;
		if(blnAimCriteria == true || blnDicomCriteria == true){
			criteria = true;
		}
		return criteria;
	}

	public void setQueryButtonText(String text){
		btnSearch.setText(text);
	}
	public JButton getQueryButton(){
		return btnSearch;
	}

	public AttributeList getFilterList(){
		return panelDICOM.getFilterList();
	}

	public void resetCriteriaPanel(){
		panel.remove(panelAVT);
		panelAVT = new AttributePanelAIM();
		panel.add(panelAVT);
		panel.remove(panelDICOM);
		AttributeList list = DicomUtil.constructEmptyAttributeList();
		panelDICOM = new AttributePanel(list);
		panel.add(panelDICOM);
		panel.remove(panelPrivateTag);
		panelPrivateTag = new AttributePanelPrivateTag();
		panel.add(panelPrivateTag);
		buildAttributePanelLayout();
		panel.repaint();
		attEntryPanel.getVerticalScrollBar().setValue(0);
	}

}


text:
import json
import requests
from fnexchange.core.plugins import AbstractPlugin

class FreshdeskPlugin(AbstractPlugin):

	def create_ticket(self,payload):
			headers = { 'Content-Type' : 'application/json' }
			elements = payload["elements"]
			response = requests.post(self.config.url,auth=(self.config.api_key,"x"),headers=headers,data = json.dumps(elements[0]))

			success=False
			if response.status_code == 201:
			  success= True
			else:
			  success= False

			return {
				'metadata': {
					'success': success
				},
				'elements': elements  # return the same thing back
			}

	def update_ticket(self,payload):
			headers = { 'Content-Type' : 'application/json' }
			elements = payload["elements"]
			ticket_id=str(elements[1]["ticket_id"])
			response = requests.put(self.config.url+'/'+ ticket_id, auth = (self.config.api_key,"x"), headers = headers, data = json.dumps(elements[0]))

			if response.status_code==200:
				success= True
			else:
				success= False

			return {
				'metadata': {
					'success': success
				},
				'elements': elements  # return the same thing back
			}

	def delete_ticket(self,payload):
			headers = { 'Content-Type' : 'application/json' }
			elements=payload["elements"]
			ticket_id=str(elements[0]["ticket_id"])
			response=requests.delete(self.config.url+'/'+ ticket_id, auth = (self.config.api_key,"x"), headers = headers)

			if response.status_code==204:
			   success= True
			else:
			   success= False

			return {
				'metadata': {
					'success': success
				},
				'elements': elements  # return the same thing back
			}
	def restore_ticket(self,payload):
			elements=payload["elements"]
			headers={'Content-Type':'application/json'}
			ticket_id=str(elements[0]["ticket_id"])
			response=requests.put(self.config.url+'/'+ticket_id+'/restore', auth = (self.config.api_key,"x"), headers = headers)

			if response.status_code==204:
				success= True
			else:
				success= False

			return {
				'metadata': {
					'success': success
				},
				'elements': elements  # return the same thing back
			}

	def view_ticket(self,payload):#Working
			headers = { 'Content-Type' : 'application/json' }
			elements=payload["elements"]
			ticket_id=str(elements[0]["ticket_id"])

			response=requests.get(self.config.url+'/'+ ticket_id,auth= (self.config.api_key,'x'), headers=headers)

			return response.content

	def create_contact(self,payload):
			headers = { 'Content-Type' : 'application/json' }
			elements=payload["elements"]
			contact_info=elements[0]["contact_info"]

			response = requests.post(self.config.url1,auth=(self.config.api_key,"x"), headers=headers,data = json.dumps(contact_info))

			if response.status_code==201:
				success= True
			else:
				success= False

			return {
				'metadata': {
					'success': success
				},
				'elements': elements  # return the same thing back
			}

	def view_contact(self,payload):#Working
			headers = { 'Content-Type' : 'application/json' }
			elements=payload["elements"]
			contact_id=str(elements[0]["contact_id"])
			response=requests.get(self.config.url1+'/'+ contact_id,auth= (self.config.api_key,'x'), headers=headers)
			return response.content

	def delete_contact(self,payload):
			headers = { 'Content-Type' : 'application/json' }
			elements=payload["elements"]
			contact_id=str(elements[0]["contact_id"])

			response = requests.delete(self.config.url1+'/'+contact_id,auth=(self.config.api_key,"x"), headers=headers)

			if response.status_code==204:
				success= True
			else:
				success= False
			print "Status Code :" + str(response.status_code)

			return {
				'metadata': {
					'success': success
				},
				'elements': elements  # return the same thing back
			}

	def update_contact(self,payload):
			headers = { 'Content-Type' : 'application/json' }
			elements = payload["elements"]
			contact_id=str(elements[1]["contact_id"])

			response = requests.put(self.config.url1+'/'+contact_id, auth = (self.config.api_key,"x"), headers = headers, data = json.dumps(elements[0]["contact_info"]))

			if response.status_code == 200:
			   success= True
			else:
			   success= False
			print "Status Code : " + str(response.status_code)

			return {
				'metadata': {
					'success': success
				},
				'elements': elements  # return the same thing back
			}


text:
set -euo pipefail
if [[ ! -d "${RUNFILES_DIR:-/dev/null}" && ! -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
  if [[ -f "$0.runfiles_manifest" ]]; then
    export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest"
  elif [[ -f "$0.runfiles/MANIFEST" ]]; then
    export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST"
  elif [[ -f "$0.runfiles/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
    export RUNFILES_DIR="$0.runfiles"
  fi
fi
if [[ -f "${RUNFILES_DIR:-/dev/null}/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
  source "${RUNFILES_DIR}/bazel_tools/tools/bash/runfiles/runfiles.bash"
elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
  source "$(grep -m1 "^bazel_tools/tools/bash/runfiles/runfiles.bash " \
            "$RUNFILES_MANIFEST_FILE" | cut -d ' ' -f 2-)"
else
  echo >&2 "ERROR: cannot find @bazel_tools//tools/bash/runfiles:runfiles.bash"
  exit 1
fi
# --- end runfiles.bash initialization ---

source "$(rlocation "io_bazel/src/test/shell/integration_test_setup.sh")" \
  || { echo "integration_test_setup.sh not found!" >&2; exit 1; }

case "$(uname -s | tr [:upper:] [:lower:])" in
msys*|mingw*|cygwin*)
  declare -r is_windows=true
  ;;
*)
  declare -r is_windows=false
  ;;
esac

if "$is_windows"; then
  export MSYS_NO_PATHCONV=1
  export MSYS2_ARG_CONV_EXCL="*"
  declare -r EXE_EXT=".exe"
else
  declare -r EXE_EXT=""
fi

# Tests in this file do not actually start a Python interpreter, but plug in a
# fake stub executable to serve as the "interpreter".

use_fake_python_runtimes_for_testsuite

#### TESTS #############################################################

# Tests that a cycle reached via a command-line aspect does not crash.
# Does not crash deterministically, because if the configured target's cycle is
# reported first, the aspect loading key's cycle is suppressed.
function test_cycle_under_command_line_aspect() {
  mkdir -p test
  cat > test/aspect.bzl << 'EOF' || fail "Couldn't write aspect.bzl"
def _simple_aspect_impl(target, ctx):
    return struct()

simple_aspect = aspect(implementation=_simple_aspect_impl)
EOF
  echo "sh_library(name = 'cycletarget', deps = [':cycletarget'])" \
      > test/BUILD || fail "Couldn't write BUILD file"

  # No flag, use the default from the rule.
  bazel build --nobuild -k //test:cycletarget \
      --aspects 'test/aspect.bzl%simple_aspect' &> $TEST_log \
      && fail "Expected failure"
  local -r exit_code="$?"
  [[ "$exit_code" == 1 ]] || fail "Unexpected exit code: $exit_code"
  expect_log "cycle in dependency graph"
  expect_log "//test:cycletarget \[self-edge\]"
  expect_not_log "IllegalStateException"
}

run_suite "Tests for aspects"