text:
var fs = require('fs'),
    WritableStream = require('stream').Writable
                     || require('readable-stream').Writable,
    inherits = require('util').inherits;

var parseParams = require('./utils').parseParams;

function Busboy(opts) {
  if (!(this instanceof Busboy))
    return new Busboy(opts);
  if (opts.highWaterMark !== undefined)
    WritableStream.call(this, { highWaterMark: opts.highWaterMark });
  else
    WritableStream.call(this);

  this._done = false;
  this._parser = undefined;

  this.opts = opts;
  if (opts.headers && typeof opts.headers['content-type'] === 'string')
    this.parseHeaders(opts.headers);
  else
    throw new Error('Missing Content-Type');
}
inherits(Busboy, WritableStream);

Busboy.prototype.emit = function(ev) {
  if (ev === 'finish' && !this._done)
    this._parser && this._parser.end();
  else
    WritableStream.prototype.emit.apply(this, arguments);
};

Busboy.prototype.parseHeaders = function(headers) {
  this._parser = undefined;
  if (headers['content-type']) {
    var parsed = parseParams(headers['content-type']),
        matched, type;
    for (var i = 0; i < TYPES_LEN; ++i) {
      type = TYPES[i];
      if (typeof type.detect === 'function')
        matched = type.detect(parsed);
      else
        matched = type.detect.test(parsed[0]);
      if (matched)
        break;
    }
    if (matched) {
      var cfg = {
        limits: this.opts.limits,
        headers: headers,
        parsedConType: parsed,
        highWaterMark: undefined,
        fileHwm: undefined,
        defCharset: undefined
      };
      if (this.opts.highWaterMark)
        cfg.highWaterMark = this.opts.highWaterMark;
      if (this.opts.fileHwm)
        cfg.fileHwm = this.opts.fileHwm;
      cfg.defCharset = this.opts.defCharset;
      this._parser = type(this, cfg);
      return;
    }
  }
  throw new Error('Unsupported content type: ' + headers['content-type']);
};

Busboy.prototype._write = function(chunk, encoding, cb) {
  if (!this._parser)
    return cb(new Error('Not ready to parse. Missing Content-Type?'));
  this._parser.write(chunk, cb);
};

var TYPES = [], TYPES_LEN = 0;
fs.readdirSync(__dirname + '/types').forEach(function(type) {
  var typemod = require(__dirname + '/types/' + type);
  if (typemod.detect) {
    TYPES.push(typemod);
    ++TYPES_LEN;
  }
});

module.exports = Busboy;


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

$string['fallbackaudio'] = 'Enlace de Audio';
$string['fallbackvideo'] = 'Enlace de video';
$string['filtername'] = 'Plugins de Multimedia';
$string['flashanimation'] = 'Animación Flash';
$string['flashanimation_help'] = 'Archivos con extensión *.swf que por razones de seguridad este filtro solamente debería de usarse en textos confiables (que NO tienen riesgo de virus).';
$string['flashvideo'] = 'Video Flash';
$string['flashvideo_help'] = 'Archivos con extensión *.flv y *.f4v , estos videoclips se ven con Flowplayer, requierer plugin de Flash y Javascript. Usa video HTML 5 como remplazo-si-falla si se especifican fuentes múltiples.';
$string['html5audio'] = 'Audio HTML 5';
$string['html5audio_help'] = 'Archivos de audio con extensiones *.ogg, *.aac y otras. Es compatible con los navegadores de internet más recientes pero desafortunadamente no existe un formato que sea soportado por todos los navegadores. El truco para que funcione está en especificar estrategias alternas de reserva (fallback) separadas con # (ejemplo: http://ejemplo.org.mx/audio.aac#http://ejemplo.org.mx/audio.aac#http://ejemplo.org.mxaudio.mp3#), El reproductor QuickTime se usa como estrategia alterna para navegadores (muy) antiguos.';
$string['html5video'] = 'Video HTML 5';
$string['html5video_help'] = 'Archivos de video con extensiones *.webm, *.m4v, *.ogv, *.mp4 y otras. Es compatible con los navegadores de internet más recientes pero desafortunadamente no existe un formato que sea soportado por todos los navegadores. El truco para que funcione está en especificar estrategias alternas de reserva (fallback) separadas con # (ejemplo: http://ejemplo.org.mx/video.m4v#http://ejemplo.org.mx/video.aac#http://ejemplo.org.mx/video.ogv#d=640x480), El reproductor QuickTime se usa como estrategia alterna para navegadores (muy) antiguos.';
$string['legacyheading'] = 'Reproductores multimedia (muy) antiguos';
$string['legacyheading_help'] = 'Los siguientes formatos no se recomiendan para uso general, usualmente se usan en instalaciones montadas en intranet con clientes administrados centralmente.';
$string['legacyquicktime'] = 'Reproductor Quicktime';
$string['legacyquicktime_help'] = 'Archivos con extensión *.mov, *.mp4, *.m4a, *.mp4 y *.mpg. Requieren el reproductor QuickTime o sus codecs..';
$string['legacyreal'] = 'Reproductor Real Media (...peligro,peligro,peligro... tiene muchos problemas)';
$string['legacyreal_help'] = 'Archivos con extensión *.rm, *.ra, *.ram, *.rp, *.rv. Requieren el reproductor RealPlayer.';
$string['legacywmp'] = 'Windows Media Player';
$string['legacywmp_help'] = 'Archivos con extensión *.avi y *.wmv. Completamente compatible con Internet Explorer en Windows, pero pueden ser problemáticos en otros exploradores o sistemas operativos.';
$string['mp3audio'] = 'Audio mp3';
$string['mp3audio_help'] = 'Archivos con extensión *.mp3. Reproducen audio empleando Flowplayer, requiere el plugin de Flash.';
$string['sitevimeo'] = 'Vimeo';
$string['sitevimeo_help'] = 'Sitio para compartir video de Vimeo.';
$string['siteyoutube'] = 'YouTube';
$string['siteyoutube_help'] = 'Sitio para compartir video YouTube, soporta ligas de video y listas de reproducción (playlists).';

redpajama_set_name: RedPajamaGithub


text:
@interface RTVoiceIOSBridge:NSObject
- (void)setVoices;
- (void)speak:(NSString *)text rate:(float)rate pitch:(float)pitch volume:(float)volume culture:(NSString *)culture;
- (void)stop;
@end

#ifdef __cplusplus
extern "C" {

    void UnitySendMessage(const char *, const char *, const char *);

}
#endif

#endif


text:
/*
 * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
 * at the root of this project for more details.
 */
package io.github.nucleuspowered.nucleus.modules.home.services;

import io.github.nucleuspowered.nucleus.api.util.data.NamedLocation;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.data.persistence.AbstractDataBuilder;
import org.spongepowered.api.data.persistence.DataContainer;
import org.spongepowered.api.data.persistence.DataQuery;
import org.spongepowered.api.data.persistence.DataTranslator;
import org.spongepowered.api.data.persistence.DataView;
import org.spongepowered.api.data.persistence.InvalidDataException;
import org.spongepowered.api.data.persistence.Queries;
import io.github.nucleuspowered.nucleus.api.module.home.data.Home;
import io.github.nucleuspowered.nucleus.core.datatypes.NucleusNamedLocation;

import java.util.Optional;
import java.util.UUID;

public class NucleusHome implements Home {

    private final static int CONTENT_VERSION = 1;

    private final static DataQuery OWNER = DataQuery.of("owner");

    private final UUID owner;
    private final NamedLocation namedLocation;

    public NucleusHome(final UUID owner, final NamedLocation location) {
        this.owner = owner;
        this.namedLocation = location;
    }

    @Override
    public UUID getOwnersUniqueId() {
        return this.owner;
    }

    @Override
    public NamedLocation getLocation() {
        return this.namedLocation;
    }

    @Override
    public int contentVersion() {
        return NucleusHome.CONTENT_VERSION;
    }

    @Override
    public DataContainer toContainer() {
        return DataContainer.createNew()
                .set(Queries.CONTENT_VERSION, this.contentVersion())
                .set(NucleusHome.OWNER, this.owner)
                .set(NucleusNamedLocation.NAMED_LOCATION_DATA_QUERY, this.namedLocation);
    }

    public static final class DataBuilder extends AbstractDataBuilder<Home> {

        public DataBuilder() {
            super(Home.class, NucleusHome.CONTENT_VERSION);
        }

        @Override
        protected Optional<Home> buildContent(final DataView container) throws InvalidDataException {
            if (!container.contains(Queries.CONTENT_VERSION)) {
                NucleusNamedLocation.upgradeLegacy(container, NucleusNamedLocation.NAMED_LOCATION_DATA_QUERY);
            }

            final DataTranslator<UUID> translator = Sponge.dataManager().translator(UUID.class).get();
            return Optional.of(new NucleusHome(
                    container.getView(NucleusHome.OWNER).map(translator::translate).get(),
                    container.getSerializable(NucleusNamedLocation.NAMED_LOCATION_DATA_QUERY, NamedLocation.class).get()
            ));
        }
    }
}


text:
<?php
//src/BlogBundle/DataFixtures/ORM/LoadImageData.php

namespace BlogBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use BlogBundle\Entity\Image;

class LoadImageData extends AbstractFixture implements OrderedFixtureInterface
{
    public function load(ObjectManager $em)
    {

	    $img_blog = new Image();
            $img_blog->setPost($em->merge($this->getReference('post-blog')));
	    $img_blog->setImage('blog.jpg');

	    $img_shop = new Image();
	    $img_shop->setPost($em->merge($this->getReference('post-shop')));
	    $img_shop->setImage('shop.jpg');

	    $em->persist($img_blog);
	    $em->persist($img_shop);

            foreach (range(0, 30) as $i) { //mamy 30 postów dlatego rand(0, 30)

                $img = new Image();

                $post = $this->getReference('post-post'.$i);
                $img->setPost($em->merge($post));

                switch ($post->getCategory()) {
                    case $this->getReference('category-blog'):
                        $img->setImage('blog.jpg');
                        break;
                    case $this->getReference('category-shop'):
                        $img->setImage('shop.jpg');
                        break;
                    default:
                       $img->setImage(null);
                }

                $em->persist($img);
            }

	    $em->flush();
    }

    public function getOrder()
    {
        return 3; // the order in which fixtures will be loaded
    }

}


text:
zarinpal rest api v3 name leak bug
use in this way
zarinpal_bug.py 0912121212
just set mobile number ...


text:
/* Check if there is HotSpots in the objective */
if (questObjective.Hotspots.Count <= 0)
{
	/* Objective CSharpScript with script InteractWithHotSpots requires valid "Hotspots" */
	Logging.Write("InteractWithHotSpots requires valid 'HotSpots'.");
	questObjective.IsObjectiveCompleted = true;
	return false;
}

if (questObjective.IgnoreFight)
		nManager.Wow.Helpers.Quest.GetSetIgnoreFight = true;

/* Search for Entry */
WoWGameObject node = ObjectManager.GetNearestWoWGameObject(ObjectManager.GetWoWGameObjectById(questObjective.Entry));
WoWUnit unit = ObjectManager.GetNearestWoWUnit(ObjectManager.GetWoWUnitByEntry(questObjective.Entry, questObjective.IsDead), questObjective.IgnoreNotSelectable, questObjective.IgnoreBlackList, questObjective.AllowPlayerControlled);
Point pos = ObjectManager.Me.Position; /* Initialize or getting an error */;
int q = QuestID; /* not used but otherwise getting warning QuestID not used */
uint baseAddress = 0;

