text:
"""Switches for the Elexa Guardian integration."""
from aioguardian.errors import GuardianError

from homeassistant.components.switch import SwitchEntity
from homeassistant.core import callback

from . import Guardian, GuardianEntity
from .const import DATA_CLIENT, DATA_VALVE_STATUS, DOMAIN, LOGGER, SWITCH_KIND_VALVE

ATTR_AVG_CURRENT = "average_current"
ATTR_INST_CURRENT = "instantaneous_current"
ATTR_INST_CURRENT_DDT = "instantaneous_current_ddt"
ATTR_TRAVEL_COUNT = "travel_count"

async def async_setup_entry(hass, entry, async_add_entities):
    """Set up Guardian switches based on a config entry."""
    guardian = hass.data[DOMAIN][DATA_CLIENT][entry.entry_id]
    async_add_entities([GuardianSwitch(guardian)], True)

class GuardianSwitch(GuardianEntity, SwitchEntity):
    """Define a switch to open/close the Guardian valve."""

    def __init__(self, guardian: Guardian):
        """Initialize."""
        super().__init__(guardian, SWITCH_KIND_VALVE, "Valve", None, "mdi:water")

        self._is_on = True

    @property
    def is_on(self):
        """Return True if the valve is open."""
        return self._is_on

    @callback
    def _update_from_latest_data(self):
        """Update the entity."""
        self._is_on = self._guardian.data[DATA_VALVE_STATUS]["state"] in (
            "start_opening",
            "opening",
            "finish_opening",
            "opened",
        )

        self._attrs.update(
            {
                ATTR_AVG_CURRENT: self._guardian.data[DATA_VALVE_STATUS][
                    "average_current"
                ],
                ATTR_INST_CURRENT: self._guardian.data[DATA_VALVE_STATUS][
                    "instantaneous_current"
                ],
                ATTR_INST_CURRENT_DDT: self._guardian.data[DATA_VALVE_STATUS][
                    "instantaneous_current_ddt"
                ],
                ATTR_TRAVEL_COUNT: self._guardian.data[DATA_VALVE_STATUS][
                    "travel_count"
                ],
            }
        )

    async def async_turn_off(self, **kwargs) -> None:
        """Turn the valve off (closed)."""
        try:
            async with self._guardian.client:
                await self._guardian.client.valve.close()
        except GuardianError as err:
            LOGGER.error("Error while closing the valve: %s", err)
            return

        self._is_on = False
        self.async_write_ha_state()

    async def async_turn_on(self, **kwargs) -> None:
        """Turn the valve on (open)."""
        try:
            async with self._guardian.client:
                await self._guardian.client.valve.open()
        except GuardianError as err:
            LOGGER.error("Error while opening the valve: %s", err)
            return

        self._is_on = True
        self.async_write_ha_state()


text:
import fs from 'fs';
import {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLList,
  GraphQLBoolean,
} from 'graphql';
import {
  resolver,
  attributeFields,
  defaultListArgs,
  defaultArgs,
} from '@falcon-client/graphql-sequelize';
import { singular } from 'pluralize';
import Sequelize from 'sequelize';

import createDefinitions from './definitions';
import {
  isJoinTable,
  findModelKey,
  formatFieldName,
  formatTypeName,
  pascalCase,
} from '../utils';
import { joinTableAssociations, tableAssociations } from './associations';
import {
  makeCreateArgs,
  makeUpdateArgs,
  makeDeleteArgs,
  getPkFieldKey,
  makePolyArgs,
  getPolyKeys,
} from './arguments';

const GenericResponseType = new GraphQLObjectType({
  name: 'GenericResponse',
  fields: {
    success: { type: GraphQLBoolean },
  },
});

export const buildSchemaFromDatabase = databaseFile => new Promise(async (resolve, reject) => {
    const db = new Sequelize({
      dialect: 'sqlite',
      storage: databaseFile,
      logging: false,
      operatorsAliases: Sequelize.Op,
    });

    resolve(await build(db));
  });

export const buildSchemaFromInfile = infile => new Promise(async (resolve, reject) => {
    const db = new Sequelize({
      dialect: 'sqlite',
      storage: ':memory:',
      logging: false,
      operatorsAliases: Sequelize.Op,
    });

    const contents = fs.readFileSync(infile);
    const statements = contents
      .toString()
      .split(/\r?\n|\r/g)
      .filter(s => s.length);

    for (const stmt of statements) {
      await db.query(stmt);
    }

    resolve(await build(db));
  });

const build = db => new Promise(async (resolve, reject) => {
    const models = {};
    let associations = [];

    const tables = await db.query(
      'SELECT name FROM sqlite_master WHERE type = "table" AND name NOT LIKE "sqlite_%"'
    );

    for (const table of tables) {
      const [info, infoMeta] = await db.query(`PRAGMA table_info("${table}")`);
      const foreignKeys = await db.query(`PRAGMA foreign_key_list("${table}")`);

      if (isJoinTable(table, tables)) {
        associations = associations.concat(
          joinTableAssociations(table, info, foreignKeys)
        );
      } else {
        models[table] = db.define(table, createDefinitions(info, table), {
          timestamps: false,
          tableName: table,
        });

        associations = associations.concat(
          tableAssociations(table, info, foreignKeys)
        );
      }
    }

    associations.forEach(({ from, to, type, options }) => {
      const key = type === 'belongsTo' ? singular(to) : to;
      const fromKey = findModelKey(from, models);
      const toKey = findModelKey(to, models);
      models[fromKey][key] = models[fromKey][type](models[toKey], options);
    });

    const types = {};
    const mutations = {};
    const queries = {};

    Object.keys(models).forEach(key => {
      const model = models[key];
      const fieldAssociations = {
        hasMany: associations
          .filter(({ type }) => type === 'hasMany')
          .filter(({ from }) => from === key)
          .map(({ to }) => models[to]),
        belongsTo: associations
          .filter(({ type }) => type === 'belongsTo')
          .filter(({ from }) => from === key)
          .map(({ to }) => models[to]),
        belongsToMany: associations
          .filter(({ type }) => type === 'belongsToMany')
          .map(({ from, to }) => [from, to])
          .filter(sides => sides.includes(key)),
      };

      const type = new GraphQLObjectType({
        name: formatTypeName(model.name),
        fields() {
          const fields = attributeFields(model);

          fieldAssociations.hasMany.forEach(associatedModel => {
            fields[formatFieldName(associatedModel.name)] = {
              type: new GraphQLList(types[associatedModel.name]),
              args: defaultListArgs(model[associatedModel.name]),
              resolve: resolver(model[associatedModel.name]),
            };
          });

          fieldAssociations.belongsTo.forEach(associatedModel => {
            const fieldName = singular(associatedModel.name);
            fields[formatFieldName(fieldName)] = {
              type: types[associatedModel.name],
              resolve: resolver(model[fieldName]),
            };
          });

          fieldAssociations.belongsToMany.forEach(sides => {
            const [other] = sides.filter(side => side !== model.name);
            fields[formatFieldName(other)] = {
              type: new GraphQLList(types[other]),
              resolve: resolver(model[other]),
            };
          });

          return fields;
        },
      });

      types[key] = type;

      queries[formatFieldName(key)] = {
        type: new GraphQLList(type),
        args: defaultListArgs(model),
        resolve: resolver(model),
      };

      queries[singular(formatFieldName(key))] = {
        type,
        args: defaultArgs(model),
        resolve: resolver(model),
      };

      mutations[`create${type}`] = {
        type,
        args: makeCreateArgs(model),
        resolve: async (obj, values, info) => {
          const thing = await model.create(values);
          return thing;
        },
      };

      mutations[`update${type}`] = {
        type,
        args: makeUpdateArgs(model),
        resolve: async (obj, values, info) => {
          const pkKey = getPkFieldKey(model);

          const thing = await model.findOne({
            where: { [pkKey]: values[pkKey] },
          });

          await thing.update(values);

          return thing;
        },
      };

      mutations[`delete${type}`] = {
        type: GenericResponseType,
        args: makeDeleteArgs(model),
        resolve: async (obj, values, info) => {
          const thing = await model.findOne({
            where: values,
          });

          await thing.destroy();

          return {
            success: true,
          };
        },
      };

      fieldAssociations.belongsToMany.forEach(sides => {
        const [other] = sides.filter(side => side !== model.name);
        const nameBits = [formatTypeName(model.name), formatTypeName(other)];

        ['add', 'remove'].forEach(prefix => {
          const connector = prefix === 'add' ? 'To' : 'From';
          const name = `${prefix}${nameBits.join(connector)}`;
          mutations[name] = {
            type: GenericResponseType,
            args: makePolyArgs(model, models[other]),
            resolve: async (obj, values, info) => {
              const key = getPkFieldKey(model);
              const [, , otherArgumentKey] = getPolyKeys(model, models[other]);

              const thingOne = await model.findById(values[key]);
              const thingTwo = await models[other].findById(
                values[otherArgumentKey]
              );

              const method = `${prefix}${pascalCase(singular(other))}`;

              await thingOne[method](thingTwo);

              return {
                success: true,
              };
            },
          };
        });
      });
    });

    const query = new GraphQLObjectType({
      name: 'Query',
      fields: queries,
    });

    const mutation = new GraphQLObjectType({
      name: 'Mutation',
      fields: mutations,
    });

    resolve(
      new GraphQLSchema({
        query,
        mutation,
      })
    );
  });

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Tracker\TargetBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class FilterType extends AbstractType
{
  public function buildForm(FormBuilder $builder, array $options)
  {
    $builder->add('campaigns', 'entity', array(
      'class' => 'TrackerCampaignBundle:Campaign',
    ));
  }

  public function getName()
  {
    return 'filter';
  }
}


