text:
/**
 * @file
 *
 * %BufferedSource is an Source wrapper that reads the underlying (wrapped)
 * Source in chunks. It is typically used by Source consumers that want
 * to read one byte at a time effieciently.
 */

/******************************************************************************
 *
 *
 * Copyright (c) 2009-2011, AllSeen Alliance. All rights reserved.
 *
 *    Permission to use, copy, modify, and/or distribute this software for any
 *    purpose with or without fee is hereby granted, provided that the above
 *    copyright notice and this permission notice appear in all copies.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ******************************************************************************/

#include <qcc/platform.h>

#include <assert.h>
#include <string.h>

#include <qcc/BufferedSource.h>
#include <qcc/Thread.h>

using namespace std;
using namespace qcc;

#define QCC_MODULE "STREAM"

BufferedSource::BufferedSource(Source& source, size_t bufSize, bool usePushBack)
    : source(&source),
    event(source.GetSourceEvent(), Event::IO_READ, true),
    bufSize(bufSize),
    usePushBack(usePushBack)
{
    buf = new uint8_t[usePushBack ? 2 * bufSize : bufSize];
    rdPtr = buf;
    endPtr = buf;
}

void BufferedSource::Reset(Source& source)
{
    this->source = &source;
    rdPtr = buf;
    endPtr = buf;
}

BufferedSource::~BufferedSource()
{
    delete [] buf;
}

QStatus BufferedSource::PullBytes(void* outBuf, size_t reqBytes, size_t& actualBytes, uint32_t timeout)
{
    QStatus status = ER_OK;
    char* outPtr = (char*) outBuf;
    bool bufEmpty = rdPtr == endPtr;

    while (0 < reqBytes) {
        /* Copy buffered bytes first */
        if (endPtr > rdPtr) {
            size_t b = min(reqBytes, (size_t) (endPtr - rdPtr));
            memcpy(outPtr, rdPtr, b);
            rdPtr += b;
            reqBytes -= b;
            outPtr += b;
        }

        /* Get more bytes from source if needed */
        if (0 < reqBytes) {
            if (reqBytes > bufSize) {
                /* Since caller wants more bytes than fit in our buffer, just
                   copy directly into his buffer */
                size_t rb;
                status = source->PullBytes(outPtr, reqBytes, rb, timeout);
                if (ER_OK == status) {
                    outPtr += rb;
                }
                if (ER_OK != status) {
                    status = (outPtr == outBuf) ? status : ER_OK;
                }
                break;
            } else {
                /* Get another chunk from source */
                size_t rb = 0;
                status = source->PullBytes(buf, bufSize, rb, timeout);
                if (ER_OK != status) {
                    status = (outBuf == outPtr) ? status : ER_OK;
                    break;
                } else {
                    rdPtr = (uint8_t*) buf;
                    endPtr = (uint8_t*) buf + rb;
                }
            }
        }
    }

    /* Keep event in sync with buffered data */
    if (bufEmpty && (rdPtr != endPtr)) {
        event.SetEvent();
    } else if (!bufEmpty && (rdPtr == endPtr)) {
        event.ResetEvent();
    }

    actualBytes = (outPtr - (char*)outBuf);

    return status;
}

QStatus BufferedSource::PushBack(const void* inBuf, size_t numPush)
{
    bool bufEmpty = rdPtr == endPtr;

    if (0 == numPush) {
        return ER_OK;
    } else if (numPush > bufSize) {
        return ER_FAIL;
    } else if (!usePushBack) {
        return ER_FAIL;
    }

    /* Check to see if we need to copy the bytes */
    if ((size_t)(rdPtr - buf) >= numPush) {
        rdPtr -= numPush;
    } else {
        /* Make room in buffer for push back bytes */
        if (endPtr > rdPtr) {
            memmove(buf + numPush, rdPtr, endPtr - rdPtr);
        }
        /* Copy pushback bytes and adjust */
        memcpy(buf, inBuf, numPush);
        rdPtr = buf;
        endPtr += numPush;
    }

    if (bufEmpty) {
        event.SetEvent();
    }
    return ER_OK;
}


text:
<?php

namespace common\models\base;

use Yii;

/**
 * This is the base-model class for table "EDBO_KOATUUL1".
 *
 * @property integer $id
 * @property integer $Id_KOATUU
 * @property string $KOATUUCode
 * @property string $Type
 * @property integer $Id_KOATUUName
 * @property string $KOATUUName
 * @property string $KOATUUFullName
 * @property string $KOATUUDateBegin
 * @property string $KOATUUDateEnd
 * @property integer $Id_Language
 * @property string $KOATUUCodeL1
 * @property string $KOATUUCodeL2
 * @property string $KOATUUCodeL3
 * @property integer $created_at
 * @property integer $updated_at
 */
class EDBOKOATUUL1 extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'EDBO_KOATUUL1';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['Id_KOATUU', 'Id_KOATUUName', 'Id_Language', 'created_at', 'updated_at'], 'integer'],
            [['KOATUUDateBegin', 'KOATUUDateEnd'], 'safe'],
            [['created_at', 'updated_at'], 'required'],
            [['KOATUUCode', 'Type', 'KOATUUName', 'KOATUUFullName', 'KOATUUCodeL1', 'KOATUUCodeL2', 'KOATUUCodeL3'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'Id_KOATUU' => Yii::t('app', 'Id  Koatuu'),
            'KOATUUCode' => Yii::t('app', 'Koatuucode'),
            'Type' => Yii::t('app', 'Type'),
            'Id_KOATUUName' => Yii::t('app', 'Id  Koatuuname'),
            'KOATUUName' => Yii::t('app', 'Koatuuname'),
            'KOATUUFullName' => Yii::t('app', 'Koatuufull Name'),
            'KOATUUDateBegin' => Yii::t('app', 'Koatuudate Begin'),
            'KOATUUDateEnd' => Yii::t('app', 'Koatuudate End'),
            'Id_Language' => Yii::t('app', 'Id  Language'),
            'KOATUUCodeL1' => Yii::t('app', 'Koatuucode L1'),
            'KOATUUCodeL2' => Yii::t('app', 'Koatuucode L2'),
            'KOATUUCodeL3' => Yii::t('app', 'Koatuucode L3'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
        ];
    }
}

redpajama_set_name: RedPajamaGithub


text:
A plugin to enable runtime localization in Sencha ExtJS & Sencha Touch applications.

## Highlights