/* If Entry found continue, otherwise continue checking around HotSpots */
if ((unit.IsValid && !nManagerSetting.IsBlackListedZone(unit.Position) && !nManagerSetting.IsBlackListed(unit.Guid)) || (node.IsValid && !nManagerSetting.IsBlackListedZone(node.Position) && !nManagerSetting.IsBlackListed(node.Guid)))
{

	/* Entry found, GoTo */
	if(node.IsValid)
	{
		unit = new WoWUnit(0);
		baseAddress = MovementManager.FindTarget(node, questObjective.Range);
	}
	else if(unit.IsValid)
	{
		node = new WoWGameObject(0);
		baseAddress = MovementManager.FindTarget(unit, questObjective.Range);
	}
	Thread.Sleep(500);

	if (MovementManager.InMovement)
        return false;
	if (questObjective.IgnoreNotSelectable)
	{
	    if ((node.IsValid && node.GetDistance > questObjective.Range) || (unit.IsValid && unit.GetDistance > questObjective.Range))
	        return false;
	}
	else
	{
        if(baseAddress <= 0)
	        return false;
        if (baseAddress > 0 && ((node.IsValid && node.GetDistance > questObjective.Range) || (unit.IsValid && unit.GetDistance > questObjective.Range)))
	    return false;
	}

	Thread.Sleep(100 + Usefuls.Latency); /* ZZZzzzZZZzz */

	/* Entry reached, dismount */
	MovementManager.StopMove();
	MountTask.DismountMount();

	/* Interact With Entry */
	if (node.IsValid)
	{
		MovementManager.Face(node);
		Interact.InteractWith(node.GetBaseAddress);
		nManagerSetting.AddBlackList(node.Guid, 30*1000);
	}
	else if (unit.IsValid)
	{
		MovementManager.Face(unit);
		Interact.InteractWith(unit.GetBaseAddress);
		nManagerSetting.AddBlackList(unit.Guid, 30*1000);
	}

	Thread.Sleep(Usefuls.Latency);

	/* Wait for the interact cast to be finished, if any */
	while (ObjectManager.Me.IsCast)
	{
		Thread.Sleep(Usefuls.Latency);
	}

	/* Do Gossip if necessary */
	if (questObjective.GossipOptionsInteractWith != 0)
	{
		Thread.Sleep(250 + Usefuls.Latency);
		nManager.Wow.Helpers.Quest.SelectGossipOption(questObjective.GossipOptionsInteractWith);
	}

	if (Others.IsFrameVisible("StaticPopup1Button1"))
		Lua.RunMacroText("/click StaticPopup1Button1");
	if (ObjectManager.Me.InCombat && !questObjective.IgnoreFight)
		return false;

	/* Wait if necessary */
	if(questObjective.WaitMs > 0)
		Thread.Sleep(questObjective.WaitMs);

	/* Interact Completed - InternalIndex and count is used to determine if obj is completed - questObjective.IsObjectiveCompleted = true; */

}else if (!MovementManager.InMovement)
{
	/* Move to Zone/Hotspot */
	if (questObjective.PathHotspots[nManager.Helpful.Math.NearestPointOfListPoints(questObjective.PathHotspots, ObjectManager.Me.Position)].DistanceTo(ObjectManager.Me.Position) > 5)
	{
		if(nManager.Wow.Helpers.Quest.TravelToQuestZone(questObjective.PathHotspots[nManager.Helpful.Math.NearestPointOfListPoints(questObjective.PathHotspots, ObjectManager.Me.Position)],
			ref questObjective.TravelToQuestZone, questObjective.ContinentId, questObjective.ForceTravelToQuestZone))
			return false;
		MovementManager.Go(PathFinder.FindPath(questObjective.PathHotspots[nManager.Helpful.Math.NearestPointOfListPoints(questObjective.PathHotspots, ObjectManager.Me.Position)]));
	}
	else
	{
		MovementManager.GoLoop(questObjective.PathHotspots);
	}
}

nManager.Wow.Helpers.Quest.GetSetIgnoreFight = false;


text:
pub use crate::mod_types::usergroups_types::*;
use crate::requests::SlackWebRequestSender;

/// Create a User Group
///
/// Wraps https://api.slack.com/methods/usergroups.create

pub async fn create<R>(
    client: &R,
    token: &str,
    request: &CreateRequest<'_>,
) -> Result<CreateResponse, CreateError<R::Error>>
where
    R: SlackWebRequestSender,
{
    let params = vec![
        Some(("token", token)),
        Some(("name", request.name)),
        request.handle.map(|handle| ("handle", handle)),
        request
            .description
            .map(|description| ("description", description)),
        request.channels.map(|channels| ("channels", channels)),
        request
            .include_count
            .map(|include_count| ("include_count", if include_count { "1" } else { "0" })),
    ];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = crate::get_slack_url_for_method("usergroups.create");
    client
        .send(&url, &params[..])
        .await
        .map_err(CreateError::Client)
        .and_then(|result| {
            serde_json::from_str::<CreateResponse>(&result)
                .map_err(|e| CreateError::MalformedResponse(result, e))
        })
        .and_then(|o| o.into())
}

/// Disable an existing User Group
///
/// Wraps https://api.slack.com/methods/usergroups.disable

pub async fn disable<R>(
    client: &R,
    token: &str,
    request: &DisableRequest<'_>,
) -> Result<DisableResponse, DisableError<R::Error>>
where
    R: SlackWebRequestSender,
{
    let params = vec![
        Some(("token", token)),
        Some(("usergroup", request.usergroup)),
        request
            .include_count
            .map(|include_count| ("include_count", if include_count { "1" } else { "0" })),
    ];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = crate::get_slack_url_for_method("usergroups.disable");
    client
        .send(&url, &params[..])
        .await
        .map_err(DisableError::Client)
        .and_then(|result| {
            serde_json::from_str::<DisableResponse>(&result)
                .map_err(|e| DisableError::MalformedResponse(result, e))
        })
        .and_then(|o| o.into())
}

/// Enable a User Group
///
/// Wraps https://api.slack.com/methods/usergroups.enable

pub async fn enable<R>(
    client: &R,
    token: &str,
    request: &EnableRequest<'_>,
) -> Result<EnableResponse, EnableError<R::Error>>
where
    R: SlackWebRequestSender,
{
    let params = vec![
        Some(("token", token)),
        Some(("usergroup", request.usergroup)),
        request
            .include_count
            .map(|include_count| ("include_count", if include_count { "1" } else { "0" })),
    ];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = crate::get_slack_url_for_method("usergroups.enable");
    client
        .send(&url, &params[..])
        .await
        .map_err(EnableError::Client)
        .and_then(|result| {
            serde_json::from_str::<EnableResponse>(&result)
                .map_err(|e| EnableError::MalformedResponse(result, e))
        })
        .and_then(|o| o.into())
}

/// List all User Groups for a team
///
/// Wraps https://api.slack.com/methods/usergroups.list

pub async fn list<R>(
    client: &R,
    token: &str,
    request: &ListRequest,
) -> Result<ListResponse, ListError<R::Error>>
where
    R: SlackWebRequestSender,
{
    let params = vec![
        Some(("token", token)),
        request
            .include_disabled
            .map(|include_disabled| ("include_disabled", if include_disabled { "1" } else { "0" })),
        request
            .include_count
            .map(|include_count| ("include_count", if include_count { "1" } else { "0" })),
        request
            .include_users
            .map(|include_users| ("include_users", if include_users { "1" } else { "0" })),
    ];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = crate::get_slack_url_for_method("usergroups.list");
    client
        .send(&url, &params[..])
        .await
        .map_err(ListError::Client)
        .and_then(|result| {
            serde_json::from_str::<ListResponse>(&result)
                .map_err(|e| ListError::MalformedResponse(result, e))
        })
        .and_then(|o| o.into())
}

/// Update an existing User Group
///
/// Wraps https://api.slack.com/methods/usergroups.update

pub async fn update<R>(
    client: &R,
    token: &str,
    request: &UpdateRequest<'_>,
) -> Result<UpdateResponse, UpdateError<R::Error>>
where
    R: SlackWebRequestSender,
{
    let params = vec![
        Some(("token", token)),
        Some(("usergroup", request.usergroup)),
        request.name.map(|name| ("name", name)),
        request.handle.map(|handle| ("handle", handle)),
        request
            .description
            .map(|description| ("description", description)),
        request.channels.map(|channels| ("channels", channels)),
        request
            .include_count
            .map(|include_count| ("include_count", if include_count { "1" } else { "0" })),
    ];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = crate::get_slack_url_for_method("usergroups.update");
    client
        .send(&url, &params[..])
        .await
        .map_err(UpdateError::Client)
        .and_then(|result| {
            serde_json::from_str::<UpdateResponse>(&result)
                .map_err(|e| UpdateError::MalformedResponse(result, e))
        })
        .and_then(|o| o.into())
}


text:
set -e

CONFIG_PATH=${CONFIG_PATH:-/etc/atlas/config-local.js}
CONFIG_TARGET_PATH="/usr/share/nginx/html/atlas/js/config-local.js"

# Copy mounted configuration file if present
if [ -f "${CONFIG_PATH}" ]; then
  echo "Using config-local.js from ${CONFIG_PATH}"
  # Don't copy but rewrite so that permissions are not changed.
  cat "${CONFIG_PATH}" > "${CONFIG_TARGET_PATH}"
fi

if [ -n "${WEBAPI_URL}" ]; then
  # make sure the WebAPI URL ends with a slash
  case $WEBAPI_URL in
    # correct, no action
    */)
      ;;
    # otherwise, add slash
    *)
      WEBAPI_URL="$WEBAPI_URL/"
      ;;
  esac
  TFILE=`mktemp`
  trap "rm -f $TFILE" 0 1 2 3 15
  # Don't copy but rewrite so that permissions are not changed.
  envsubst '$WEBAPI_URL' < "$CONFIG_TARGET_PATH" > "$TFILE"
  cat "$TFILE" > "$CONFIG_TARGET_PATH"
  rm -f "$TFILE"
fi


text:
require 'spec_helper'

describe AQL::Node::Literal::Composed::Document::Attribute, '#aql' do
  class Node
    include Concord.new(:token)

    def visit(buffer)
      buffer.append(token)
    end
  end

  let(:object) { described_class.new(Node.new('foo'), Node.new('bar')) }

  expect_aql('foo: bar')
end


text:
#include <iostream>
using namespace std;
#include <cstring>

/* For using ::   srand(time(NULL));   */
#include <stdlib.h>
#include <time.h>

/* Contains the definition of packet, frame, etc.*/
#include "protocol.h"

/* total number of packets to send */
#define TOT_PACKETS 5

/*************************** Global variables ***************************/

/* starting data to be sent by sender*/
int i=1;

/* can have values {s, r} for sender's turn and receiver's turn respectively */
char turn;
/* Disconnect set to '0'  to start the loop */
int DISCONNECT=0;
/* Global frame treated as buffer*/
frame globalFrame;

/*************************** Function prototypes ***************************/

void sender2();
void receiver2();

void from_network_layer(packet&);
void to_network_layer(packet&);

void from_physical_layer(frame&);
void to_physical_layer(frame&);

void wait_for_event_sender(event_type&);
void wait_for_event_reciever(event_type&);

/*************************** Main function  ***************************/

/* for delay effect */
void delay(unsigned int mseconds)
{
    clock_t goal = mseconds + clock();
    while (goal > clock());
}

int main()
{
    /* random no' generator , generating new random no's . Used as int x=rand()%4; */
    srand(time(NULL));

    cout<<"\n*********** STOP and WAIT for NOISELESS Channel Simulation *********\n";
    cout<<"\n\nCONNECTED . . . . \n\n";
    while(!DISCONNECT)
    {
        sender2();
        delay(300);
        receiver2();
    }
    cout<<"\n\nDISCONNECTED . . . .  \n\n";

    return 0;
}

