text:
* [*Hideous Destructor*](https://github.com/MatthewTheGlutton/HideousDestructor) by vaecrius (Matt).
* [*Receiver*](https://github.com/David20321/7DFPS) by David Rosen and Wolfire Games.
* The *ARMA* series by Bohemia Interactive.

# Code
* SanyaWaffles: `GetPlayerInput` wrapper.
* Gutawer: Dynamic key-help HUD.
* DenisBelmondo: [ZTracer](https://forum.zdoom.org/viewtopic.php?f=37&t=56821) particle-based bullet tracers.

# Graphics
* [PimpMyGun](http://pimpmygun.doctornoob.com/) by Dr. Noob for the weapon graphics.

# Sounds
* jacklmurr27: [Glock 19 handling noises](http://FreeSound.org/s/393734) (CC0 1.0)
* gryffdavid: [Bouncing shell casings](http://FreeSound.org/s/318964) (CC0 1.0)
* jack-freedom5712: [Rounds being inserted to magazine](http://FreeSound.org/s/365146) (CC BY 3.0)

# Special thanks
* Gutawer for being patient and helping me over and over again via `#scripting` on the official ZDoom Discord server.
* The entire GZDoom team for their efforts to make the best Doom engine ever.
* Anyone else who I've gotten help from so far.

# Links
* [CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/)
* [CC BY 3.0](https://creativecommons.org/licenses/by/3.0/)


text:
"use babel";

import "leaflet";

export default L.Control.extend({
  options: {
    position: "topleft"
  },

  onAdd: function(map) {
    const container = L.DomUtil.create("div", "leaflet-bar leaflet-control leaflet-control-showzoom");

    container.innerHTML = `<strong>${map.getZoom()}</strong>`;

    this.listener = function(evt) {
      container.innerHTML = `<strong>${map.getZoom()}</strong>`;
    };

    map.on("zoomend", this.listener);

    return container;
  },

  onRemove: function(map) {
    map.off("zoomend", this.listener);
  }
});

redpajama_set_name: RedPajamaGithub


text:
<?php

require_once 'config.php';

// include the tools -- so we can for one parse and validate
$tools = array(
	       "PosterTranscoder" => 'poster.php',
	       );

foreach ($tools as $tool) {
  include $tool;
}

$process = curl_init('http://'.PMS_IP.':'. PMS_PORT);
$headers = array('Content-Type: application/xml; charset=utf-8',
                 'Content-Length: 0',
                 'X-Plex-Client-Identifier: RARflixTools',
                 );
if (defined('TOKEN') && TOKEN) {
  array_push($headers, 'X-Plex-Token:' . TOKEN);
}
curl_setopt($process, CURLOPT_HTTPHEADER, $headers );
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_TIMEOUT, 5);
curl_setopt($process, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($process);

$authCode = curl_getinfo($process, CURLINFO_HTTP_CODE);
if($authCode == 200) {
  $uri_base = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  $uri_base = preg_replace("/\/$/",'',$uri_base);
  $arr = array(); // json_arr container

  // set some defaults
  $arr["rarflix"]['PosterTranscoder'] = false;
  $arr["rarflix"]['PMSaccess'] = false;
  $arr["rarflix"]['Version'] = VERSION;

  // is the PosterTranscoder available?
  if (function_exists("gd_info")) {
    if (defined('PosterTranscoder') and PosterTranscoder == true) {
      $arr["rarflix"]['PosterTranscoder'] = true;
      $arr["rarflix"]['PosterTranscoderType'] = INDICATOR;
      $arr["rarflix"]['PosterTranscoderUrl'] = $uri_base . '/' . $tools['PosterTranscoder'];
    } else {
      $arr["error"]['PosterTranscoder'] = 'PosterTranscoder Disabled';
    }
  } else {
    $arr["error"]['PosterTranscoder'] = 'php-gd not installed?';
  }

  // check to see if we have access to the PMS
  //  we might want to try an load a photo for a better check
  $xml = simplexml_load_string($data);
  if (!empty($xml['machineIdentifier']))  $arr["rarflix"]['PMSaccess'] = true;

  // return json
  print json_encode($arr);
} else {
  if(curl_errno($process)) {
    $curlError = curl_error($process);
    echo $curlError;
    curl_close($process);
  } else {
    print $data;
  }
}

?>


text:
module Azure::SQL::Mgmt::V2018_06_01_preview
  module Models
    #
    # A database schema resource.
    #
    class DatabaseSchema < ProxyResource

      include MsRestAzure

      #
      # Mapper for DatabaseSchema class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'DatabaseSchema',
          type: {
            name: 'Composite',
            class_name: 'DatabaseSchema',
            model_properties: {
              id: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'id',
                type: {
                  name: 'String'
                }
              },
              name: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'name',
                type: {
                  name: 'String'
                }
              },
              type: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'type',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
<?php

// $artistSlug referres to the `slug` column of the `Artists` table

// after this function is complete, all new shows will have been
// added to the `Shows` table and the `Tracks` and `Venues` tables
// will have been updated appropriately.

function refresh_artist($artistSlug) {

	$dbhandle = database_connect();

	$query = "select name from artists where slug = '$artistSlug'";

	$result = mysqli_query($dbhandle, $query);

	if (mysqli_num_rows($result) == 0) {
		print("artist does not exist: ".$artistSlug."\n");

	}
	else {
		print("artist already exists\n");
	}

}

function refresh_show($archiveIdentifier) {

	$details_FRONT = 'https://archive.org/details/';
	$details_TAIL = '?output=json';

	$dbhandle = database_connect();
	$query = "select * from shows where archive_identifier = '$archiveIdentifier'";

	$result = mysqli_query($dbhandle, $query);

	$URL = $details_FRONT.$archiveIdentifier.$details_TAIL;
	$json = file_get_contents($URL);
	$infos = json_decode($json, true);

	$info = $infos['metadata'];

	$title = $info['title'][0];
	$date = $info['date'][0];
	$year = $info['year'][0];
	$source = $info['source'][0];
	$lineage = $info['lineage'][0];
	$transferer = $info['transferer'][0];
	$taper = $info ['taper'][0];
	$description = $info['description'][0];

	$reviews_count = intval($infos['reviews']['info']['num_reviews']);
	$avg_rating = intval($infos['reviews']['info']['avg_rating']);
	//$reviews = $infos['reviews']['reviews'];

	if (mysqli_num_rows($result) == 0) {

		print("data inserted\n");

		$query = "insert into shows (title, date, year, source,
				  lineage, transferer, taper, description, archive_identifier, reviews,
				  reviews_count, average_rating, duration, track_count, is_soundboard, weighted_avg,
				  createdAt, updatedAt, venueId, ArtistId)
				  values ('".mysqli_real_escape_string($dbhandle, $title)."','$date',
				  '$year', '".mysqli_real_escape_string($dbhandle, $source)."','$lineage','$transferer','$taper',
				  '".mysqli_real_escape_string($dbhandle, $description)."', '$archiveIdentifier', 0, '$reviews_count',
				  '$avg_rating', 0, 0, 0, 0, 0, 0, 0, 0)";
	}

	else {
		print("data updated\n");
		$query = "update shows
				  set title='".mysqli_real_escape_string($dbhandle, $title)."',
				  date='$date', year='$year', source='".mysqli_real_escape_string($dbhandle, $source)."',
				  lineage='$lineage', transferer='$transferer', taper='$taper',
				  description='".mysqli_real_escape_string($dbhandle, $description)."',
				  archive_identifier='$archiveIdentifier', reviews=0,
				  reviews_count='$reviews_count', average_rating='$avg_rating', duration=0,
				  track_count=0, is_soundboard=0, weighted_avg=0,
				  createdAt=0, updatedAt=0, venueId=0, ArtistId=0
				  where archive_identifier = '$archiveIdentifier'";

	}

	$result = mysqli_query($dbhandle,$query);
	if (!$result) {
		print(mysqli_error($dbhandle)."\n");
	}
	//venues, tracks, shows
}

//update shows for each artist
function update_shows_by_artist() {

	$collection_FRONT = "http://archive.org/advancedsearch.php?q=collection%3A";
	$collection_TAIL = "&fl%5B%5D=date&fl%5B%5D=identifier&fl%5B%5D=year&sort%5B%5D=year+asc&sort%5B%5D=&sort%5B%5D=&rows=9999999&page=1&output=json&save=yes";

	$dbhandle = database_connect();
	$query="select archive_collection from artists";
	$result = mysqli_query($dbhandle, $query);

	while ($row=mysqli_fetch_array($result)) {

		$URL = $collection_FRONT.$row[0].$collection_TAIL;

		$json = file_get_contents($URL);
		$infos = json_decode($json, true);
		$info = $infos["response"]["docs"];

		foreach ($info as $show) {

			$ai = $show["identifier"];

			refresh_show($ai);
		}
	}
}

//database connect
function database_connect(){
		$dbhandle = mysqli_connect("127.0.0.1","root","snowman42","lotusod");
		if (mysqli_connect_errno())
		{
  			echo "MySQL Connection Failure: " . mysqli_connect_error();
  		}
  		return $dbhandle;
}

//clear shows table
function clearshows () {

	$dbhandle = database_connect();

	$query = "truncate table shows";

	$result = mysqli_query($dbhandle, $query);
}

//check if it is artist or show

if ($argv[1] == 'artist') {

	refresh_artist($argv[2]);

}

else if ($argv[1] == 'show') {

	$stdin = fopen('php://stdin', 'r');

	while (1) {

		update_shows_by_artist();
		print("enter exit to stop the program: \n");

		$read = array($stdin);
		$write = array();
		$except = array();

		if (stream_select($read, $write, $except, 2)) {
			$input = fgets($stdin);

			if ($input == 'exit'.PHP_EOL) {
				fclose($stdin);
				exit();
			}
		}

		sleep(1);
	}
}

else if ($argv[1] == 'clear') {

	clearshows ();
}

else {
	print("Please re-enter the type of info you want to inquiry\n");
}

?>


text:
module.exports = {
  navigateFallback: '/index.html',
  stripPrefix: 'dist',
  root: 'dist/',
  staticFileGlobs: [
    'dist/index.html',
    'dist/**.js',
    'dist/**.css'
  ],
  maximumFileSizeToCacheInBytes: 3997152
};


text:
Fixes # .

Changes proposed in this pull request:
-
-
-

@pcssi


text:
*Changes since #v0.4.0*
- allow project import/export to work with id as well as slug
- adding instructions for how to recompile markdown.js for future ref.


text:
require 'sensu-plugin/metric/cli'
require 'json'
require 'net/http'
require 'uri'
require 'socket'
require 'sensu-plugins-dcos'

class DCOSMetrics < Sensu::Plugin::Metric::CLI::Graphite
  include Common

  option :scheme,
         description: 'Metric naming scheme',
         short: '-s SCHEME',
         long: '--scheme SCHEME',
         default: "#{Socket.gethostname}.dcos"

  option :server,
         description: 'DCOS Host',
         short: '-h SERVER',
         long: '--host SERVER',
         default: 'localhost'

  option :port,
         description: 'DCOS-metrics port',
         short: '-p PORT',
         long: '--port PORT',
         required: false,
         default: '61001'

  option :uri,
         description: 'Endpoint URI',
         short: '-u URI',
         long: '--uri URI',
         default: '/system/v1/metrics/v0/node'

  def run
    all_metrics = get_data("http://#{config[:server]}:#{config[:port]}#{config[:uri]}")
    if all_metrics.key?('datapoints')
      all_metrics['datapoints'].each do |metric|
        if metric.key?('tags')
          metric['tags'].each do |k, v|
            metric['name'] = [metric['name'], k, v].join('.')
          end
        end
        metric['name'].tr!('/', '.')
        metric['name'].squeeze!('.')
        metric['unit'] = 'na' if metric['unit'].empty?
        output([config[:scheme], metric['unit'], metric['name']].join('.'), metric['value'])
      end
    end
    ok
  end
end


text:
'''
A hash based index
'''
# Import python libs
import struct
import os

# Import maras libs
import maras.utils

# Import third party libs
import msgpack

class HMapIndex(object):
    '''
    Hash index
    '''
    def __init__(
            self,
            name,
            dbpath,
            hash_limit=0xfffff,
            key_hash='sha1',
            header_len=1000):
        self.dbpath = dbpath
        self.path = os.path.join(dbpath, '{0}.index'.format(name))
        self.hash_limit = hash_limit
        self.key_hash, self.key_size = maras.utils.get_hash_data(key_hash)
        self.header = {'hlim': hash_limit,
                       'keyh': key_hash,
                       'ksz': self.key_size,
                       'nsz': 8}
        self.header_len = header_len
        self.h_delim = '_||_||_'
        self.fp = self.__open_index()
        self.h_bucket_fmt, self.h_bucket_size = self.__gen_bucket_fmt()

    def __gen_hbucket_fmt(self):
        '''
        Generate the hash bucket struct format based on the sizes in the
        header
        '''
        # Match msgpack big edian
        # hbucket format is:
        # key, data_location, next
        # key is length of the hash function
        # data_location and next are longs
        fmt = '>s{0}LL'.format(self.key_size)
        test_struct = struct.pack(fmt, maras.util.rand_hex_str(self.key_size), 0, 0)
        return fmt, len(test_struct)

    def __open_index(self):
        '''
        Auto create or open the index
        '''
        if not os.path.exists(self.path):
            return self.create()
        return self.open_index()

    def create(self):
        '''
        Create a new index
        '''
        if os.path.exists(self.path):
            raise ValueError('Index exists')
        fp_ = open(self.path, 'w+b')
        header = '{0}{1}'.format(msgpack.dumps(self.header), self.h_delim)
        fp_.write(header)
        return fp_

    def open_index(self):
        '''
        Open an existing index
        '''
        if not os.path.isfile(self.path):
            raise ValueError('No Index Exists')
        fp_ = open(self.path, 'rb')
        raw_head = fp_.read(self.header_len)
        self.header = msgpack.loads(raw_head[:raw_head.index(self.h_delim)])
        self.hash_limit = self.header['hlim']
        self.key_hash, self.key_size = maras.utils.get_hash_data(self.header['keyh'])
        fp_.seek(0)
        return fp_

    def _hash_position(self, key, first):
        '''
        Calculate the position of the hash based on the key and start location
        '''
        return abs(hash(key) & self.hash_limit) * self.h_bucket_size + first

    def _get_h_entry(self, pos):
        '''
        Return the unpacked tuple if it exists, else None
        '''
        self.fp.seek(pos)
        raw = self.fp.read(self.h_bucket_size)
        try:
            return struct.unpack(self.h_bucket_fmt, raw)
        except Exception:
            return None

    def _find_h_tail(self, rec_top, entry):
        '''
        Use the entry to find the end of the linked list of referenced h_refs
        '''
        while entry[2]:
            rec_top = entry[2]
            entry = self._get_entry(entry[2])
        return rec_top, entry

    def _write_h_entry(self, h_pos, key, id_, start, size, next_):
        '''
        Write the hash entry
        '''
        top = self._write_d_entry(id_, start, size)
        h_entry = struct.pack(self.h_bucket_fmt, key, top, next_)
        self.fp.seek(h_pos)
        self.fp.write(h_entry)

    def _write_collision(self, entry, h_pos, key, id_, start, size):
        '''
        '''
        top = self._write_d_entry(id_, start, size)
        # find the tail
        tail_pos, tail = self._find_h_tail(h_pos, entry)
        tail_entry = struct.pack(self.h_bucket_fmt, tail[0], tail[1], top)
        self.fp.seek(tail_pos)
        self.fp.write(tail_entry)
        self.fp.seek(0, 2)
        h_entry = struct.pack(self.h_bucket_fmt, key, top, 0)
        self.fp.write(h_entry)

    def _write_d_entry(self, id_, start, size):
        '''
        Write the data ref entry
        '''
        self.fp.seek(0, 2)
        if self.fp.tell() < self.header_len:
            self.fp.seek(self.header_len)
        top = self.fp.tell()
        self.fp.write(struct.pack(self.h_bucket_fmt, id_, start, size))
        return top

    def insert(self, key, id_, start, size):
        '''
        Insert the data into the specified location
        '''
        if not id_:
            id_ = maras.utils.rand_hex_str(self.key_size)
        h_pos = self._hash_position(key, self.header_len)
        entry = self._get_entry(h_pos)
        if entry is None:
            self._write_h_entry(h_pos, key, id_, start, size, 0)
        elif key != entry[0]:
            # hash_collision
            self._write_collision(entry, h_pos, key, id_, start, size)
        return True


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Videos on Dicas de Front End</title>
    <link>http://dicasdefrontend.com.br/tags/videos/</link>
    <description>Recent content in Videos on Dicas de Front End</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en</language>
    <lastBuildDate>Sun, 07 Sep 2014 00:00:00 +0000</lastBuildDate>

	<atom:link href="http://dicasdefrontend.com.br/tags/videos/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Dica #17</title>
      <link>http://dicasdefrontend.com.br/post/dica-17/</link>
      <pubDate>Sun, 07 Sep 2014 00:00:00 +0000</pubDate>

      <guid>http://dicasdefrontend.com.br/post/dica-17/</guid>
      <description>Novidades Segredos do Chrome DevTools #2 Saem 5 novos vídeos explorando as ferramentas do Chrome DevTools. Dicas valiosas e videos muito didáticos!
Artigos The book is on the table [8 min] Uma coletânea de livros feita pelo Vitor Britto para se aprender (e muito bem) Javascript.
Otimização de imagens [7 min] Dicas sobre como otimizar imagens para web, quais os melhores formatos e traz também uma lista de ferramentas úteis sobre o assunto.</description>
    </item>

    <item>
      <title>Dica #13</title>
      <link>http://dicasdefrontend.com.br/post/dica-13/</link>
      <pubDate>Mon, 28 Jul 2014 00:00:00 +0000</pubDate>

      <guid>http://dicasdefrontend.com.br/post/dica-13/</guid>
      <description>Novidades Segredos do Chrome Dev Tools Zeno Rocha fez uma série de videos com dicas sobre o DevTools do Google. Cada vídeo tem em média 6 minutos, são bastante úteis e didáticos!
Rolagem contínua em sites de notícias ajuda a conter taxa de rejeição Através da rolagem contínua de conteúdo os sites de notícia aumentaram a retenção dos usuários que caem no site via redes sociais.
Artigos Quanto vale 1 pixel?</description>
    </item>

    <item>
      <title>Dica #8</title>
      <link>http://dicasdefrontend.com.br/post/dica-8/</link>
      <pubDate>Mon, 16 Jun 2014 00:00:00 +0000</pubDate>

      <guid>http://dicasdefrontend.com.br/post/dica-8/</guid>
      <description>Novidades O software que inspirou o HTML foi finalmente lançado após 54 anos Conheça o OpenXanadu, projeto de hipertexto iniciado em 1960, bem antes da criação do HTML. Dá uma olhada nesse exemplo de um xanadoc.
Artigos (e guia) CSS on steroids [5 min] Aprenda algumas práticas para aprimorar seu código CSS e entenda as vantagens de se utilizar pré-processadores.
Wireframe, protótipo e mockup – Qual a diferença? [7 min] Você sabe distinguir essas três formas de representar um projeto?</description>
    </item>

  </channel>
</rss>


text:
require 'benchmark'
require 'rbconfig'

lib = File.expand_path('../../lib', __FILE__)

cext = "#{lib}/ffi_c.#{RbConfig::CONFIG['DLEXT']}"
if (RUBY_ENGINE == 'ruby' || RUBY_ENGINE == 'rbx') && !File.exist?(cext)
  abort "#{cext} is not compiled. Compile it with 'rake compile' first."
end

$LOAD_PATH.unshift(lib)
require 'ffi'

require_relative '../spec/ffi/fixtures/compile'

ITER = ENV['ITER'] ? ENV['ITER'].to_i : 100_000

LIBTEST_PATH = TestLibrary::PATH


text:
namespace CodingConnected.TraCI.NET
{
    internal class TraCICommand
    {
        public byte Identifier { get; set; }
        public byte[] Contents { get; set; }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/1/10
 * Time: 17:08
 */

namespace app\common\model;
use think\Model;

class User extends Model
{
    protected $table = 'user';

//    public function profile()
//    {
//        return $this->hasOne('Group','groupid');
//    }
}


text:
"""This code example runs a report that an upgraded publisher would use to
include statistics before the upgrade. To download the report run
download_report.py."""

__author__ = 'api.shamjeff@gmail.com (Jeff Sham)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..'))
import time

# Import appropriate classes from the client library.
from adspygoogle import DfpClient

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service.
report_service = client.GetService('ReportService', version='v201206')

# Create report job.
report_job = {
    'reportQuery': {
        'dimensions': ['ORDER'],
        'columns': ['MERGED_AD_SERVER_IMPRESSIONS', 'MERGED_AD_SERVER_CLICKS',
                    'MERGED_AD_SERVER_CTR',
                    'MERGED_AD_SERVER_CPM_AND_CPC_REVENUE',
                    'MERGED_AD_SERVER_AVERAGE_ECPM'],
        'dateRangeType': 'LAST_MONTH'
    }
}

# Run report.
report_job = report_service.RunReportJob(report_job)[0]

# Wait for report to complete.
status = report_job['reportJobStatus']
while status != 'COMPLETED' and status != 'FAILED':
  print 'Report job with \'%s\' id is still running.' % report_job['id']
  time.sleep(30)
  status = report_service.GetReportJob(report_job['id'])[0]['reportJobStatus']

if status == 'FAILED':
  print ('Report job with id \'%s\' failed to complete successfully.'
         % report_job['id'])
else:
  print 'Report job with id \'%s\' completed successfully.' % report_job['id']


text:
//
//  Document.h
//  Aspose_Cloud_SDK_For_iOS
//
//  Created by Muhammad Sohail Ismail on 11/15/14.
//  Copyright (c) 2014 Muhammad Sohail Ismail. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ASPOSEWConvertWebPageToWordDocumentResponse.h"
#import "ASPOSEWSplitDocumentResponse.h"
#import "ASPOSEWTrackingChangesResponse.h"
#import "ASPOSEWStatisticsOfDocumentResponse.h"

/**
 * Using 'ASPOSEWDocument' class you can append documents to source document, convert individual page to new format, accept/reject revisions in source document and get statistical data of the document.
 */
@interface ASPOSEWDocument : NSObject

/**
 Convert a Word document to images, multipage tiff, HTML, PDF and other file formats.

 @param fileName Name of the Word document on cloud
 @param designatedFormat A format to which word docuemnt will be converted
 @param outFileName Converted document will save on device with this name

 @return A path to converted word document
 */
+ (NSString *) convertWordDocumentOnCloudStorage:(NSString *) fileName toFileFormat:(NSString *) designatedFormat
                         andSaveOnDeviceWithName: (NSString *) outFileName;

/**
 Convert Word document that is locally stored on device to images, multipage tiff, HTML, PDF and other file formats.

 @param fileData File data
 @param designatedFormat A format to which word docuemnt will be converted
 @param outFileName Converted document will save on device with this name

 @return A path to converted word document
 */
+ (NSString *) convertWordDocumentOnDevice:(NSData *) fileData toFileFormat:(NSString *) designatedFormat
                           andSaveWithName: (NSString *) outFileName;

/**
 Convert a Word document to other formats with additional settings.

 @param fileName Name of the Word document on cloud.
 @param additionalOptionsInXMLFormat Additional settings in XML format.
 @param outFileName Converted document will save on disk with this name.

 @return A path to converted word document
 */
+ (NSString *) convertWordDocumentOnCloudStorage:(NSString *) fileName withAdditionalSettings:(NSString *) additionalOptionsInXMLFormat
                         andSaveOnDeviceWithName:(NSString *) outFileName;

/**
 Convert a live web page to Word document.

 @param webDocumentData  String that contains web document URL and save options.
 @param contentType Type of content. Can be either JSON or XML.

 @return An object that contains URL to word document
 */
+ (ASPOSEWSaveResult *) convertWebPagesToWordDocument:(NSString *) webDocumentData contentType:(NSString *) contentType;

/**
 Append a document or documents specified in the list to the original source document.

 @param appendDocs List of documents to append.
 @param fileName Name of the document to which documents will be appended.
 @param importFormatsModes Defines which formatting will be used: appended or destination document. Can be KeepSourceFormatting or UseDestinationStyles.

 @return BOOL variable indicates whether documents appended successfully
 */
+ (BOOL) appendListofDocuments:(NSArray *) appendDocs toSourceDocument:(NSString *) fileName
         withImportFormatModes:(NSArray *) importFormatsModes;

/**
 Split all pages to new PDFs.

 @param fileName Name of the Word document on cloud.

 @return An object that contains list of paths to new PDF files
 */
+ (ASPOSEWSplitResult *) splitAllPagesToNewPDFs:(NSString *) fileName;

/**
 Split specific pages to any supported format.

 @param fileName Name of the Word document on cloud.
 @param designatedFormat A format to which word document will be converted.
 @param fromPage The start page number for splitting.
 @param toPage The last page number for splitting.

 @return An object that contains list of paths to converted pages
 */
+ (ASPOSEWSplitResult *) splitSpecificPages:(NSString *) fileName toFormat:(NSString *) designatedFormat
                      fromPageNumber:(int) fromPage toPageNumber:(int) toPage;

/**
 Accept all revisions in source document.

 @param fileName Name of the Word document on cloud. Result of the operation will be saved to this source document.

 @return An object that contains URLs to updated source document
 */
+ (ASPOSEWTrackingChangesResult *) acceptAllTrackingChanges:(NSString *) fileName;

/**
 Accept all revisions in source document.

 @param fileName Name of the Word document on cloud
 @param outputFile Updated file save on device with this name.

 @return An object that contains URLs to source and destination document
 */
+ (ASPOSEWTrackingChangesResult *) acceptAllTrackingChanges:(NSString *) fileName andSaveAs:(NSString *)outputFile;

/**
 Reject all revisions in source document.

 @param fileName Name of the Word document stored on the cloud. Result of the operation will be saved to this source document.

 @return An object that contains URLs to updated source document
 */
+ (ASPOSEWTrackingChangesResult *) rejectAllTrackingChanges:(NSString *) fileName;

/**
 Reject all revisions in source document.

 @param fileName Name of the source Word document stored on the cloud
 @param outputFile Result name of the document after the operation.
 @return An object that contains URLs to source and destination document
 */
+ (ASPOSEWTrackingChangesResult *) rejectAllTrackingChanges:(NSString *) fileName andSaveAs:(NSString *)outputFile;

/**
 Get statistical data of the document like word and paragraph count.

 @param fileName Name of the Word document stored on cloud

 @return An object that contains stats of document as whole as well as of each page
 */
+ (ASPOSEWStatisticsOfDocumentResponse *) statisticsOfDocument: (NSString *) fileName;

/**
 Convert Word to images, multipage TIFF, HTML, PDF and other File Format using third party storage.

 @param fileName Name of the Word document stored on cloud.
 @param designatedFormat Format to convert.
 @param storageName Third party cloud storage name. For details please visit http://www.aspose.com/docs/display/totalcloud/How+to+Configure+3rd+Party+Cloud+Storages
 @param folderName If file is not at root folder (Optional)
 @param outFileName Converted file will save on device with this name.

 @return A path to converted word document saved on device
 */
+ (NSString *) convertWordDocumentToOtherFileFormatUsingThirdPartyStorage:(NSString *) fileName
                                                designatedFormat:(NSString *) designatedFormat
                                                storageName: (NSString *) storageName
                                                folderName: (NSString *) folderName
                                                andSaveOnDeviceWithName: (NSString *) outFileName;
@end


text:
/* eslint-disable no-console */
export function log(...args) {
  console.log(...args)
}

export function warn(...args) {
  console.warn(...args)
}

export function error(...args) {
  console.error(...args)
}


text:
package nl.ulso.magisto.io;

import java.nio.file.Path;

import static nl.ulso.magisto.io.Paths.createPath;

public class DummyPathEntry {

    private final Path path;
    private final long timestamp;

    private DummyPathEntry(Path path, long timestamp) {
        this.path = path;
        this.timestamp = timestamp;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        final DummyPathEntry that = (DummyPathEntry) o;
        return path.equals(that.path);
    }

    @Override
    public int hashCode() {
        return path.hashCode();
    }

    public static DummyPathEntry createPathEntry(String fileName) {
        return new DummyPathEntry(createPath(fileName), System.currentTimeMillis());
    }

    public static DummyPathEntry createPathEntry(Path path) {
        return new DummyPathEntry(createPath(path.getFileName().toString()), System.currentTimeMillis());
    }

    public static DummyPathEntry createPathEntry(String first, String... more) {
        return new DummyPathEntry(createPath(first, more), System.currentTimeMillis());
    }

    public Path getPath() {
        return path;
    }

    public long getTimestamp() {
        return timestamp;
    }
}


text:
// Template Source: BaseEntityCollectionRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.requests;

import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.DeviceAppManagement;
import com.microsoft.graph.models.AndroidManagedAppProtection;
import com.microsoft.graph.models.TargetedManagedAppPolicyAssignment;
import com.microsoft.graph.models.ManagedMobileApp;
import com.microsoft.graph.models.TargetedManagedAppGroupType;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

import com.microsoft.graph.requests.AndroidManagedAppProtectionCollectionRequestBuilder;
import com.microsoft.graph.requests.AndroidManagedAppProtectionRequestBuilder;
import com.microsoft.graph.requests.AndroidManagedAppProtectionCollectionRequest;
import com.microsoft.graph.http.BaseCollectionRequestBuilder;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.PrimitiveRequestBuilder;
import com.microsoft.graph.models.TargetedManagedAppProtectionAssignParameterSet;
import com.microsoft.graph.models.TargetedManagedAppProtectionTargetAppsParameterSet;
import com.microsoft.graph.models.ManagedAppProtectionTargetAppsParameterSet;
import com.microsoft.graph.models.ManagedAppPolicyTargetAppsParameterSet;
// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Android Managed App Protection Collection Request Builder.
 */
public class AndroidManagedAppProtectionCollectionRequestBuilder extends BaseCollectionRequestBuilder<AndroidManagedAppProtection, AndroidManagedAppProtectionRequestBuilder, AndroidManagedAppProtectionCollectionResponse, AndroidManagedAppProtectionCollectionPage, AndroidManagedAppProtectionCollectionRequest> {

    /**
     * The request builder for this collection of DeviceAppManagement
     *
     * @param requestUrl     the request URL
     * @param client         the service client
     * @param requestOptions the options for this request
     */
    public AndroidManagedAppProtectionCollectionRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
        super(requestUrl, client, requestOptions, AndroidManagedAppProtectionRequestBuilder.class, AndroidManagedAppProtectionCollectionRequest.class);
    }

    /**
     * Gets the raw count request for the collection
     * @return The raw count request for the collection
     */
    @Nonnull
    public PrimitiveRequestBuilder<Long> count() {
        return new PrimitiveRequestBuilder<Long>(getRequestUrlWithAdditionalSegment("$count"), getClient(), null, Long.class);
    }
}


text:
InsomniacProcessor is a [swarrot](https://github.com/swarrot/swarrot) processor.
The goal of this processor is to prevent the consumer from sleeping once
the queue is empty, which will stop the consumer.


text:
@extends('bootstrap.layouts.master')

@section('page-title')
    {{ $role->present()->fullName }}
@endsection

@section('content-title')
    {{ $role->present()->fullName }}
@endsection

@section('content')

        {!! Form::open(array('route' => array('admin.roles.show', $role->id), 'method' => 'delete')) !!}
            {!! HTML::iconRoute('admin.roles.edit', Translate::recursive('common.edit'), 'edit', array($role->id), array('class' => 'btn btn-outline-secondary')) !!}
            {!! Form::iconSubmit(Translate::recursive('common.delete'), 'trash-alt', array('class' => 'btn btn-danger')) !!}
        {!! Form:: close() !!}

{{ Translate::recursive('models.user.plural') }}

                        ID
                        {{ Translate::recursive('members.name') }}

                    @foreach( $role->users as $user )

                            {{ $user->id }}
                            {!! HTML::linkRoute('admin.users.show', $user->present()->fullName, array($user->id)) !!}

                    @endforeach

@endsection


text:
package com.mead.android.crazymonkey.sdk;

public enum Tool {
    AAPT("aapt", ".exe", new PlatformToolLocator()),
    ADB("adb", ".exe", new PlatformToolLocator()),
    ANDROID("android", ".bat"),
    EMULATOR("emulator", ".exe"),
    EMULATOR_ARM("emulator-arm", ".exe"),
    EMULATOR_MIPS("emulator-mips", ".exe"),
    EMULATOR_X86("emulator-x86", ".exe"),
    EMULATOR64_ARM("emulator64-arm", ".exe"),
    EMULATOR64_MIPS("emulator64-mips", ".exe"),
    EMULATOR64_X86("emulator64-x86", ".exe"),
    MKSDCARD("mksdcard", ".exe");

    public static Tool[] EMULATORS = new Tool[] { EMULATOR,
           EMULATOR_ARM,   EMULATOR_MIPS,   EMULATOR_X86,
           EMULATOR64_ARM, EMULATOR64_MIPS, EMULATOR64_X86
    };

    public static Tool[] REQUIRED = new Tool[] {
        AAPT, ADB, ANDROID, EMULATOR
    };

    public final String executable;
    public final String windowsExtension;
    public final ToolLocator toolLocator;
    Tool(String executable, String windowsExtension) {
        this(executable, windowsExtension, new DefaultToolLocator());
    }

    Tool(String executable, String windowsExtension, ToolLocator toolLocator) {
        this.executable = executable;
        this.windowsExtension = windowsExtension;
        this.toolLocator = toolLocator;
    }

    public String getExecutable(boolean isUnix) {
        if (isUnix) {
            return executable;
        }
        return executable + windowsExtension;
    }

    public String findInSdk(AndroidSdk androidSdk) throws SdkInstallationException {
        return toolLocator.findInSdk(androidSdk, this);
    }

    public static String[] getAllExecutableVariants() {
        return getAllExecutableVariants(values());
    }

    public static String[] getAllExecutableVariants(final Tool[] tools) {
        String[] executables = new String[tools.length * 2];
        for (int i = 0, n = tools.length; i < n; i++) {
            executables[i*2] = tools[i].getExecutable(true);
            executables[i*2+1] = tools[i].getExecutable(false);
        }

        return executables;
    }

    @Override
    public String toString() {
        return executable;
    }
}


text:
module.exports = function(config){
    config.set({
    basePath : '../',

    files : [
//      'app/lib/angular/angular.js',
//      'app/lib/angular/angular-*.js',
			'../../web/bundles/frontend/lib/angular/angular.js',
			'../../web/bundles/frontend/lib/angular/angular-*.js',
      '../../web/bundles/frontend/js/**/*.js',
      'test/lib/angular/angular-mocks.js',
      'test/unit/**/*.js'
    ],

    exclude : [
      'app/lib/angular/angular-loader.js',
      'app/lib/angular/*.min.js',
      'app/lib/angular/angular-scenario.js'
    ],

    autoWatch : true,

    frameworks: ['jasmine'],

    browsers : ['Chrome'],

    plugins : [
            'karma-junit-reporter',
            'karma-chrome-launcher',
            'karma-firefox-launcher',
            'karma-jasmine'
            ],

    junitReporter : {
      outputFile: 'test_out/unit.xml',
      suite: 'unit'
    }

})}


text:
=pod

=head1 NAME

RC4_set_key, RC4 - RC4 encryption

=head1 SYNOPSIS

 #include <openssl/rc4.h>

 void RC4_set_key(RC4_KEY *key, int len, const unsigned char *data);

 void RC4(RC4_KEY *key, unsigned long len, const unsigned char *indata,
          unsigned char *outdata);

=head1 DESCRIPTION

This library implements the Alleged RC4 cipher, which is described for
example in I<Applied Cryptography>.  It is believed to be compatible
with RC4[TM], a proprietary cipher of RSA Security Inc.

RC4 is a stream cipher with variable key length.  Typically, 128 bit
(16 byte) keys are used for strong encryption, but shorter insecure
key sizes have been widely used due to export restrictions.

RC4 consists of a key setup phase and the actual encryption or
decryption phase.

RC4_set_key() sets up the B<RC4_KEY> B<key> using the B<len> bytes long
key at B<data>.

RC4() encrypts or decrypts the B<len> bytes of data at B<indata> using
B<key> and places the result at B<outdata>.  Repeated RC4() calls with
the same B<key> yield a continuous key stream.

Since RC4 is a stream cipher (the input is XORed with a pseudo-random
key stream to produce the output), decryption uses the same function
calls as encryption.

=head1 RETURN VALUES

RC4_set_key() and RC4() do not return values.

=head1 NOTE

Applications should use the higher level functions
L<EVP_EncryptInit(3)> etc. instead of calling these
functions directly.

It is difficult to securely use stream ciphers. For example, do not perform
multiple encryptions using the same key stream.

=head1 SEE ALSO

L<EVP_EncryptInit(3)>

=head1 COPYRIGHT

Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.

Licensed under the OpenSSL license (the "License").  You may not use
this file except in compliance with the License.  You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.

=cut


text:
<?xml version="1.0" encoding="UTF-8"?>
<actions>
        <action>
            <actionName>CUSTOM-tomcat:run -Dmaven.tomcat.port=8282</actionName>
            <displayName>tomcat:run -Dmaven.tomcat.port=8282</displayName>
            <goals>
                <goal>tomcat:run</goal>
                <goal>-Dmaven.tomcat.port=8282</goal>
            </goals>
        </action>
        <action>
            <actionName>CUSTOM-clean install tomcat7:run -Dmaven.tomcat.port=8282</actionName>
            <displayName>clean install tomcat7:run -Dmaven.tomcat.port=8282</displayName>
            <goals>
                <goal>clean</goal>
                <goal>install</goal>
                <goal>tomcat7:run</goal>
                <goal>-Dmaven.tomcat.port=8282</goal>
            </goals>
        </action>
    </actions>


text:
import os
import unittest
import zipimport

from iptest import IronPythonTestCase, path_modifier, run_test, stdout_trapper, is_netcoreapp

class ZipImportTest(IronPythonTestCase):

    @unittest.skipIf(is_netcoreapp, "TODO: figure out")
    def test_encoded_module(self):
        """https://github.com/IronLanguages/ironpython2/issues/129"""
        with path_modifier(os.path.join(self.test_dir, 'gh129.zip')):
            import something
            self.assertEqual(something.test(), u'\u041f\u0440\u0438\u0432\u0435\u0442 \u043c\u0438\u0440!')

    def test_zipimport_str(self):
        self.assertEqual(str(zipimport.ZipImportError("test")), "test")

run_test(__name__)


text:
import { parse } from 'qs';
import { create, remove, update, query, getRoleForEdit, createOrUpdateRole } from './service';
import { feedback, urls } from '../../../utils';

export default {

  namespace: 'roles',
  state: {
    list: [],
    loading: false,
    currentItem: {},
    modalVisible: false,
    modalType: 'create',
    pagination: {
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条`,
      current: 1,
      total: null,
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === urls.common.roles) {
          dispatch({
            type: 'query',
            payload: location.query,
          });
        }
      });
    },
  },

  effects: {
    *query({ payload }, { call, put }) {
      yield put({ type: 'showLoading' });
      const { data } = yield call(query, parse(payload));
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.result.items,
            pagination: {
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: total => `共 ${total} 条`,
              total: data.result.totalCount,
              current: 0,
            },
          },
        });
      }
    },
    *getRoleForEdit({ payload }, { call, put }) {
      yield put({ type: 'showLoading' });
      const { data } = yield call(getRoleForEdit, parse(payload));
      if (data.success) {
        yield put({
          type: 'showModal',
          payload: {
            modalType: 'update',
            currentItem: data.result,
          },
        });
      }
    },
    *createOrUpdateRole({ payload }, { call, put }) {
      const { data } = yield call(createOrUpdateRole, parse(payload));
      if (data.success) {
        feedback.message.success('保存成功');
        yield put({ type: 'hideModal' });
        yield put({ type: 'query' });
      } else {
        feedback.message.error('保存失败');
      }
    },
    *delete({ payload }, { call, put }) {
      yield put({ type: 'showLoading' });
      const { data } = yield call(remove, { id: payload });
      if (data && data.success) {
        feedback.message.success('删除成功');
        yield put({ type: 'query' });
      } else {
        feedback.message.error('删除失败');
      }
    },
    *create({ payload }, { call, put }) {
      yield put({ type: 'hideModal' });
      yield put({ type: 'showLoading' });
      const { data } = yield call(create, payload);
      if (data && data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data,
            pagination: {
              total: data.page.total,
              current: data.page.current,
            },
          },
        });
      }
    },
    *update({ payload }, { select, call, put }) {
      yield put({ type: 'hideModal' });
      yield put({ type: 'showLoading' });
      const id = yield select(({ roles }) => roles.currentItem.id);
      const newRole = { ...payload, id };
      const { data } = yield call(update, newRole);
      if (data && data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data,
            pagination: {
              total: data.page.total,
              current: data.page.current,
            },
          },
        });
      }
    },
  },
  reducers: {
    showLoading(state) {
      return { ...state, loading: true };
    },
    querySuccess(state, action) {
      return { ...state, ...action.payload, loading: false };
    },
    showModal(state, action) {
      return { ...state, ...action.payload, modalVisible: true, loading: false };
    },
    hideModal(state) {
      return { ...state, modalVisible: false };
    },
    message(state) {
      return { ...state };
    },
  },

};


text:
package persistence.metadata.model;

public class KunderaMetadata {
	private CoreMetadata coreMetadata;
	private ApplicationMetadata applicationMetadata;

	private static KunderaMetadata INSTANCE = new KunderaMetadata();

	private KunderaMetadata() {
		// update should be made later, use Configurator to set values in the
		// KunderarMetadata
		// init the configurator in application listener
		getApplicationMetadata();
		getCoreMetadata();

	}

	public static synchronized KunderaMetadata getInstance() {
		return INSTANCE;
	}

	public ApplicationMetadata getApplicationMetadata() {
		if (this.applicationMetadata == null) {
			this.applicationMetadata = new ApplicationMetadata();
		}
		return this.applicationMetadata;
	}

	public void setApplicationMetadata(ApplicationMetadata applicationMetadata) {
		this.applicationMetadata = applicationMetadata;
	}

	public CoreMetadata getCoreMetadata() {
		if (this.coreMetadata == null) {
			this.coreMetadata = new CoreMetadata();
		}
		return this.coreMetadata;
	}

	public void setCoreMetadata(CoreMetadata coreMetadata) {
		this.coreMetadata = coreMetadata;
	}

}


text:
require 'helper'
require 'sower/node'
class TestNode < Test::Unit::TestCase
  def setup
    assert(@node = Sower::Node.new('my_identity'))
  end

  context "A Node instance" do
    should "respond to identity" do
      assert_respond_to @node, :identity
    end

    should "respond to edges" do
      assert_respond_to @node, :edges
    end

    should "return a Array of Edge when sent #edges" do
      graph = Sower::Graph.new
      tail = Sower::Node.new('tail')
      head = Sower::Node.new('head')
      other_tail = Sower::Node.new('other_tail')
      graph.add_nodes @node, tail, head, other_tail
      graph.add_edge(tail,head)
      graph.add_edge(other_tail,tail)
      assert_instance_of Array, tail.edges(graph, :head)
      assert_equal [], @node.edges(graph,:both)
      assert_equal [], @node.edges(graph,:tail)
      assert_equal [], @node.edges(graph,:head)
      assert_equal [Sower::Edge.new(tail,head)],tail.edges(graph, :head)
      assert_equal [Sower::Edge.new(other_tail,tail)],tail.edges(graph,:tail)
      assert_equal [Sower::Edge.new(tail,head), Sower::Edge.new(other_tail,tail)],tail.edges(graph)
      assert_equal [Sower::Edge.new(tail,head), Sower::Edge.new(other_tail,tail)],tail.edges(graph,:both)
    end

    should "respond to []" do
      assert_respond_to @node, :[]
      assert_instance_of Sower::Relation::Attribute, @node[:id]
    end

    should "respond to statement" do
      assert_respond_to @node, :statement
    end

  end

  context "Node class" do
    should "respond to ident" do
      assert_respond_to Sower::Node, :ident
    end

    should "return identity when sent #ident" do
      assert_equal "creations", Sower::Node.ident('creations')
      assert_equal "creations", Sower::Node.ident(:identity => 'creations')
      assert_equal "my_identity", Sower::Node.ident(@node)
    end

    should "raise ArgumentError when sent #ident with disallowed argument" do
      assert_raise ArgumentError do
        Sower::Node.ident(Object.new)
      end
    end

  end
end


text:
title: Data Berita PILKADA Surabaya
organization: KPU KOTA SURABAYA
notes: Data Berita PILKADA Surabaya
resources:
  - name: CSV News
    url: 'https://github.com/pemiluAPI/pemilu-data/raw/master/berita-pilkada-surabaya/news.csv'
    format: csv
  - name: CSV Resources
    url: 'https://github.com/pemiluAPI/pemilu-data/raw/master/berita-pilkada-surabaya/resources.csv'
    format: csv
category:
  - Berita PILKADA Surabaya
maintainer: ''
maintainer_email: ''
---


text:
<?xml version="1.0"?>
<!--

-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <attribute name="class" value="emizen_brand_view"/>
        <referenceContainer name="content">
            <block class="Emizentech\ShopByBrand\Block\View" name="brand.view"  template="Emizentech_ShopByBrand::emizen_brand/view.phtml" cacheable="false">
             </block>
        </referenceContainer>
    </body>
</page>


text:
package net.sf.kraken.protocols.oscar;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

import net.kano.joscar.ByteBlock;
import net.kano.joscar.flap.FlapPacketEvent;
import net.kano.joscar.flapcmd.SnacCommand;
import net.kano.joscar.net.ClientConnEvent;
import net.kano.joscar.net.ConnDescriptor;
import net.kano.joscar.snac.SnacPacketEvent;
import net.kano.joscar.snaccmd.conn.ClientVersionsCmd;
import net.kano.joscar.snaccmd.conn.ConnCommand;
import net.kano.joscar.snaccmd.conn.RateInfoRequest;
import net.kano.joscar.snaccmd.conn.ServerReadyCmd;
import net.kano.joscar.snaccmd.conn.SnacFamilyInfo;
import net.kano.joscar.snaccmd.mailcheck.ActivateMailCmd;
import net.kano.joscar.snaccmd.mailcheck.MailCheckCmd;
import net.kano.joscar.snaccmd.mailcheck.MailStatusRequest;
import net.kano.joscar.snaccmd.mailcheck.MailUpdate;

import org.slf4j.*;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.LocaleUtils;
import org.xmpp.packet.Message;

/**
 * @author Daniel Henninger
 */
public class EmailConnection extends ServiceConnection {

    static Logger Log = LoggerFactory.getLogger(EmailConnection.class);

    private Integer lastMailCount = 0;

    public EmailConnection(ConnDescriptor cd, OSCARSession mainSession, ByteBlock cookie, int serviceFamily) {
        super(cd, mainSession, cookie, serviceFamily);
        this.serviceFamily = serviceFamily;
    }

    @Override
    protected void handleStateChange(ClientConnEvent e) {
        Log.debug("OSCAR email service state change from "+e.getOldState()+" to "+e.getNewState());
    }

    @Override
    protected void handleFlapPacket(FlapPacketEvent e) {
//        Log.debug("OSCAR email flap packet received: "+e);
        super.handleFlapPacket(e);
    }

    @Override
    protected void clientReady() {
        super.clientReady();
        request(new MailStatusRequest());
        request(new ActivateMailCmd());
        startKeepAlive();
    }

    @Override
    protected void handleSnacPacket(SnacPacketEvent e) {
//        Log.debug("OSCAR email snac packet received: "+e);

        SnacCommand cmd = e.getSnacCommand();

        if (cmd instanceof ServerReadyCmd) {
            ServerReadyCmd src = (ServerReadyCmd) cmd;
            setSnacFamilies(src.getSnacFamilies());

            Collection<SnacFamilyInfo> familyInfos = new ArrayList<SnacFamilyInfo>();
            familyInfos.add(ConnCommand.FAMILY_INFO);
            familyInfos.add(MailCheckCmd.FAMILY_INFO);
            setSnacFamilyInfos(familyInfos);

            getMainSession().registerSnacFamilies(this);

            request(new ClientVersionsCmd(familyInfos));
            request(new RateInfoRequest());
        }
        else if (cmd instanceof MailUpdate) {
            MailUpdate mu = (MailUpdate)cmd;
            if (JiveGlobals.getBooleanProperty("plugin.gateway."+getMainSession().getTransport().getType()+".mailnotifications", true) && lastMailCount < mu.getUnreadCount()) {
                Integer diff = mu.getUnreadCount() - lastMailCount;
                if (diff > 0) {
                    getMainSession().getTransport().sendMessage(
                            getMainSession().getJID(),
                            getMainSession().getTransport().getJID(),
                            LocaleUtils.getLocalizedString("gateway.oscar.mail", "kraken", Arrays.asList(Integer.toString(diff), mu.getDomain(), mu.getUrl())),
                            Message.Type.headline
                    );
                }
            }
            lastMailCount = mu.getUnreadCount();
        }
        else {
            super.handleSnacPacket(e);
        }
    }

}


text:
//
//  MKCollectionViewCell.m
//  pagePeekingCollectionView
//
//  Created by Mayank Kumar on 4/2/14.
//  Copyright (c) 2014 Mayank. All rights reserved.
//

#import "MKCollectionViewCell.h"

@implementation MKCollectionViewCell

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    	<title>alexander lew | transportation planner – MBTA</title>

<link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet">
<link rel="stylesheet" href="css/leaflet.css">
    <link rel="stylesheet" href="../../css/bootstrap.min.css">
    <link rel="stylesheet" href="../../css/style.css">
     <link rel="stylesheet" href="css/style.css">

Alexander Lew | Transportation Planner

Home

About

MBTA Trains in Operation

      This map was a project for CS 50: Introduction to Computer Science and one of my first projects in Javascript.
      The map uses the MBTA real time API to show the geographic location of each train in operation as well as
      the train's destination. The map updates the train's location every 15 seconds.

      This project was originally built on MBTA API v2, which has since been deprecated for real-time predictions and vehicle positions. This has since been updated to use MBTA's latest V3 API.


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.6/handlebars.min.js">
  </script>
  <script id="data-template" type="text/x-handlebars-template">
    {{Hello world}}
  </script>
  <title>Document</title>
</head>
<body>
  <section id="handlebars">
  </section>
</body>
</html>


text:
<?php

namespace Magento\Config\Test\Unit\Block\System\Config\Form;

class FieldsetTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Config\Block\System\Config\Form\Fieldset
     */
    protected $_object;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $_elementMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $_requestMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $_urlModelMock;

    /**
     * @var array
     */
    protected $testData = [
        'htmlId' => 'test_field_id',
        'name' => 'test_name',
        'label' => 'test_label',
        'elementHTML' => 'test_html',
        'legend' => 'test_legend',
        'comment' => 'test_comment',
        'tooltip'     => 'test_tooltip',
    ];

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $_layoutMock;

    /**
     * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager
     */
    protected $_testHelper;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $_helperMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $authSessionMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $userMock;

    /**
     * @return void
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    protected function setUp()
    {
        $this->authSessionMock = $this->getMockBuilder('Magento\Backend\Model\Auth\Session')
            ->setMethods(['getUser'])
            ->disableOriginalConstructor()
            ->getMock();

        $this->userMock = $this->getMockBuilder('Magento\User\Model\User')
            ->setMethods(['getExtra'])
            ->disableOriginalConstructor()
            ->getMock();

        $this->authSessionMock->expects($this->any())
            ->method('getUser')
            ->willReturn($this->userMock);

        $this->_requestMock = $this->getMockBuilder('Magento\Framework\App\RequestInterface')
            ->disableOriginalConstructor()
            ->getMock();
        $this->_requestMock->expects($this->any())
            ->method('getParam')
            ->willReturn('Test Param');
        $this->_urlModelMock = $this->getMock('Magento\Backend\Model\Url', [], [], '', false, false);
        $this->_layoutMock = $this->getMock('Magento\Framework\View\Layout', [], [], '', false, false);
        $groupMock = $this->getMock(
            'Magento\Config\Model\Config\Structure\Element\Group',
            [],
            [],
            '',
            false
        );
        $groupMock->expects($this->any())->method('getFieldsetCss')->will($this->returnValue('test_fieldset_css'));

        $this->_helperMock = $this->getMock('Magento\Framework\View\Helper\Js', [], [], '', false, false);

        $data = [
            'request' => $this->_requestMock,
            'authSession' => $this->authSessionMock,
            'urlBuilder' => $this->_urlModelMock,
            'layout' => $this->_layoutMock,
            'jsHelper' => $this->_helperMock,
            'data' => ['group' => $groupMock],
        ];
        $this->_testHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        $this->_object = $this->_testHelper->getObject('Magento\Config\Block\System\Config\Form\Fieldset', $data);

        $this->_elementMock = $this->getMock(
            'Magento\Framework\Data\Form\Element\Text',
            [
                'getId',
                'getHtmlId',
                'getName',
                'getElements',
                'getLegend',
                'getComment',
                'getIsNested',
                'getExpanded',
                'getForm'
            ],
            [],
            '',
            false,
            false,
            true
        );

        $this->_elementMock->expects($this->any())
            ->method('getId')
            ->will($this->returnValue($this->testData['htmlId']));
        $this->_elementMock->expects($this->any())
            ->method('getHtmlId')
            ->will($this->returnValue($this->testData['htmlId']));
        $this->_elementMock->expects($this->any())
            ->method('getName')
            ->will($this->returnValue($this->testData['name']));
        $this->_elementMock->expects($this->any())
            ->method('getLegend')
            ->will($this->returnValue($this->testData['legend']));
        $this->_elementMock->expects($this->any())
            ->method('getComment')
            ->will($this->returnValue($this->testData['comment']));
    }

    /**
     * @param $expanded
     * @param $nested
     * @param extra
     * @dataProvider testRenderWithoutStoredElementsDataProvider
     */
    public function testRenderWithoutStoredElements($expanded, $nested, $extra)
    {
        $this->userMock->expects($this->any())->method('getExtra')->willReturn($extra);
        $collection = $this->_testHelper->getObject('Magento\Framework\Data\Form\Element\Collection');
        $formMock = $this->getMock('Magento\Framework\Data\Form', [], [], '', false);
        $this->_elementMock->expects($this->any())->method('getForm')->willReturn($formMock);
        $formMock->expects($this->any())->method('getElements')->willReturn($collection);
        $this->_elementMock->expects($this->any())->method('getElements')->will($this->returnValue($collection));
        $this->_elementMock->expects($this->any())->method('getIsNested')->will($this->returnValue($nested));
        $this->_elementMock->expects($this->any())->method('getExpanded')->will($this->returnValue($expanded));
        $actualHtml = $this->_object->render($this->_elementMock);
        $this->assertContains($this->testData['htmlId'], $actualHtml);
        $this->assertContains($this->testData['legend'], $actualHtml);
        $this->assertContains($this->testData['comment'], $actualHtml);
        if ($nested) {
            $this->assertContains('nested', $actualHtml);
        }
    }

    /**
     * @param $expanded
     * @param $nested
     * @param $extra
     * @dataProvider testRenderWithStoredElementsDataProvider
     */
    public function testRenderWithStoredElements($expanded, $nested, $extra)
    {
        $this->userMock->expects($this->any())->method('getExtra')->willReturn($extra);
        $this->_helperMock->expects($this->any())->method('getScript')->will($this->returnArgument(0));
        $fieldMock = $this->getMockBuilder('Magento\Framework\Data\Form\Element\Text')
            ->setMethods(['getId', 'getTooltip', 'toHtml', 'getHtmlId', 'getIsNested', 'getExpanded'])
            ->disableOriginalConstructor()
            ->getMock();
        $fieldMock->expects($this->any())->method('getId')->will($this->returnValue('test_field_id'));
        $fieldMock->expects($this->any())->method('getTooltip')->will($this->returnValue('test_field_tootip'));
        $fieldMock->expects($this->any())->method('toHtml')->will($this->returnValue('test_field_toHTML'));
        $fieldMock->expects($this->any())->method('getHtmlId')->willReturn('test_field_HTML_id');

        $fieldSetMock = $this->getMockBuilder('Magento\Framework\Data\Form\Element\Fieldset')
            ->setMethods(['getId', 'getTooltip', 'toHtml', 'getHtmlId', 'getIsNested', 'getExpanded'])
            ->disableOriginalConstructor()
            ->getMock();
        $fieldSetMock->expects($this->any())->method('getId')->will($this->returnValue('test_fieldset_id'));
        $fieldSetMock->expects($this->any())->method('getTooltip')->will($this->returnValue('test_fieldset_tootip'));
        $fieldSetMock->expects($this->any())->method('toHtml')->will($this->returnValue('test_fieldset_toHTML'));
        $fieldSetMock->expects($this->any())->method('getHtmlId')->willReturn('test_fieldset_HTML_id');

        $factory = $this->getMock('Magento\Framework\Data\Form\Element\Factory', [], [], '', false);

        $factoryColl = $this->getMock(
            'Magento\Framework\Data\Form\Element\CollectionFactory',
            [],
            [],
            '',
            false
        );

        $formMock = $this->getMock('Magento\Framework\Data\Form\AbstractForm', [], [$factory, $factoryColl]);

        $collection = $this->_testHelper->getObject(
            'Magento\Framework\Data\Form\Element\Collection',
            ['container' => $formMock]
        );
        $collection->add($fieldMock);
        $collection->add($fieldSetMock);
        $formMock = $this->getMock('Magento\Framework\Data\Form', [], [], '', false);
        $this->_elementMock->expects($this->any())->method('getForm')->willReturn($formMock);
        $formMock->expects($this->any())->method('getElements')->willReturn($collection);
        $this->_elementMock->expects($this->any())->method('getElements')->will($this->returnValue($collection));
        $this->_elementMock->expects($this->any())->method('getIsNested')->will($this->returnValue($nested));
        $this->_elementMock->expects($this->any())->method('getExpanded')->will($this->returnValue($expanded));

        $actual = $this->_object->render($this->_elementMock);

        $this->assertContains('test_field_toHTML', $actual);

        $expected = '
test_field_tootip
';
        $this->assertContains($expected, $actual);
        if ($nested) {
            $this->assertContains('nested', $actual);
        }
    }

    /**
     * @return array
     */
    public function testRenderWithoutStoredElementsDataProvider()
    {
        return $this->dataProvider();
    }

    /**
     * @return array
     */
    public function testRenderWithStoredElementsDataProvider()
    {
        return $this->dataProvider();
    }

    /**
     * @return array
     */
    protected function dataProvider()
    {
        return [
            'expandedNestedExtra' => [
                'expanded' => true,
                'nested'   => true,
                'extra'    => [],
            ],
            'collapsedNotNestedExtra' => [
                'expanded' => false,
                'nested'   => false,
                'extra'    => ['configState' => [$this->testData['htmlId'] => true]],
            ],
            'collapsedNotNestedNoExtra' => [
                'expanded' => true,
                'nested'   => false,
                'extra'    => [],
            ],
        ];
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     이 코드는 도구를 사용하여 생성되었습니다.
//     런타임 버전:4.0.30319.34014
//
//     파일 내용을 변경하면 잘못된 동작이 발생할 수 있으며, 코드를 다시 생성하면
//     이러한 변경 내용이 손실됩니다.
// </auto-generated>
//------------------------------------------------------------------------------

namespace BIT.Properties {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Control, F")]
        public global::Shortcut.Hotkey Key_0 {
            get {
                return ((global::Shortcut.Hotkey)(this["Key_0"]));
            }
            set {
                this["Key_0"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Control, C")]
        public global::Shortcut.Hotkey Key_1 {
            get {
                return ((global::Shortcut.Hotkey)(this["Key_1"]));
            }
            set {
                this["Key_1"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Control, V")]
        public global::Shortcut.Hotkey Key_2 {
            get {
                return ((global::Shortcut.Hotkey)(this["Key_2"]));
            }
            set {
                this["Key_2"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Control, B")]
        public global::Shortcut.Hotkey Key_3 {
            get {
                return ((global::Shortcut.Hotkey)(this["Key_3"]));
            }
            set {
                this["Key_3"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Control, N")]
        public global::Shortcut.Hotkey Key_4 {
            get {
                return ((global::Shortcut.Hotkey)(this["Key_4"]));
            }
            set {
                this["Key_4"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Control, H")]
        public global::Shortcut.Hotkey Key_5 {
            get {
                return ((global::Shortcut.Hotkey)(this["Key_5"]));
            }
            set {
                this["Key_5"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Control, T")]
        public global::Shortcut.Hotkey Key_6 {
            get {
                return ((global::Shortcut.Hotkey)(this["Key_6"]));
            }
            set {
                this["Key_6"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Control, G")]
        public global::Shortcut.Hotkey Key_7 {
            get {
                return ((global::Shortcut.Hotkey)(this["Key_7"]));
            }
            set {
                this["Key_7"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Control, V")]
        public global::Shortcut.Hotkey Key_8 {
            get {
                return ((global::Shortcut.Hotkey)(this["Key_8"]));
            }
            set {
                this["Key_8"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string Leap_0 {
            get {
                return ((string)(this["Leap_0"]));
            }
            set {
                this["Leap_0"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string Leap_1 {
            get {
                return ((string)(this["Leap_1"]));
            }
            set {
                this["Leap_1"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string Leap_2 {
            get {
                return ((string)(this["Leap_2"]));
            }
            set {
                this["Leap_2"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string Leap_3 {
            get {
                return ((string)(this["Leap_3"]));
            }
            set {
                this["Leap_3"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string Myo_0 {
            get {
                return ((string)(this["Myo_0"]));
            }
            set {
                this["Myo_0"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string Myo_1 {
            get {
                return ((string)(this["Myo_1"]));
            }
            set {
                this["Myo_1"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string Myo_2 {
            get {
                return ((string)(this["Myo_2"]));
            }
            set {
                this["Myo_2"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string Myo_3 {
            get {
                return ((string)(this["Myo_3"]));
            }
            set {
                this["Myo_3"] = value;
            }
        }
    }
}


text:
{% load staticfiles %}

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">


text:
<resources>
    <string name="app_name">BaiduLbs</string>

    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>

    <string name="action_settings">Settings</string>
</resources>


text:
var jsonrpc = require('../lib/index');
var HttpTransport = jsonrpc.transports.server.http;
var TcpTransport = jsonrpc.transports.server.tcp;
var shared = require('../lib/transports/shared/tcp');
var JSONRPCserver = jsonrpc.server;
var ErrorCode = jsonrpc.errorcode;
var http = require('http');
var net = require('net');

exports.loopbackHttp = function(test) {
    test.expect(3);
    var jsonRpcServer = new JSONRPCserver(new HttpTransport(98765), {
        loopback: function(arg1, callback) {
            callback(null, arg1);
        }
    });
    var testJSON = JSON.stringify({
        id: 1,
        method: 'loopback',
        params: [{ hello: 'world' }]
    });
    var req = http.request({
        hostname: 'localhost',
        port: 98765,
        path: '/',
        method: 'POST'
    }, function(res) {
        res.setEncoding('utf8');
        var resultString = '';
        res.on('data', function(data) {
            resultString += data;
        });
        res.on('end', function() {
            test.equal(200, res.statusCode, 'The http transport provided an OK status code');
            var resultObj;
            try {
                resultObj = JSON.parse(resultString);
            } catch(e) {
                // Do nothing, test will fail
            }
            test.equal(resultObj.id, 1, 'The JSON-RPC server sent back the same ID');
            test.equal(resultObj.result.hello, 'world', 'The loopback method worked as expected');
            test.done();
            jsonRpcServer.transport.server.close();
        });
    });
    req.write(testJSON);
    req.end();
};

exports.loopbackHttpBatch = function(test) {
    test.expect(8);
    var jsonRpcServer = new JSONRPCserver(new HttpTransport(98123), {
        loopback: function(arg1, callback) {
            callback(null, arg1);
        }
    });
    var testJSON = JSON.stringify([
        {
            id: 1,
            method: 'loopback',
            params: [{ hello: 'world' }]
        },
        {
            id: 2,
            method: 'noexists',
            params: [{ hello: 'world' }]
        },
        {
            id: 3,
            method: 'loopback',
            params: [{ hello: 'batch world' }]
        }
    ]);
    var req = http.request({
        hostname: 'localhost',
        port: 98123,
        path: '/',
        method: 'POST'
    }, function(res) {
        res.setEncoding('utf8');
        var resultString = '';
        res.on('data', function(data) {
            resultString += data;
        });
        res.on('end', function() {
            test.equal(200, res.statusCode, 'The http transport provided an OK status code');
            var resultObj;
            try {
                resultObj = JSON.parse(resultString);
            } catch(e) {
                // Do nothing, test will fail
            }
            test.equal(Array.isArray(resultObj), true, 'The batch response is array');
            var obj;
            {
                obj = resultObj[0];
                test.equal(obj.id, 1, 'The JSON-RPC server sent back the same ID');
                test.equal(obj.result.hello, 'world', 'The loopback method worked as expected');
            }
            {
                obj = resultObj[1];
                test.equal(obj.id, 2, 'The JSON-RPC server sent back the same ID');
                test.equal(obj.error.code, -32601, 'The method is not found');
            }
            {
                obj = resultObj[2];
                test.equal(obj.id, 3, 'The JSON-RPC server sent back the same ID');
                test.equal(obj.result.hello, 'batch world', 'The loopback method worked as expected');
            }
            test.done();
            jsonRpcServer.transport.server.close();
        });
    });
    req.write(testJSON);
    req.end();
};

exports.failureTcp = function(test) {
    test.expect(2);
    var jsonRpcServer = new JSONRPCserver(new TcpTransport(99863), {
        failure: function(arg1, callback) {
            callback(new Error("I have no idea what I'm doing"));
        }
    });
    var con = net.connect({
        port: 99863,
        host: 'localhost'
    }, function() {
        con.write(shared.formatMessage({
            id: 1,
            method: 'failure',
            params: [{ hello: 'world' }]
        }));
    });
    var buffers = [], bufferLen = 0, messageLen = 0;
    con.on('data', function(data) {
        buffers.push(data);
        bufferLen += data.length;
        if(messageLen === 0) messageLen = shared.getMessageLen(buffers);
        if(bufferLen === messageLen + 4) con.end();
    });
    con.on('end', function() {
        try {
            var res = shared.parseBuffer(buffers, messageLen);
            test.equal(res[1].error.code, ErrorCode.internalError);
            test.equal(res[1].error.message, "I have no idea what I'm doing", 'Returns the error as an error');
        } catch(e) {
            // Do nothing
        }
        jsonRpcServer.transport.server.close();
        test.done();
    });
};

exports.nonexistentMethod = function(test) {
    test.expect(3);
    var jsonRpcServer = new JSONRPCserver(new HttpTransport(99111), {});
    var testJSON = JSON.stringify({
        id: 25,
        method: 'nonexistent',
        params: []
    });
    var req = http.request({
        hostname: 'localhost',
        port: 99111,
        path: '/',
        method: 'POST'
    }, function(res) {
        res.setEncoding('utf8');
        var resultString = '';
        res.on('data', function(data) {
            resultString += data;
        });
        res.on('end', function() {
            var resultObj;
            try {
                resultObj = JSON.parse(resultString);
            } catch(e) {
                // Do nothing, test will fail
            }
            test.equal(resultObj.id, 25, 'The JSON-RPC server sent back the correct ID');
            test.equal(resultObj.error.code, ErrorCode.methodNotFound);
            test.equal(resultObj.error.message, 'Requested method does not exist.', 'The JSON-RPC server returned the expected error message.');
            jsonRpcServer.shutdown(test.done.bind(test));
        });
    });
    req.write(testJSON);
    req.end();
};

exports.noncompliantJSON = function(test) {
    test.expect(3);
    var jsonRpcServer = new JSONRPCserver(new HttpTransport(99123), {});
    var testJSON = JSON.stringify({ hello: 'world' });
    var req = http.request({
        hostname: 'localhost',
        port: 99123,
        path: '/',
        method: 'POST'
    }, function(res) {
        res.setEncoding('utf8');
        var resultString = '';
        res.on('data', function(data) {
            resultString += data;
        });
        res.on('end', function() {
            var resultObj;
            try {
                resultObj = JSON.parse(resultString);
            } catch(e) {
                // Do nothing, test will fail
            }
            test.equal(resultObj.id, -1, 'The JSON-RPC server sent back the correct ID');
            test.equal(resultObj.error.code, ErrorCode.invalidRequest);
            test.equal(resultObj.error.message, 'Did not receive valid JSON-RPC data.', 'The JSON-RPC server returned the expected error message.');
            jsonRpcServer.shutdown(test.done.bind(test));
        });
    });
    req.write(testJSON);
    req.end();
};


text:
'use strict';

const assert = require('assert');

const test = require('../lib/test');
const {By} = require('..');

test.suite(function(env) {
  var driver;
  after(function() { return driver.quit(); });

  it('should return lower case tag name', async function() {
    driver = await env.builder().build();
    await driver.get(test.Pages.formPage);

    let el = await driver.findElement(By.id('cheese'));
    assert.equal(await el.getTagName(), 'input');
  });
});


text:
import withStyles from '../theme/withStyles'
import transitions from 'material-ui/styles/transitions'

export default ({
  palette,
  spacing,
  colorManipulator,
}) => {
  const tileSize = spacing.desktopKeylineIncrement * 3
  const padding = spacing.desktopGutter * 2
  const margin = spacing.desktopGutterMini / 2

  return ({
    dashboardTile: {
      boxSizing: 'border-box',
      backgroundColor: '#444444',
      calcTextColor: color => colorManipulator.lighten(color, 0.95),
      calcValueColor: color => colorManipulator.lighten(color, 0.95),
      calcTitleColor: color => colorManipulator.lighten(color, 0.75),
      bylineColor: palette.disabledColor,
      hoverScale: 1.015,
      width: tileSize,
      height: tileSize,
      margin,
      padding,
    },
  })
}

// (spacing.desktopKeylineIncrement * 3) + (spacing.desktopGutter * 2) + ((spacing.desktopGutterMini / 2) * 2)
export const tileSize = 288 + 16

const mapThemeToStyles = ({
  typography,
  spacing,
  dashboardTile,
}, {
  style = {},
  hovered,
  onClick,
}) => {
  const tileColor = style.backgroundColor || dashboardTile.backgroundColor
  const scale = onClick && hovered ? dashboardTile.hoverScale : 1
  return ({
    container: {
      position: 'relative',
      display: 'inline-block',
      verticalAlign: 'top',
      margin: dashboardTile.margin,
      padding: dashboardTile.padding,
      width: dashboardTile.width,
      height: dashboardTile.height,
      textAlign: 'center',
      color: dashboardTile.calcTextColor(tileColor),
      transition: transitions.easeOut(null, 'transform', null),
      transform: `scale(${scale}, ${scale})`,
      ...style,
    },
    value: {
      fontFamily: 'Arial Black',
      color: dashboardTile.calcValueColor(tileColor),
      fontWeight: 1000,
      fontSize: 1.25 * spacing.desktopKeylineIncrement,
    },
    customRow: {
      color: dashboardTile.calcTitleColor(tileColor),
      fontWeight: typography.fontWeightMedium,
      fontSize: spacing.desktopGutter - 5,
    },
    title: {
      color: dashboardTile.calcTitleColor(tileColor),
      fontWeight: typography.fontWeightMedium,
      fontSize: spacing.desktopGutter - 5,
    },
    byline: {
      color: dashboardTile.bylineColor,
      fontWeight: typography.fontWeightLight,
      fontSize: spacing.desktopGutterLess,
    },
    content: {
      marginTop: spacing.desktopGutter,
    },
    blankRow: {
      fontSize: spacing.desktopGutterMini,
      lineHeight: `${spacing.desktopGutterMini}px`,
    },
    dataRow: {
      fontWeight: typography.fontWeightLight,
      fontSize: spacing.desktopGutterLess,
      cursor: 'pointer',
    },
    dataRowLabel: {
      display: 'inline-block',
      textAlign: 'left',
      width: '70%',
      fontSize: spacing.desktopGutterLess,
      fontWeight: typography.fontWeightLight,
    },
    dataRowValue: {
      display: 'inline-block',
      textAlign: 'right',
      width: '30%',
      fontWeight: typography.fontWeightMedium,
    },

  })
}

export const injectStylesSheet = Component =>
  withStyles(mapThemeToStyles)(Component)


text:
from crowdsourcing.serializers.worker import *
from crowdsourcing.serializers.project import *
from crowdsourcing.models import *
from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework.decorators import detail_route
from rest_framework.permissions import IsAuthenticated
from django.shortcuts import get_object_or_404
from crowdsourcing.permissions.util import *
from crowdsourcing.permissions.user import IsWorker

class SkillViewSet(viewsets.ModelViewSet):
    queryset = Skill.objects.all()
    serializer_class = SkillSerializer
    permission_classes = [IsOwnerOrReadOnly]

    @detail_route(methods=['post'])
    def update_skill(self, request, id=None):
        skill_serializer = SkillSerializer(data=request.data)
        skill = self.get_object()
        if skill_serializer.is_valid():
            skill_serializer.update(skill, skill_serializer.validated_data)
            return Response({'status': 'Updated Skills'})
        else:
            return Response(skill_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

    def list(self, request, *args, **kwargs):
        try:
            skill = self.queryset
            skill_serializer = SkillSerializer(skill, many=True)
            return Response(skill_serializer.data)
        except:
            return Response([])

    def destroy(self, request, *args, **kwargs):
        skill_serializer = SkillSerializer()
        skill = self.get_object()
        skill_serializer.delete(skill)
        return Response({'Status': 'Deleted Skills'})

class WorkerViewSet(viewsets.ModelViewSet):
    queryset = Worker.objects.all()
    serializer_class = WorkerSerializer
    lookup_value_regex = '[^/]+'
    lookup_field = 'profile__user__username'
    # permission_classes = [IsOwnerOrReadOnly]

    @detail_route(methods=['post'], permission_classes=[IsAuthenticated])
    def update_worker(self, request, pk=None):
        worker_serializer = WorkerSerializer(data=request.data)
        worker = self.get_object()
        if worker_serializer.is_valid():
            worker_serializer.update(worker, worker_serializer.validated_data)
            return Response({'status': 'Updated Worker'})
        else:
            return Response(worker_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def list(self, request, *args, **kwargs):
        try:
            worker = Worker.objects.all()
            worker_serializer = WorkerSerializer(worker, many=True)
            return Response(worker_serializer.data)
        except:
            return Response([])

    def destroy(self, request, *args, **kwargs):
        worker_serializer = WorkerSerializer()
        worker = self.get_object()
        worker_serializer.delete(worker)
        return Response({'status': 'Deleted Worker'})

    @detail_route(methods=['GET'])
    def portfolio(self, request, *args, **kwargs):
        worker = self.get_object()
        modules = Module.objects.all().filter(deleted=False, status=4, task__taskworker__worker=worker).distinct()
        serializer = ModuleSerializer(instance=modules, many=True, fields=('id', 'name', 'project', 'categories',
                                                                           'num_reviews', 'completed_on', 'num_raters',
                                                                           'total_tasks', 'average_time'))
        return Response(serializer.data)

    def retrieve(self, request, profile__user__username=None):
        worker = get_object_or_404(self.queryset, profile__user__username=profile__user__username)
        serializer = self.serializer_class(worker)
        return Response(serializer.data)

class WorkerSkillViewSet(viewsets.ModelViewSet):
    queryset = WorkerSkill.objects.all()
    serializer_class = WorkerSkillSerializer
    permission_classes = [IsAuthenticated, IsWorker]

    def retrieve(self, request, *args, **kwargs):
        worker = get_object_or_404(self.queryset, worker=request.worker)
        serializer = WorkerSkillSerializer(instance=worker)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        serializer = WorkerSkillSerializer(data=request.data)
        if serializer.is_valid():
            serializer.create(worker=request.user.userprofile.worker)
            return Response({'status': 'Worker skill created'})
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

    def destroy(self, request, *args, **kwargs):
        workerskill_serializer = WorkerSkillSerializer()
        worker_skill = get_object_or_404(self.queryset,
                                         worker=request.user.userprofile.worker, skill=kwargs['pk'])
        worker_skill.delete()
        return Response({'status': 'Deleted WorkerSkill'})

class WorkerModuleApplicationViewSet(viewsets.ModelViewSet):
    queryset = WorkerModuleApplication.objects.all()
    serializer_class = WorkerModuleApplicationSerializer
    permission_classes = [IsOwnerOrReadOnly]

    def retrieve(self, request, *args, **kwargs):
        worker = get_object_or_404(self.queryset, worker=request.worker)
        serializer = WorkerModuleApplicationSerializer(instance=worker)
        return Response(serializer.data)


text:
package io.github.m0pt0pmatt.spongesurvivalgames.commands.game.print;

import io.github.m0pt0pmatt.spongesurvivalgames.commands.CommandArgs;
import io.github.m0pt0pmatt.spongesurvivalgames.commands.SurvivalGamesCommand;
import io.github.m0pt0pmatt.spongesurvivalgames.sponsor.Sponsors;
import org.bukkit.command.CommandSender;

import java.util.Map;

public class PrintSponsorsCommand extends SurvivalGamesCommand {

    @Override
    public boolean execute(CommandSender sender, Map<CommandArgs, String> arguments) {

        if (!super.execute(sender, arguments)) {
            return false;
        }

        sender.sendMessage("Available Sponsors:");
        sender.sendMessage(Sponsors.listAll().toString());
        return true;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hedwigia 32: 121 (1893)

#### Original name
Acolium subocellatum Müll. Arg.

### Remarks
null


text:
/*
 * Class DiffFragmentBuilder
 * @author Jeka
 */
package com.intellij.openapi.diff.impl;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.diff.impl.string.DiffString;
import com.intellij.openapi.diff.ex.DiffFragment;
import com.intellij.openapi.util.TextRange;
import com.intellij.util.diff.Diff;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.LinkedList;
import java.util.List;

/**
 Builds a sequence of DiffFragment objects thus diffing 2 files
 Parses the output of CVS 'diff' command assumed to be in the RCS Normal Format
 Format of the output chunks for the command: 'diff file1 file2':
 change-command
 < from-file-line
 < from-file-line...
 ---
 > to-file-line
 > to-file-line...

 Where:
 Change-Command -> Line a Range
 Change-Command -> Range c Range
 Change-Command -> Range d Line
 Range -> Line , Line
 Range -> Line
 Line -> number-of-line

 The commands are:
 a: append a range of lines from the file2 after line Line of the file1
 c: change the range of lines in the file1 to the range from file2
 d: Delete the lines in range Range from the file1; line Line is where they would have appeared in the file2 had they not been deleted
 */
public class DiffFragmentBuilder {

  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.diff.impl.DiffFragmentBuilder");

  @NotNull private final DiffString[] mySource1;
  @NotNull private final DiffString[] mySource2;
  private int myLastLine1 = 1;
  private int myLastLine2 = 1;
  @NotNull private final List<DiffFragment> myData = new LinkedList<DiffFragment>();

  public DiffFragmentBuilder(@NotNull DiffString[] source1, @NotNull DiffString[] source2) {
    mySource1 = source1;
    mySource2 = source2;
    init();
  }

  @NotNull
  private List<DiffFragment> getFragments() {
    return myData;
  }

  private void finish() {
    DiffString text1 = null;
    DiffString text2 = null;
    if (myLastLine1 <= mySource1.length) {
      text1 = concatenate(mySource1, myLastLine1, mySource1.length);
    }
    if (myLastLine2 <= mySource2.length) {
      text2 = concatenate((mySource2), myLastLine2, mySource2.length);
    }
    if (text1 != null || text2 != null) {
      myData.add(DiffFragment.unchanged(text1, text2));
    }
  }

  private void init() {
    myData.clear();
    myLastLine1 = myLastLine2 = 1;
  }

  private void append(int line, @NotNull TextRange range) {
    LOG.debug("DiffFragmentBuilder.append(" + line + "," + range + "), modified:");
    DiffString text1 = null;
    DiffString text2 = null;
    int start = range.getStartOffset();
    int end = range.getEndOffset();
    if (myLastLine1 <= line) {
      text1 = concatenate(mySource1, myLastLine1, line);
    }
    if (myLastLine2 < start) {
      text2 = concatenate(mySource2, myLastLine2, start - 1);
    }
    if (text1 != null || text2 != null) {
      myData.add(DiffFragment.unchanged(text1, text2));
    }
    myData.add(new DiffFragment(null, concatenate(mySource2, start, end)));
    myLastLine1 = line + 1;
    myLastLine2 = end + 1;
  }

  private void change(@NotNull TextRange range1, @NotNull TextRange range2) {
    LOG.debug("DiffFragmentBuilder.change(" + range1 + "," + range2 + ")");

    DiffString text1 = null, text2 = null;
    int start1 = range1.getStartOffset();
    int end1 = range1.getEndOffset();
    int start2 = range2.getStartOffset();
    int end2 = range2.getEndOffset();
    if (myLastLine1 < start1) {
      text1 = concatenate(mySource1, myLastLine1, start1 - 1);
    }
    if (myLastLine2 < start2) {
      text2 = concatenate(mySource2, myLastLine2, start2 - 1);
    }
    if (text1 != null || text2 != null) {
      myData.add(DiffFragment.unchanged(text1, text2));
    }
    myData.add(new DiffFragment(concatenate(mySource1, start1, end1),
                                concatenate(mySource2, start2, end2)));
    myLastLine1 = end1 + 1;
    myLastLine2 = end2 + 1;
  }

  private void delete(@NotNull TextRange range, int line) {
    LOG.debug("DiffFragmentBuilder.delete(" + range + "," + line + ")");

    DiffString text1 = null;
    DiffString text2 = null;
    int start = range.getStartOffset();
    int end = range.getEndOffset();
    if (myLastLine1 < start) {
      text1 = concatenate(mySource1, myLastLine1, start - 1);
    }
    if (myLastLine2 <= line) {
      text2 = concatenate(mySource2, myLastLine2, line);
    }
    if (text1 != null || text2 != null) {
      myData.add(DiffFragment.unchanged(text1, text2));
    }
    myData.add(new DiffFragment(concatenate(mySource1, start, end), null));
    myLastLine1 = end + 1;
    myLastLine2 = line + 1;
  }

  @NotNull
  private static DiffString concatenate(@NotNull DiffString[] strings, int start, int end) {
    return DiffString.concatenate(strings, start - 1, end - start + 1);
  }

  @NotNull
  public DiffFragment[] buildFragments(@Nullable Diff.Change change) {
    while (change != null) {
      if (change.inserted > 0 && change.deleted > 0) {
        change(
                new TextRange(change.line0 + 1, change.line0 + change.deleted),
                new TextRange(change.line1 + 1, change.line1 + change.inserted)
        );
      }
      else if (change.inserted > 0) {
        append(change.line0, new TextRange(change.line1 + 1, change.line1 + change.inserted));
      }
      else if (change.deleted > 0) {
        delete(new TextRange(change.line0 + 1, change.line0 + change.deleted), change.line1);
      }
      change = change.link;
    }
    finish();

    final List<DiffFragment> fragments = getFragments();
    return fragments.toArray(new DiffFragment[myData.size()]);
  }
}


text:
if [[ $# -ne 1 ]] ; then
    echo 'Need to specify destination.'
    exit 0
fi

ROOT_PATH=`dirname "${0}"`/../
DEST_PATH="${1}"

AIRSHIP_PATH="${ROOT_PATH}/Airship"
AIRSHIP_LIB_PATH="${ROOT_PATH}/AirshipLib"
AIRSHIP_KIT_PATH="${ROOT_PATH}/AirshipKit"

# Build the distribution binary
rm -rf "${AIRSHIP_LIB_PATH}/distribution_binaries"
bash "${AIRSHIP_LIB_PATH}/buildTarget.sh" AirshipLib
bash "${AIRSHIP_LIB_PATH}/update_library_reference.sh"

# Remove any old deploy
rm -rf "${DEST_PATH}/Airship"
mkdir -p "${DEST_PATH}/Airship"

# Prepare Airship
#################
echo "cp -R \"${AIRSHIP_PATH}\" \"${DEST_PATH}\""
cp -R "${AIRSHIP_PATH}" "${DEST_PATH}"

# Copy AirshipKit
#################
echo "cp -R \"${AIRSHIP_KIT_PATH}\" \"${DEST_PATH}\""
cp -R "${AIRSHIP_KIT_PATH}" "${DEST_PATH}"

# Remove all non .h files from /Library and /Common
# Remove all non UA_ items & dirs from Airship/External
find "${DEST_PATH}/Airship/Common" \! -name "*.h" -type f -delete
find "${DEST_PATH}/Airship/Push" \! -name "*.h" -type f -delete
find "${DEST_PATH}/Airship/Inbox" \! -name "*.h" -type f -delete

# Delete internal test headers
rm -rf `find "${DEST_PATH}/Airship" -name "*+Internal.h" `

find "${DEST_PATH}/Airship/External" \! '(' -name "UA_*.h" -o -name "UA_" ')' -type f -delete
find "${DEST_PATH}/Airship/External" -type d -empty -delete
rm -rf "${DEST_PATH}/Airship/TestSamples"
rm -rf "${DEST_PATH}/Airship/Test"

# Remove the Appledoc documenation settings from the distribution
rm "${DEST_PATH}/Airship/AppledocSettings.plist"

find "${DEST_PATH}/Airship" -name "*.orig" -delete


text:
const fs = require('fs')
const path = require('path')
for (const d of fs.readdirSync("../types")) {
  const dir = path.join("../types", d)
  const files = fs.readdirSync(dir)
  if (files.length === 0 || files.length === 1) {
    console.log("Deleting unused directory", dir)
    fs.rmdirSync(dir, { recursive: true })
  }
}