text:
:::code-1
this is my content
:::

add my code ::code-1:: here


text:
/* Sticky footer styles
-------------------------------------------------- */

html,
body {
  height: 100%;
  /* The html and body elements cannot have any padding or margin. */
}

/* Make section header links more stoic */
h3 > a, h3 > a:hover {
    color: black;
    text-decoration: none;
}

/* Wrapper for page content to push down footer */
#wrap {
  min-height: 100%;
  height: auto !important;
  height: 100%;
  /* Negative indent footer by its height */
  margin: 0 auto -60px;
  /* Pad bottom by footer height */
  padding: 0 0 60px;
}

/* Set the fixed height of the footer here */
#footer {
  height: 60px;
  background-color: #f5f5f5;
}

/* Custom page CSS
-------------------------------------------------- */
/* Not required for template or sticky footer method. */

.container {
  width: auto;
  max-width: 680px;
  padding: 0 15px;
}
.container .credit {
  margin: 20px 0;
}


text:
"""
Tests the delivery of template driven pages
"""

##########################################################################
## Imports
##########################################################################

import elmr

from flask.ext.testing import TestCase
from tests.initdb import syncdb, dropdb

##########################################################################
## Template Testing
##########################################################################

class TemplateTests(TestCase):
    """
    Test the template delivery of pages in the app.
    """

    render_templates = False

    def create_app(self):
        elmr.app.config.from_object('elmr.config.TestingConfig')
        return elmr.app

    @classmethod
    def setUpClass(cls):
        syncdb(metatables=True)

    @classmethod
    def tearDownClass(cls):
        dropdb(metatables=True)

    def test_home_template(self):
        """
        Assert that the home page uses the home template.
        """
        reponse = self.client.get("/")
        self.assert_template_used('home.html')

    def test_admin_template(self):
        """
        Assert that the admin page uses the admin template.
        """
        reponse = self.client.get("/admin/")
        self.assert_template_used('admin.html')

    def test_benjamin_development_template(self):
        """
        Assert that the benjamin development page uses the benjamin template.
        """
        reponse = self.client.get("/benjamin/")
        self.assert_template_used('development/benjamin.html')

    def test_assaf_development_template(self):
        """
        Assert that the assaf development page uses the assaf template.
        """
        reponse = self.client.get("/assaf/")
        self.assert_template_used('development/assaf.html')


text:
/*
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#ifndef AVFILTER_INTERNAL_H
#define AVFILTER_INTERNAL_H

/**
 * @file
 * internal API functions
 */

#include "libavutil/internal.h"
#include "avfilter.h"
#include "avfiltergraph.h"
#include "formats.h"
#include "framepool.h"
#include "thread.h"
#include "version.h"
#include "video.h"
#include "libavcodec/avcodec.h"

typedef struct AVFilterCommand {
    double time;                ///< time expressed in seconds
    char *command;              ///< command
    char *arg;                  ///< optional argument for the command
    int flags;
    struct AVFilterCommand *next;
} AVFilterCommand;

/**
 * Update the position of a link in the age heap.
 */
void ff_avfilter_graph_update_heap(AVFilterGraph *graph, AVFilterLink *link);

/**
 * A filter pad used for either input or output.
 */
struct AVFilterPad {
    /**
     * Pad name. The name is unique among inputs and among outputs, but an
     * input may have the same name as an output. This may be NULL if this
     * pad has no need to ever be referenced by name.
     */
    const char *name;

    /**
     * AVFilterPad type.
     */
    enum AVMediaType type;

    /**
     * Callback function to get a video buffer. If NULL, the filter system will
     * use ff_default_get_video_buffer().
     *
     * Input video pads only.
     */
    AVFrame *(*get_video_buffer)(AVFilterLink *link, int w, int h);

    /**
     * Callback function to get an audio buffer. If NULL, the filter system will
     * use ff_default_get_audio_buffer().
     *
     * Input audio pads only.
     */
    AVFrame *(*get_audio_buffer)(AVFilterLink *link, int nb_samples);

    /**
     * Filtering callback. This is where a filter receives a frame with
     * audio/video data and should do its processing.
     *
     * Input pads only.
     *
     * @return >= 0 on success, a negative AVERROR on error. This function
     * must ensure that frame is properly unreferenced on error if it
     * hasn't been passed on to another filter.
     */
    int (*filter_frame)(AVFilterLink *link, AVFrame *frame);

    /**
     * Frame poll callback. This returns the number of immediately available
     * samples. It should return a positive value if the next request_frame()
     * is guaranteed to return one frame (with no delay).
     *
     * Defaults to just calling the source poll_frame() method.
     *
     * Output pads only.
     */
    int (*poll_frame)(AVFilterLink *link);

    /**
     * Frame request callback. A call to this should result in some progress
     * towards producing output over the given link. This should return zero
     * on success, and another value on error.
     *
     * Output pads only.
     */
    int (*request_frame)(AVFilterLink *link);

    /**
     * Link configuration callback.
     *
     * For output pads, this should set the link properties such as
     * width/height. This should NOT set the format property - that is
     * negotiated between filters by the filter system using the
     * query_formats() callback before this function is called.
     *
     * For input pads, this should check the properties of the link, and update
     * the filter's internal state as necessary.
     *
     * For both input and output filters, this should return zero on success,
     * and another value on error.
     */
    int (*config_props)(AVFilterLink *link);

    /**
     * The filter expects a fifo to be inserted on its input link,
     * typically because it has a delay.
     *
     * input pads only.
     */
    int needs_fifo;

    /**
     * The filter expects writable frames from its input link,
     * duplicating data buffers if needed.
     *
     * input pads only.
     */
    int needs_writable;
};

struct AVFilterGraphInternal {
    void *thread;
    avfilter_execute_func *thread_execute;
};

struct AVFilterInternal {
    avfilter_execute_func *execute;
};

/**
 * Tell if an integer is contained in the provided -1-terminated list of integers.
 * This is useful for determining (for instance) if an AVPixelFormat is in an
 * array of supported formats.
 *
 * @param fmt provided format
 * @param fmts -1-terminated list of formats
 * @return 1 if present, 0 if absent
 */
int ff_fmt_is_in(int fmt, const int *fmts);

/* Functions to parse audio format arguments */

/**
 * Parse a pixel format.
 *
 * @param ret pixel format pointer to where the value should be written
 * @param arg string to parse
 * @param log_ctx log context
 * @return >= 0 in case of success, a negative AVERROR code on error
 */
av_warn_unused_result
int ff_parse_pixel_format(enum AVPixelFormat *ret, const char *arg, void *log_ctx);

/**
 * Parse a sample rate.
 *
 * @param ret unsigned integer pointer to where the value should be written
 * @param arg string to parse
 * @param log_ctx log context
 * @return >= 0 in case of success, a negative AVERROR code on error
 */
av_warn_unused_result
int ff_parse_sample_rate(int *ret, const char *arg, void *log_ctx);

/**
 * Parse a time base.
 *
 * @param ret unsigned AVRational pointer to where the value should be written
 * @param arg string to parse
 * @param log_ctx log context
 * @return >= 0 in case of success, a negative AVERROR code on error
 */
av_warn_unused_result
int ff_parse_time_base(AVRational *ret, const char *arg, void *log_ctx);

/**
 * Parse a sample format name or a corresponding integer representation.
 *
 * @param ret integer pointer to where the value should be written
 * @param arg string to parse
 * @param log_ctx log context
 * @return >= 0 in case of success, a negative AVERROR code on error
 */
av_warn_unused_result
int ff_parse_sample_format(int *ret, const char *arg, void *log_ctx);

/**
 * Parse a channel layout or a corresponding integer representation.
 *
 * @param ret 64bit integer pointer to where the value should be written.
 * @param nret integer pointer to the number of channels;
 *             if not NULL, then unknown channel layouts are accepted
 * @param arg string to parse
 * @param log_ctx log context
 * @return >= 0 in case of success, a negative AVERROR code on error
 */
av_warn_unused_result
int ff_parse_channel_layout(int64_t *ret, int *nret, const char *arg,
                            void *log_ctx);

void ff_update_link_current_pts(AVFilterLink *link, int64_t pts);

/**
 * Set the status field of a link from the source filter.
 * The pts should reflect the timestamp of the status change,
 * in link time base and relative to the frames timeline.
 * In particular, for AVERROR_EOF, it should reflect the
 * end time of the last frame.
 */
void ff_avfilter_link_set_in_status(AVFilterLink *link, int status, int64_t pts);

/**
 * Set the status field of a link from the destination filter.
 * The pts should probably be left unset (AV_NOPTS_VALUE).
 */
void ff_avfilter_link_set_out_status(AVFilterLink *link, int status, int64_t pts);

void ff_command_queue_pop(AVFilterContext *filter);

/* misc trace functions */

/* #define FF_AVFILTER_TRACE */

#ifdef FF_AVFILTER_TRACE
#    define ff_tlog(pctx, ...) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__)
#else
#    define ff_tlog(pctx, ...) do { if (0) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__); } while (0)
#endif

#define FF_TPRINTF_START(ctx, func) ff_tlog(NULL, "%-16s: ", #func)

char *ff_get_ref_perms_string(char *buf, size_t buf_size, int perms);

void ff_tlog_ref(void *ctx, AVFrame *ref, int end);