/*************************** Function definitions ***************************/

/* Sender function - sends a frame and waits for acknowledgement */
void sender2()
{
    static frame s;
    packet buffer;
    event_type event;
    static bool isFirstTime=true;

    if(isFirstTime)
    {
        // code for first time
        from_network_layer(buffer);
        s.info = buffer;
        cout<<"SENDER : Info = "<<s.info.data<<"\t\t         ";
        turn = 'r';
        to_physical_layer(s);
        isFirstTime=false;
    }
    wait_for_event_sender(event);

    if(turn=='s')
    {
       // event will always be .. frame_arrival
         if(event==frame_arrival){
           from_network_layer(buffer);
            s.info = buffer;
            cout<<"SENDER : Info = "<<s.info.data<<"\t\t         ";
        turn = 'r';
            to_physical_layer(s);
        }
}}

/* Receiver function - receives a frame and sends the acknowledgement */
void receiver2()
{
    frame r,s;
    event_type event;

    wait_for_event_reciever(event);

    if(turn=='r')
    {
        // event will always be .. frame_arrival
        if(event==frame_arrival){
            from_physical_layer(r);
                to_network_layer(r.info);
            turn = 's';
            to_physical_layer(s);
        }
    }
    }

/* Fetch a packet from the network layer for transmission on the channel */
void from_network_layer(packet &buffer)
{
    strcpy(buffer.data,"My Data");
}

/* Pass the frame to the physical layer for transmission. */
void to_physical_layer(frame &buffer)
{
    globalFrame= buffer;
}

/* Deliver information from an inbound frame to the network layer. */
void to_network_layer(packet &buffer)
{
    cout<<"\tRECIEVER : Packet with data "<<buffer.data<<" recieved , Ack Sent\n";

    i++;
    if(i>TOT_PACKETS)          //if all packets received then disconnect
    {
        DISCONNECT = 1;
    }

}

/* Go get an inbound frame from the physical layer and copy it to r. */
void from_physical_layer(frame &buffer)
{
    buffer=globalFrame;
}

/* SENDER calls - Wait for an event to happen; return its type in event. */
void wait_for_event_sender(event_type &e)
{
    if(turn=='s')
    {
            e = frame_arrival;
        }
}

/* RECEIEVR calls - Wait for an event to happen; return its type in event. */
void wait_for_event_reciever(event_type &e)
{
    if(turn=='r')
    {
        e = frame_arrival;
    }
}


text:
$(document).ready(function() {
	var settings = {
		showForks: false,
		title: {
			color: 'white',
			bold: false,
			italic: true
		},
		command: {
			color: 'green',
			bold: true,
			italic: false,
			backgroundColor: 'pink'
		},
		name: {
			color: 'purple'
		},
		extraDetails: 'responses/extra-details.json',
		customCommands: [
			{
				name: 'spiritanimal',
				title: 'Spirit Animal',
				description: 'the animal I most identify with',
				type: 'basic',
				data: ['extra', 'spiritanimal']
			},
			{
				name: 'geolocation',
				title: 'Geolocation',
				description: 'checks if geolocation is enabled',
				type: 'system',
				handler: function() {
					return 'Geolocation is ' +
					(navigator.geolocation ?  '' : 'not ') +
						'supported for this browser';
				}
			},
			{
				name: 'projectyears',
				title: 'Project Years',
				description: 'years since the project started',
				type: 'calculated',
				data: ['extra', 'project_start'],
				dataIsObject: true,
				handler: function(value) {
					var startYear = (new Date(value.unixtime)).getFullYear();
					var endYear = (new Date()).getFullYear();
					return 'Started ' + (endYear - startYear) +
						' years ago to ' + value.motivation;
				}
			},
			{
				name: 'countries',
				title: 'Countries',
				description: 'countries that I\'ve been to',
				type: 'array',
				data: ['extra', 'countriestravelledto'],
				handlers: {
					organisation: function(value) {
						return value.name;
					},
					title: function(value) {
						return value.cities.join(', ');
					},
					date: function(value) {
						return value.timeperiod;
					}
				}
			},
			{
				name: 'location',
				title: 'Location',
				description: 'current location',
				type: 'calculated',
				data: ['basics', 'location'],
				dataIsObject: true,
				handler: function(data) {
					return 'The great city of ' + data.city;
				}
			}
		]
	};
	$('body').CMDResume('responses/details.json', settings);
});


text:
A super simple MySQL driven XML sitemap in PHP.

Each time the script is loaded up, it will automatically ping the database and update the file with new pages or remove pages that no longer exist.

This is handy for Google Webmaster Tools, as each time its bot visits the url you specified, it will always be an updated list.

### Usage
Copy the code from the xml-sitemap.php file.

	- Add your databse connection details
	- Specifiy any static pages you want. I.e. ones that aren't database driven
	- Add your SQL. E.g. SELECT * FROM table WHERE page_is_active = '1'
	- Visit the page in your browser and Voila!


text:
Audio streaming server

---
### How to setup
Your music path is where you want the server to get your songs from. Default is ./upload

Change your music path: "const musicPath" is defined in own_modules/mod.js

Care for song with special characters (space, ', ", é ...)

Prerequisite: node.js installed

In the folder of your choice

```bash
$ git clone https://github.com/ArthurLS/ListenUp.git
$ npm install
$ npm start
```
Now that the server is running, connect to localhost:PORT. (default is 4000)

Click on the SounBank tab to see your songs and add some to the shared playlist!

All the client have the same playlist.

---
### License
Apache License Version 2.0


text:
import xs from '../../src/index';
import concat from '../../src/extra/concat';
import dropUntil from '../../src/extra/dropUntil';
import delay from '../../src/extra/delay';
import * as assert from 'assert';

describe('dropUntil (extra)', () => {
  it('should start emitting the stream when another stream emits next', (done: any) => {
    const source = xs.periodic(50).take(6);
    const other = xs.periodic(220).take(1);
    const stream = source.compose(dropUntil(other));
    const expected = [4, 5];

    stream.addListener({
      next: (x: number) => {
        assert.strictEqual(x, expected.shift());
      },
      error: (err: any) => done(err),
      complete: () => {
        assert.strictEqual(expected.length, 0);
        done();
      }
    });
  });

  it('should emit no items if another stream is empty', (done: any) => {
    const source = xs.periodic(10).take(10);
    const other = xs.empty().compose(delay(50));
    const stream = source.compose(dropUntil(other));
    let emissions = 0;
    stream.addListener({
      next: () => emissions++,
      error: (err: any) => done(err),
      complete: () => {
        assert.strictEqual(emissions, 0);
        done();
      }
    });
  });

  it('should not wait for another stream to complete', (done: any) => {
    const source = xs.periodic(50).take(2);
    const other = concat(xs.of('foo'), xs.never());
    const stream = source.compose(dropUntil(other));
    const expected = [0, 1];
    stream.addListener({
      next: (x: number) => {
        assert.strictEqual(x, expected.shift());
      },
      error: (err: any) => done(err),
      complete: () => {
        assert.strictEqual(expected.length, 0);
        done();
      }
    });
  });

  it('should not complete the stream when another non empty stream emits complete', (done: any) => {
    const source = xs.periodic(50).take(8);
    const other = xs.periodic(1).take(1).compose(delay(220));
    const stream = source.compose(dropUntil(other));
    const expected = [4, 5, 6, 7];

    stream.addListener({
      next: (x: number) => {
        assert.strictEqual(x, expected.shift());
      },
      error: (err: any) => done(err),
      complete: () => {
        assert.strictEqual(expected.length, 0);
        done();
      }
    });
  });
});


text:
<?php

namespace Tests\Mollie\TestHelpers;

trait AmountObjectTestHelpers
{
    protected function assertAmountObject($value, $currency, $amountObject)
    {
        $this->assertEquals(
            $this->createAmountObject($value, $currency),
            $amountObject
        );
    }

    protected function createAmountObject($value, $currency)
    {
        return (object) [
            'value' => $value,
            'currency' => $currency,
        ];
    }
}


text:
package org.springframework.boot.autoconfigure.web;

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

import javax.servlet.ServletException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.util.ApplicationContextTestUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Tests for {@link BasicErrorController} using {@link MockMvc} but not
 * {@link SpringRunner}.
 *
 * @author Dave Syer
 * @author Sebastien Deleuze
 */
public class BasicErrorControllerDirectMockMvcTests {

	@Rule
	public final ExpectedException thrown = ExpectedException.none();

	private ConfigurableWebApplicationContext wac;

	private MockMvc mockMvc;

	@After
	public void close() {
		ApplicationContextTestUtils.closeAll(this.wac);
	}

	public void setup(ConfigurableWebApplicationContext context) {
		this.wac = context;
		this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
	}

	@Test
	public void errorPageAvailableWithParentContext() throws Exception {
		setup((ConfigurableWebApplicationContext) new SpringApplicationBuilder(
				ParentConfiguration.class).child(ChildConfiguration.class)
						.run("--server.port=0"));
		MvcResult response = this.mockMvc
				.perform(get("/error").accept(MediaType.TEXT_HTML))
				.andExpect(status().is5xxServerError()).andReturn();
		String content = response.getResponse().getContentAsString();
		assertThat(content).contains("status=999");
	}

	@Test
	public void errorPageAvailableWithMvcIncluded() throws Exception {
		setup((ConfigurableWebApplicationContext) new SpringApplication(
				WebMvcIncludedConfiguration.class).run("--server.port=0"));
		MvcResult response = this.mockMvc
				.perform(get("/error").accept(MediaType.TEXT_HTML))
				.andExpect(status().is5xxServerError()).andReturn();
		String content = response.getResponse().getContentAsString();
		assertThat(content).contains("status=999");
	}

	@Test
	public void errorPageNotAvailableWithWhitelabelDisabled() throws Exception {
		setup((ConfigurableWebApplicationContext) new SpringApplication(
				WebMvcIncludedConfiguration.class).run("--server.port=0",
						"--server.error.whitelabel.enabled=false"));
		this.thrown.expect(ServletException.class);
		this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML));
	}

	@Test
	public void errorControllerWithAop() throws Exception {
		setup((ConfigurableWebApplicationContext) new SpringApplication(
				WithAopConfiguration.class).run("--server.port=0"));
		MvcResult response = this.mockMvc
				.perform(get("/error").accept(MediaType.TEXT_HTML))
				.andExpect(status().is5xxServerError()).andReturn();
		String content = response.getResponse().getContentAsString();
		assertThat(content).contains("status=999");
	}

	@Target(ElementType.TYPE)
	@Retention(RetentionPolicy.RUNTIME)
	@Documented
	@Import({ EmbeddedServletContainerAutoConfiguration.class,
			DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class,
			HttpMessageConvertersAutoConfiguration.class, ErrorMvcAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class })
	protected @interface MinimalWebConfiguration {

	}

	@Configuration
	@MinimalWebConfiguration
	protected static class ParentConfiguration {

	}

	@Configuration
	@MinimalWebConfiguration
	@EnableWebMvc
	protected static class WebMvcIncludedConfiguration {

		// For manual testing
		public static void main(String[] args) {
			SpringApplication.run(WebMvcIncludedConfiguration.class, args);
		}

	}

	@Configuration
	@MinimalWebConfiguration
	protected static class VanillaConfiguration {

		// For manual testing
		public static void main(String[] args) {
			SpringApplication.run(VanillaConfiguration.class, args);
		}

	}

	@Configuration
	@MinimalWebConfiguration
	protected static class ChildConfiguration {

		// For manual testing
		public static void main(String[] args) {
			new SpringApplicationBuilder(ParentConfiguration.class)
					.child(ChildConfiguration.class).run(args);
		}

	}

	@Configuration
	@EnableAspectJAutoProxy(proxyTargetClass = false)
	@MinimalWebConfiguration
	@Aspect
	protected static class WithAopConfiguration {

		@Pointcut("within(@org.springframework.stereotype.Controller *)")
		private void controllerPointCut() {
		};

		@Around("controllerPointCut()")
		public Object mvcAdvice(ProceedingJoinPoint pjp) throws Throwable {
			return pjp.proceed();
		}

	}

}


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

  if (typeof sigma === 'undefined') {
    throw 'sigma is not declared';
  }

  // Default function to compute path length between two nodes:
  // the euclidian
  var defaultPathLengthFunction = function(node1, node2, previousPathLength) {
    var isEverythingDefined =
      node1 != undefined &&
      node2 != undefined &&
      node1.x != undefined &&
      node1.y != undefined &&
      node2.x != undefined &&
      node2.y != undefined;
    if(!isEverythingDefined) {
      return undefined;
    }

    return (previousPathLength || 0) + Math.sqrt(
      Math.pow((node2.y - node1.y), 2) + Math.pow((node2.x - node1.x), 2)
    );
  };

  sigma.classes.graph.addMethod(
    'astar',
    function(srcId, destId, settings) {
      var currentSettings = new sigma.classes.configurable(
        // Default settings
        {
          // Graph is directed, affects which edges are taken into account
          undirected: false,
          // Function to compute the distance between two connected node
          pathLengthFunction: defaultPathLengthFunction,
          // Function to compute an distance between two nodes
          // if undefined, uses pathLengthFunction
          heuristicLengthFunction: undefined
        },
        settings || {});

      var pathLengthFunction = currentSettings("pathLengthFunction"),
          heuristicLengthFunction = currentSettings("heuristicLengthFunction") || pathLengthFunction;

      var srcNode = this.nodes(srcId),
          destNode = this.nodes(destId);

      var closedList = {},
          openList = [];

      var addToLists = function(node, previousNode, pathLength, heuristicLength) {
        var nodeId = node.id;
        var newItem = {
          pathLength: pathLength,
          heuristicLength: heuristicLength,
          node: node,
          nodeId: nodeId,
          previousNode: previousNode
        };

        if(closedList[nodeId] == undefined || closedList[nodeId].pathLength > pathLength) {
          closedList[nodeId] = newItem;

          var item;
          var i;
          for(i = 0; i < openList.length; i++) {
            item = openList[i];
            if(item.heuristicLength > heuristicLength) {
              break;
            }
          }

          openList.splice(i, 0, newItem);
        }
      };

      addToLists(srcNode, null, 0, 0);

      var pathFound = false;

      // Depending of the type of graph (directed or not),
      // the neighbors are either the out neighbors or all.
      var allNeighbors;
      if(currentSettings("undirected")) {
        allNeighbors = this.allNeighborsIndex;
      }
      else {
        allNeighbors = this.outNeighborsIndex;
      }

      var inspectedItem,
          neighbors,
          neighbor,
          pathLength,
          heuristicLength,
          i;
      while(openList.length > 0) {
        inspectedItem = openList.shift();

        // We reached the destination node
        if(inspectedItem.nodeId == destId) {
          pathFound = true;
          break;
        }

        neighbors = Object.keys(allNeighbors[inspectedItem.nodeId]);
        for(i = 0; i < neighbors.length; i++) {
          neighbor = this.nodes(neighbors[i]);
          pathLength = pathLengthFunction(inspectedItem.node, neighbor, inspectedItem.pathLength);
          heuristicLength = heuristicLengthFunction(neighbor, destNode);
          addToLists(neighbor, inspectedItem.node, pathLength, heuristicLength);
        }
      }

      if(pathFound) {
        // Rebuilding path
        var path = [],
            currentNode = destNode;

        while(currentNode) {
          path.unshift(currentNode);
          currentNode = closedList[currentNode.id].previousNode;
        }

        return path;
      }
      else {
        return undefined;
      }
    }
  );
}).call(window);


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!--在去title的同时还保留高版本的样式主题-->
        <!-- Customize your theme here. -->
        <item name="android:windowNoTitle">true</item>
    </style>

    <style name="TitleStyle" >

        <item name="android:gravity">center</item>
        <item name="android:textSize">20dp</item>
        <item name="android:padding">10dp</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:background">#0f0</item>

    </style>

    <style name="nextBtn">
        <item name="android:text">下一页</item>
        <item name="android:onClick">nextPage</item>
        <item name="android:layout_alignParentRight">true</item>
        <item name="android:layout_alignParentBottom">true</item>
        <item name="android:drawableRight">@drawable/next</item>
        <item name="android:background">@drawable/selector_next_btn_bg</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
    </style>

    <style name="preBtn">
        <item name="android:text">上一页</item>
        <item name="android:onClick">prePage</item>
        <item name="android:layout_alignParentLeft">true</item>
        <item name="android:layout_alignParentBottom">true</item>
        <item name="android:drawableLeft">@drawable/previous</item>
        <item name="android:background">@drawable/selector_next_btn_bg</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
    </style>