* Provides plugin for UI components that enables runtime locale changes.
* Works with Sencha ExtJS version 4.x and up, Sencha Touch version 2.x+ and up.
* Build versions for debugging and production.
* JSDuck documentation.
* [MIT License](https://github.com/psmithiv/nineam-localization-plugin/blob/master/MIT-LICENSE.txt) compatible with both
ExtJS and Touch licenses.

## Getting Started

Simply add the debug or minified production JS file to your html file:

```html
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>nineam-localization-plugin-ext</title>
    <link rel="stylesheet" href="resources/css/default/app.css">
    <!-- <x-compile> -->
        <!-- <x-bootstrap> -->
            <script src="ext/ext-dev.js"></script>
            <script src="bootstrap.js"></script>
        <!-- </x-bootstrap> -->
        <script src="libs/locale-manager-debug.js"></script>
        <script src="app/app.js"></script>
    <!-- </x-compile> -->
</head>
<body></body>
</html>
```

Create some localization properties by locating the default ExtJS or Touch locale file for English: ext-lang-en.js.
Add some properties to it at the bottom of the file by creating a new properties class:

```js
Ext.define("Ext.locales.en.Global", {
    title: 'en.title',
    btnWidth: 300,
    comp: {
        title: 'en.comp.title'
    }
});
```

Notice that we can add both string values for labels and numeric values for setting (for example) the width of a button.
The properties can contain much, much more than just content for labels. If you wanted to create the same properties
for Spanish you'd simply locate the file 'ext-lang-es.js' and add a new class 'Ext.locales.es.Global' with the
same properties but different values.

Next, create a LocalesStore object setting the locale information as the store's data property in the application's
init() method:

```js
Ext.application({
    init: function() {
        var locales = Ext.create('nineam.localization.store.LocalesStore', {
            data: [
                {id: 'en_us', label: 'English', url: 'locale/ext-lang-en.js', propertiesClass: 'Ext.locales.en.Global'},
                {id: 'es_us', label: 'Spanish', url: 'locale/ext-lang-es.js', propertiesClass: 'Ext.locales.es.Global'}
            ]
        });
    }
});
```

In the same init method, we need to actually set the locale:

```js
Ext.application({
    init: function() {
        var locales = Ext.create('nineam.localization.store.LocalesStore', {
            data: [
                {id: 'en_us', label: 'English', url: 'locale/ext-lang-en.js', propertiesClass: 'Ext.locales.en.Global'},
                {id: 'es_us', label: 'Spanish', url: 'locale/ext-lang-es.js', propertiesClass: 'Ext.locales.es.Global'}
            ]
        });

        var lm = nineam.localization.LocaleManager;
        lm.setLocales(locales);

        var locale = lm.getPersistedLocale();
        lm.setLocale(locale);
    }
});
```

Finally, we need  to use the LocaleManager as both a plugin to UI components and as a singleton with access to
properties. Let's start by taking a simple label component and adding the plugin:

```js
{
    itemId: "myLabel",
    xtype: 'label',
    plugins: [
        { ptype: 'localization', method: 'setText', key: 'comp.title' }
    ]
}
```

Here we're setting the plugin to the type 'localization' which hooks the UI component to our LocaleManager plugin.
Here's how it works: when a locale is changed on the LocaleManager at runtime, it updates any UI components using
it as a plugin by calling the 'method' property specified by the plugin and using the value of the 'key' as the
parameter to that method. In our example, the key 'comp.title' resolves to 'en.comp.title' as defined above in
Ext.locales.en.Global.

You can also access properties of the LocaleManger via code:

```js
myLabel.setText(nineam.locale.LocaleManager.getProperty("comp.title"));
```

## Examples

* [ExtJS](https://github.com/psmithiv/nineam-localization-plugin/tree/master/examples/ext-4.1.1-example)
A simple example ExtJS application demonstrating runtime localization capabilities.
* [Touch](https://github.com/psmithiv/nineam-localization-plugin/tree/master/examples/touch-2.2.1-example)
A simple example Touch application demonstrating runtime localization capabilities.
* [Cafe Townsend Demo Project](https://github.com/WebAppSolutionInc/sencha-cafe-townsend) - A HTML5 implementation
using Sencha ExtJS, Sencha Touch, DeftJS, FlowMVC, & Localization Plugin.

## Roadmap

* Unit Tests

## Developers

* [Paul Smith IV](mailto: paul.smith.iv@ninthavenuemedia.com) (Creator)
* [Brian Riley](https://github.com/brianmriley)


text:
package JKernelMachines.fr.lip6.kernel.extra;

import java.util.ArrayList;

import JKernelMachines.fr.lip6.kernel.Kernel;

/**
 * performs a product of several minor kernels
 * @author dpicard
 *
 * @param <T>
 */
public class ProductKernel<T> extends Kernel<T> {

	/**
	 *
	 */
	private static final long serialVersionUID = 6273022923321895693L;

	ArrayList<Kernel<T>> kernels;
	ArrayList<Double> weights;

	public ProductKernel ()
	{
		super();

		kernels = new ArrayList<Kernel<T>>();
		weights = new ArrayList<Double>();
	}

	@Override
	public double valueOf(T t1, T t2) {

		double prod = 1.0;

		for(int i = 0 ; i < kernels.size(); i++)
			prod *= Math.pow(kernels.get(i).valueOf(t1, t2), weights.get(i));

		return prod;
	}

	@Override
	public double valueOf(T t1) {
		return valueOf(t1, t1);
	}

	/**
	 * adds a kernel to to product
	 * @param k
	 */
	public void addKernel(Kernel<T> k)
	{
		kernels.add(k);
		weights.add(1.0);
	}

	public void addKernel(Kernel<T> k, double w)
	{
		kernels.add(k);
		weights.add(w);
	}

	/**
	 * removes a kernel from the product
	 * @param k
	 */
	public void removeKernel(Kernel<T> k)
	{
		kernels.remove(k);
	}

}


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

namespace Abnaki.Windows.GUI
{
    /// <summary>
    /// Supports general initialization.
    /// Expected to be implemented widely.
    /// </summary>
    public interface IMainControl
    {
        /// <summary>
        /// After this becomes a descendant of main window
        /// </summary>
        void EmplacedInWindow();

        /// <summary>
        /// Manages panels.  Can be null.
        /// </summary>
        IDockSystem DockingSystem { get; }

        void ConfigureMenu(IMainMenu menu);

        /// <summary>
        /// Change main window Title
        /// </summary>
        event Action<string> MainTitle;
    }
}


text:
@class PeopleCollaborator;

@interface PeopleServices : NSObject

+ (void)loginWithUsername:(NSString *)user
                 password:(NSString *)password
                  success:(void(^)(PeopleCollaborator *colaborador))success
                  failure:(void(^)(NSError *error))failure;

+ (void)colaboradoresForSearchTerm:(NSString *)searchTerm
                           success:(void(^)(NSArray *colaboradores))success
                           failure:(void(^)(NSError *error))failure;

+ (void)colaboradorProfileForLogin:(NSString *)login
                           success:(void(^)(PeopleCollaborator *colaborador))success
                           failure:(void(^)(NSError *error))failure;

+ (void)photoForUser:(NSString *)user
             success:(void(^)(UIImage *image))success
             failure:(void(^)(NSError *error))failure;

+ (void)profileForUser:(NSString *)user
               success:(void (^)(PeopleCollaborator *colarabor))success
               failure:(void (^)(NSError *error))failure;

+ (void)setUsername:(NSString *)username
           password:(NSString *)password;

@end


text:
'use strict';

var bunyan = require('bunyan');

function logStream(logStdout) {

  var log = [];
  var parrot = bunyan.createLogger({
    name: 'test-logger',
    level: 'warn'
  });

  function write(chunk, encoding, callback) {
    try {
        var entry = JSON.parse(chunk);
        var levelMatch = /^(\w+)/.exec(entry.levelPath);
        if (logStdout && levelMatch) {
            var level = levelMatch[1];
            if (parrot[level]) {
                parrot[level](entry);
            }
        }
    } catch (e) {
        console.error('something went wrong trying to parrot a log entry', e, chunk);
    }

    log.push(chunk);
  }

  // to implement the stream writer interface
  function end(chunk, encoding, callback) {
  }

  function get() {
    return log;
  }

  function slice() {

    var begin = log.length;
    var end   = null;

    function halt() {
      if (end === null) {
        end = log.length;
      }
    }

    function get() {
      return log.slice(begin, end);
    }

    return {
      halt: halt,
      get: get
    };

  }

  return {
    write: write,
    end: end,
    slice: slice,
    get: get
  };
}

module.exports = logStream;


text:
namespace AngleSharp.Dom.Css
{
    using AngleSharp.Css;
    using System;

    /// <summary>
    /// The nth-child selector.
    /// </summary>
    sealed class FirstChildSelector : ChildSelector
    {
        public FirstChildSelector()
            : base(PseudoClassNames.NthChild)
        {
        }

        public override Boolean Match(IElement element)
        {
            var parent = element.ParentElement;

            if (parent != null)
            {
                var n = Math.Sign(_step);
                var k = 0;

                for (var i = 0; i < parent.ChildNodes.Length; i++)
                {
                    var child = parent.ChildNodes[i] as IElement;

                    if (child != null && _kind.Match(child))
                    {
                        k += 1;

                        if (child == element)
                        {
                            var diff = k - _offset;
                            return diff == 0 || (Math.Sign(diff) == n && diff % _step == 0);
                        }
                    }
                }
            }

            return false;
        }
    }
}


text:
<?php
namespace Concrete\Core\Page\Stack;
use Loader;
use Concrete\Core\Legacy\PageList;
use Page;
use \Concrete\Core\Legacy\DatabaseItemList;

class StackList extends PageList {

	public function __construct() {
		$c = Page::getByPath(STACKS_PAGE_PATH);
		$this->ignoreAliases = true;
		$this->ignorePermissions = true;
		$this->addToQuery('inner join Stacks on Stacks.cID = p1.cID');
		$this->filterByParentID($c->getCollectionID());
		$this->sortBy('p1.cDisplayOrder', 'asc');
	}

	public function filterByGlobalAreas() {
		$this->filter('stType', Stack::ST_TYPE_GLOBAL_AREA);
	}

	public function filterByUserAdded() {
		$this->filter('stType', Stack::ST_TYPE_USER_ADDED);
	}

	public static function export(\SimpleXMLElement $x) {
		$db = Loader::db();
		$r = $db->Execute('select stName, cID, stType from Stacks order by stName asc');
		if ($r->NumRows()) {
			$gas = $x->addChild('stacks');
			while ($row = $r->FetchRow()) {
				$stack = Stack::getByName($row['stName']);
				if (is_object($stack)) {
					$stack->export($gas);
				}
			}
		}
	}

	public function get($itemsToGet = 0, $offset = 0) {
		if ($this->getQuery() == '') {
			$this->setBaseQuery();
		}
		$stacks = array();
		$this->setItemsPerPage($itemsToGet);
		$r = DatabaseItemList::get($itemsToGet, $offset);
		foreach($r as $row) {
			$s = Stack::getByID($row['cID'], 'RECENT');
			$stacks[] = $s;
		}
		return $stacks;
	}

}


text:
import { createPool } from 'mariadb';
import { Middleware } from 'koa';
import { appLogger } from './logger';
import { getEnv } from './env';

export const pool = createPool({
  host: getEnv('MARIADB_HOST'),
  port: Number(getEnv('MARIADB_PORT', '3306')),
  database: getEnv('MARIADB_DATABASE'),
  user: getEnv('MARIADB_USER'),
  password: getEnv('MARIADB_PASSWORD'),
  bigIntAsNumber: true,
  insertIdAsNumber: true,
  decimalAsNumber: true,
});

const logger = appLogger.child({ module: 'db' });

export async function initDatabase() {
  const scripts = [
    `CREATE TABLE IF NOT EXISTS user (
      id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
      osmId INT UNSIGNED NULL UNIQUE,
      facebookUserId VARCHAR(32) CHARSET latin1 COLLATE latin1_bin NULL UNIQUE,
      googleUserId VARCHAR(32) CHARSET latin1 COLLATE latin1_bin NULL UNIQUE,
      name VARCHAR(255) CHARSET utf8 COLLATE utf8_general_ci NOT NULL,
      email VARCHAR(255) CHARSET utf8 COLLATE utf8_general_ci NULL,
      isAdmin BOOL NOT NULL DEFAULT 0,
      createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      lat FLOAT(8, 6) NULL,
      lon FLOAT(9, 6) NULL,
      settings VARCHAR(4096) CHARSET utf8 COLLATE utf8_bin NOT NULL DEFAULT '{}',
      preventTips BOOL NOT NULL DEFAULT 0,
      sendGalleryEmails BOOL NOT NULL DEFAULT 1,
      language CHAR(2) NULL,
      lastPaymentAt TIMESTAMP NULL,
      rovasToken VARCHAR(255) CHARSET ascii NULL
    ) ENGINE=InnoDB`,

    `CREATE TABLE IF NOT EXISTS auth (
      authToken VARCHAR(255) CHARSET ascii PRIMARY KEY,
      userId INT UNSIGNED NOT NULL,
      createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      osmAuthToken VARCHAR(255) CHARSET latin1 COLLATE latin1_bin NULL UNIQUE,
      osmAuthTokenSecret VARCHAR(255) CHARSET latin1 COLLATE latin1_bin NULL,
      facebookAccessToken VARCHAR(255) CHARSET latin1 COLLATE latin1_bin NULL,
      googleIdToken VARCHAR(4095) CHARSET latin1 COLLATE latin1_bin NULL,
      FOREIGN KEY (userId) REFERENCES user (id) ON DELETE CASCADE
    ) ENGINE=InnoDB`,

    `CREATE TABLE IF NOT EXISTS picture (
      id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
      pathname VARCHAR(255) CHARSET utf8 COLLATE utf8_bin NOT NULL UNIQUE,
      userId INT UNSIGNED NOT NULL,
      title VARCHAR(255) CHARSET utf8 COLLATE utf8_general_ci NULL,
      description VARCHAR(4096) CHARSET utf8 COLLATE utf8_general_ci NULL,
      takenAt TIMESTAMP NULL,
      createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      lat FLOAT(8, 6) NOT NULL,
      lon FLOAT(9, 6) NOT NULL,
      pano BIT NOT NULL,
      FOREIGN KEY (userId) REFERENCES user (id) ON DELETE CASCADE,
      INDEX USING BTREE (lat),
      INDEX USING BTREE (lon)
    ) ENGINE=InnoDB`,

    `CREATE TABLE IF NOT EXISTS pictureTag (
      pictureId INT UNSIGNED NOT NULL,
      name VARCHAR(255) CHARSET utf8 COLLATE utf8_general_ci,
      PRIMARY KEY (pictureId, name),
      FOREIGN KEY (pictureId) REFERENCES picture (id) ON DELETE CASCADE
    ) ENGINE=InnoDB`,

    `CREATE TABLE IF NOT EXISTS pictureComment (
      id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
      pictureId INT UNSIGNED NOT NULL,
      userId INT UNSIGNED NOT NULL,
      createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      comment VARCHAR(4096) CHARSET utf8 COLLATE utf8_general_ci,
      FOREIGN KEY (pictureId) REFERENCES picture (id) ON DELETE CASCADE,
      FOREIGN KEY (userId) REFERENCES user (id) ON DELETE CASCADE
    ) ENGINE=InnoDB`,

    `CREATE TABLE IF NOT EXISTS pictureRating (
      userId INT UNSIGNED NOT NULL,
      pictureId INT UNSIGNED NOT NULL,
      stars TINYINT UNSIGNED NOT NULL,
      ratedAt TIMESTAMP NOT NULL,
      PRIMARY KEY (pictureId, userId),
      FOREIGN KEY (pictureId) REFERENCES picture (id) ON DELETE CASCADE,
      FOREIGN KEY (userId) REFERENCES user (id) ON DELETE CASCADE
    ) ENGINE=InnoDB`,

    `CREATE TABLE IF NOT EXISTS trackingDevice (
      id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
      userId INT UNSIGNED NOT NULL,
      name VARCHAR(255) CHARSET utf8 COLLATE utf8_general_ci NOT NULL,
      token VARCHAR(255) CHARSET ascii NOT NULL UNIQUE,
      maxCount INT UNSIGNED NULL,
      maxAge INT UNSIGNED NULL,
      createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      CONSTRAINT tdUserFk FOREIGN KEY (userId) REFERENCES user (id) ON DELETE CASCADE
    ) ENGINE=InnoDB`,

    `CREATE TABLE IF NOT EXISTS trackingPoint (
      id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
      deviceId INT UNSIGNED NOT NULL,
      createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      lat FLOAT(8, 6) NOT NULL,
      lon FLOAT(9, 6) NOT NULL,
      altitude FLOAT NULL,
      speed FLOAT NULL,
      accuracy FLOAT NULL,
      hdop FLOAT NULL,
      bearing FLOAT NULL,
      battery FLOAT NULL,
      gsmSignal FLOAT NULL,
      message VARCHAR(255) CHARSET utf8 COLLATE utf8_general_ci NULL,
      CONSTRAINT tpDeviceIdFk FOREIGN KEY (deviceId) REFERENCES trackingDevice (id) ON DELETE CASCADE,
      INDEX tpCreatedAtIdx (createdAt)
    ) ENGINE=InnoDB`,

    `CREATE TABLE IF NOT EXISTS trackingAccessToken (
      id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
      deviceId INT UNSIGNED NOT NULL,
      token VARCHAR(255) CHARSET ascii NOT NULL UNIQUE,
      createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      timeFrom TIMESTAMP NULL,
      timeTo TIMESTAMP NULL,
      listingLabel VARCHAR(255) CHARSET utf8 COLLATE utf8_general_ci NULL,
      note VARCHAR(255) CHARSET utf8 COLLATE utf8_general_ci NULL,
      CONSTRAINT tatDeviceIdFk FOREIGN KEY (deviceId) REFERENCES trackingDevice (id) ON DELETE CASCADE,
      INDEX tatCreatedAtIdx (createdAt)
    ) ENGINE=InnoDB`,

    `CREATE TABLE IF NOT EXISTS map (
      id CHAR(8) PRIMARY KEY,
      createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      modifiedAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      name VARCHAR(255) CHARSET utf8 COLLATE utf8_general_ci NULL,
      userId INT UNSIGNED NOT NULL,
      public BOOL NOT NULL DEFAULT 0,
      data MEDIUMTEXT CHARSET utf8 COLLATE utf8_bin NOT NULL DEFAULT '{}',
      CONSTRAINT umUserFk FOREIGN KEY (userId) REFERENCES user (id) ON DELETE CASCADE,
      INDEX umCreatedAtIdx (createdAt)
    ) ENGINE=InnoDB`,

    `CREATE TABLE IF NOT EXISTS mapWriteAccess (
      mapId CHAR(8) NOT NULL,
      userId INT UNSIGNED NOT NULL,
      PRIMARY KEY (mapId, userId),
      CONSTRAINT mwaUserFk FOREIGN KEY (userId) REFERENCES user (id) ON DELETE CASCADE,
      CONSTRAINT mwaMapFk FOREIGN KEY (mapId) REFERENCES map (id) ON DELETE CASCADE
    ) ENGINE=InnoDB`,
  ];

  const updates: string[] = [
    // 'ALTER TABLE user ADD COLUMN sendGalleryEmails BOOL NOT NULL DEFAULT 1',
    // 'ALTER TABLE user ADD COLUMN language CHAR(2) NULL',
    // 'ALTER TABLE user ADD lastPaymentAt TIMESTAMP NULL',
    // 'ALTER TABLE user ADD rovasToken VARCHAR(255) CHARSET ascii NULL',
    // 'ALTER TABLE map MODIFY COLUMN id CHAR(8)',
    // 'ALTER TABLE map ADD COLUMN modifiedAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP',
    'ALTER TABLE picture ADD COLUMN pano BIT NOT NULL DEFAULT 0',
  ];

  const db = await pool.getConnection();

  try {
    for (const script of scripts) {
      await db.query(script);
    }

    for (const script of updates) {
      try {
        await db.query(script);
      } catch (err) {
        logger.info(`Unsuccessful SQL ${script}: ${err.message}`);
      }
    }
  } finally {
    db.release();
  }
}

export function runInTransaction(): Middleware {
  return async (ctx, next) => {
    const conn = await pool.getConnection();

    try {
      await conn.beginTransaction();

      const old = ctx.state.dbConn;

      ctx.state.dbConn = conn;

      await next();

      ctx.state.dbConn = old;

      await conn.commit();
    } finally {
      conn.release();
    }
  };
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';

import image1 from 'assets/images/c.png';
import image2 from 'assets/images/s.png';
import image3 from 'assets/images/m.png';

import Card from 'Equilab/Card';

import styles from './Testimonials.scss';

const testimonials = [
  {
    description:
      '"Amazing that you now can see pace distance and training statistics in then same place."',
    name: 'Sivert "sibban" Jonsson',
    sub: 'Former World Cup rider and class B-coach',
    image: image2,
  },
  {
    description:
      '"This app shows black on white how mucj you have exercised, no excuses anymore among my students!"',
    name: 'Magnus Skulason',
    sub: 'Multiple world cup medalist',
    image: image3,
  },
  {
    description:
      '"Being able to see how my fellow riders exercise gives me not only safety, but it is also very fun to see the training without being there."',
    name: 'Charlotte Tillman',
    sub: 'National team rider and winner of Swedish Cup',
    image: image1,
  },
];

class Testimonials extends Component {
  renderTestimonial = ({ description, name, sub, image }) => (
    <Card key={name} name={name} description={description} sub={sub} image={image} />
  );

  render() {
    return (
      <div className={`row ${styles.wrapper}`}>

See what others think

        <div className={`${styles.maxWidth}`}>{testimonials.map(this.renderTestimonial)}

    );
  }
}

Testimonials.propTypes = {};

export default Testimonials;


text:
%  \end{longtable} %problem with latex compiler. See issue #129
\end{center}


text:
package pacioli.ast.unit;

import pacioli.Location;
import pacioli.ast.Visitor;

public class NumberUnitNode extends AbstractUnitNode {

    public final String number;

    public NumberUnitNode(String number, Location location) {
        super(location);
        this.number = number;
    }

    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}


text:
export default ({ app }) => {
  const { localePath } = app
  app.router.afterEach((to, from) => {
    app.store.commit('updateBreadcrumbs', { to, from, localePath })
  })
}


text:
using System;
using System.Runtime.InteropServices;

using MonoTouch.CoreLocation;
using MonoTouch.ObjCRuntime;

namespace BingMaps
{
//		public static class BMMarker_Manual_Extensions
//		{
//			public static CLLocationCoordinate2D GetCoordinate (this IBMMarker This)
//			{
//				CLLocationCoordinate2D result;
//				Messaging.CLLocationCoordinate2D_objc_msgSend_stret (out result, This.Handle, Selector.GetHandle ("coordinate"));
//				return result;
//			}
//		}
//
//	    partial class Messaging
//		{
//			[DllImport ("/usr/lib/libobjc.dylib", EntryPoint = "objc_msgSend_stret")]
//			public static extern void CLLocationCoordinate2D_objc_msgSend_stret (out CLLocationCoordinate2D retval, IntPtr receiver, IntPtr selector);
//		}
//
//
//		public partial class BMUserLocation
//		{
//			public virtual string Title {
//				get {
//					return GetTitle ();
//				}
//				set {
//					SetTitle (value);
//				}
//			}
//
//			public virtual string Subtitle {
//				get {
//					return GetSubtitle ();
//				}
//				set {
//					SetSubtitle (value);
//				}
//			}
//		}
//
//		public partial class BMMarker
//		{
//			public virtual string Title {
//				get {
//					return GetTitle ();
//				}
//			}
//
//			public virtual string Subtitle {
//				get {
//					return GetSubtitle ();
//				}
//			}
//		}
//

	public partial class BMMapView
	{

		public static BMCoordinateSpan BMCoordinateSpanMake (double latitudeDelta, double longitudeDelta)
		{
			BMCoordinateSpan span;
			span.LatitudeDelta = latitudeDelta;
			span.LongitudeDelta = longitudeDelta;
			return span;
		}

		public static BMCoordinateRegion BMCoordinateRegionMake (CLLocationCoordinate2D centerCoordinate, BMCoordinateSpan span)
		{
			BMCoordinateRegion region;
			region.Center = centerCoordinate;
			region.Span = span;
			return region;
		}

		public static BMMarkerView GetDefaultMarkerView(BMMarker marker)
		{
			BMPushpinView pinView = new BMPushpinView (marker, null);

			pinView.PinColor = BMPushpinColor.Orange;
			pinView.AnimatesDrop = true;

			pinView.CanShowCallout = true;
			pinView.Enabled = true;
			pinView.Opaque = false;

			return pinView;
		}

	}
}


text:
module.exports = function (ngModule) {

  ngModule.service('timer', ['$q', 'NanoTimer', function ($q, NanoTimer) {

    function Timer() {
      this.timer = new NanoTimer();
    }

    Timer.prototype.dispose = function () {
      this.timer.clearInterval();
      this.timer = undefined;
    }

    Timer.prototype.start = function (callback, interval) {
      this.timer.setInterval(callback, '', interval + 'u');
    }

    Timer.prototype.stop = function () {
      this.timer.clearInterval();
    }

    return new Timer();

  }]);

}


text:
package com.microsoft.azure.cognitiveservices.search.autosuggest.models;

import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonSubTypes;

/**
 * The Action model.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "_type", defaultImpl = Action.class)
@JsonTypeName("Action")
@JsonSubTypes({
    @JsonSubTypes.Type(name = "SearchAction", value = SearchAction.class)
})
public class Action extends CreativeWork {
    /**
     * The result property.
     */
    @JsonProperty(value = "result", access = JsonProperty.Access.WRITE_ONLY)
    private List<Thing> result;

    /**
     * The displayName property.
     */
    @JsonProperty(value = "displayName", access = JsonProperty.Access.WRITE_ONLY)
    private String displayName;

    /**
     * The isTopAction property.
     */
    @JsonProperty(value = "isTopAction", access = JsonProperty.Access.WRITE_ONLY)
    private Boolean isTopAction;

    /**
     * The serviceUrl property.
     */
    @JsonProperty(value = "serviceUrl", access = JsonProperty.Access.WRITE_ONLY)
    private String serviceUrl;

    /**
     * Get the result value.
     *
     * @return the result value
     */
    public List<Thing> result() {
        return this.result;
    }

    /**
     * Get the displayName value.
     *
     * @return the displayName value
     */
    public String displayName() {
        return this.displayName;
    }

    /**
     * Get the isTopAction value.
     *
     * @return the isTopAction value
     */
    public Boolean isTopAction() {
        return this.isTopAction;
    }

    /**
     * Get the serviceUrl value.
     *
     * @return the serviceUrl value
     */
    public String serviceUrl() {
        return this.serviceUrl;
    }

}


text:
package com.thebluealliance.androidclient.subscribers;

import org.greenrobot.eventbus.EventBus;

import javax.inject.Inject;

import rx.Subscriber;

/**
 * A class to take data from an observable and push it to the EventBus
 */
public class EventBusSubscriber extends Subscriber<Object> {
    private EventBus mEventBus;

    @Inject
    public EventBusSubscriber(EventBus eventBus) {
        mEventBus = eventBus;
    }

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void onNext(Object o) {
        mEventBus.post(o);
    }
}


text:
Docker NGINX + Magento container

## About

This container is optimized for running Magento using NGINX

This container requires a seperate dedicated mysql container (mysql) to run.
You can find mysql either at docker (https://registry.hub.docker.com/_/mysql/)

## Usage by example

### For Mac OS users - Boot2docker Vagrant Box

Boot2docker Vagrant box for optimized Docker and Docker Compose use on Mac and Windows.
https://github.com/blinkreaction/boot2docker-vagrant

Install on Mac OS:

```shell
curl https://raw.githubusercontent.com/blinkreaction/boot2docker-vagrant/master/setup.sh | bash
```

### The mysql container

```shell
docker run --name mysql -e MYSQL_ROOT_PASSWORD=123 -d mysql
```

### The magento container

```shell
docker run -d --name project -p 80:80 -v /.ssh/:/root/.ssh -v project:/var/www/magento -v modules:/var/www/modules --link mysql:db komplizierte/docker-nginx-magento
```

#### XDebug:

```shell
./scripts/xdebug-start.sh
./scripts/xdebug-stop.sh
```

#### Resolve permissions in container

```shell
chown -R nobody:nogroup project/
```

## Comments

In our example the magento container is linked to the mysql container under the alias db.
This means that you'll have to edit your config file in such a way that the mysql host is no longer localhost but db.

Regards,


text:
/**
 *

 * Contains XPath functions and operators specified in
 * XQuery 1.0 and XPath 2.0 Functions and
 * Operators and classes that support their usage.
 *

 *

 * Make sure to extend AbstractFunction for all new functions and add the signature information to
 * the FuncDef enum.
 *

 *
 * @author Tina Scherer, University of Konstanz
 */
package org.sirix.service.xml.xpath.functions;


text:
Clever-core is the core package of the CLEVER project. It's used to manage packages and extend functionality.

## The repository contains
* Core functionality for managing CLEVER packages.

## Basic Usage

Install Package:
```
$ npm install clever-core
```


text:
/*
 * This header file is used to define all configuration parameters
 * required by the interconnection network.
 */

#ifndef __MEM_RUBY_NETWORK_GARNET_BASEGARNETNETWORK_HH__
#define __MEM_RUBY_NETWORK_GARNET_BASEGARNETNETWORK_HH__

#include "mem/ruby/network/garnet/NetworkHeader.hh"
#include "mem/ruby/network/Network.hh"
#include "mem/ruby/network/fault_model/FaultModel.hh"
#include "params/BaseGarnetNetwork.hh"

class BaseGarnetNetwork : public Network
{
  public:
    typedef BaseGarnetNetworkParams Params;
    BaseGarnetNetwork(const Params *p);

    void init();
    int getNiFlitSize() {return m_ni_flit_size; }
    int getVCsPerVnet() {return m_vcs_per_vnet; }
    bool isFaultModelEnabled() {return m_enable_fault_model;}
    FaultModel* fault_model;

    void increment_injected_flits(int vnet) { m_flits_injected[vnet]++; }
    void increment_received_flits(int vnet) { m_flits_received[vnet]++; }

    void
    increment_network_latency(Cycles latency, int vnet)
    {
        m_network_latency[vnet] += latency;
    }

    void
    increment_queueing_latency(Cycles latency, int vnet)
    {
        m_queueing_latency[vnet] += latency;
    }

    // returns the queue requested for the given component
    MessageBuffer* getToNetQueue(NodeID id, bool ordered, int network_num,
                                 std::string vnet_type);
    MessageBuffer* getFromNetQueue(NodeID id, bool ordered, int network_num,
                                   std::string vnet_type);

    bool isVNetOrdered(int vnet) { return m_ordered[vnet]; }
    bool validVirtualNetwork(int vnet) { return m_in_use[vnet]; }
    virtual void checkNetworkAllocation(NodeID id, bool ordered,
        int network_num, std::string vnet_type) = 0;

    virtual void regStats();
    virtual void collateStats() {}

  protected:
    int m_ni_flit_size;
    int m_vcs_per_vnet;
    bool m_enable_fault_model;

    // Statistical variables
    Stats::Vector m_flits_received;
    Stats::Vector m_flits_injected;
    Stats::Vector m_network_latency;
    Stats::Vector m_queueing_latency;

    Stats::Formula m_avg_vnet_latency;
    Stats::Formula m_avg_vqueue_latency;
    Stats::Formula m_avg_network_latency;
    Stats::Formula m_avg_queueing_latency;
    Stats::Formula m_avg_latency;
};

#endif // __MEM_RUBY_NETWORK_GARNET_BASEGARNETNETWORK_HH__


text:
from collections import OrderedDict
import json

from django.db import models
from django.contrib.postgres.fields import JSONField as Builtin_JSONField
from django.core.serializers.json import Serializer as Builtin_Serializer
from django.utils.encoding import smart_text

class JSONField(Builtin_JSONField):
    def value_from_object(self, obj):
        value = getattr(obj, self.attname)
        if value:
            return json.loads(value)
        else:
            return None


text:
package nv.jedis.example;

import redis.clients.jedis.Jedis;

/**
 *
 */
public class App {
    public static void main( String[] args ) {
        // Connecting to Redis on localhost
        Jedis jedis = new Jedis("localhost");
        // adding a new key
        jedis.set("key", "value");
        // getting the key value
        System.out.println(jedis.get("key"));

        // Counter Example
        System.out.println(jedis.get("counter"));
        jedis.incr("counter");
        System.out.println(jedis.get("counter"));
        //---------------------------------------

        // Caching Example
        // adding a new key
        String cacheKey = "cachekey";
        jedis.set(cacheKey, "cached value");
        // setting the TTL in seconds
        jedis.expire(cacheKey, 15);
        // Getting the remaining ttl
        System.out.println("TTL:" + jedis.ttl(cacheKey));
        sleep(1000);
        System.out.println("TTL:" + jedis.ttl(cacheKey));
        // Getting the cache value
        System.out.println("Cached Value:" + jedis.get(cacheKey));
        // Wait for the TTL finishs
        sleep(15000);
        // trying to get the expired key
        System.out.println("Expired Key:" + jedis.get(cacheKey));
        //---------------------------------------

        // Set, List Example
        //Adding a set as value
        jedis.sadd(cacheKey,"Java","C#","Python");//SADD
        //Getting all values in the set: SMEMBERS
        System.out.println("Languages: " + jedis.smembers(cacheKey));
        //Adding new values
        jedis.sadd(cacheKey,"Java","Ruby");
        //Getting the values... it doesn't allow duplicates
        System.out.println("Languages: " + jedis.smembers(cacheKey));
        //---------------------------------------
    }

    private static void sleep(int milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}


text:
module PagarMe
  class TransactionCommon < Model

    def initialize(response = {})
      super(response)

      self.payment_method ||= 'credit_card'
      self.installments   ||= 1
      self.status         ||= 'local'
    end

    def create
      check_card_object
      super
    end

    def save
      check_card_object
      super
    end

    private
    def check_card_object
      if card
        if card.id
          self.card_id = self.card.id
        else
          self.card_number           = card.card_number
          self.card_holder_name      = card.card_holder_name
          self.card_expiration_year  = card.card_expiration_year
          self.card_expiration_month = card.card_expiration_month
          self.card_cvv              = card.card_cvv
          self.card_expiration_date  = "#{card_expiration_month}#{card_expiration_year}"
        end
        self.card = nil
      end

      self.card_expiration_date ||= "#{card_expiration_month}#{card_expiration_year}"
    end
  end
end


text:
namespace net.openstack.Providers.Rackspace.Objects.Response
{
    using System.Collections.Generic;
    using System.Linq;
    using Newtonsoft.Json;

    [JsonObject(MemberSerialization.OptIn)]
    internal class BulkDeleteResponse
    {
        [JsonProperty("Number Not Found")]
        public int NumberNotFound { get; set; }

        [JsonProperty("Response Status")]
        public string Status { get; set; }

        [JsonProperty("Errors")]
        public IEnumerable<IEnumerable<string>> Errors { get; set; }

        [JsonProperty("Number Deleted")]
        public int NumberDeleted { get; set; }

        [JsonProperty("Response Body")]
        public string ResponseBody { get; set; }

        public IEnumerable<string> AllItems { get; set; }

        public bool IsItemError(string s)
        {
            return Errors.Any(e => e.Any(e2 => e2.Equals(s)));
        }
    }
}


text:
package interpreter.tree;

import interpreter.ProgramExecutionException;

import java.util.List;
import java.util.function.BooleanSupplier;

import codeblocks.Block;

/**
 * An if-else program flow command. (genera if, ifelse)
 * @author Brandon Oubre
 */
public class If extends Command {
	private BooleanResult condition;
	private List<Command> trueCase;
	private List<Command> falseCase;

	/**
	 * Create a new if-else command.
	 * @param block The associated block.
	 * @param condition The test condition for the statement.
	 * @param trueCase The commands to execute if the condition is true.
	 * @param falseCase The commands to execute if the condition is false. (May be <tt>null</tt> if nothing is executed.)
	 */
	public If(Block block, BooleanResult condition, List<Command> trueCase, List<Command> falseCase) {
		super(block);
		assert condition != null : "The test condition must exist!";
		assert trueCase != null : "True case must exist!";
		this.condition = condition;
		this.trueCase = trueCase;
		this.falseCase = falseCase;
	}

	@Override
	public void execute(BooleanSupplier testStop) throws ProgramExecutionException {
		List<Command> selectedCase = condition.getResult() ? trueCase : falseCase;
		for (Command c : selectedCase) {
			if (testStop.getAsBoolean()) {
				return;
			}
			c.execute(testStop);
		}
	}

	@Override
	public void parseDump(StringBuilder sb, int indent) {
		indent(sb, indent);
		sb.append(toString() + "\n");

		indent(sb, indent);
		sb.append(">CONDITION: \n");
		if (condition instanceof BlockNode) {
			((BlockNode) condition).parseDump(sb, indent + DUMP_INDENT);
		}

		indent(sb, indent);
		sb.append(">TRUE CASE: \n");
		for (BlockNode node : trueCase) {
			node.parseDump(sb, indent + DUMP_INDENT);
		}

		if (falseCase != null) {
			indent(sb, indent);
			sb.append(">FALSE CASE: \n");
			for (BlockNode node : falseCase) {
				node.parseDump(sb, indent + DUMP_INDENT);
			}
		}
	}
}


text:
"""
Parse latency (vs. traffic rate) for DSR simulation.

Revision Info
=============
* $LastChangedBy: mandke $
* $LastChangedDate: 2011-12-09 12:55:44 -0600 (Fri, 09 Dec 2011) $
* $LastChangedRevision: 5364 $

:author: Ketan Mandke <kmandke@mail.utexas.edu>

:copyright:
    Copyright 2009-2011 The University of Texas at Austin

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""
__docformat__ = "restructuredtext en"

from wins import *
from wins.ieee80211 import *

from optparse import OptionParser
import sys

import numpy as np

from config_parse import FILTER_DISCONNECTED

def read_trace(options, tracefile):
    # load trace from file
    tr = Trace()
    tr.read(tracefile)
    # return trace
    return tr

def hasfield(event, *args):
    """Check if event has all the specified arguments."""
    ok = all([(a in event) for a in args])
    return ok

def parse_info(options, trace):
    # (data, param) variables
    data = []
    param = {'plen': None}
    rate = None
    envspeed = None
    # event parameters
    macargs     = ('mac-txts', )
    agtargs     = ('net-root', )
    # paramaters for logging data
    sendbuffer = {}     # log sent packets using AGT name for index
    sendnodes  = {}     # nodes that sent data : number delivered
    # default arguments for buffer entry
    defaultpkt = {'txts':None, 'rxts':None, 'hopcount':None, 'sender':None}
    for e in trace.events:
        # check timestamp - [tmin, tmax]
        ts = float(e['ts'])
        if (ts<options.tmin): continue
        elif (ts>options.tmax): break
        # get event/object/packet parameters
        obj, evt = e['obj'], e['event']
        pname, pid = e['packet'], e['pid']
        rname, rid = e['root'], e['rid']
        nname, nid = e['node'], e['nid']
        pkt = "%s(%s)"%(pname, pid)
        root = "%s(%s)"%(rname, rid)
        node = "%s(%s)"%(nname, nid)
        # check for AGT SND
        if (obj=="AGT") and (evt=="SND"):
            assert (pkt not in sendbuffer)
            sendbuffer[pkt] = defaultpkt.copy()
            sendbuffer[pkt]['txts'] = float(ts)
            sendbuffer[pkt]['sender'] = node
            if node not in sendnodes: sendnodes[node] = 0
        # check for AGT RCV
        if (obj=="AGT") and (evt=="RCV"):
            assert (pkt in sendbuffer)
            sendbuffer[pkt]['rxts'] = float(ts)
            sender = sendbuffer[pkt]['sender']
            assert (sender in sendnodes)
            sendnodes[sender] += 1
        # check for DSR SND
        hasagt = hasfield(e, 'agt-root')
        if (obj=="DSR") and (evt=="SND") and hasagt:
            agt = e['agt-root']
            assert (agt in sendbuffer)
            nhops = None
            if   (rname=="DSR|SRCROUTE"):
                assert hasfield(e, 'srcroute.addresses')
                srcroute = eval(e['srcroute.addresses'])
                nhops = len(srcroute) + 1
            elif (rname=="DSR"):
                nhops = 1
            assert (nhops is not None)
            sendbuffer[agt]['hopcount'] = nhops
        # check for other parameters
        if (obj=="AGT") and (evt=="SND"):
            assert hasfield(e, 'plen')
            plen = int(e['plen'])
            if param['plen'] is None: param['plen'] = plen
            else:                     assert (plen==param['plen'])
        if (obj=="MON") and (evt=="RATE"):
            assert hasfield(e, 'rate')
            rate = float(e['rate'])
        if (obj=="MON") and (evt=="MODEL"):
            assert hasfield(e, 'environmentspeed')
            envspeed = float(e['environmentspeed'])
    # skip data from disconnected topologies
    if FILTER_DISCONNECTED:
        isdisconnected = False
        for s, v in sendnodes.items():
            if (v==0): isdisconnected = True
        if isdisconnected:
            sys.stderr.write("WARNING: Skipping data for disconnected topology!\n")
            return data, param
    # calculate delay from sendbuffer
    assert (rate is not None)
    for p,d in sendbuffer.items():
        plen = param['plen']
        assert (plen is not None)
        if (d['rxts'] is None):
            # packet was not delivered -> ignore
            x, y = rate, 0
        else:
            # packet was delivered
            x, latency = rate, d['rxts']-d['txts']
            L = 8*plen               # length in bits
            tput = (1e-6*L/latency)     # throughput in Mbps
            nhops = 1
            if options.perhop:
                assert (d['hopcount'] is not None)
                nhops = d['hopcount']
            y = 1.0*latency/nhops
            dp = {'x': x, 'y': y, 'ndata': 1}
            data.append(dp)
    # set remaining parameters
    param['use-yerror'] = True
    return data, param

def parse_delay():
    usage = "%prog [OPTIONS] TRACEFILE1 [TRACEFILE2 ...]\n" + \
            "      Writes parsed data to standard output."
    parser = OptionParser(usage=usage)
    parser.add_option("", "--tmin", dest="tmin", \
            type="float", default=-np.inf, \
            help="Specify simulation time to start from [default=%default]")
    parser.add_option("", "--tmax", dest="tmax", \
            type="float", default=np.inf, \
            help="Specify simulation time to stop at [default=%default]")
    parser.add_option("-f", "--fmt", dest="fmt", \
            default="bo", help="Format of data parsed from tracefiles [default=%default]")
    parser.add_option("", "--label", dest="label", \
            default="Hydra PHY", help="Specify label for newly parsed data [default=%default]")
    parser.add_option("", "--per-hop", dest="perhop", action="store_true", \
            default=False, help="Normalize delay by the number of hops in the route.")
    (options, args) = parser.parse_args()

    if len(args)<1:
        print "Insufficient number of arguments."
        parser.print_help()
        raise SystemExit

    # get trace files
    tracefile = args[0:]
    numtraces = len(tracefile)

    # set default parameters
    defaultparam = {'xlabel': "Traffic Rate (packets/sec)", \
                    'ylabel': "Delay (sec)", \
                    'title': "End-to-End Delay vs. Traffic Rate", \
                    'label': None, \
                    'source': None, \
                    'format': None}

    # define formats
    formats = [(options.fmt, options.fmt[0]+"x:")]     # use same format for all
    #formats = [('ro','rx:'), ('bo', 'bx:'), ('go', 'gx:')]

    # parse data from each data set
    for k in range(numtraces):
        # get tracefile
        tfile = tracefile[k]
        trace = read_trace(options, tfile) # treat as normal wins trace file
        if not trace: continue
        # get other parameters
        fmt = formats[k%len(formats)]
        # parse trace to get (data, param)
        sys.stderr.write("Parsing trace from %s ... \n"%(tfile))
        data, dparam = parse_info(options, trace)
        if data:
            param = defaultparam.copy()
            param.update(dparam)
            param['format'] = fmt[0]
            param['source'] = tfile
            param['label']  = options.label
            pdata = {'data': data, 'parameters':param}
            sys.stdout.write("%s\n"%(pdata))

if __name__ == '__main__':
    parse_delay()


text:
@interface PodsDummy_Pods_FoodInspections_Expecta : NSObject
@end
@implementation PodsDummy_Pods_FoodInspections_Expecta
@end


text:
<?php

declare(strict_types=1);

/**
 * This file is part of Narrowspark Framework.
 *
 * (c) Daniel Bannert <d.bannert@anolilab.de>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Viserio\Component\Bus;

use Closure;
use Psr\Container\ContainerInterface;
use Viserio\Component\Pipeline\Pipeline;
use Viserio\Component\Support\Traits\InvokerAwareTrait;
use Viserio\Contract\Bus\Dispatcher as DispatcherContract;
use Viserio\Contract\Bus\Exception\InvalidArgumentException;
use Viserio\Contract\Container\Traits\ContainerAwareTrait;
use Viserio\Contract\Pipeline\Pipeline as PipelineContract;

class Dispatcher implements DispatcherContract
{
    use ContainerAwareTrait;
    use InvokerAwareTrait;

    protected PipelineContract $pipeline;

    /**
     * The pipes to send commands through before dispatching.
     *
     * @var array
     */
    protected array $pipes = [];

    /**
     * All of the command-to-handler mappings.
     *
     * @var array
     */
    protected array $mappings = [];

    /**
     * The method to call on handler.
     *
     * @var string
     */
    protected string $method = 'handle';

    /**
     * The fallback mapping Closure.
     *
     * @var null|Closure
     */
    protected $mapper;

    /**
     * Create a new command dispatcher instance.
     *
     * @param \Psr\Container\ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;

        $pipeline = new Pipeline();
        $pipeline->setContainer($container);

        $this->pipeline = $pipeline;
    }

    /**
     * {@inheritdoc}
     */
    public function via(string $method): DispatcherContract
    {
        $this->method = $method;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function resolveHandler($command): object
    {
        if (\method_exists($command, $this->method)) {
            return $command;
        }

        return $this->container->get($this->getHandlerClass($command));
    }

    /**
     * {@inheritdoc}
     */
    public function getHandlerClass($command): string
    {
        if (\method_exists($command, $this->method)) {
            return \get_class($command);
        }

        return $this->inflectSegment($command, 0);
    }

    /**
     * {@inheritdoc}
     */
    public function getHandlerMethod($command): string
    {
        if (\method_exists($command, $this->method)) {
            return $this->method;
        }

        return $this->inflectSegment($command, 1);
    }

    /**
     * {@inheritdoc}
     */
    public function maps(array $commands): void
    {
        $this->mappings = \array_merge($this->mappings, $commands);
    }

    /**
     * {@inheritdoc}
     */
    public function mapUsing(Closure $mapper): void
    {
        $this->mapper = $mapper;
    }

    /**
     * {@inheritdoc}
     */
    public function dispatch($command, ?Closure $afterResolving = null)
    {
        return $this->pipeline->send($command)->through($this->pipes)->then(function ($command) use ($afterResolving) {
            if (\method_exists($command, $this->method)) {
                return $this->getInvoker()->call([$command, $this->method]);
            }

            $handler = $this->resolveHandler($command);

            if ($afterResolving !== null) {
                $afterResolving($handler);
            }

            return $handler->{$this->getHandlerMethod($command)}($command);
        });
    }

    /**
     * {@inheritdoc}
     */
    public function pipeThrough(array $pipes): DispatcherContract
    {
        $this->pipes = $pipes;

        return $this;
    }

    /**
     * Get the given handler segment for the given command.
     *
     * @param object $command
     * @param int    $segment
     *
     * @throws \Viserio\Contract\Bus\Exception\InvalidArgumentException
     *
     * @return string
     */
    protected function inflectSegment(object $command, int $segment): string
    {
        $className = \get_class($command);

        // Get the given segment from a given class handler.
        if (isset($this->mappings[$className])) {
            return \explode('@', $this->mappings[$className])[$segment];
        }

        // Get the given segment from a given class handler using the custom mapper.
        if (\is_callable($this->mapper)) {
            return \explode('@', \call_user_func($this->mapper, [$command]))[$segment];
        }

        throw new InvalidArgumentException(\sprintf('No handler registered for command [%s].', $className));
    }
}


text:
using System.Linq;
using System.Threading.Tasks;
using Famoser.OfflineMedia.Business.Managers;
using Famoser.OfflineMedia.Business.Models.NewsModel;
using Famoser.OfflineMedia.Business.Repositories.Base;
using Famoser.OfflineMedia.Business.Repositories.Interfaces;
using Famoser.OfflineMedia.Data.Entities.Database;
using Famoser.OfflineMedia.Data.Entities.Database.Relations;
using Famoser.SqliteWrapper.Repositories;
using Famoser.SqliteWrapper.Services.Interfaces;
using Nito.AsyncEx;

namespace Famoser.OfflineMedia.Business.Repositories
{
    public class ThemeRepository : BaseRepository, IThemeRepository
    {
        private readonly GenericRepository<ThemeModel, ThemeEntity> _themeGenericRepository;
        private readonly ISqliteService _sqliteService;

        public ThemeRepository(ISqliteService sqliteService)
        {
            _sqliteService = sqliteService;

            _themeGenericRepository = new GenericRepository<ThemeModel, ThemeEntity>(_sqliteService);
        }

        private bool _isInitialized;
        private readonly AsyncLock _asyncLock = new AsyncLock();
        private Task Initialize()
        {
            return ExecuteSafe(async () =>
            {
                using (await _asyncLock.LockAsync())
                {
                    if (_isInitialized)
                        return;

                    _isInitialized = true;
                    ThemeManager.AddThemes(await _themeGenericRepository.GetAllAsync());
                }
            });
        }

        public async Task AddThemeToArticleAsync(ArticleModel article, string theme)
        {
            await Initialize();

            await ExecuteSafe(async () =>
            {
                var normalizedTheme = NormalizeThemeName(theme);
                var themeModel = ThemeManager.TryGetSimilarTheme(normalizedTheme);
                if (themeModel == null)
                {
                    themeModel = new ThemeModel()
                    {
                        NormalizedName = normalizedTheme,
                        Name = theme
                    };
                    //concurrency: soem other thread may have added the same theme
                    var tm = ThemeManager.TryAddTheme(themeModel);
                    if (tm == themeModel)
                        await _themeGenericRepository.AddAsync(themeModel);
                }
                if (article.Themes.Contains(themeModel))
                    return;

                article.Themes.Add(themeModel);
                await _sqliteService.Add(new ThemeArticleRelations()
                {
                    ArticleId = article.GetId(),
                    ThemeId = themeModel.GetId()
                });
            });
        }

        private string NormalizeThemeName(string str)
        {
            return str.ToLowerInvariant();
        }

        public async Task AddRelatedThemesArticlesAsync(ArticleModel article)
        {
            await Initialize();

            await ExecuteSafe(async () =>
            {
                var aId = article.GetId();
                var relations = await _sqliteService.GetByCondition<ThemeArticleRelations>(a => a.ArticleId == aId, null, false, 0, 0);
                var ids = relations.Select(q => q.ThemeId);
                foreach (var source in ThemeManager.GetAllThemes().Where(d => ids.Any(id => id == d.GetId())))
                {
                    article.Themes.Add(source);
                }
            });
        }

        public async Task LoadArticleThemesAsync(ArticleModel am)
        {
            await Initialize();

            await ExecuteSafe(async () =>
            {
                var id = am.GetId();
                var cm = await _sqliteService.GetByCondition<ThemeArticleRelations>(d => d.ArticleId == id, null, false, 0, 0);
                foreach (var entry in cm.ToArray())
                {
                    var theme = ThemeManager.GetAllThemes().FirstOrDefault(t => t.GetId() == entry.ThemeId);
                    if (theme != null)
                    {
                        am.Themes.Add(theme);
                    }
                }
            });
        }
    }
}


text:
using NUnit.Framework;
using System;
using DnDGen.TreasureGen.Tables;
using DnDGen.TreasureGen.Items;

namespace DnDGen.TreasureGen.Tests.Integration.Tables.Items.Magical.Intelligence
{
    [TestFixture]
    public class IsRodIntelligentTests : BooleanPercentileTests
    {
        protected override string tableName
        {
            get { return string.Format(TableNameConstants.Percentiles.Formattable.IsITEMTYPEIntelligent, ItemTypeConstants.Rod); }
        }

        [Test]
        public override void ReplacementStringsAreValid()
        {
            AssertReplacementStringsAreValid();
        }

        [TestCase(false, 2, 100)]
        public override void BooleanPercentile(Boolean isTrue, int lower, int upper)
        {
            base.BooleanPercentile(isTrue, lower, upper);
        }

        [TestCase(true, 1)]
        public override void BooleanPercentile(Boolean isTrue, int roll)
        {
            base.BooleanPercentile(isTrue, roll);
        }

        [Test]
        public override void TableIsComplete()
        {
            AssertTableIsComplete();
        }
    }
}


text:
package com.microsoft.azure.management.appservice;

import com.microsoft.azure.management.resources.fluentcore.arm.Region;
import com.microsoft.rest.RestClient;
import org.junit.Assert;
import org.junit.Test;

import java.util.List;
import java.util.Map;

public class FunctionDeploymentSlotsTests extends AppServiceTest {
    private static String RG_NAME_1 = "";
    private static String WEBAPP_NAME_1 = "";
    private static String SLOT_NAME_1 = "";
    private static String SLOT_NAME_2 = "";
    private static String SLOT_NAME_3 = "";

    @Override
    protected void initializeClients(RestClient restClient, String defaultSubscription, String domain) {
        WEBAPP_NAME_1 = generateRandomResourceName("java-funcapp-", 20);
        RG_NAME_1 = generateRandomResourceName("javacsmrg", 20);
        SLOT_NAME_1 = generateRandomResourceName("java-slot-", 20);
        SLOT_NAME_2 = generateRandomResourceName("java-slot-", 20);
        SLOT_NAME_3 = generateRandomResourceName("java-slot-", 20);

        super.initializeClients(restClient, defaultSubscription, domain);
    }

    @Test
    public void canCRUDFunctionSwapSlots() throws Exception {
        // Create with consumption
        FunctionApp functionApp1 = appServiceManager.functionApps().define(WEBAPP_NAME_1)
                .withRegion(Region.US_WEST)
                .withNewResourceGroup(RG_NAME_1)
                .withNewAppServicePlan(PricingTier.STANDARD_S1)
                .withAppSetting("appkey", "appvalue")
                .withStickyAppSetting("stickykey", "stickyvalue")
                .withConnectionString("connectionName", "connectionValue", ConnectionStringType.CUSTOM)
                .withStickyConnectionString("stickyName", "stickyValue", ConnectionStringType.CUSTOM)
                .withJavaVersion(JavaVersion.JAVA_1_7_0_51)
                .withWebContainer(WebContainer.TOMCAT_7_0_50)
                .create();
        Assert.assertNotNull(functionApp1);
        Assert.assertEquals(Region.US_WEST, functionApp1.region());
        AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId());
        Assert.assertNotNull(plan1);
        Assert.assertEquals(Region.US_WEST, plan1.region());

        // Create a deployment slot with empty config
        FunctionDeploymentSlot slot1 = functionApp1.deploymentSlots().define(SLOT_NAME_1)
                .withBrandNewConfiguration()
                .withPythonVersion(PythonVersion.PYTHON_27)
                .create();
        Assert.assertNotNull(slot1);
        Assert.assertNotEquals(JavaVersion.JAVA_1_7_0_51, slot1.javaVersion());
        Assert.assertEquals(PythonVersion.PYTHON_27, slot1.pythonVersion());
        Map<String, AppSetting> appSettingMap = slot1.appSettings();
        Assert.assertFalse(appSettingMap.containsKey("appkey"));
        Assert.assertFalse(appSettingMap.containsKey("stickykey"));
        Map<String, ConnectionString> connectionStringMap = slot1.connectionStrings();
        Assert.assertFalse(connectionStringMap.containsKey("connectionName"));
        Assert.assertFalse(connectionStringMap.containsKey("stickyName"));

        // Create a deployment slot with web app's config
        FunctionDeploymentSlot slot2 = functionApp1.deploymentSlots().define(SLOT_NAME_2)
                .withConfigurationFromParent()
                .create();
        Assert.assertNotNull(slot2);
        Assert.assertEquals(JavaVersion.JAVA_1_7_0_51, slot2.javaVersion());
        appSettingMap = slot2.appSettings();
        Assert.assertEquals("appvalue", appSettingMap.get("appkey").value());
        Assert.assertEquals(false, appSettingMap.get("appkey").sticky());
        Assert.assertEquals("stickyvalue", appSettingMap.get("stickykey").value());
        Assert.assertEquals(true, appSettingMap.get("stickykey").sticky());
        connectionStringMap = slot2.connectionStrings();
        Assert.assertEquals("connectionValue", connectionStringMap.get("connectionName").value());
        Assert.assertEquals(false, connectionStringMap.get("connectionName").sticky());
        Assert.assertEquals("stickyValue", connectionStringMap.get("stickyName").value());
        Assert.assertEquals(true, connectionStringMap.get("stickyName").sticky());

        // Update deployment slot
        slot2.update()
                .withoutJava()
                .withPythonVersion(PythonVersion.PYTHON_34)
                .withAppSetting("slot2key", "slot2value")
                .withStickyAppSetting("sticky2key", "sticky2value")
                .apply();
        Assert.assertNotNull(slot2);
        Assert.assertEquals(JavaVersion.OFF, slot2.javaVersion());
        Assert.assertEquals(PythonVersion.PYTHON_34, slot2.pythonVersion());
        appSettingMap = slot2.appSettings();
        Assert.assertEquals("slot2value", appSettingMap.get("slot2key").value());

        // Create 3rd deployment slot with configuration from slot 2
        FunctionDeploymentSlot slot3 = functionApp1.deploymentSlots().define(SLOT_NAME_3)
                .withConfigurationFromDeploymentSlot(slot2)
                .create();
        Assert.assertNotNull(slot3);
        Assert.assertEquals(JavaVersion.OFF, slot3.javaVersion());
        Assert.assertEquals(PythonVersion.PYTHON_34, slot3.pythonVersion());
        appSettingMap = slot3.appSettings();
        Assert.assertEquals("slot2value", appSettingMap.get("slot2key").value());

        // Get
        FunctionDeploymentSlot deploymentSlot = functionApp1.deploymentSlots().getByName(SLOT_NAME_3);
        Assert.assertEquals(slot3.id(), deploymentSlot.id());

        // List
        List<FunctionDeploymentSlot> deploymentSlots = functionApp1.deploymentSlots().list();
        Assert.assertEquals(3, deploymentSlots.size());

        // Swap
        slot3.swap(slot1.name());
        slot1 = functionApp1.deploymentSlots().getByName(SLOT_NAME_1);
        Assert.assertEquals(JavaVersion.OFF, slot1.javaVersion());
        Assert.assertEquals(PythonVersion.PYTHON_34, slot1.pythonVersion());
        Assert.assertEquals(PythonVersion.PYTHON_27, slot3.pythonVersion());
        Assert.assertEquals("appvalue", slot1.appSettings().get("appkey").value());
        Assert.assertEquals("slot2value", slot1.appSettings().get("slot2key").value());
        Assert.assertEquals("sticky2value", slot3.appSettings().get("sticky2key").value());
        Assert.assertEquals("stickyvalue", slot3.appSettings().get("stickykey").value());
    }
}


text:
#include "webrtc/modules/video_coding/receiver.h"

#include <assert.h>

#include <cstdlib>
#include <utility>
#include <vector>

#include "webrtc/base/logging.h"
#include "webrtc/base/trace_event.h"
#include "webrtc/modules/video_coding/encoded_frame.h"
#include "webrtc/modules/video_coding/internal_defines.h"
#include "webrtc/modules/video_coding/media_opt_util.h"
#include "webrtc/system_wrappers/include/clock.h"

namespace webrtc {

enum { kMaxReceiverDelayMs = 10000 };

VCMReceiver::VCMReceiver(VCMTiming* timing,
                         Clock* clock,
                         EventFactory* event_factory)
    : VCMReceiver::VCMReceiver(timing,
                               clock,
                               event_factory,
                               nullptr,  // NackSender
                               nullptr)  // KeyframeRequestSender
{}

VCMReceiver::VCMReceiver(VCMTiming* timing,
                         Clock* clock,
                         EventFactory* event_factory,
                         NackSender* nack_sender,
                         KeyFrameRequestSender* keyframe_request_sender)
    : VCMReceiver(
          timing,
          clock,
          std::unique_ptr<EventWrapper>(event_factory
                                            ? event_factory->CreateEvent()
                                            : EventWrapper::Create()),
          std::unique_ptr<EventWrapper>(event_factory
                                            ? event_factory->CreateEvent()
                                            : EventWrapper::Create()),
          nack_sender,
          keyframe_request_sender) {}

VCMReceiver::VCMReceiver(VCMTiming* timing,
                         Clock* clock,
                         std::unique_ptr<EventWrapper> receiver_event,
                         std::unique_ptr<EventWrapper> jitter_buffer_event)
    : VCMReceiver::VCMReceiver(timing,
                               clock,
                               std::move(receiver_event),
                               std::move(jitter_buffer_event),
                               nullptr,  // NackSender
                               nullptr)  // KeyframeRequestSender
{}

VCMReceiver::VCMReceiver(VCMTiming* timing,
                         Clock* clock,
                         std::unique_ptr<EventWrapper> receiver_event,
                         std::unique_ptr<EventWrapper> jitter_buffer_event,
                         NackSender* nack_sender,
                         KeyFrameRequestSender* keyframe_request_sender)
    : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
      clock_(clock),
      jitter_buffer_(clock_,
                     std::move(jitter_buffer_event),
                     nack_sender,
                     keyframe_request_sender),
      timing_(timing),
      render_wait_event_(std::move(receiver_event)),
      max_video_delay_ms_(kMaxVideoDelayMs) {
  Reset();
}

VCMReceiver::~VCMReceiver() {
  render_wait_event_->Set();
  delete crit_sect_;
}

void VCMReceiver::Reset() {
  CriticalSectionScoped cs(crit_sect_);
  if (!jitter_buffer_.Running()) {
    jitter_buffer_.Start();
  } else {
    jitter_buffer_.Flush();
  }
}

void VCMReceiver::UpdateRtt(int64_t rtt) {
  jitter_buffer_.UpdateRtt(rtt);
}

int64_t VCMReceiver::TimeUntilNextProcess() {
  return jitter_buffer_.TimeUntilNextProcess();
}

void VCMReceiver::Process() {
  jitter_buffer_.Process();
}

int32_t VCMReceiver::InsertPacket(const VCMPacket& packet,
                                  uint16_t frame_width,
                                  uint16_t frame_height) {
  // Insert the packet into the jitter buffer. The packet can either be empty or
  // contain media at this point.
  bool retransmitted = false;
  const VCMFrameBufferEnum ret =
      jitter_buffer_.InsertPacket(packet, &retransmitted);
  if (ret == kOldPacket) {
    return VCM_OK;
  } else if (ret == kFlushIndicator) {
    return VCM_FLUSH_INDICATOR;
  } else if (ret < 0) {
    return VCM_JITTER_BUFFER_ERROR;
  }
  if (ret == kCompleteSession && !retransmitted) {
    // We don't want to include timestamps which have suffered from
    // retransmission here, since we compensate with extra retransmission
    // delay within the jitter estimate.
    timing_->IncomingTimestamp(packet.timestamp, clock_->TimeInMilliseconds());
  }
  return VCM_OK;
}

void VCMReceiver::TriggerDecoderShutdown() {
  jitter_buffer_.Stop();
  render_wait_event_->Set();
}

VCMEncodedFrame* VCMReceiver::FrameForDecoding(uint16_t max_wait_time_ms,
                                               int64_t* next_render_time_ms,
                                               bool prefer_late_decoding) {
  const int64_t start_time_ms = clock_->TimeInMilliseconds();
  uint32_t frame_timestamp = 0;
  int min_playout_delay_ms = -1;
  int max_playout_delay_ms = -1;
  // Exhaust wait time to get a complete frame for decoding.
  VCMEncodedFrame* found_frame =
      jitter_buffer_.NextCompleteFrame(max_wait_time_ms);

  if (found_frame) {
    frame_timestamp = found_frame->TimeStamp();
    min_playout_delay_ms = found_frame->EncodedImage().playout_delay_.min_ms;
    max_playout_delay_ms = found_frame->EncodedImage().playout_delay_.max_ms;
  } else {
    if (!jitter_buffer_.NextMaybeIncompleteTimestamp(&frame_timestamp))
      return nullptr;
  }

  if (min_playout_delay_ms >= 0)
    timing_->set_min_playout_delay(min_playout_delay_ms);

  if (max_playout_delay_ms >= 0)
    timing_->set_max_playout_delay(max_playout_delay_ms);

  // We have a frame - Set timing and render timestamp.
  timing_->SetJitterDelay(jitter_buffer_.EstimatedJitterMs());
  const int64_t now_ms = clock_->TimeInMilliseconds();
  timing_->UpdateCurrentDelay(frame_timestamp);
  *next_render_time_ms = timing_->RenderTimeMs(frame_timestamp, now_ms);
  // Check render timing.
  bool timing_error = false;
  // Assume that render timing errors are due to changes in the video stream.
  if (*next_render_time_ms < 0) {
    timing_error = true;
  } else if (std::abs(*next_render_time_ms - now_ms) > max_video_delay_ms_) {
    int frame_delay = static_cast<int>(std::abs(*next_render_time_ms - now_ms));
    LOG(LS_WARNING) << "A frame about to be decoded is out of the configured "
                    << "delay bounds (" << frame_delay << " > "
                    << max_video_delay_ms_
                    << "). Resetting the video jitter buffer.";
    timing_error = true;
  } else if (static_cast<int>(timing_->TargetVideoDelay()) >
             max_video_delay_ms_) {
    LOG(LS_WARNING) << "The video target delay has grown larger than "
                    << max_video_delay_ms_ << " ms. Resetting jitter buffer.";
    timing_error = true;
  }

  if (timing_error) {
    // Timing error => reset timing and flush the jitter buffer.
    jitter_buffer_.Flush();
    timing_->Reset();
    return NULL;
  }

  if (prefer_late_decoding) {
    // Decode frame as close as possible to the render timestamp.
    const int32_t available_wait_time =
        max_wait_time_ms -
        static_cast<int32_t>(clock_->TimeInMilliseconds() - start_time_ms);
    uint16_t new_max_wait_time =
        static_cast<uint16_t>(VCM_MAX(available_wait_time, 0));
    uint32_t wait_time_ms = timing_->MaxWaitingTime(
        *next_render_time_ms, clock_->TimeInMilliseconds());
    if (new_max_wait_time < wait_time_ms) {
      // We're not allowed to wait until the frame is supposed to be rendered,
      // waiting as long as we're allowed to avoid busy looping, and then return
      // NULL. Next call to this function might return the frame.
      render_wait_event_->Wait(new_max_wait_time);
      return NULL;
    }
    // Wait until it's time to render.
    render_wait_event_->Wait(wait_time_ms);
  }

  // Extract the frame from the jitter buffer and set the render time.
  VCMEncodedFrame* frame = jitter_buffer_.ExtractAndSetDecode(frame_timestamp);
  if (frame == NULL) {
    return NULL;
  }
  frame->SetRenderTime(*next_render_time_ms);
  TRACE_EVENT_ASYNC_STEP1("webrtc", "Video", frame->TimeStamp(), "SetRenderTS",
                          "render_time", *next_render_time_ms);
  if (!frame->Complete()) {
    // Update stats for incomplete frames.
    bool retransmitted = false;
    const int64_t last_packet_time_ms =
        jitter_buffer_.LastPacketTime(frame, &retransmitted);
    if (last_packet_time_ms >= 0 && !retransmitted) {
      // We don't want to include timestamps which have suffered from
      // retransmission here, since we compensate with extra retransmission
      // delay within the jitter estimate.
      timing_->IncomingTimestamp(frame_timestamp, last_packet_time_ms);
    }
  }
  return frame;
}

void VCMReceiver::ReleaseFrame(VCMEncodedFrame* frame) {
  jitter_buffer_.ReleaseFrame(frame);
}

void VCMReceiver::ReceiveStatistics(uint32_t* bitrate, uint32_t* framerate) {
  assert(bitrate);
  assert(framerate);
  jitter_buffer_.IncomingRateStatistics(framerate, bitrate);
}

uint32_t VCMReceiver::DiscardedPackets() const {
  return jitter_buffer_.num_discarded_packets();
}

void VCMReceiver::SetNackMode(VCMNackMode nackMode,
                              int64_t low_rtt_nack_threshold_ms,
                              int64_t high_rtt_nack_threshold_ms) {
  CriticalSectionScoped cs(crit_sect_);
  // Default to always having NACK enabled in hybrid mode.
  jitter_buffer_.SetNackMode(nackMode, low_rtt_nack_threshold_ms,
                             high_rtt_nack_threshold_ms);
}

void VCMReceiver::SetNackSettings(size_t max_nack_list_size,
                                  int max_packet_age_to_nack,
                                  int max_incomplete_time_ms) {
  jitter_buffer_.SetNackSettings(max_nack_list_size, max_packet_age_to_nack,
                                 max_incomplete_time_ms);
}

VCMNackMode VCMReceiver::NackMode() const {
  CriticalSectionScoped cs(crit_sect_);
  return jitter_buffer_.nack_mode();
}

std::vector<uint16_t> VCMReceiver::NackList(bool* request_key_frame) {
  return jitter_buffer_.GetNackList(request_key_frame);
}

void VCMReceiver::SetDecodeErrorMode(VCMDecodeErrorMode decode_error_mode) {
  jitter_buffer_.SetDecodeErrorMode(decode_error_mode);
}

VCMDecodeErrorMode VCMReceiver::DecodeErrorMode() const {
  return jitter_buffer_.decode_error_mode();
}

int VCMReceiver::SetMinReceiverDelay(int desired_delay_ms) {
  CriticalSectionScoped cs(crit_sect_);
  if (desired_delay_ms < 0 || desired_delay_ms > kMaxReceiverDelayMs) {
    return -1;
  }
  max_video_delay_ms_ = desired_delay_ms + kMaxVideoDelayMs;
  // Initializing timing to the desired delay.
  timing_->set_min_playout_delay(desired_delay_ms);
  return 0;
}

void VCMReceiver::RegisterStatsCallback(
    VCMReceiveStatisticsCallback* callback) {
  jitter_buffer_.RegisterStatsCallback(callback);
}

}  // namespace webrtc


text:
FROM baseboxorg/nodejs
MAINTAINER Anthony Lai <anthony.lai@hostname.io>

RUN npm install hipache -g

ADD config.json config.json
ADD start.sh start.sh

EXPOSE 80
RUN rm /usr/sbin/policy-rc.d
CMD ["/start.sh"]


text:
package com.badlogic.gdx.artemis.components;

import com.artemis.Component;
import com.artemis.ComponentType;
import com.badlogic.gdx.math.Vector2;

public class Bound extends Component {
	public static ComponentType CType = ComponentType.getTypeFor(Bound.class);

	private final float width;
	private final float height;
	public final float radius;
	public final Vector2 center;

	public Bound(float width, float height)
	{
		this.width = width;
		this.height = height;
		this.center = new Vector2(width/2.0f, height/2.0f);
		this.radius = this.center.dst(Vector2.Zero);
	}
}


text:
from selenium import webdriver
import unittest

class AdminPageTest(unittest.TestCase):

    def setUp(self):
        self.browser = webdriver.Firefox()
        self.browser.implicitly_wait(3)

    def tearDown(self):
        self.browser.quit()

    def test_visit_admin_page(self):
        # Visit admin page
        self.browser.get('http://localhost:8000/admin')
        # Check page title
        self.assertIn('Django site admin', self.browser.title)

class API_fetch_tests(unittest.TestCase):

    def setUp(self):
        self.browser = webdriver.Firefox()

    def tearDown(self):
        self.browser.quit()

    def test_fetch_Ingredient_JSON(self):
        pass

    def test_fetch_Drink_JSON(self):
        pass

class ReactAppTests(unittest.TestCase):

    def setUp(self):
        self.browser = webdriver.Firefox()

    def tearDown(self):
        self.browser.quit()

    def test_fetch_index(self):
        self.browser.get('http://localhost:8000/index')
        self.assertIn('Cocktails', self.browser.title)

if __name__ == '__main__':
    print('test')
    unittest.main()


text:
<!DOCTYPE html>

 <meta charset="UTF-8">

<title>DictT2fRange—Wolfram Language Documentation</title>
<meta name="buildnumber" content="0000000" />
<meta name="historydata" content="{XX, , , }" />
<meta name="keywords" content="DictT2fRange" />

<meta name="description" content="DictT2fRange is an option for CreateT2Dictionary and EPGT2Fit. is specifies the range and step of the T2 fat values in the dictionary {min, max, step} in ms. If a single value is given this fixed value is used a long as EPGCalibrate is False." />

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

<link rel="stylesheet" href="../css/reference.css" />

            <link rel="stylesheet" href="../css/clipboard.css" />

   Q M R I TOOLS PACKAGE SYMBOL

DictT2fRange

DictT2fRange
is an option for CreateT2Dictionary and EPGT2Fit. is specifies the range and step of the T2 fat values in the dictionary {min, max, step} in ms. If a single value is given this fixed value is used a long as EPGCalibrate is False.


text:
#region Usings

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

using org.GraphDefined.Vanaheimr.Illias;

#endregion

namespace org.GraphDefined.Vanaheimr.Hermod.HTTP
{

    /// <summary>
    /// A node which stores information for maintaining multiple http hostnames.
    /// </summary>
    public class HostnameNode : IEnumerable<URL_Node>
    {

        #region Data

        /// <summary>
        /// A mapping from URIs to URINodes.
        /// </summary>
        private readonly Dictionary<HTTPPath, URL_Node> _URINodes;

        #endregion

        #region Properties

        /// <summary>
        /// The hostname for this (virtual) http service.
        /// </summary>
        public HTTPHostname  Hostname    { get; }

        /// <summary>
        /// Return all defined URIs.
        /// </summary>
        public IEnumerable<HTTPPath> URIs
            => _URINodes.Keys;

        /// <summary>
        /// Return all URI nodes.
        /// </summary>
        public IEnumerable<URL_Node> URLNodes
            => _URINodes.Values;

        #endregion

        #region (internal) Constructor(s)

        /// <summary>
        /// Creates a new hostname node.
        /// </summary>
        /// <param name="Hostname">The hostname(s) for this (virtual) http service.</param>
        internal HostnameNode(HTTPHostname Hostname)
        {

            #region Check Hostname

            if (Hostname == null)
                throw new ArgumentNullException(nameof(Hostname), "The given HTTP hostname must not be null!");

            var    HostHeader  = Hostname.ToString().Split(new Char[1] { ':' }, StringSplitOptions.None).Select(v => v.Trim()).ToArray();
            UInt16 HostPort    = 80;

            // 1.2.3.4          => 1.2.3.4:80
            // 1.2.3.4:80       => ok
            // 1.2.3.4 : 80     => ok
            // 1.2.3.4:*        => ok
            // 1.2.3.4:a        => invalid
            // 1.2.3.4:80:      => ok
            // 1.2.3.4:80:0     => invalid

            // rfc 2616 - 3.2.2
            // If the port is empty or not given, port 80 is assumed.
            if (HostHeader.Length == 1)
                this.Hostname = HTTPHostname.Parse(Hostname + ":" + HostPort);

            else if ((HostHeader.Length == 2 && (!UInt16.TryParse(HostHeader[1], out HostPort) && HostHeader[1] != "*")) ||
                      HostHeader.Length  > 2)
                      throw new ArgumentException("Invalid Hostname!", nameof(Hostname));

            else
                this.Hostname = HTTPHostname.Parse(HostHeader[0] + ":" + HostHeader[1]);

            #endregion

            this._URINodes  = new Dictionary<HTTPPath, URL_Node>();

        }

        #endregion

        #region AddHandler(...)

        public void AddHandler(HTTPDelegate              HTTPDelegate,

                               HTTPPath?                 URLTemplate                 = null,
                               HTTPMethod?               Method                      = null,
                               HTTPContentType           HTTPContentType             = null,

                               HTTPAuthentication        URIAuthentication           = null,
                               HTTPAuthentication        HTTPMethodAuthentication    = null,
                               HTTPAuthentication        ContentTypeAuthentication   = null,

                               HTTPRequestLogHandler     HTTPRequestLogger           = null,
                               HTTPResponseLogHandler    HTTPResponseLogger          = null,

                               HTTPDelegate              DefaultErrorHandler         = null,
                               URLReplacement            AllowReplacement            = URLReplacement.Fail)

        {

            lock (_URINodes)
            {

                if (!URLTemplate.HasValue)
                    URLTemplate = HTTPPath.Parse("/");

                if (!_URINodes.TryGetValue(URLTemplate.Value, out URL_Node _URINode))
                {

                    _URINode = _URINodes.AddAndReturnValue(URLTemplate.Value,
                                                           new URL_Node(URLTemplate.Value,
                                                                       URIAuthentication));

                }

                _URINode.AddHandler(HTTPDelegate,

                                    Method ?? HTTPMethod.GET,
                                    HTTPContentType,

                                    HTTPMethodAuthentication,
                                    ContentTypeAuthentication,

                                    HTTPRequestLogger,
                                    HTTPResponseLogger,

                                    DefaultErrorHandler,
                                    AllowReplacement);

            }

        }

        #endregion

        #region Contains(URITemplate)

        /// <summary>
        /// Determines whether the given URI template is defined.
        /// </summary>
        /// <param name="URITemplate">An URI template.</param>
        public Boolean Contains(HTTPPath URITemplate)

            => _URINodes.ContainsKey(URITemplate);

        #endregion

        #region Get     (URITemplate)

        /// <summary>
        /// Return the URI node for the given URI template.
        /// </summary>
        /// <param name="URITemplate">An URI template.</param>
        public URL_Node Get(HTTPPath URITemplate)
        {

            if (_URINodes.TryGetValue(URITemplate, out URL_Node uriNode))
                return uriNode;

            return null;

        }

        #endregion

        #region TryGet  (URITemplate, out URINode)

        /// <summary>
        /// Return the URI node for the given URI template.
        /// </summary>
        /// <param name="URITemplate">An URI template.</param>
        /// <param name="URINode">The attached URI node.</param>
        public Boolean TryGet(HTTPPath URITemplate, out URL_Node URINode)

            => _URINodes.TryGetValue(URITemplate, out URINode);

        #endregion

        #region IEnumerable<URINode> members

        /// <summary>
        /// Return all URI nodes.
        /// </summary>
        public IEnumerator<URL_Node> GetEnumerator()
            => _URINodes.Values.GetEnumerator();

        /// <summary>
        /// Return all URI nodes.
        /// </summary>
        IEnumerator IEnumerable.GetEnumerator()
            => _URINodes.Values.GetEnumerator();

        #endregion

        #region (override) ToString()

        /// <summary>
        /// Return a text representation of this object.
        /// </summary>
        public override String ToString()

            => Hostname.ToString();

        #endregion

    }

}


text:
import { Navigate } from "react-router-dom";

export const BuildNotFound = () => {
  // @TODO implement a 404 page
  return <Navigate to="/" />;
};


text:
package com.m1.mimeui.mimedom;

import com.m1.mimeui.api.EntityHandler;
import com.m1.mimeui.api.analyzer.ContentTypeAdjudicator;
import com.m1.mimeui.api.analyzer.PartProvider;
import com.m1.mimeui.api.analyzer.PartProviderFactory;
import com.m1.mimeui.api.mimedom.AnalyzedMessage;
import com.m1.mimeui.api.mimedom.AnalyzedMessageFactory;

import java.net.URI;

public class AnalyzedMessageFactoryImpl<E> implements AnalyzedMessageFactory<E>
{
    private final EntityHandler<E> entityHandler;
    private final PartProviderFactory<E> partProviderFactory;

    public AnalyzedMessageFactoryImpl (final EntityHandler<E> entityHandler,
                                       final PartProviderFactory<E> partProviderFactory)
    {
        this.entityHandler = entityHandler;
        this.partProviderFactory = partProviderFactory;
    }

    @Override
    public AnalyzedMessage getAnalyzedMessage (final E messageEntity,
                                               final ContentTypeAdjudicator contentTypeAdjudicator)
    {
        final EntityHandler.EntityType entityType = this.entityHandler.getEntityType(messageEntity);
        final PartProvider<E> partProvider = this.partProviderFactory.getPartProvider(entityType);

        // Implementation Note: RFC-2557 Section 5 items d and e: We default each message to "thismessage:/", not the
        // current server's URL (if applicable). That-is, we do not support item d.

        return new AnalyzedMessageImpl(
                partProvider.getParts(messageEntity, URI.create("thismessage:/"), contentTypeAdjudicator),
                this.entityHandler.getSubject(messageEntity),
                this.entityHandler.getSentDate(messageEntity),
                this.entityHandler.getSender(messageEntity),
                this.entityHandler.getFroms(messageEntity),
                this.entityHandler.getRecipients(messageEntity)
        );
    }
}


text:
<?php
/* @var $this yii\web\View */
/* @var $model frontend\models\Orders */
use yii\helpers\Html;
use yii\helpers\Url;

$events = [];
//Testing
$Event = new \yii2fullcalendar\models\Event();
$Event->id = 1;
$Event->title = $model->orderServices[0]->title;
$Event->start = $model->delivery_starts;
$Event->end = $model->delivery_ends;
$events[] = $Event;
?>

    <?php /* time/loc */ ?>

<?= Yii::t('app', 'Vreme izvršenja usluge') ?>

<?= f_datetime($model->delivery_starts) ?>  <?= f_datetime($model->delivery_ends) ?>

        <?= \yii2fullcalendar\yii2fullcalendar::widget([
            'events'=> $events,
            'options' => [
                'lang' => 'sr',
                'defaultView' => 'agendaWeek',
                //... more options to be defined here!
            ],
        ]) ?>