void ff_tlog_link(void *ctx, AVFilterLink *link, int end);

/**
 * Insert a new pad.
 *
 * @param idx Insertion point. Pad is inserted at the end if this point
 *            is beyond the end of the list of pads.
 * @param count Pointer to the number of pads in the list
 * @param padidx_off Offset within an AVFilterLink structure to the element
 *                   to increment when inserting a new pad causes link
 *                   numbering to change
 * @param pads Pointer to the pointer to the beginning of the list of pads
 * @param links Pointer to the pointer to the beginning of the list of links
 * @param newpad The new pad to add. A copy is made when adding.
 * @return >= 0 in case of success, a negative AVERROR code on error
 */
int ff_insert_pad(unsigned idx, unsigned *count, size_t padidx_off,
                   AVFilterPad **pads, AVFilterLink ***links,
                   AVFilterPad *newpad);

/** Insert a new input pad for the filter. */
static inline int ff_insert_inpad(AVFilterContext *f, unsigned index,
                                   AVFilterPad *p)
{
    return ff_insert_pad(index, &f->nb_inputs, offsetof(AVFilterLink, dstpad),
                  &f->input_pads, &f->inputs, p);
}

/** Insert a new output pad for the filter. */
static inline int ff_insert_outpad(AVFilterContext *f, unsigned index,
                                    AVFilterPad *p)
{
    return ff_insert_pad(index, &f->nb_outputs, offsetof(AVFilterLink, srcpad),
                  &f->output_pads, &f->outputs, p);
}

/**
 * Poll a frame from the filter chain.
 *
 * @param  link the input link
 * @return the number of immediately available frames, a negative
 * number in case of error
 */
int ff_poll_frame(AVFilterLink *link);

/**
 * Request an input frame from the filter at the other end of the link.
 *
 * The input filter may pass the request on to its inputs, fulfill the
 * request from an internal buffer or any other means specific to its function.
 *
 * When the end of a stream is reached AVERROR_EOF is returned and no further
 * frames are returned after that.
 *
 * When a filter is unable to output a frame for example due to its sources
 * being unable to do so or because it depends on external means pushing data
 * into it then AVERROR(EAGAIN) is returned.
 * It is important that a AVERROR(EAGAIN) return is returned all the way to the
 * caller (generally eventually a user application) as this step may (but does
 * not have to be) necessary to provide the input with the next frame.
 *
 * If a request is successful then some progress has been made towards
 * providing a frame on the link (through ff_filter_frame()). A filter that
 * needs several frames to produce one is allowed to return success if one
 * more frame has been processed but no output has been produced yet. A
 * filter is also allowed to simply forward a success return value.
 *
 * @param link the input link
 * @return     zero on success
 *             AVERROR_EOF on end of file
 *             AVERROR(EAGAIN) if the previous filter cannot output a frame
 *             currently and can neither guarantee that EOF has been reached.
 */
int ff_request_frame(AVFilterLink *link);

int ff_request_frame_to_filter(AVFilterLink *link);

#define AVFILTER_DEFINE_CLASS(fname)            \
    static const AVClass fname##_class = {      \
        .class_name = #fname,                   \
        .item_name  = av_default_item_name,     \
        .option     = fname##_options,          \
        .version    = LIBAVUTIL_VERSION_INT,    \
        .category   = AV_CLASS_CATEGORY_FILTER, \
    }

/**
 * Find the index of a link.
 *
 * I.e. find i such that link == ctx->(in|out)puts[i]
 */
#define FF_INLINK_IDX(link)  ((int)((link)->dstpad - (link)->dst->input_pads))
#define FF_OUTLINK_IDX(link) ((int)((link)->srcpad - (link)->src->output_pads))

/**
 * Send a frame of data to the next filter.
 *
 * @param link   the output link over which the data is being sent
 * @param frame a reference to the buffer of data being sent. The
 *              receiving filter will free this reference when it no longer
 *              needs it or pass it on to the next filter.
 *
 * @return >= 0 on success, a negative AVERROR on error. The receiving filter
 * is responsible for unreferencing frame in case of error.
 */
int ff_filter_frame(AVFilterLink *link, AVFrame *frame);

/**
 * Allocate a new filter context and return it.
 *
 * @param filter what filter to create an instance of
 * @param inst_name name to give to the new filter context
 *
 * @return newly created filter context or NULL on failure
 */
AVFilterContext *ff_filter_alloc(const AVFilter *filter, const char *inst_name);

/**
 * Remove a filter from a graph;
 */
void ff_filter_graph_remove_filter(AVFilterGraph *graph, AVFilterContext *filter);

/**
 * Run one round of processing on a filter graph.
 */
int ff_filter_graph_run_once(AVFilterGraph *graph);

/**
 * Normalize the qscale factor
 * FIXME the H264 qscale is a log based scale, mpeg1/2 is not, the code below
 *       cannot be optimal
 */
static inline int ff_norm_qscale(int qscale, int type)
{
    switch (type) {
    case FF_QSCALE_TYPE_MPEG1: return qscale;
    case FF_QSCALE_TYPE_MPEG2: return qscale >> 1;
    case FF_QSCALE_TYPE_H264:  return qscale >> 2;
    case FF_QSCALE_TYPE_VP56:  return (63 - qscale + 2) >> 2;
    }
    return qscale;
}

/**
 * Get number of threads for current filter instance.
 * This number is always same or less than graph->nb_threads.
 */
int ff_filter_get_nb_threads(AVFilterContext *ctx);

#endif /* AVFILTER_INTERNAL_H */


text:
using GSF.ASN1;
using GSF.ASN1.Attributes;
using GSF.ASN1.Coders;

namespace GSF.MMS.Model
{

    [ASN1PreparedElement]
    [ASN1BoxedType(Name = "AlarmAckRule")]
    public class AlarmAckRule : IASN1PreparedElement
    {
        private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(AlarmAckRule));
        private long val;

        public AlarmAckRule()
        {
        }

        public AlarmAckRule(long value)
        {
            Value = value;
        }

        [ASN1Integer(Name = "AlarmAckRule")]
        public long Value
        {
            get
            {
                return val;
            }
            set
            {
                val = value;
            }
        }

        public void initWithDefaults()
        {
        }

        public IASN1PreparedElementData PreparedData
        {
            get
            {
                return preparedData;
            }
        }
    }
}


text:
import blinker  # import is not needed, but it has to be installed in order to use signals
from skool.difficulty import mistrik
from skool.utils import makepath
from skool.settings import *
from mongoengine import *
from mongoengine import signals
import distance
import operator
import sys
connect('skool', host=MONGODB_HOST, port=MONGODB_PORT, username=MONGODB_USER, password=MONGODB_PASS)

def get_stopwords():
    with open(makepath('stopwords/czech.txt'), 'r') as fh:
        data = set([word.strip().decode('utf-8') for word in fh.readlines()])
    return list(data)

class Label(Document):
    id = SequenceField(required=True, unique=True, primary_key=True)
    name = StringField(required=True, unique=True)
    valid = BooleanField(required=True, default=True)
    label = BooleanField()

    @classmethod
    def filter_labels(cls, threshold=100):
        print "Gathering labels frequencies"
        labelfreq = {}
        for label in Label.objects:
            labelfreq[label.id] = 0
        for page in Page.objects:
            sys.stdout.write('.')
            sys.stdout.flush()
            for l in page.labels_all:
                labelfreq[l.id] += 1
        print "Filtering labels"
        sd = sorted(labelfreq.items(), key=operator.itemgetter(1))
        res = []
        for key, val in sd:
            sys.stdout.write('.')
            sys.stdout.flush()
            l = Label.objects(id=key).first()
            if val >= threshold:
                res.append((l.name, key, val))
                l.valid = True
            else:
                l.valid = False
            l.save()
        print "Done", len(res), "labels are OK"

class Category(Document):

    '''
    >>> _ = Category.objects(name="Skákal pes » Oves » Zelenou louku").delete()
    >>> c = Category(name="Skákal pes » Oves » Zelenou louku")
    >>> _ = c.save()
    >>> [l.name for l in c.labels]
    [u'sk\\xe1kal pes', u'oves', u'zelenou louku']
    >>> Category.objects(name="Skákal pes » Oves » Zelenou louku").delete()
    1
    '''
    name = StringField(required=True, unique=True)
    labels = ListField(ReferenceField(Label))

    @classmethod
    def categories_to_labels(cls, sender, document):
        if not document.labels:
            add = []
            labs = [x.strip().lower() for x in document.name.split(u"»")]
            for lab in labs:
                res = Label.objects(name=lab).first()
                if not res:
                    res = Label(name=lab)
                    res.save()
                add.append(res)
            document.labels = add

signals.pre_save.connect(Category.categories_to_labels, sender=Category)

class Language(Document):
    id = IntField(required=True, unique=True, primary_key=True)
    name = StringField(required=True, unique=True)

class Keyword(Document):
    name = StringField(required=True, unique=True)