</resources>


text:
var uuid = require('uuid')
var debug = require('debug')('pdf:db')
var error = require('./error')
var webhook = require('./webhook')
var utils = require('./utils')

function createQueue (db, options = {}) {
  var createQueueMethod = function (func) {
    return function() {
      var args = Array.prototype.slice.call(arguments, 0)
      return func.apply(func, [db].concat(args))
    }
  }

  return {
    addToQueue: createQueueMethod(addToQueue),
    attemptPing: createQueueMethod(attemptPing),
    close: createQueueMethod(close),
    getById: createQueueMethod(getById),
    getList: createQueueMethod(getList),
    getNext: createQueueMethod(getNext),
    getAllUnfinished: createQueueMethod(getAllUnfinished),
    getNextWithoutSuccessfulPing: createQueueMethod(getNextWithoutSuccessfulPing),
    isBusy: createQueueMethod(isBusy),
    processJob: createQueueMethod(processJob),
    purge: createQueueMethod(purge),
    setIsBusy: createQueueMethod(setIsBusy)
  }
}

function addToQueue (db, data) {
  var id = uuid()
  var createdAt = utils.getCurrentDateTimeAsString()

  var defaults = {
    meta: {}
  }

  if (!data.url || !utils.isValidUrl(data.url)) {
    return error.createErrorResponse(error.ERROR_INVALID_URL)
  }

  if (data.meta && typeof data.meta !== 'object') {
    return error.createErrorResponse(error.ERROR_META_IS_NOT_OBJECT)
  }

  data = Object.assign(defaults, data, {
    id: id,
    created_at: createdAt,
    completed_at: null,
    generations: [],
    pings: [],
    storage: {}
  })

  debug('Pushing job to queue with data %s', JSON.stringify(data))

  return db.pushToQueue(data)
}

function close(db) {
  return db.close()
}

// =========
// RETRIEVAL
// =========

function getList (db, failed = false, completed = false, limit) {
  return db.getList(failed, completed, limit)
}

function getById (db, id) {
  return db.getById(id)
}

function getNext (db, shouldWait, maxTries = 5) {
  return getAllUnfinished(db, shouldWait, maxTries).then(function (jobs) {
    return jobs.length > 0 ? jobs[0] : null;
  })
}

function getAllUnfinished (db, shouldWait, maxTries = 5) {
  return db.getAllUnfinished (shouldWait, maxTries)
}

function getNextWithoutSuccessfulPing (db, shouldWait, maxTries = 5) {
  return db.getNextWithoutSuccessfulPing(shouldWait, maxTries)
}

function isBusy (db) {
  return db.isBusy()
}

function purge (db, failed = false, pristine = false, maxTries = 5) {
  return db.purge(failed, pristine, maxTries)
}

function setIsBusy(db, isBusy) {
  return db.setIsBusy(isBusy)
}

// ==========
// PROCESSING
// ==========

function processJob (db, generator, job, webhookOptions) {
  return generator(job.url, job)
    .then(function (response) {
      return _logGeneration(db, job.id, response)
        .then(function (logResponse) {
          if (!error.isError(response)) {
            debug('Job %s was processed, marking job as complete.', job.id)

            return Promise.all([
              _markAsCompleted(db, job.id),
              _setStorage(db, job.id, response.storage)
            ]).then(function () {
              if (!webhookOptions) {
                return response
              }

              // Re-fetch the job as storage has been added
              return getById(db, job.id).then(function (job) {
                // Important to return promise otherwise the npm cli process will exit early
                return attemptPing(db, job, webhookOptions)
                  .then(function() {
                    return response
                  })
              })
            })
          }

          return response
        })
    })
}

// =======
// PINGING
// =======

function attemptPing (db, job, webhookOptions) {
  if (!(typeof webhookOptions === 'object')) {
    throw new Error('No webhook is configured.')
  }

  return webhook.ping(job, webhookOptions)
    .then(response => {
      return _logPing(db, job.id, response)
        .then(function () {
          return response
        })
    })
}

// ===============
// PRIVATE METHODS
// ===============

function _logGeneration (db, id, response) {
  debug('Logging try for job ID %s', id)

  return db.logGeneration(id, response)
}

function _logPing (db, id, response) {
  debug('Logging ping for job ID %s', id)

  return db.logPing(id, response)
}

function _markAsCompleted (db, id) {
  var completed_at = utils.getCurrentDateTimeAsString()

  debug('Marking job ID %s as completed at %s', id, completed_at)

  return db.markAsCompleted(id)
}

function _setStorage (db, id, storage) {
  return db.setStorage(id, storage)
}

module.exports = createQueue


text:
/* this file is shared between sel4test-driver an sel4test-tests */
#ifndef __TEST_H
#define __TEST_H

#include <autoconf.h>
#include <sel4/bootinfo.h>

#include <vka/vka.h>
#include <vka/object.h>
#include <sel4utils/elf.h>
#include <simple/simple.h>
#include <vspace/vspace.h>

/* max test name size */
#define TEST_NAME_MAX 20

/* Increase if the sel4test-tests binary
 * has new loadable sections added */
#define MAX_REGIONS 4

/* data shared between sel4test-driver and the sel4test-tests app.
 * all caps are in the sel4test-tests process' cspace */
typedef struct {
    /* page directory of the test process */
    seL4_CPtr page_directory;
    /* root cnode of the test process */
    seL4_CPtr root_cnode;
    /* tcb of the test process */
    seL4_CPtr tcb;
    /* the domain cap */
    seL4_CPtr domain;
#ifndef CONFIG_KERNEL_STABLE
    /* asid pool cap for the test process to use when creating new processes */
    seL4_CPtr asid_pool;
#endif
#ifdef CONFIG_IOMMU
    seL4_CPtr io_space;
#endif /* CONFIG_IOMMU */
    /* cap to the sel4platsupport default timer irq handler */
    seL4_CPtr timer_irq;
#ifdef CONFIG_ARCH_ARM
    /* cap to the sel4platsupport default timer physical frame */
    seL4_CPtr timer_frame;
#endif
#ifdef CONFIG_ARCH_IA32
    /* cap to the sel4platsupport default timer io port */
    seL4_CPtr io_port;
#endif

    /* size of the test processes cspace */
    seL4_Word cspace_size_bits;
    /* range of free slots in the cspace */
    seL4_SlotRegion free_slots;

    /* range of untyped memory in the cspace */
    seL4_SlotRegion untypeds;
    /* size of untyped that each untyped cap corresponds to
     * (size of the cap at untypeds.start is untyped_size_bits_lits[0]) */
    uint8_t untyped_size_bits_list[CONFIG_MAX_NUM_BOOTINFO_UNTYPED_CAPS];
    /* name of the test to run */
    char name[TEST_NAME_MAX];
    /* priority the test process is running at */
    int priority;

    /* List of elf regions in the test process image, this
     * is provided so the test process can launch copies of itself.
     *
     * Note: copies should not rely on state from the current process
     * or the image. Only use copies to run code functions, pass all
     * required state as arguments. */
    sel4utils_elf_region_t elf_regions[MAX_REGIONS];

    /* the number of elf regions */
    int num_elf_regions;
} test_init_data_t;

#endif /* __TEST_H */


text:
require 'rails_helper'

RSpec.describe WelcomeController, type: :controller do
    describe "GET #landing" do

        it "should return http success" do
            get :landing
            expect(response).to be_success
            expect(response).to have_http_status(200)
        end

        it "should render the landing template" do
            get :landing
            expect(response).to render_template("landing")
        end

    end

end


text:
using System.Linq;
using Meganium.Api.Entities;

namespace Meganium.Api.ViewModels
{
    public class PostIndexVm
    {
        public PostType PostType { get; set; }
        public object PostFields { get; set; }
        public IQueryable<Post> Posts { get; set; }
    }
}


text:
class wxActivityIndicatorBase : public wxControl
{
public:
    // Start or stop the activity animation (it is stopped initially).
    virtual void Start() = 0;
    virtual void Stop() = 0;

    // Return true if the control is currently showing activity.
    virtual bool IsRunning() const = 0;

    // Override some base class virtual methods.
    virtual bool AcceptsFocus() const { return false; }
    virtual bool HasTransparentBackground() { return true; }

protected:
    // choose the default border for this window
    virtual wxBorder GetDefaultBorder() const { return wxBORDER_NONE; }
};

#ifndef __WXUNIVERSAL__
#if defined(__WXGTK20__)
    #define wxHAS_NATIVE_ACTIVITYINDICATOR
    #include "gtk_activityindicator.h"
#elif defined(__WXOSX_COCOA__)
    #define wxHAS_NATIVE_ACTIVITYINDICATOR
    #include "osx_activityindicator.h"
#endif
#endif // !__WXUNIVERSAL__

#ifndef wxHAS_NATIVE_ACTIVITYINDICATOR
    #include "generic_activityindicator.h"
#endif

#endif // _WX_ACTIVITYINDICATOR_H_


text:
<?php

// set class namespace
namespace PequenoSpotifyModule;

// set used namespaces
use PequenoSpotifyModule\Service\SpotifyService;
use PequenoSpotifyModule\Item\AbstractItem;
use PequenoSpotifyModule\Item\Album;
use PequenoSpotifyModule\Item\Artist;
use PequenoSpotifyModule\Item\Track;

class ResultSet implements \Iterator, \Countable
{
    /** @var int */
    protected $numResults = null;

    /** @var int */
    protected $limit = null;

    /** @var int */
    protected $offset = null;

    /** @var string */
    protected $query = null;

    /** @var string */
    protected $type = null;

    /** @var int */
    protected $numPage = null;

    /** @var AbstractItem[] */
    protected $results = null;

    /**
     * Class contructor
     * @access public
     * @param  \stdClass $rawResults Raw result from SpotifyService
     * @return ResultSet
     */
    public function __construct($rawResults)
    {
        // extract search informations
        $this->extractSearchInfos($rawResults);

        // extract search results
        $this->extractSearchResults($rawResults);
    }

    /**
     * Get result total count
     * @access public
     * @return int
     */
    public function getSizeOfResults()
    {
        // return result total count
        return $this->numResults;
    }

    /**
     * Add AbstractItem on search results
     * @access private
     * @param  AbstractItem   $item item to add at search results
     * @return AbstractItem[]
     */
    private function addSearchResult($item)
    {
        // create container if necessary
        if (!is_array($this->results)) {

            // create result container
            $this->results = array();
        }

        // check we have an AbstractItem instance
        if ($item instanceof AbstractItem) {

            // add item to container
            $this->results[] = $item;
        }

        // return container
        return $this->results;
    }

    /**
     * Extract search informations
     * @access protected
     * @param  \stdClass $rawResults Raw result from SpotifyService
     * @return ResultSet
     */
    protected function extractSearchInfos($rawResults)
    {
        // is search informations available ?
        if (isset($rawResults->info)) {

            // get search informations
            $this->numResults = (int) $rawResults->info->num_results;
            $this->numPage = (int) $rawResults->info->page;
            $this->limit = (int) $rawResults->info->limit;
            $this->offset = (int) $rawResults->info->offset;
            $this->query = (string) $rawResults->info->query;
            $this->type = (string) $rawResults->info->type;
        }

        // return ResultSet
        return $this;
    }

    /**
     * Extract search result items
     * @access protected
     * @param  \stdClass $rawResults Raw result from SpotifyService
     * @return ResultSet
     */
    protected function extractSearchResults($rawResults)
    {
        switch ($this->type) {
            // albums search
            case SpotifyService::SEARCH_ALBUM:
                $this->extractAlbums($rawResults);
                break;
            // artists search
            case SpotifyService::SEARCH_ARTIST:
                $this->extractArtists($rawResults);
                break;
            // tracks search
            case SpotifyService::SEARCH_TRACK:
                $this->extractTracks($rawResults);
                break;
        }

        // return ResultSet
        return $this;
    }

    /**
     * Extract search albums
     * @access protected
     * @param  \stdClass $rawResults Raw result from SpotifyService
     * @return ResultSet
     */
    protected function extractAlbums($rawResults)
    {
        // are albums available ?
        if (isset($rawResults->albums) && is_array($rawResults->albums)) {

            // iterate albums
            foreach ($rawResults->albums as $album) {

                // create album instance
                $albumItem = Album::extractInfos($album);

                // store search result
                $this->addSearchResult($albumItem);
            }
        }

        // return ResultSet
        return $this;
    }

    /**
     * Extract search artists
     * @access protected
     * @param  \stdClass $rawResults Raw result from SpotifyService
     * @return ResultSet
     */
    protected function extractArtists($rawResults)
    {
        // are artists available ?
        if (isset($rawResults->artists) && is_array($rawResults->artists)) {

            // iterate artists
            foreach ($rawResults->artists as $artist) {

                // create artist instance
                $artistItem = Artist::extractInfos($artist);

                // store search result
                $this->addSearchResult($artistItem);
            }
        }

        // return ResultSet
        return $this;
    }

    /**
     * Extract search tracks
     * @access protected
     * @param  \stdClass $rawResults Raw result from SpotifyService
     * @return ResultSet
     */
    protected function extractTracks($rawResults)
    {
        // are tracks available ?
        if (isset($rawResults->tracks) && is_array($rawResults->tracks)) {

            // iterate tracks
            foreach ($rawResults->tracks as $track) {

                // create Track instance
                $trackItem = Track::extractInfos($track);

                // store search result
                $this->addSearchResult($trackItem);
            }
        }

        // return ResultSet
        return $this;
    }

    /**
     * Get search resultat as indice
     * @access public
     * @param  int               $indice Search result indice
     * @return AbstractItem|null
     */
    public function getResultAt($indice)
    {
        // return AbstractItem if exist, else null
        return (isset($this->results[$indice])) ? $this->results[$indice] : null;
    }

    /**
     * Get current search AbstractItem
     * @access public
     * @return AbstractItem
     */
    public function current()
    {
        // return current AbstractItem
        return current($this->results);
    }

    /**
     * Move cursor to next position
     * @access public
     * @return void
     */
    public function next()
    {
        next($this->results);
    }

    /**
     * Get current cursor position
     * @access public
     * @return int
     */
    public function key()
    {
        return key($this->results);
    }

    /**
     * Is current cursor position valid ?
     * @access public
     * @return bool
     */
    public function valid()
    {
        return (bool) (($this->key() !== null) && ($this->key() !== false));
    }

    /**
     * Rest cursor position to start
     * @access public
     * @return void
     */
    public function rewind()
    {
        reset($this->results);
    }

    /**
     * Get search results count (from query, not total)
     * @access public
     * @return int
     */
    public function count()
    {
        // return search result count
        return count($this->results);
    }
}


text:
@class MainViewController;
@class FlipsideViewController;
@interface ViewController : UIViewController{

    IBOutlet UIButton *infoButton;
    MainViewController *mainViewController;
    FlipsideViewController *flipsideViewController;
    UINavigationBar *flipsideNavigationBar;
}

@property (nonatomic, retain) UIButton *infoButton;
@property (nonatomic, retain) MainViewController *mainViewController;
@property (nonatomic, retain) UINavigationBar *flipsideNavigationBar;
@property (nonatomic, retain) FlipsideViewController *flipsideViewController;

- (IBAction)toggleView;

@end


text:
import os
import sh
import json
import configparser

def read_config(profile="default"):
    """
    Read the region and keys from the user's configuration files

    :param profile: the profile from which to read data
    :return: tuple with the id, region, key, and secret
    """
    awsid = sh.aws("sts", "get-caller-identity", "--output", "text", "--query", "Account").strip()

    config = configparser.RawConfigParser()

    try:
        config.read('%s/.aws/config' % os.environ['HOME'])
        region = config.get(profile, 'region')
    except:
        print("Error reading the '~/.aws/config' file.")
        raise

        # check if the user has defined his credentials
    try:
        config.read('%s/.aws/credentials' % os.environ['HOME'])
        key = config.get(profile, 'aws_access_key_id')
        secret = config.get(profile, 'aws_secret_access_key')
    except:
        print("Error reading the '~/.aws/credentials' file.")
        raise
    return awsid, region, key, secret

def arn_base():
    """
    Get the Amazon Resource Name (ARN) prefix for IoT

    :return: the ARN prefix
    """
    awsid, region, key, secret = read_config()
    return "arn:aws:iot:%s:%s:" % (region, awsid)

def create_thing(name):
    """
    Create a Thing in the configured region

    :param name: name of the Thing
    :return: the properties of this thing
    """
    response = sh.aws("iot", "create-thing", "--thing-name", name)
    return json.loads(str(response))

def delete_thing(thing):
    """
    Delete a Thing in the configured region

    :param thing: name of the Thing
    :return: None
    """
    delete_thing_by_name(thing['thingName'])

def delete_thing_by_name(name):
    """
    Delete a Thing in the configured region by specifying its name

    :param name: name of the Thing
    :return: None
    """
    sh.aws("iot", "delete-thing", "--thing-name", name)

def describe_thing(thing):
    """
    Get Thing properties

    :param thing:  json properties of the Thing
    :return: dictionary with the Thing's description
    """
    return describe_thing_by_name(thing['thingName'])

def describe_thing_by_name(name):
    """
    Get Thing properties by specifying its name

    :param name:  name of the Thing
    :return: dictionary with the Thing's description
    """
    response = sh.aws("iot", "describe-thing", "--thing-name", name)
    return json.loads(str(response))

def create_keys_and_certificate():
    """
    Create and activate keys and certificate

    :return: dictionary with the certificateArn, certificatePem, PublicKey, PrivateKey, and certificateId
    """
    response = sh.aws("iot", "create-keys-and-certificate", "--set-as-active")
    return json.loads(str(response))

def delete_certificate(cert):
    """
    Inactivate and delete a certificate

    :param cert: the certificate json data
    :return: None
    """
    delete_certificate_by_id(cert['certificateId'])