class Page(Document):

    '''Single web page

    >>> _ = Page.objects(url="http://www.example.com/").delete()
    >>> _ = Site.objects(url="http://www.example.com/").delete()
    >>> cze = Language.objects(name='Čeština').first()
    >>> p = Site(url="http://www.example.com/", language=cze)
    >>> _ = p.save()
    >>> c = Page(url="http://www.example.com/", btext="Skákal pes přes oves. Přes zelenou louku.", parent=p)
    >>> _ = c.save()
    >>> c.cze
    True
    >>> c.diff
    44
    >>> c.cleanbtext
    u'sk\\xe1kal pes p\u0159es oves p\u0159es zelenou louku'
    >>> c.cleannostops
    u'sk\\xe1kal pes oves zelenou louku'
    >>> Page.objects(url="http://www.example.com/").delete()
    1
    >>> Site.objects(url="http://www.example.com/").delete()
    1
    '''
    btext = StringField()
    cleanbtext = StringField()
    cleannostops = StringField()
    url = URLField(required=True)
    label_teacher = ListField(ReferenceField(Category))
    label_model = ListField(ReferenceField(Label))
    diff = FloatField()
    # v uvozovkach kvuli circular reference
    parent = ReferenceField('Site')
    recs = ListField(ReferenceField('Page'))
    # introduce State variable, instead of all these?
    directory = BooleanField(required=True, default=False)
    classified = BooleanField(required=True, default=False)
    deleted = BooleanField(required=True, default=False)
    labeled = BooleanField(required=True, default=False)
    educational = BooleanField(required=True, default=False)

    @property
    def labels_teacher(self):
        return [x for cat in self.label_teacher for x in cat.labels]

    @property
    def labels_all(self):
        return [x for cat in self.parent.categories for x in cat.labels if x.valid]

    @property
    def cze(self):
        if self.parent and self.parent.language:
            return self.parent.language.name == u"Čeština"
        else:
            return False

    @property
    def keywords(self):
        return self.parent.keywords

    class Meta:  # try to delete this
        app_label = 'skool'

    @classmethod
    def compute_diff(cls, sender, document):
        if document.cze and not document.diff:
            document.diff = mistrik(document.btext)

    @classmethod
    def clean_btexts(cls, document):
        if document.cze and document.btext and not document.cleannostops:
            chars = ',;:.\'"!?$\\/-()[]{}=*+|'
            trans = dict.fromkeys(map(ord, chars), u' ')
            btext = document.btext
            btext = btext.translate(trans)
            btext = btext.lower()
            btext = ' '.join(btext.split())
            document.cleanbtext = btext
            stops = get_stopwords()
            document.cleannostops = ' '.join([x for x in document.cleanbtext.split() if x not in stops])

    @classmethod
    def predict_labels(cls, document):
        if document.cleannostops:
            from skool.classify import classify
            res = classify(document.cleannostops)
            add = []
            for r in res:
                l = Label.objects(id=r).first()
                if l:
                    add.append(l)
            document.label_model = add

    @classmethod
    def update_page_recs(cls, document):
        res = {}
        for site in Page.objects():
            if site != document:
                kwa, kwb = document.label_model, site.label_model
                ca = set(kwa)
                cb = set(kwb)
                if len(ca) > 0 and len(cb) > 0:
                    res[site.id] = distance.sorensen(ca, cb)
                else:
                    res[site.id] = 1  # 1 = totally different
        best = sorted(res.iteritems(), key=operator.itemgetter(1), reverse=False)[:10]
        ret = []
        for (obj, score) in best:
            s = Page.objects(id=obj).first()
            ret.append(s)
        document.recs = ret
        document.save()

    @classmethod
    def compute_recs(cls, document):
        if not document.parent and not document.recs:
            Page.update_page_recs(document)

    @classmethod
    def pre_save_seq(cls, sender, document):
        cls.clean_btexts(document)
        if not document.label_model:
            cls.predict_labels(document)
        cls.compute_recs(document)

    @classmethod
    def predict_all_labels(cls):
        for page in [x for x in Page.objects() if x.cze]:
            Page.predict_labels(page)
            page.save()
            sys.stdout.write('.')
            sys.stdout.flush()

signals.pre_save.connect(Page.compute_diff, sender=Page)
signals.pre_save.connect(Page.pre_save_seq, sender=Page)

class Site(Document):

    '''
    >>> _ = Keyword.objects(name="example1").delete()
    >>> _ = Keyword.objects(name="example2").delete()
    >>> _ = Keyword.objects(name="example3").delete()
    >>> k1 = Keyword(name="example1")
    >>> _ = k1.save()
    >>> k2 = Keyword(name="example2")
    >>> _ = k2.save()
    >>> k3 = Keyword(name="example3")
    >>> _ = k3.save()
    >>> _ = Site.objects(url="http://www.example.com/").delete()
    >>> _ = Site.objects(url="http://www.exexample.com/").delete()
    >>> a = Site(url="http://www.example.com/", keywords=[k1, k2])
    >>> _ = a.save()
    >>> b = Site(url="http://www.exexample.com/", keywords=[k2, k3])
    >>> _ = b.save()
    >>> b.recs[0].url
    u'http://www.example.com/'
    >>> Site.compute_recs(Site, a)
    >>> a.recs[0].url
    u'http://www.exexample.com/'
    >>> Site.objects(url="http://www.example.com/").delete()
    1
    >>> Site.objects(url="http://www.exexample.com/").delete()
    1
    >>> Keyword.objects(name="example1").delete()
    1
    >>> Keyword.objects(name="example2").delete()
    1
    >>> Keyword.objects(name="example3").delete()
    1
    '''
    url = URLField(required=True, unique=True)
    title = StringField()
    description = StringField()
    description2 = StringField()
    author = StringField()
    rating_rvp = DecimalField(min_value=0, max_value=5)
    rating_users = DecimalField(min_value=0, max_value=5)
    published = DateTimeField()
    show = IntField(min_value=0)
    image_url = URLField()
    recs = ListField(ReferenceField('Site'))
    children_labeled = ListField(ReferenceField(Page))
    categories = ListField(ReferenceField(Category))
    keywords = ListField(ReferenceField(Keyword))
    children = ListField(ReferenceField(Page))
    language = ReferenceField(Language)

    @classmethod
    def update_site_recs(cls, document, sites=None):
        res = {}
        if not sites:
            sites = Site.objects()
            sites.timeout(False)
        for site in sites:
            if site != document:
                kwa, kwb = document.keywords, site.keywords
                ca = set(kwa)
                cb = set(kwb)
                if len(ca) > 0 and len(cb) > 0:
                    res[site.id] = distance.sorensen(ca, cb)
                else:
                    res[site.id] = 1  # 1 = totally different
        best = sorted(res.iteritems(), key=operator.itemgetter(1), reverse=False)[:10]
        ret = []
        for (obj, score) in best:
            s = Site.objects(id=obj).first()
            ret.append(s)
        document.recs = ret
        document.save()

    @classmethod
    def update_all_recs(cls):
        sites = Site.objects()
        sites.timeout(False)    # disable cursor timeout
        print "Rebuilding", len(sites), "Site's recommendations"
        cnt = 0
        for site in sites:
            Site.update_site_recs(site, sites)
            cnt += 1
            sys.stdout.write('.')
            sys.stdout.flush()
        print cnt, "sites processed"

if __name__ == '__main__':
    import doctest
    # doctest.ELLIPSIS_MARKER = '-etc-'
    # doctest.testmod(optionflags=doctest.ELLIPSIS)
    # or just assign result to dummy _
    doctest.testmod()


text:
package kubectl

import (
	"fmt"
	"strconv"
	"strings"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/util/intstr"
)

// The only difference between ServiceGeneratorV1 and V2 is that the service port is named "default" in V1, while it is left unnamed in V2.
type ServiceGeneratorV1 struct{}

func (ServiceGeneratorV1) ParamNames() []GeneratorParam {
	return paramNames()
}

func (ServiceGeneratorV1) Generate(params map[string]interface{}) (runtime.Object, error) {
	params["port-name"] = "default"
	return generate(params)
}

type ServiceGeneratorV2 struct{}

func (ServiceGeneratorV2) ParamNames() []GeneratorParam {
	return paramNames()
}

func (ServiceGeneratorV2) Generate(params map[string]interface{}) (runtime.Object, error) {
	return generate(params)
}

func paramNames() []GeneratorParam {
	return []GeneratorParam{
		{"default-name", true},
		{"name", false},
		{"selector", true},
		// port will be used if a user specifies --port OR the exposed object
		// has one port
		{"port", false},
		// ports will be used iff a user doesn't specify --port AND the
		// exposed object has multiple ports
		{"ports", false},
		{"labels", false},
		{"external-ip", false},
		{"create-external-load-balancer", false},
		{"load-balancer-ip", false},
		{"type", false},
		{"protocol", false},
		{"container-port", false}, // alias of target-port
		{"target-port", false},
		{"port-name", false},
		{"session-affinity", false},
	}
}