def delete_certificate_by_id(id):
    """
    Inactivate and delete a certificate with the given id

    :param id: the certificateID
    :return: None
    """
    # inactivate certificate
    sh.aws("iot", "update-certificate", "--certificate-id", id, "--new-status", "INACTIVE")

    arn = describe_certificate_by_id(id)["certificateArn"]

    # detach all policies
    policies_data = json.loads(str(sh.aws("iot", "list-principal-policies", "--principal", arn)))
    for policy in policies_data["policies"]:
        sh.aws("iot", "detach-principal-policy", "--policy-name", policy["policyName"], "--principal", arn)

    # detach all things
    things_data = json.loads(str(sh.aws("iot", "list-principal-things", "--principal", arn)))
    for thing in things_data["things"]:
        sh.aws("iot", "detach-thing-principal", "--thing-name", thing, "--principal", arn)

    # we safely delete certificate now
    sh.aws("iot", "delete-certificate", "--certificate-id", id)

def describe_certificate(cert):
    """
    Get certificate info for the given id

    :param cert: the certificateId
    :return: dictionary with certificate properties
    """
    return describe_certificate_by_id(cert['certificateId'])

def describe_certificate_by_id(id):
    """
    Get certificate info for the given id

    :param id: the certificateId
    :return: dictionary with certificate properties
    """
    response = sh.aws("iot", "describe-certificate", "--certificate-id", id)
    return json.loads(str(response))['certificateDescription']

def write_keys_and_certificates(cert, path=os.environ['PWD']):
    """
    Write the certificate and keys to files

    :param cert: json with the certificate and keys
    :param path: output path (default: $PWD)
    :return: None
    """

    base_filename = path + "/" + cert['certificateId'][:10]

    certpem_file = open("%s-certificate.pem.crt" % base_filename, 'w')
    certpem_file.write(cert['certificatePem'])
    certpem_file.close()

    pubkey_file = open("%s-public.pem.key" % base_filename, 'w')
    pubkey_file.write(cert['keyPair']['PublicKey'])
    pubkey_file.close()

    privatekey_file = open("%s-private.pem.key" % base_filename, 'w')
    privatekey_file.write(cert['keyPair']['PrivateKey'])
    privatekey_file.close()

def create_policy(name, effect, action, topic):
    """

    :param name: policy name
    :param effect: policy effect ("Allow" or "Deny")
    :param action: action allowed or denied by policy (e.g. "iot:Publish", "iot:Connect", "iot:Subscribe")
    :param topic: topic on which the policy takes effect
    :return: dictionary with the policy properties
    """
    policy = dict(Version="2012-10-17")
    policy["Statement"] = [dict(Effect=effect, Action=[action], Resource=[arn_base() + "topic/" + topic])]
    return create_policy_from_string(name, str(json.dumps(policy)))

def create_policy_from_string(name, doc):
    """
    Create a policy

    :param name: policy name
    :param doc: json document string describing the policy
    :return: dictionary with the policy properties
    """
    response = sh.aws("iot", "create-policy", "--policy-name", name, "--policy-document", doc)
    return json.loads(str(response))

def describe_policy(policy):
    """
    Get policy document (json)

    :param name: policy name
    :return: dictionary with the policy properties
    """
    return describe_policy_by_name(policy['policyName'])

def describe_policy_by_name(name):
    """
    Get policy document (json) by specifying its name

    :param name: policy name
    :return: dictionary with the policy properties
    """
    response = sh.aws("iot", "get-policy", "--policy-name", name)
    return json.loads(str(response))

def delete_policy(policy):
    """
    Delete a policy

    :param policy: policy properties dictionary
    :return: None
    """
    delete_policy_by_name(policy['policyName'])

def delete_policy_by_name(name):
    """
    Delete a policy by specifying its name

    :param name: policy name
    :return: None
    """
    sh.aws("iot", "delete-policy", "--policy-name", name)

def attach_policy(certificate, policy):
    """
    Attach a policy to a certificate

    :param certificate: certificate json data
    :param policy: policy json data
    :return: None
    """
    attach_policy_by_arn_and_name(certificate["certificateArn"], policy["policyName"])

def attach_policy_by_arn_and_name(certificate_arn, policy_name):
    """
    Attach a policy to a certificate (using arn and name)

    :param certificate_arn: arn of the certificate
    :param policy_name: the policy hame
    :return:
    """
    sh.aws("iot", "attach-principal-policy", "--principal", certificate_arn, "--policy-name", policy_name)

def attach_to_thing(thing, certificate):
    """
    Attach certificate to a thing

    :param thing: thing json data
    :param certificate: certificate json data
    :return: None
    """
    attach_to_thing_by_arn_and_name(thing["thingName"], certificate["certificateArn"])

def attach_to_thing_by_arn_and_name(thing_name, certificate_arn):
    """
    Attach certificate to a thing (using arn and name)

    :param certificate_arn: arn of the certificate
    :param thing_name: the thing hame
    :return:
    """
    sh.aws("iot", "attach-thing-principal", "--principal", certificate_arn, "--thing-name", thing_name)


text:
'use strict'

module.exports = org

var assert = require('assert')
var url = require('url')

var subcommands = {}

function org (subcommand, uri, params, cb) {
  orgAssertions(subcommand, uri, params, cb)
  return subcommands[subcommand].call(this, uri, params, cb)
}

subcommands.set = subcommands.add = function (uri, params, cb) {
  return this.request(apiUri(uri, 'org', params.org, 'user'), {
    method: 'PUT',
    auth: params.auth,
    body: JSON.stringify({
      user: params.user,
      role: params.role
    })
  }, cb)
}

subcommands.rm = function (uri, params, cb) {
  return this.request(apiUri(uri, 'org', params.org, 'user'), {
    method: 'DELETE',
    auth: params.auth,
    body: JSON.stringify({
      user: params.user
    })
  }, cb)
}

subcommands.ls = function (uri, params, cb) {
  return this.request(apiUri(uri, 'org', params.org, 'user'), {
    method: 'GET',
    auth: params.auth
  }, cb)
}

function apiUri (registryUri) {
  var path = Array.prototype.slice.call(arguments, 1)
    .map(encodeURIComponent)
    .join('/')
  return url.resolve(registryUri, '-/' + path)
}

function orgAssertions (subcommand, uri, params, cb) {
  assert(subcommand, 'subcommand is required')
  assert(subcommands.hasOwnProperty(subcommand),
         'org subcommand must be one of ' + Object.keys(subcommands))
  assert(typeof uri === 'string', 'registry URI is required')
  assert(typeof params === 'object', 'params are required')
  assert(typeof params.auth === 'object', 'auth is required')
  assert(!cb || typeof cb === 'function', 'callback must be a function')
  assert(typeof params.org === 'string', 'org name is required')
  if (subcommand === 'rm' || subcommand === 'add' || subcommand === 'set') {
    assert(typeof params.user === 'string', 'user is required')
  }
}


text:
"""Run a server displaying the administrative UI for the application."""

import logging
import os.path

import google
import jinja2
import webapp2

from google.appengine.tools.devappserver2.admin import admin_request_handler
from google.appengine.tools.devappserver2.admin import blobstore_viewer
from google.appengine.tools.devappserver2.admin import console
from google.appengine.tools.devappserver2.admin import cron_handler
from google.appengine.tools.devappserver2.admin import datastore_indexes_viewer
from google.appengine.tools.devappserver2.admin import datastore_stats_handler
from google.appengine.tools.devappserver2.admin import datastore_viewer
from google.appengine.tools.devappserver2.admin import mail_request_handler
from google.appengine.tools.devappserver2.admin import memcache_viewer
from google.appengine.tools.devappserver2.admin import modules_handler
from google.appengine.tools.devappserver2.admin import quit_handler
from google.appengine.tools.devappserver2.admin import search_handler
from google.appengine.tools.devappserver2.admin import static_file_handler
from google.appengine.tools.devappserver2.admin import taskqueue_queues_handler
from google.appengine.tools.devappserver2.admin import taskqueue_tasks_handler
from google.appengine.tools.devappserver2.admin import xmpp_request_handler
from google.appengine.tools.devappserver2 import wsgi_server

class AdminApplication(webapp2.WSGIApplication):
  """A WSGI application that serves an administrative UI for the application."""

  def __init__(self, dispatch, configuration):
    """Initializer for AdminApplication.

    Args:
      dispatch: A dispatcher.Dispatcher instance used to route requests and
          provide state about running servers.
      configuration: An application_configuration.ApplicationConfiguration
          instance containing the configuration for the application.
    """
    super(AdminApplication, self).__init__(
        [('/datastore', datastore_viewer.DatastoreRequestHandler),
         ('/datastore/edit/(.*)', datastore_viewer.DatastoreEditRequestHandler),
         ('/datastore/edit', datastore_viewer.DatastoreEditRequestHandler),
         ('/datastore-indexes',
          datastore_indexes_viewer.DatastoreIndexesViewer),
         ('/datastore-stats', datastore_stats_handler.DatastoreStatsHandler),
         ('/console', console.ConsoleRequestHandler),
         ('/console/restart/(.+)', console.ConsoleRequestHandler.restart),
         ('/memcache', memcache_viewer.MemcacheViewerRequestHandler),
         ('/blobstore', blobstore_viewer.BlobstoreRequestHandler),
         ('/blobstore/blob/(.+)', blobstore_viewer.BlobRequestHandler),
         ('/taskqueue', taskqueue_queues_handler.TaskQueueQueuesHandler),
         ('/taskqueue/queue/(.+)',
          taskqueue_tasks_handler.TaskQueueTasksHandler),
         ('/cron', cron_handler.CronHandler),
         ('/xmpp', xmpp_request_handler.XmppRequestHandler),
         ('/mail', mail_request_handler.MailRequestHandler),
         ('/quit', quit_handler.QuitHandler),
         ('/search', search_handler.SearchIndexesListHandler),
         ('/search/document', search_handler.SearchDocumentHandler),
         ('/search/index', search_handler.SearchIndexHandler),
         ('/assets/(.+)', static_file_handler.StaticFileHandler),
         ('/instances', modules_handler.ModulesHandler),
         webapp2.Route('/',
                       webapp2.RedirectHandler,
                       defaults={'_uri': '/instances'})],
        debug=True)
    self.dispatcher = dispatch
    self.configuration = configuration

class AdminServer(wsgi_server.WsgiServer):
  """Serves an administrative UI for the application over HTTP."""

  def __init__(self, host, port, dispatch, configuration, xsrf_token_path):
    """Initializer for AdminServer.

    Args:
      host: A string containing the name of the host that the server should bind
          to e.g. "localhost".
      port: An int containing the port that the server should bind to e.g. 80.
      dispatch: A dispatcher.Dispatcher instance used to route requests and
          provide state about running servers.
      configuration: An application_configuration.ApplicationConfiguration
          instance containing the configuration for the application.
      xsrf_token_path: A string containing the path to a file that contains the
          XSRF configuration for the admin UI.
    """
    self._host = host
    self._xsrf_token_path = xsrf_token_path
    super(AdminServer, self).__init__((host, port),
                                      AdminApplication(dispatch, configuration))

  def start(self):
    """Start the AdminServer."""
    admin_request_handler.AdminRequestHandler.init_xsrf(self._xsrf_token_path)
    super(AdminServer, self).start()
    logging.info('Starting admin server at: http://%s:%d', self._host,
                 self.port)

  def quit(self):
    """Quits the AdminServer."""
    super(AdminServer, self).quit()
    console.ConsoleRequestHandler.quit()


text:
namespace Conversation
{
	internal enum ConversationState
	{
		Closed,
		Opened,
		InContext
	}
}


text:
import { DESCRIPTORS, TYPED_ARRAYS } from '../helpers/constants';