func generate(genericParams map[string]interface{}) (runtime.Object, error) {
	params := map[string]string{}
	for key, value := range genericParams {
		strVal, isString := value.(string)
		if !isString {
			return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key)
		}
		params[key] = strVal
	}
	selectorString, found := params["selector"]
	if !found || len(selectorString) == 0 {
		return nil, fmt.Errorf("'selector' is a required parameter.")
	}
	selector, err := ParseLabels(selectorString)
	if err != nil {
		return nil, err
	}

	labelsString, found := params["labels"]
	var labels map[string]string
	if found && len(labelsString) > 0 {
		labels, err = ParseLabels(labelsString)
		if err != nil {
			return nil, err
		}
	}

	name, found := params["name"]
	if !found || len(name) == 0 {
		name, found = params["default-name"]
		if !found || len(name) == 0 {
			return nil, fmt.Errorf("'name' is a required parameter.")
		}
	}
	ports := []api.ServicePort{}
	servicePortName, found := params["port-name"]
	if !found {
		// Leave the port unnamed.
		servicePortName = ""
	}
	// ports takes precedence over port since it will be
	// specified only when the user hasn't specified a port
	// via --port and the exposed object has multiple ports.
	var portString string
	if portString, found = params["ports"]; !found {
		portString, found = params["port"]
		if !found {
			return nil, fmt.Errorf("'port' is a required parameter.")
		}
	}
	portStringSlice := strings.Split(portString, ",")
	for i, stillPortString := range portStringSlice {
		port, err := strconv.Atoi(stillPortString)
		if err != nil {
			return nil, err
		}
		name := servicePortName
		// If we are going to assign multiple ports to a service, we need to
		// generate a different name for each one.
		if len(portStringSlice) > 1 {
			name = fmt.Sprintf("port-%d", i+1)
		}
		ports = append(ports, api.ServicePort{
			Name:     name,
			Port:     port,
			Protocol: api.Protocol(params["protocol"]),
		})
	}

	service := api.Service{
		ObjectMeta: api.ObjectMeta{
			Name:   name,
			Labels: labels,
		},
		Spec: api.ServiceSpec{
			Selector: selector,
			Ports:    ports,
		},
	}
	targetPortString := params["target-port"]
	if len(targetPortString) == 0 {
		targetPortString = params["container-port"]
	}
	if len(targetPortString) > 0 {
		var targetPort intstr.IntOrString
		if portNum, err := strconv.Atoi(targetPortString); err != nil {
			targetPort = intstr.FromString(targetPortString)
		} else {
			targetPort = intstr.FromInt(portNum)
		}
		// Use the same target-port for every port
		for i := range service.Spec.Ports {
			service.Spec.Ports[i].TargetPort = targetPort
		}
	} else {
		// If --target-port or --container-port haven't been specified, this
		// should be the same as Port
		for i := range service.Spec.Ports {
			port := service.Spec.Ports[i].Port
			service.Spec.Ports[i].TargetPort = intstr.FromInt(port)
		}
	}
	if params["create-external-load-balancer"] == "true" {
		service.Spec.Type = api.ServiceTypeLoadBalancer
	}
	if len(params["external-ip"]) > 0 {
		service.Spec.ExternalIPs = []string{params["external-ip"]}
	}
	if len(params["type"]) != 0 {
		service.Spec.Type = api.ServiceType(params["type"])
	}
	if service.Spec.Type == api.ServiceTypeLoadBalancer {
		service.Spec.LoadBalancerIP = params["load-balancer-ip"]
	}
	if len(params["session-affinity"]) != 0 {
		switch api.ServiceAffinity(params["session-affinity"]) {
		case api.ServiceAffinityNone:
			service.Spec.SessionAffinity = api.ServiceAffinityNone
		case api.ServiceAffinityClientIP:
			service.Spec.SessionAffinity = api.ServiceAffinityClientIP
		default:
			return nil, fmt.Errorf("unknown session affinity: %s", params["session-affinity"])
		}
	}
	return &service, nil
}


text:
<title>Test for CSS transitions and re-wrapping of inlines</title>

This is some text with a transition.


text:
<?php

defined('JPATH_BASE') or die;

jimport('joomla.form.formfield');

class JFormFieldUpdate extends JFormField {
	protected $type = 'Update';

	protected function getInput() {
		return '

';
	}
}

?>


text:
require 'active_support/core_ext/benchmark'
require 'net/https'
require 'date'
require 'time'
require 'uri'

module ActiveResource
  # Class to handle connections to remote web services.
  # This class is used by ActiveResource::Base to interface with REST
  # services.
  class Connection

    HTTP_FORMAT_HEADER_NAMES = {  :get => 'Accept',
      :put => 'Content-Type',
      :post => 'Content-Type',
      :delete => 'Accept',
      :head => 'Accept'
    }

    attr_reader :site, :user, :password, :auth_type, :timeout, :proxy, :ssl_options
    attr_accessor :format

    class << self
      def requests
        @@requests ||= []
      end
    end

    # The +site+ parameter is required and will set the +site+
    # attribute to the URI for the remote resource service.
    def initialize(site, format = ActiveResource::Formats::XmlFormat)
      raise ArgumentError, 'Missing site URI' unless site
      @user = @password = nil
      @uri_parser = URI.const_defined?(:Parser) ? URI::Parser.new : URI
      self.site = site
      self.format = format
    end

    # Set URI for remote service.
    def site=(site)
      @site = site.is_a?(URI) ? site : @uri_parser.parse(site)
      @user = @uri_parser.unescape(@site.user) if @site.user
      @password = @uri_parser.unescape(@site.password) if @site.password
    end

    # Set the proxy for remote service.
    def proxy=(proxy)
      @proxy = proxy.is_a?(URI) ? proxy : @uri_parser.parse(proxy)
    end

    # Sets the user for remote service.
    def user=(user)
      @user = user
    end

    # Sets the password for remote service.
    def password=(password)
      @password = password
    end

    # Sets the auth type for remote service.
    def auth_type=(auth_type)
      @auth_type = legitimize_auth_type(auth_type)
    end

    # Sets the number of seconds after which HTTP requests to the remote service should time out.
    def timeout=(timeout)
      @timeout = timeout
    end

    # Hash of options applied to Net::HTTP instance when +site+ protocol is 'https'.
    def ssl_options=(opts={})
      @ssl_options = opts
    end

    # Executes a GET request.
    # Used to get (find) resources.
    def get(path, headers = {})
      with_auth { format.decode(request(:get, path, build_request_headers(headers, :get, self.site.merge(path))).body) }
    end

    # Executes a DELETE request (see HTTP protocol documentation if unfamiliar).
    # Used to delete resources.
    def delete(path, headers = {})
      with_auth { request(:delete, path, build_request_headers(headers, :delete, self.site.merge(path))) }
    end

    # Executes a PUT request (see HTTP protocol documentation if unfamiliar).
    # Used to update resources.
    def put(path, body = '', headers = {})
      with_auth { request(:put, path, body.to_s, build_request_headers(headers, :put, self.site.merge(path))) }
    end

    # Executes a POST request.
    # Used to create new resources.
    def post(path, body = '', headers = {})
      with_auth { request(:post, path, body.to_s, build_request_headers(headers, :post, self.site.merge(path))) }
    end

    # Executes a HEAD request.
    # Used to obtain meta-information about resources, such as whether they exist and their size (via response headers).
    def head(path, headers = {})
      with_auth { request(:head, path, build_request_headers(headers, :head, self.site.merge(path))) }
    end

    private
      # Makes a request to the remote service.
      def request(method, path, *arguments)
        result = ActiveSupport::Notifications.instrument("request.active_resource") do |payload|
          payload[:method]      = method
          payload[:request_uri] = "#{site.scheme}://#{site.host}:#{site.port}#{path}"
          payload[:result]      = http.send(method, path, *arguments)
        end
        handle_response(result)
      rescue Timeout::Error => e
        raise TimeoutError.new(e.message)
      rescue OpenSSL::SSL::SSLError => e
        raise SSLError.new(e.message)
      end

      # Handles response and error codes from the remote service.
      def handle_response(response)
        case response.code.to_i
          when 301,302
            raise(Redirection.new(response))
          when 200...400
            response
          when 400
            raise(BadRequest.new(response))
          when 401
            raise(UnauthorizedAccess.new(response))
          when 403
            raise(ForbiddenAccess.new(response))
          when 404
            raise(ResourceNotFound.new(response))
          when 405
            raise(MethodNotAllowed.new(response))
          when 409
            raise(ResourceConflict.new(response))
          when 410
            raise(ResourceGone.new(response))
          when 422
            raise(ResourceInvalid.new(response))
          when 401...500
            raise(ClientError.new(response))
          when 500...600
            raise(ServerError.new(response))
          else
            raise(ConnectionError.new(response, "Unknown response code: #{response.code}"))
        end
      end

      # Creates new Net::HTTP instance for communication with the
      # remote service and resources.
      def http
        configure_http(new_http)
      end

      def new_http
        if @proxy
          Net::HTTP.new(@site.host, @site.port, @proxy.host, @proxy.port, @proxy.user, @proxy.password)
        else
          Net::HTTP.new(@site.host, @site.port)
        end
      end

      def configure_http(http)
        http = apply_ssl_options(http)

        # Net::HTTP timeouts default to 60 seconds.
        if @timeout
          http.open_timeout = @timeout
          http.read_timeout = @timeout
        end

        http
      end

      def apply_ssl_options(http)
        return http unless @site.is_a?(URI::HTTPS)

        http.use_ssl     = true
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE
        return http unless defined?(@ssl_options)

        http.ca_path     = @ssl_options[:ca_path] if @ssl_options[:ca_path]
        http.ca_file     = @ssl_options[:ca_file] if @ssl_options[:ca_file]

        http.cert        = @ssl_options[:cert] if @ssl_options[:cert]
        http.key         = @ssl_options[:key]  if @ssl_options[:key]

        http.cert_store  = @ssl_options[:cert_store]  if @ssl_options[:cert_store]
        http.ssl_timeout = @ssl_options[:ssl_timeout] if @ssl_options[:ssl_timeout]

        http.verify_mode     = @ssl_options[:verify_mode]     if @ssl_options[:verify_mode]
        http.verify_callback = @ssl_options[:verify_callback] if @ssl_options[:verify_callback]
        http.verify_depth    = @ssl_options[:verify_depth]    if @ssl_options[:verify_depth]

        http
      end

      def default_header
        @default_header ||= {}
      end

      # Builds headers for request to remote service.
      def build_request_headers(headers, http_method, uri)
        authorization_header(http_method, uri).update(default_header).update(http_format_header(http_method)).update(headers)
      end

      def response_auth_header
        @response_auth_header ||= ""
      end

      def with_auth
        retried ||= false
        yield
      rescue UnauthorizedAccess => e
        raise if retried || auth_type != :digest
        @response_auth_header = e.response['WWW-Authenticate']
        retried = true
        retry
      end

      def authorization_header(http_method, uri)
        if @user || @password
          if auth_type == :digest
            { 'Authorization' => digest_auth_header(http_method, uri) }
          else
            { 'Authorization' => 'Basic ' + ["#{@user}:#{@password}"].pack('m').delete("\r\n") }
          end
        else
          {}
        end
      end

      def digest_auth_header(http_method, uri)
        params = extract_params_from_response

        ha1 = Digest::MD5.hexdigest("#{@user}:#{params['realm']}:#{@password}")
        ha2 = Digest::MD5.hexdigest("#{http_method.to_s.upcase}:#{uri.path}")

        params.merge!('cnonce' => client_nonce)
        request_digest = Digest::MD5.hexdigest([ha1, params['nonce'], "0", params['cnonce'], params['qop'], ha2].join(":"))
        "Digest #{auth_attributes_for(uri, request_digest, params)}"
      end

      def client_nonce
        Digest::MD5.hexdigest("%x" % (Time.now.to_i + rand(65535)))
      end

      def extract_params_from_response
        params = {}
        if response_auth_header =~ /^(\w+) (.*)/
          $2.gsub(/(\w+)="(.*?)"/) { params[$1] = $2 }
        end
        params
      end

      def auth_attributes_for(uri, request_digest, params)
        [
          %Q(username="#{@user}"),
          %Q(realm="#{params['realm']}"),
          %Q(qop="#{params['qop']}"),
          %Q(uri="#{uri.path}"),
          %Q(nonce="#{params['nonce']}"),
          %Q(nc="0"),
          %Q(cnonce="#{params['cnonce']}"),
          %Q(opaque="#{params['opaque']}"),
          %Q(response="#{request_digest}")].join(", ")
      end

      def http_format_header(http_method)
        {HTTP_FORMAT_HEADER_NAMES[http_method] => format.mime_type}
      end

      def legitimize_auth_type(auth_type)
        return :basic if auth_type.nil?
        auth_type = auth_type.to_sym
        [:basic, :digest].include?(auth_type) ? auth_type : :basic
      end
  end
end


text:
package xdoclet.modules.ojb.model;

/**
 * Definition of an index descriptor for a ojb-persistent class.
 *
 * @author Thomas Dudziak (tomdz@users.sourceforge.net)
 */
public class IndexDescriptorDef extends DefBase
{
    /**
     * Creates a new index descriptor definition object.
     *
     * @param name The name of the index
     */
    public IndexDescriptorDef(String name)
    {
        super(name);
    }
}


text:
'use strict';

// Vehicle logs controller
angular.module('vehicle-logs').controller('VehicleLogsController', ['$scope', '$stateParams', '$location', 'Authentication', 'VehicleLogs',
	function($scope, $stateParams, $location, Authentication, VehicleLogs) {
		$scope.authentication = Authentication;

		// Create new Vehicle log
		$scope.create = function() {
			// Create new Vehicle log object
			var vehicleLog = new VehicleLogs ({
				weekStartingDate: this.weekStartingDate,
        vehicleNo: this.vehicleNo
			});

			// Redirect after save
			vehicleLog.$save(function(response) {
				$location.path('vehicle-logs/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Vehicle log
		$scope.remove = function(vehicleLog) {
			if ( vehicleLog ) {
				vehicleLog.$remove();

				for (var i in $scope.vehicleLogs) {
					if ($scope.vehicleLogs [i] === vehicleLog) {
						$scope.vehicleLogs.splice(i, 1);
					}
				}
			} else {
				$scope.vehicleLog.$remove(function() {
					$location.path('vehicle-logs');
				});
			}
		};

		// Update existing Vehicle log
		$scope.update = function() {
			var vehicleLog = $scope.vehicleLog;

			vehicleLog.$update(function() {
				$location.path('vehicle-logs/' + vehicleLog._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Vehicle logs
		$scope.find = function() {
			$scope.vehicleLogs = VehicleLogs.query();
		};

		// Find existing Vehicle log
		$scope.findOne = function() {
			$scope.vehicleLog = VehicleLogs.get({
				vehicleLogId: $stateParams.vehicleLogId
			});
		};
	}
]);


text:
package org.camunda.bpm.engine.test.standalone.db;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

import org.apache.ibatis.session.SqlSession;
import org.camunda.bpm.engine.impl.ProcessEngineImpl;
import org.camunda.bpm.engine.impl.ProcessEngineLogger;
import org.camunda.bpm.engine.impl.db.sql.DbSqlSession;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase;
import org.slf4j.Logger;

/**
 * @author Tom Baeyens
 */
public class MetaDataTest extends PluggableProcessEngineTestCase {

private static Logger LOG = ProcessEngineLogger.TEST_LOGGER.getLogger();

  public void testMetaData() {
    ((ProcessEngineImpl)processEngine)
      .getProcessEngineConfiguration()
      .getCommandExecutorTxRequired()
      .execute(new Command<Object>() {
        public Object execute(CommandContext commandContext) {
          // PRINT THE TABLE NAMES TO CHECK IF WE CAN USE METADATA INSTEAD
          // THIS IS INTENDED FOR TEST THAT SHOULD RUN ON OUR QA INFRASTRUCTURE TO SEE IF METADATA
          // CAN BE USED INSTEAD OF PERFORMING A QUERY THAT MIGHT FAIL
          try {
            SqlSession sqlSession = commandContext.getSession(DbSqlSession.class).getSqlSession();
            ResultSet tables = sqlSession.getConnection().getMetaData().getTables(null, null, null, null);
            while (tables.next()) {
              ResultSetMetaData resultSetMetaData = tables.getMetaData();
              int columnCount = resultSetMetaData.getColumnCount();
              for (int i=1; i<=columnCount; i++) {
                LOG.info("result set column "+i+" | "+resultSetMetaData.getColumnName(i)+" | "+resultSetMetaData.getColumnLabel(i)+" | "+tables.getString(i));
              }
              LOG.info("-------------------------------------------------------");
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
          return null;
        }
      });
  }

  public void testMariaDbDatabaseType() {
    if (isMariaDbConfigured()) {
      assertEquals("mariadb",  processEngineConfiguration.getDatabaseType());
    }
  }

  public boolean isMariaDbConfigured() {
    return processEngineConfiguration.getJdbcUrl().toLowerCase().contains("mariadb") ||
      processEngineConfiguration.getJdbcDriver().toLowerCase().contains("mariadb");
  }
}


text:
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.ServiceBus.Models;

namespace Azure.ResourceManager.ServiceBus
{
    /// <summary>
    /// A Class representing a ServiceBusDisasterRecovery along with the instance operations that can be performed on it.
    /// If you have a <see cref="ResourceIdentifier" /> you can construct a <see cref="ServiceBusDisasterRecoveryResource" />
    /// from an instance of <see cref="ArmClient" /> using the GetServiceBusDisasterRecoveryResource method.
    /// Otherwise you can get one from its parent resource <see cref="ServiceBusNamespaceResource" /> using the GetServiceBusDisasterRecovery method.
    /// </summary>
    public partial class ServiceBusDisasterRecoveryResource : ArmResource
    {
        /// <summary> Generate the resource identifier of a <see cref="ServiceBusDisasterRecoveryResource"/> instance. </summary>
        public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string namespaceName, string @alias)
        {
            var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{@alias}";
            return new ResourceIdentifier(resourceId);
        }

        private readonly ClientDiagnostics _serviceBusDisasterRecoveryDisasterRecoveryConfigsClientDiagnostics;
        private readonly DisasterRecoveryConfigsRestOperations _serviceBusDisasterRecoveryDisasterRecoveryConfigsRestClient;
        private readonly ServiceBusDisasterRecoveryData _data;

        /// <summary> Initializes a new instance of the <see cref="ServiceBusDisasterRecoveryResource"/> class for mocking. </summary>
        protected ServiceBusDisasterRecoveryResource()
        {
        }

        /// <summary> Initializes a new instance of the <see cref = "ServiceBusDisasterRecoveryResource"/> class. </summary>
        /// <param name="client"> The client parameters to use in these operations. </param>
        /// <param name="data"> The resource that is the target of operations. </param>
        internal ServiceBusDisasterRecoveryResource(ArmClient client, ServiceBusDisasterRecoveryData data) : this(client, data.Id)
        {
            HasData = true;
            _data = data;
        }

        /// <summary> Initializes a new instance of the <see cref="ServiceBusDisasterRecoveryResource"/> class. </summary>
        /// <param name="client"> The client parameters to use in these operations. </param>
        /// <param name="id"> The identifier of the resource that is the target of operations. </param>
        internal ServiceBusDisasterRecoveryResource(ArmClient client, ResourceIdentifier id) : base(client, id)
        {
            _serviceBusDisasterRecoveryDisasterRecoveryConfigsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.ServiceBus", ResourceType.Namespace, Diagnostics);
            TryGetApiVersion(ResourceType, out string serviceBusDisasterRecoveryDisasterRecoveryConfigsApiVersion);
            _serviceBusDisasterRecoveryDisasterRecoveryConfigsRestClient = new DisasterRecoveryConfigsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, serviceBusDisasterRecoveryDisasterRecoveryConfigsApiVersion);
#if DEBUG
			ValidateResourceId(Id);
#endif
        }

        /// <summary> Gets the resource type for the operations. </summary>
        public static readonly ResourceType ResourceType = "Microsoft.ServiceBus/namespaces/disasterRecoveryConfigs";

        /// <summary> Gets whether or not the current instance has data. </summary>
        public virtual bool HasData { get; }

        /// <summary> Gets the data representing this Feature. </summary>
        /// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
        public virtual ServiceBusDisasterRecoveryData Data
        {
            get
            {
                if (!HasData)
                    throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
                return _data;
            }
        }

        internal static void ValidateResourceId(ResourceIdentifier id)
        {
            if (id.ResourceType != ResourceType)
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
        }

        /// <summary> Gets a collection of ServiceBusDisasterRecoveryAuthorizationRuleResources in the ServiceBusDisasterRecovery. </summary>
        /// <returns> An object representing collection of ServiceBusDisasterRecoveryAuthorizationRuleResources and their operations over a ServiceBusDisasterRecoveryAuthorizationRuleResource. </returns>
        public virtual ServiceBusDisasterRecoveryAuthorizationRuleCollection GetServiceBusDisasterRecoveryAuthorizationRules()
        {
            return GetCachedClient(Client => new ServiceBusDisasterRecoveryAuthorizationRuleCollection(Client, Id));
        }

        /// <summary>
        /// Gets an authorization rule for a namespace by rule name.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/authorizationRules/{authorizationRuleName}
        /// Operation Id: DisasterRecoveryAuthorizationRules_Get
        /// </summary>
        /// <param name="authorizationRuleName"> The authorization rule name. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="authorizationRuleName"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="authorizationRuleName"/> is null. </exception>
        [ForwardsClientCalls]
        public virtual async Task<Response<ServiceBusDisasterRecoveryAuthorizationRuleResource>> GetServiceBusDisasterRecoveryAuthorizationRuleAsync(string authorizationRuleName, CancellationToken cancellationToken = default)
        {
            return await GetServiceBusDisasterRecoveryAuthorizationRules().GetAsync(authorizationRuleName, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Gets an authorization rule for a namespace by rule name.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/authorizationRules/{authorizationRuleName}
        /// Operation Id: DisasterRecoveryAuthorizationRules_Get
        /// </summary>
        /// <param name="authorizationRuleName"> The authorization rule name. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="authorizationRuleName"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="authorizationRuleName"/> is null. </exception>
        [ForwardsClientCalls]
        public virtual Response<ServiceBusDisasterRecoveryAuthorizationRuleResource> GetServiceBusDisasterRecoveryAuthorizationRule(string authorizationRuleName, CancellationToken cancellationToken = default)
        {
            return GetServiceBusDisasterRecoveryAuthorizationRules().Get(authorizationRuleName, cancellationToken);
        }

        /// <summary>
        /// Retrieves Alias(Disaster Recovery configuration) for primary or secondary namespace
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}
        /// Operation Id: DisasterRecoveryConfigs_Get
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<ServiceBusDisasterRecoveryResource>> GetAsync(CancellationToken cancellationToken = default)
        {
            using var scope = _serviceBusDisasterRecoveryDisasterRecoveryConfigsClientDiagnostics.CreateScope("ServiceBusDisasterRecoveryResource.Get");
            scope.Start();
            try
            {
                var response = await _serviceBusDisasterRecoveryDisasterRecoveryConfigsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new ServiceBusDisasterRecoveryResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Retrieves Alias(Disaster Recovery configuration) for primary or secondary namespace
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}
        /// Operation Id: DisasterRecoveryConfigs_Get
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<ServiceBusDisasterRecoveryResource> Get(CancellationToken cancellationToken = default)
        {
            using var scope = _serviceBusDisasterRecoveryDisasterRecoveryConfigsClientDiagnostics.CreateScope("ServiceBusDisasterRecoveryResource.Get");
            scope.Start();
            try
            {
                var response = _serviceBusDisasterRecoveryDisasterRecoveryConfigsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new ServiceBusDisasterRecoveryResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Deletes an Alias(Disaster Recovery configuration)
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}
        /// Operation Id: DisasterRecoveryConfigs_Delete
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<ArmOperation> DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default)
        {
            using var scope = _serviceBusDisasterRecoveryDisasterRecoveryConfigsClientDiagnostics.CreateScope("ServiceBusDisasterRecoveryResource.Delete");
            scope.Start();
            try
            {
                var response = await _serviceBusDisasterRecoveryDisasterRecoveryConfigsRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
                var operation = new ServiceBusArmOperation(response);
                if (waitUntil == WaitUntil.Completed)
                    await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Deletes an Alias(Disaster Recovery configuration)
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}
        /// Operation Id: DisasterRecoveryConfigs_Delete
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default)
        {
            using var scope = _serviceBusDisasterRecoveryDisasterRecoveryConfigsClientDiagnostics.CreateScope("ServiceBusDisasterRecoveryResource.Delete");
            scope.Start();
            try
            {
                var response = _serviceBusDisasterRecoveryDisasterRecoveryConfigsRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
                var operation = new ServiceBusArmOperation(response);
                if (waitUntil == WaitUntil.Completed)
                    operation.WaitForCompletionResponse(cancellationToken);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Creates or updates a new Alias(Disaster Recovery configuration)
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}
        /// Operation Id: DisasterRecoveryConfigs_CreateOrUpdate
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="data"> Parameters required to create an Alias(Disaster Recovery configuration). </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="data"/> is null. </exception>
        public virtual async Task<ArmOperation<ServiceBusDisasterRecoveryResource>> UpdateAsync(WaitUntil waitUntil, ServiceBusDisasterRecoveryData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(data, nameof(data));

            using var scope = _serviceBusDisasterRecoveryDisasterRecoveryConfigsClientDiagnostics.CreateScope("ServiceBusDisasterRecoveryResource.Update");
            scope.Start();
            try
            {
                var response = await _serviceBusDisasterRecoveryDisasterRecoveryConfigsRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false);
                var operation = new ServiceBusArmOperation<ServiceBusDisasterRecoveryResource>(Response.FromValue(new ServiceBusDisasterRecoveryResource(Client, response), response.GetRawResponse()));
                if (waitUntil == WaitUntil.Completed)
                    await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Creates or updates a new Alias(Disaster Recovery configuration)
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}
        /// Operation Id: DisasterRecoveryConfigs_CreateOrUpdate
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="data"> Parameters required to create an Alias(Disaster Recovery configuration). </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="data"/> is null. </exception>
        public virtual ArmOperation<ServiceBusDisasterRecoveryResource> Update(WaitUntil waitUntil, ServiceBusDisasterRecoveryData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(data, nameof(data));

            using var scope = _serviceBusDisasterRecoveryDisasterRecoveryConfigsClientDiagnostics.CreateScope("ServiceBusDisasterRecoveryResource.Update");
            scope.Start();
            try
            {
                var response = _serviceBusDisasterRecoveryDisasterRecoveryConfigsRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken);
                var operation = new ServiceBusArmOperation<ServiceBusDisasterRecoveryResource>(Response.FromValue(new ServiceBusDisasterRecoveryResource(Client, response), response.GetRawResponse()));
                if (waitUntil == WaitUntil.Completed)
                    operation.WaitForCompletion(cancellationToken);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// This operation disables the Disaster Recovery and stops replicating changes from primary to secondary namespaces
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/breakPairing
        /// Operation Id: DisasterRecoveryConfigs_BreakPairing
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response> BreakPairingAsync(CancellationToken cancellationToken = default)
        {
            using var scope = _serviceBusDisasterRecoveryDisasterRecoveryConfigsClientDiagnostics.CreateScope("ServiceBusDisasterRecoveryResource.BreakPairing");
            scope.Start();
            try
            {
                var response = await _serviceBusDisasterRecoveryDisasterRecoveryConfigsRestClient.BreakPairingAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
                return response;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// This operation disables the Disaster Recovery and stops replicating changes from primary to secondary namespaces
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/breakPairing
        /// Operation Id: DisasterRecoveryConfigs_BreakPairing
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response BreakPairing(CancellationToken cancellationToken = default)
        {
            using var scope = _serviceBusDisasterRecoveryDisasterRecoveryConfigsClientDiagnostics.CreateScope("ServiceBusDisasterRecoveryResource.BreakPairing");
            scope.Start();
            try
            {
                var response = _serviceBusDisasterRecoveryDisasterRecoveryConfigsRestClient.BreakPairing(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
                return response;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Invokes GEO DR failover and reconfigure the alias to point to the secondary namespace
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/failover
        /// Operation Id: DisasterRecoveryConfigs_FailOver
        /// </summary>
        /// <param name="failoverProperties"> Parameters required to create an Alias(Disaster Recovery configuration). </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response> FailOverAsync(FailoverProperties failoverProperties = null, CancellationToken cancellationToken = default)
        {
            using var scope = _serviceBusDisasterRecoveryDisasterRecoveryConfigsClientDiagnostics.CreateScope("ServiceBusDisasterRecoveryResource.FailOver");
            scope.Start();
            try
            {
                var response = await _serviceBusDisasterRecoveryDisasterRecoveryConfigsRestClient.FailOverAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, failoverProperties, cancellationToken).ConfigureAwait(false);
                return response;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Invokes GEO DR failover and reconfigure the alias to point to the secondary namespace
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/failover
        /// Operation Id: DisasterRecoveryConfigs_FailOver
        /// </summary>
        /// <param name="failoverProperties"> Parameters required to create an Alias(Disaster Recovery configuration). </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response FailOver(FailoverProperties failoverProperties = null, CancellationToken cancellationToken = default)
        {
            using var scope = _serviceBusDisasterRecoveryDisasterRecoveryConfigsClientDiagnostics.CreateScope("ServiceBusDisasterRecoveryResource.FailOver");
            scope.Start();
            try
            {
                var response = _serviceBusDisasterRecoveryDisasterRecoveryConfigsRestClient.FailOver(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, failoverProperties, cancellationToken);
                return response;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
    }
}


text:
title: "18/04/2019 - Oferta de feina a la Fundació Pau Costa"
dataPub: 18/04/2019

clase: 'noticia'

---
La Fundació Pau Costa està buscant especialista en incendis forestals per cobrir una baixa de maternitat, amb la possibilitat d'allargar el contracte.

Tota la informació de l'oferta es pot trobar a la web de la Fundació Pau Costa.


text:
Carbon Wallet Recovery Tool
============================

You can use this open source tool to send all the coins from your CarbonWallet backup to any bitcoin address you choose.

http://onchain.github.io/carbonwallet-recovery

In order to do this you will need the data from your wallet backup that you either printed out or saved somewhere. It looks  something like this.

![Wallet Backup](https://raw.githubusercontent.com/onchain/carbonwallet-recovery/gh-pages/wallet-backup.png)

You can download this github code and use it locally or you can trust github and access it with the link below.

http://onchain.github.io/carbonwallet-recovery

## Usage

### Required input

To complete this recovery process, you will need the following information:

* 2 extended public keys (xpubkeys)
* 1 BIP38 Keys
* Your Carbon Wallet passphrase
* Your CarbonKey backup passphrase

### Online/Offline

Internet connection is only required in **Step 1**, where you input the public keys, so that we can fetch the unspent outputs from your vault addresses.

Before inputting your keys in **Step 2** and signing the transaction you can safely go _offline_.

In **Step 3** you will get a signed transaction in raw hex form.

You can then copy this transaction and verify it with [Bitcoin Core](https://bitcoin.org/en/download) and `decoderawtransaction` or using an online tool like [Coinb.in](http://coinb.in/multisig/#verify).

After verifying you then broadcast it using [Bitcoin Core](https://bitcoin.org/en/download) and `sendrawtransaction` or any other API or client that supports broadcasting transactions into the Bitcoin network.

### Running

http://onchain.github.io/carbonwallet-recovery

#### Running locally

Download the files and access index.html from your browser. (Tested with Firefox)


text:
namespace chromecast {

scoped_ptr<base::Value> DeserializeFromJson(const std::string& text) {
  JSONStringValueDeserializer deserializer(text);

  int error_code;
  std::string error_msg;
  scoped_ptr<base::Value> value(
      deserializer.Deserialize(&error_code, &error_msg));
  DLOG_IF(ERROR, !value) << "JSON error " << error_code << ":" << error_msg;

  // Value will hold the nullptr in case of an error.
  return value.Pass();
}

scoped_ptr<std::string> SerializeToJson(const base::Value& value) {
  scoped_ptr<std::string> json_str(new std::string());
  JSONStringValueSerializer serializer(json_str.get());
  if (!serializer.Serialize(value))
    json_str.reset(nullptr);
  return json_str.Pass();
}

}  // namespace chromecast


text:
		<title>Amjs softbody rope demo</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="main.css">

Ammo.js physics soft body rope demo
Press Q or A to move the arm.


text:
import sys

from ctypes import cdll
import ctypes
import xml.etree.ElementTree

libName = 'MinVR_Python'

from sys import platform as _platform
if _platform == "linux" or _platform == "linux2":
    libFilePath = 'lib/lib' + libName + '.so'
elif _platform == "darwin":
    libFilePath = 'lib/lib' + libName + '.dylib'
elif _platform == "win32":
    libFilePath = 'bin/' + libName + '.dll'

lib = None

def openLibrary(config):
	e = xml.etree.ElementTree.parse(config).getroot()
	pluginpath = e.findall('PluginPath')[0].text
	global lib
	lib = cdll.LoadLibrary(pluginpath + '/' + libName + '/' + libFilePath)

eventcallback_type = ctypes.CFUNCTYPE(None, ctypes.c_char_p)
rendercallback_type = ctypes.CFUNCTYPE(None, ctypes.c_void_p)

class VRMain(object):
	def __init__(self, config):
		openLibrary(config)
		self.obj = lib.VRMain_init(config)
		self.eventHandlers = []
		self.renderHandlers = []
		self.eventCB = self.getEventCallbackFunc()
		self.eventhandler = lib.VRMain_registerEventCallback(self.obj, self.eventCB)
		self.renderCB = self.getRenderCallbackFunc()
		self.renderhandler = lib.VRMain_registerRenderCallback(self.obj, self.renderCB)
		pluginList = ctypes.create_string_buffer(500)
		lib.setPluginList.restype = ctypes.c_bool
		hasPlugins = lib.setPluginList(self.obj, pluginList)
		if (hasPlugins):
			for plugin in pluginList.value.split(","):
				sys.path.append(pluginpath + '/' + plugin + '/python')
				a = __import__(plugin)
				a.registerWithMinVR(self)
	def shutdown(self):
		lib.VRMain_shutdown(self.obj, self.eventhandler, self.renderhandler)
	def addEventHandler(self, handler):
		self.eventHandlers.append(handler)
	def addRenderHandler(self, handler):
		self.renderHandlers.append(handler)
	def getEventCallbackFunc(self):
		def func(eventName):
			self.handleEvent(eventName)
		return eventcallback_type(func)
	def handleEvent(self, eventName):
		eName = eventName
		for handler in self.eventHandlers:
			handler.onVREvent(eName)
	def getRenderCallbackFunc(self):
		def func(renderState):
			self.handleRender(renderState)
		return rendercallback_type(func)
	def handleRender(self, renderState):
		for handler in self.renderHandlers:
			handler.onVRRenderScene(VRDataIndex(renderState))
	def mainloop(self):
		lib.VRMain_mainloop(self.obj)

class VREventHandler(object):
	def __init__(self):
		pass
	def onVREvent(self, eventName):
		print "Event"

class VRRenderHandler(object):
	def __init__(self):
		pass
	def onVRRenderScene(self, renderState):
		print "Rendering Scene"
	def onVRRenderContext(self):
		print "Rendering Context"

class VRDataIndex(object):
	def __init__(self, index):
		self.getDatumType = lib.VRDataIndex_getType
		self.getDatumType.argtypes = (ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p)
		self.getIntValue = lib.VRDataIndex_getIntValue
		self.getIntValue.argtypes = (ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p)
		self.index = index
	def getValue(self, valName, nameSpace):
		datumType = self.getDatumType(self.index, valName, nameSpace)
		if datumType == 1:
			return self.getIntValue(self.index, valName, nameSpace)
		return None


text:
```php
<?php

$model = new \Payum\Model\Payment();
$model->setCurrencyCode('USD');
$model->setTotalAmount(1);
$model->setDetails(array(
    'RETURNURL' => 'http://return.url',
    'CANCELURL' => 'http://cancel.url',
));

$gateway->execute(new \Payum\Core\Request\Capture($model);

// or using raw format

$model = array(
   'PAYMENTREQUEST_0_CURRENCYCODE' => 'USD',
   'PAYMENTREQUEST_0_AMT' => 1,
   'RETURNURL' => 'http://return.url',
   'CANCELURL' => 'http://cancel.url',
));

$gateway->execute(new \Payum\Core\Request\Capture($model);
```

Back to [examples](index.md).
Back to [index](../index.md).


text:
<?php putenv("FOO_FEE=HelloWorld");
echo getenv("FOO_FEE"); ?>


text:
package org.jetbrains.idea.svn.dialogs;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.CalledInAwt;
import com.intellij.util.Consumer;
import com.intellij.util.ValueHolder;
import com.intellij.util.containers.Convertor;
import com.intellij.util.continuation.TaskDescriptor;

// cache. persistent. by request
public class FactsCalculator<In, Out> {
  private final Project myProject;
  private final String myTaskTitle;
  private final ValueHolder<Out, In> myCache;
  private final Convertor<In, Out> myLive;

  public FactsCalculator(Project project, String taskTitle, ValueHolder<Out, In> cache, Convertor<In, Out> live) {
    myProject = project;
    myTaskTitle = taskTitle;
    myCache = cache;
    myLive = live;
  }

  @CalledInAwt
  public void get(final In in, final Consumer<Out> resultConsumer) {
    createRunOrContinuation(in, resultConsumer).execute();
  }

  private RunOrContinuation<Out> createRunOrContinuation(final In in, final Consumer<Out> resultConsumer) {
    return new RunOrContinuation<Out>(myProject, myTaskTitle) {
      @Override
      protected Out calculate() {
        return myCache.getValue(in);
      }
      @Override
      protected Out calculateLong() {
        final Out result = myLive.convert(in);
        if (result != null) {
          myCache.setValue(result, in);
        }
        return result;
      }
      @Override
      protected void processResult(Out out) {
        resultConsumer.consume(out);
      }
    };
  }

  @CalledInAwt
  public TaskDescriptor getTask(final In in, final Consumer<Out> resultConsumer) {
    return createRunOrContinuation(in, resultConsumer).getTask();
  }
}


text:
node-red-node-seniot-iharmony
====================

A Node-Red node to get http response.

Install
-------

Run the following command in the root directory of your Node-RED install

    npm install node-red-node-seniot-iharmony

Usage
-----