if (DESCRIPTORS) QUnit.test('%TypedArrayPrototype%.reverse', assert => {
  // we can't implement %TypedArrayPrototype% in all engines, so run all tests for each typed array constructor
  for (const { name, TypedArray } of TYPED_ARRAYS) {
    const { reverse } = TypedArray.prototype;
    assert.isFunction(reverse, `${ name }::reverse is function`);
    assert.arity(reverse, 0, `${ name }::reverse arity is 0`);
    assert.name(reverse, 'reverse', `${ name }::reverse name is 'reverse'`);
    assert.looksNative(reverse, `${ name }::reverse looks native`);
    const array = new TypedArray([1, 2]);
    assert.same(array.reverse(), array, 'return this');
    assert.arrayEqual(new TypedArray([1, 2, 3, 4]).reverse(), [4, 3, 2, 1], 'works #1');
    assert.arrayEqual(new TypedArray([1, 2, 3]).reverse(), [3, 2, 1], 'works #2');
    assert.throws(() => reverse.call([1, 2]), "isn't generic");
  }
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DynThings.WebPortal.Models.ViewModels
{

    public class Monitor

    {
        public long ID { get; set; }
        public string Title { get; set; }
        public bool IsActive { get; set; }
        public string OwnerID { get; set; }
        public string X { get; set; }
        public string Y { get; set; }
        public string Z { get; set; }

        public LocationViewType locationViewType { get; set; }

        public List<Location> MLocations;

    }

}


text:
var request = require('request'),
    xml2js = require('xml2js-expat'),
    async = require('async');

var fetch_feed = function (url, cb) {

    request(url, function (error, response, body) {

        console.log("Got response. Code = " + response.statusCode);

        if (!error && response.statusCode === 200) {
            var r = body;
            var contentType = response.headers["content-type"].split(';')[0];
            if (contentType) {

                console.log("contentType = " + contentType);

                // Parsing XML
                var feed_content_types = ["text/xml", "application/rss+xml", "application/xml"];
                if (feed_content_types.indexOf(contentType) !== -1) {
                    console.log("parsing...");
                    var parser = new xml2js.Parser();
                    parser.addListener('end', function (r) {
                        //console.log(r);
                        var result = r.channel ? r.channel.item : r.entry;
                        cb(null, result);
                    });
                    parser.addListener('error', function (r) {
                        console.log("Error parsing feed...");
                    });
                    parser.parseString(body);
                    return;
                }
            }

        } else {
            // TODO: we should indicate errors in the response
            cb(null, []);
        }
    });
};

var fetch_feeds = function (urls, cb) {

    var items = [];
    async.forEachSeries(urls, function (url, cb) {

        fetch_feed(url, function (err, result) {
            items = items.concat(result);
            cb(err, result);
        });

    }, function () {
        cb(null, items);
    });

};

exports.fetch_feeds = fetch_feeds;

exports.worker = function (task, config) {

    var input = JSON.parse(task.config.input);

    // fetch must be able to get multiple URLs
    var urls = [];
    if (Array.isArray(input.URL)) {
        input.URL.forEach(function (u) {
            urls.push(u);
        });
    } else {
        urls.push(input.URL);
    }

    console.log(urls);

    fetch_feeds(urls, function (err, items) {
        task.respondCompleted({
            _OUTPUT: items
        });
    });

};


text:
const ReplTestFixture = require('../repl/repl_test_fixture'),
      assert = require('assert');

let test = new ReplTestFixture();
describe('LegacyCollection', function() {
  before(() => test.databaseSetup());
  after(() => test.databaseTeardown());
  beforeEach(() => test.setup());

  it('should return a new collection when subcollections access is attempted', function(done) {
    // Execute command
    test.repl.eval('x = db.some_coll.my_coll', test.context, '', function(err, result) {
      assert.equal(null, err);
      assert.ok(test.context.x);
      assert.equal(test.context.x.namespace, 'test_runner.some_coll.my_coll');
      done();
    });
  });
});


text:
import SongTag from './SongTag'

class Song {
  constructor (json) {
    if (json !== undefined) {
      this.fromJson(json)
    }
  }
  fromJson (json) {
    this.id = json.id
    this.name = json.name
    this.artists = json.artists
    this.album = json.album
    if (json.hasOwnProperty('startTime')) {
      this.startTime = json.startTime
    }
    if (json.hasOwnProperty('endTime')) {
      this.endTime = json.endTime
    }
    this.files = Object.assign({}, json.files)
    this.tags = json.tags
      .concat([
        (() => {
          const bitrateString = (json.observations.bitrate !== 0 ? `${json.observations.bitrate}kbps` : '')
          return `from ${json.observations.codec} (${json.observations.grok}` + (bitrateString.length > 0 ? ` at ${bitrateString})` : ')')
        })()
      ])
      .map(tag => new SongTag(tag))
    // (() => {
    //   this.nameWords = this.name.split(' ').map(
    //     (text, index) => {
    //       return {
    //         text,
    //         id: this.id + index
    //       }
    //     }
    //   )
    // })();
  }
}

export default Song


text:
@media screen and (max-width: 640px) {
    .container {padding: 0;}
    .navbar {padding: 0 15px;}
}

.table > tbody + tbody.diaries_body {border-top: none;}

.table > tbody > tr.diaries_header > td {padding-top: 40px; vertical-align: bottom; border-top: none;}

.table > tbody > tr.diaries_header_mobile > td {border-top: none;}

.table > tbody > tr#diaries_total > td {padding-top: 40px; vertical-align: bottom; border-top: none;}

.navbar-default {
    background-color: #36A9E1;
    border-color: none;
}
.navbar-default .navbar-brand {
    color: #ffffff;
    height: auto;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
    color: #d2e9f4;
}
.navbar-default .navbar-nav > li > a {
    color: #ffffff;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
    color: #d2e9f4;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
    color: #d2e9f4;
    background-color: #1e8fc6;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
    color: #d2e9f4;
    background-color: #1e8fc6;
}
.navbar-default .navbar-nav > .dropdown > a .caret {
    border-top-color: #ffffff;
    border-bottom-color: #ffffff;
}
.navbar-default .navbar-nav > .dropdown > a:hover .caret,
.navbar-default .navbar-nav > .dropdown > a:focus .caret {
    border-top-color: #d2e9f4;
    border-bottom-color: #d2e9f4;
}
.navbar-default .navbar-nav > .dropdown .dropdown-menu .divider {
    background-color: #ffffff;
}
.navbar-default .navbar-nav > .open > a .caret,
.navbar-default .navbar-nav > .open > a:hover .caret,
.navbar-default .navbar-nav > .open > a:focus .caret {
    border-top-color: #d2e9f4;
    border-bottom-color: #d2e9f4;
}
.navbar-default .navbar-toggle {
    border-color: #1e8fc6;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
    background-color: #1e8fc6;
}
.navbar-default .navbar-toggle .icon-bar {
    background-color: #ffffff;
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
    border-color: #ffffff;
}
@media (max-width: 767px) {
    .navbar-default .navbar-nav .open .dropdown-menu > li > a {
        color: #ffffff;
    }
    .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
    .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
        color: #000040;
    }
}

.navbar-nav > li > a {padding-top: 10px !important; padding-bottom: 10px !important;}
.navbar {min-height: 40px !important}

.navbar-brand {line-height: 10px;}

.delete_mobile {width: 100px; padding: 0; background: red; color: #fff;}

.diary_action {width: 40px;}

.brand_name_mobile {font-size: 12px;}

.line_total_td {padding-left: 10px;}

.add_food_select {max-width: 95%;}
.add_food_quantity {max-width: 80px;}

.t-left {text-align: left;}
.t-center {text-align: center;}
.t-right {text-align: right;}
.f-right {float: right;}

.pointer {cursor: pointer;}

.clear {clear: both;}

.table > tbody > tr > td.manual_diary_line {padding: 4px 8px;}
.table > tbody > tr > td.manual_diary_line .manual_diary_input {height: 30px;}

.form-horizontal .control-label.t-left {text-align: left;}

a.dropdown-toggle {cursor: pointer;}


text:
require_relative '../../imcmo'
require_relative '../../imccoremeta'
require_relative '../../imcmeta'

class BiosBootModeConsts
    ACTUAL_BOOT_MODE_LEGACY = "Legacy"
    ACTUAL_BOOT_MODE_UEFI = "Uefi"
    ACTUAL_BOOT_MODE_UNKNOWN = "Unknown"
end

class BiosBootMode < ManagedObject
    #This is BiosBootMode class.

    @@consts = BiosBootModeConsts.new()
#    @@naming_props = set([])

    @@mo_meta = {
        "classic" => MoMeta.new("BiosBootMode", "biosBootMode", "boot-mode", VersionMeta::VERSION201A, "OutputOnly", 0xf, [], ["admin", "user"], ["Get"]),
        "modular" => MoMeta.new("BiosBootMode", "biosBootMode", "boot-mode", VersionMeta::VERSION2013E, "OutputOnly", 0xf, [], ["admin", "user"], ["Get"])
    }

    def self.mo_meta
        @@mo_meta
    end

    @@prop_meta = {

        "classic" => {
        "actual_boot_mode" => MoPropertyMeta.new("actual_boot_mode", "actualBootMode", "string", VersionMeta::VERSION201A, MoPropertyMeta::READ_ONLY, nil, nil, nil, nil, ["Legacy", "Uefi", "Unknown"], []),
        "child_action" => MoPropertyMeta.new("child_action", "childAction", "string", VersionMeta::VERSION201A, MoPropertyMeta::INTERNAL, nil, nil, nil, nil, [], []),
        "dn" => MoPropertyMeta.new("dn", "dn", "string", VersionMeta::VERSION201A, MoPropertyMeta::READ_ONLY, 0x2, 0, 255, nil, [], []),
        "rn" => MoPropertyMeta.new("rn", "rn", "string", VersionMeta::VERSION201A, MoPropertyMeta::READ_ONLY, 0x4, 0, 255, nil, [], []),
        "status" => MoPropertyMeta.new("status", "status", "string", VersionMeta::VERSION201A, MoPropertyMeta::READ_ONLY, 0x8, nil, nil, %q{((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}}, [], []),
        },

        "modular" => {
            "actual_boot_mode" => MoPropertyMeta.new("actual_boot_mode", "actualBootMode", "string", VersionMeta::VERSION2013E, MoPropertyMeta::READ_ONLY, nil, nil, nil, nil, ["Legacy", "Uefi", "Unknown"], []),
            "child_action" => MoPropertyMeta.new("child_action", "childAction", "string", VersionMeta::VERSION2013E, MoPropertyMeta::INTERNAL, nil, nil, nil, nil, [], []),
            "dn" => MoPropertyMeta.new("dn", "dn", "string", VersionMeta::VERSION2013E, MoPropertyMeta::READ_ONLY, 0x2, 0, 255, nil, [], []),
            "rn" => MoPropertyMeta.new("rn", "rn", "string", VersionMeta::VERSION2013E, MoPropertyMeta::READ_ONLY, 0x4, 0, 255, nil, [], []),
            "status" => MoPropertyMeta.new("status", "status", "string", VersionMeta::VERSION2013E, MoPropertyMeta::READ_ONLY, 0x8, nil, nil, %q{((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}}, [], []),
        },

    }

    def self.prop_meta
        @@prop_meta
    end

    @@prop_map = {

        "classic" => {
        "actualBootMode" => "actual_boot_mode",
        "childAction" => "child_action",
        "dn" => "dn",
        "rn" => "rn",
        "status" => "status",
        },

        "modular" => {
            "actualBootMode" => "actual_boot_mode",
            "childAction" => "child_action",
            "dn" => "dn",
            "rn" => "rn",
            "status" => "status",
        },

    }

    def self.prop_map
        @@prop_map
    end

    attr_reader :actual_boot_mode
    attr_reader :child_action
    attr_reader :status

    def initialize(parent_mo_or_dn: nil,  **kwargs)
        @dirty_mask = 0
        @actual_boot_mode = nil
        @child_action = nil
        @status = nil

        super(class_id: "BiosBootMode", parent_mo_or_dn: parent_mo_or_dn, **kwargs)

    end
end


text:
package in.tosc.ghumo.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

import in.tosc.ghumo.R;

import static java.lang.Math.abs;
import static java.lang.Math.floor;

public class ScrollingImageView extends View {
    private final int speed;
    private final Bitmap bitmap;

    private Rect clipBounds = new Rect();
    private float offset = 0;

    private boolean isStarted;

    public ScrollingImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ParallaxView, 0, 0);
        try {
            speed = ta.getDimensionPixelSize(R.styleable.ParallaxView_speed, 10);
            bitmap = BitmapFactory.decodeResource(getResources(), ta.getResourceId(R.styleable.ParallaxView_src, 0));
        } finally {
            ta.recycle();
        }
        start();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), bitmap.getHeight());
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (canvas == null) {
            return;
        }

        canvas.getClipBounds(clipBounds);

        float layerWidth = bitmap.getWidth();
        if (offset < -layerWidth) {
            offset += (floor(abs(offset) / layerWidth) * layerWidth);
        }

        float left = offset;
        while (left < clipBounds.width()) {
            canvas.drawBitmap(bitmap, getBitmapLeft(layerWidth, left), 0, null);
            left += layerWidth;
        }

        if (isStarted) {
            offset -= abs(speed);
            postInvalidateOnAnimation();
        }
    }

    private float getBitmapLeft(float layerWidth, float left) {
        if (speed < 0) {
            return clipBounds.width() - layerWidth - left;
        } else {
            return left;
        }
    }

    public void start() {
        if (!isStarted) {
            isStarted = true;
            postInvalidateOnAnimation();
        }
    }

    public void stop() {
        if (isStarted) {
            isStarted = false;
            invalidate();
        }
    }
}


text:
/**
 * Replace all comments with some innocuous character.
 *
 * @param {string} source
 * @param {[string]} blurChar="`"
 * @return {string} - The result string, with comments replaced
 */
export default function (source, blurChar="`") {
  return source.replace(/\/\*.*\*\//g, blurChar)
}


text:
app.directive("clock", function()
{
	return {
		restrict: 'A',
		link: function(scope, element)
		{
			var ctx = element[0].getContext('2d');

			function backingScale(context)
			{
				if ('devicePixelRatio' in window)
				{
					if (window.devicePixelRatio > 1)
					{
						return window.devicePixelRatio;
					}
				}

				return 1;
			}
			var scaleFactor = backingScale(ctx);

			var width = 20 * scaleFactor, height = 20 * scaleFactor;

			element[0].setAttribute('width', width*scaleFactor);
			element[0].setAttribute('height', height*scaleFactor);

			element[0].style.width = width;
			element[0].style.height = height;

			ctx.scale(scaleFactor, scaleFactor);

			var d = new Date(scope.post.originalDate),
				seconds = d.getSeconds(),
				minutes = d.getMinutes(),
				hours = (d.getHours() > 12) ? d.getHours() - 12 : d.getHours();

			// Draw clock border
			ctx.beginPath();
			ctx.arc(width/2, height/2, (height/2)-2, 0, 2 * Math.PI, false);
			ctx.lineWidth = 2 * scaleFactor;
			ctx.strokeStyle = "#FFF";
			ctx.stroke();

			ctx.lineCap = 'round';

			// Draw the minute hand
			ctx.save();
			ctx.translate(width/2, height/2);
			var minuteRotation = Math.PI + ((Math.PI / 30) * minutes);
			ctx.rotate( minuteRotation );
			ctx.beginPath();
			ctx.moveTo(0, 0);
			ctx.lineWidth = 2 * scaleFactor;
			ctx.lineTo(0, (height/2)-(4*scaleFactor));
			ctx.stroke();
			ctx.restore();

			// Draw the hour hand
			ctx.save();
			ctx.translate(width/2, height/2);
			var minuteRotation = Math.PI + ((Math.PI / 6) * hours);
			ctx.rotate( minuteRotation );
			ctx.beginPath();
			ctx.moveTo(0, 0);
			ctx.lineWidth = 2 * scaleFactor;
			ctx.lineTo(0, (height/2)-(6*scaleFactor));
			ctx.strokeStyle = "#A5A5A5";
			ctx.stroke();
			ctx.restore();

			// Draw the second hand
			ctx.save();
			ctx.translate(width/2, height/2);
			var minuteRotation = Math.PI + ((Math.PI / 30) * seconds);
			ctx.rotate( minuteRotation );
			ctx.beginPath();
			ctx.moveTo(0, 0);
			ctx.lineWidth = 1 * scaleFactor;
			ctx.lineTo(0, (height/2)-(4*scaleFactor));
			ctx.strokeStyle = "#FF0000";
			ctx.stroke();
			ctx.restore();
		}
	}
})


text:
package com.scorpiac.javarant.responses;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.scorpiac.javarant.User;

public class UserResponse extends Response<User> {
    @JsonProperty
    void setProfile(User profile) {
        value = profile;
    }
}


text:
using Markdig.Syntax;

namespace Markdig.Renderers.Html
{
    /// <summary>
    /// A HTML renderer for a <see cref="ThematicBreakBlock"/>.
    /// </summary>
    /// <seealso cref="HtmlObjectRenderer{ThematicBreakBlock}" />
    public class ThematicBreakRenderer : HtmlObjectRenderer<ThematicBreakBlock>
    {
        protected override void Write(HtmlRenderer renderer, ThematicBreakBlock obj)
        {
            if (renderer.EnableHtmlForBlock)
            {
                renderer.Write("<hr").WriteAttributes(obj).WriteLine(" />");
            }
        }
    }
}


text:
require 'active_support/all'
require 'pathname'

module GoodData
  module Helpers
    class << self
      def home_directory
        running_on_windows? ? ENV['USERPROFILE'] : ENV['HOME']
      end

      def running_on_windows?
        RUBY_PLATFORM =~ /mswin32|mingw32/
      end

      def running_on_a_mac?
        RUBY_PLATFORM =~ /-darwin\d/
      end

      def error(msg)
        STDERR.puts(msg)
        exit 1
      end

      def find_goodfile(pwd=`pwd`.strip!, options={})
        root = Pathname(options[:root] || '/')
        pwd = Pathname(pwd).expand_path
        begin
          gf = pwd + 'Goodfile'
          if gf.exist?
            return gf
          end
          pwd = pwd.parent
        end until root == pwd
        nil
      end

      def hash_dfs(thing, &block)
        if !thing.is_a?(Hash) && !thing.is_a?(Array)
        elsif thing.is_a?(Array)
          thing.each do |child|
            hash_dfs(child, &block)
          end
        else
          thing.each do |key, val|
            yield(thing, key)
            hash_dfs(val, &block)
          end
        end
      end

      # TODO: Implement without using ActiveSupport
      def sanitize_string(str, filter=/[^a-z_]/, replacement='')
        str = ActiveSupport::Inflector.transliterate(str).downcase
        str.gsub(filter, replacement)
      end

      # TODO: Implement without using ActiveSupport
      def humanize(str)
        return ActiveSupport::Inflector.humanize(str)
      end

    end
  end
end


text:
/**
* TaskWorkerService
* @namespace crowdsource.task-worker.services
*/
(function () {
  'use strict';

  angular
    .module('crowdsource.task-worker.services')
    .factory('TaskWorker', TaskWorker);

  TaskWorker.$inject = ['$cookies', '$q', '$location', 'HttpService'];

  /**
  * @namespace TaskWorker
  * @returns {Factory}
  */

  function TaskWorker($cookies, $q, $location, HttpService) {
    /**
    * @name TaskWorker
    * @desc The Factory to be returned
    */
    var TaskWorker = {
      getTaskWorker: getTaskWorker,
      submitResult: submitResult,
      attemptAllocateTask: attemptAllocateTask
    };

    return TaskWorker;

    function getTaskWorker(taskWorkerId) {
      var settings = {
        url: '/api/task-worker/' + taskWorkerId + '/',
        method: 'GET'
      };
      return HttpService.doRequest(settings);
    }

    function submitResult(taskWorkerId, results) {
      var settings = {
        url: '/api/task-worker-result/' + taskWorkerId + '/',
        method: 'PUT',
        data: {
          result: results
        }
      };
      return HttpService.doRequest(settings);
    }

    function attemptAllocateTask(module_id) {
      var settings = {
        url: '/api/task-worker/',
        method: 'POST',
        data: {
          module: module_id
        }
      };
      return HttpService.doRequest(settings);
    }

  }
})();


text:
<?php
namespace Jarouche\ViaCEP;

/**
 * Interface para definir um tipo para todos as classes
 * @author Rodrigo Jarouche <rjarouche@gmail.com>
 * @package ViaCEP
 * @version 0.1
 */
interface ViaCEPInterface
{
    /**
     * Método retornaCEP
     * Método para o retorno dos dados do CEP pesquisado
     * @param string $cep
     * @return Array Array com os dados do CEP pesquisado, caso não exista irá retornar um array ('erro' => true);
     */
     public function retornaCEP($cep);

    /**
     * Método retornaConteudoRequisicao
     * Método para o retorno dos dados da requisição bruta, este método deve ser usado apenas depois de uma requisição já feita através de @see retornaCEP
     * @return String String da requisição pura
     * @throws Exception
     */
     public function retornaConteudoRequisicao();
}


text:
<?php

namespace Cncal\Getui\Sdk\IGetui\Req;

use Cncal\Getui\Sdk\Protobuf\PBMessage;

class Button extends PBMessage
{
    var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED;

    public function __construct($reader = NULL)
    {
        parent::__construct($reader);
        $this->fields["1"] = "PBString";
        $this->values["1"] = "";
        $this->fields["2"] = "PBInt";
        $this->values["2"] = "";
    }

    function text()
    {
        return $this->_get_value("1");
    }

    function set_text($value)
    {
        return $this->_set_value("1", $value);
    }

    function next()
    {
        return $this->_get_value("2");
    }

    function set_next($value)
    {
        return $this->_set_value("2", $value);
    }
}


text:
'use strict';

const Ravel = require('ravel');
const Resource = Ravel.Resource;

/**
 * Endpoints for npm access ls-collaborators.
 */
class PackageCollaborators extends Resource {
  constructor () {
    super('/-/package/:packageId/collaborators');
  }
}

module.exports = PackageCollaborators;


text:
require 'test_helper'

class PlaceHelperTest < ActionView::TestCase
end


text:
require 'rails'
require 'action_controller/railtie'
require 'action_view/railtie'
require 'active_record'
require 'database_cleaner'

::ActiveRecord::Base.configurations = {'test' => {:adapter => 'sqlite3', :database => ':memory:'}}
::ActiveRecord::Base.establish_connection('test')

module Chanko
  class Application < Rails::Application
    config.secret_token = '0606ef9eca2318ec13ae836a4f786232'
    config.session_store :cookie_store, :key => "_myapp_session"
    config.active_support.deprecation = :log
    initialize!
  end
end

require 'app/route'
require 'app/controller'

class User < ::ActiveRecord::Base
end

class Recipe < ::ActiveRecord::Base
end

class CreateAllTables < ::ActiveRecord::Migration
  def self.up
    create_table(:users) {|t| t.string :name }
    create_table(:recipes) {|t| t.string :title; t.integer :user_id }
  end
end