text:
using Google.Api.Ads.Dfp.Lib;
using Google.Api.Ads.Dfp.Util.v201411;
using Google.Api.Ads.Dfp.v201411;

using System;

namespace Google.Api.Ads.Dfp.Examples.CSharp.v201411 {
  /// <summary>
  /// This code example gets all rate cards.
  ///
  /// Tags: RateCardService.getRateCardsByStatement
  /// </summary>
  class GetAllRateCards : SampleBase {
    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example gets all rate cards.";
      }
    }

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      SampleBase codeExample = new GetAllRateCards();
      Console.WriteLine(codeExample.Description);
      codeExample.Run(new DfpUser());
    }

    /// <summary>
    /// Run the code example.
    /// </summary>
    /// <param name="user">The DFP user object running the code example.</param>
    public override void Run(DfpUser user) {
      // Get the RateCardService.
      RateCardService rateCardService =
          (RateCardService) user.GetService(DfpService.v201411.RateCardService);

      // Create a statement to get all rate cards.
      StatementBuilder statementBuilder = new StatementBuilder()
          .OrderBy("id ASC")
          .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);

      // Sets default for page.
      RateCardPage page = new RateCardPage();
      try {
        do {
          // Get rate cards by statement.
          page = rateCardService.getRateCardsByStatement(statementBuilder.ToStatement());

          if (page.results != null && page.results.Length > 0) {
            int i = page.startIndex;
            foreach (RateCard rateCard in page.results) {
              Console.WriteLine("{0}) Rate card with ID = '{1}' and name '{2}' was" +
                  " found.", i++, rateCard.id, rateCard.name);
            }
          }

          statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
        } while (statementBuilder.GetOffset() < page.totalResultSetSize);

        Console.WriteLine("Number of results found: {0}", page.totalResultSetSize);
      } catch (Exception ex) {
        Console.WriteLine("Failed to get rate cards. Exception says \"{0}\"",
            ex.Message);
      }
    }
  }
}


text:
$.ajaxSetup({async: false});

var map,
        currentPlayIndex = false,
        cunli;

$.getJSON('Dengue.json', function (data) {
    DengueTW = data
});
function initialize() {

    /*map setting*/
    $('#map-canvas').height(window.outerHeight / 2.2);

    map = new google.maps.Map(document.getElementById('map-canvas'), {
        zoom: 12,
        center: {lat: 22.643894, lng: 120.317828}
    });

    $.getJSON('../cunli.json', function (data) {
        cunli = map.data.addGeoJson(topojson.feature(data, data.objects.cunli));
    });

    cunli.forEach(function (value) {
        var key = value.getProperty('VILLAGE_ID'),
                count = 0;
        if (DengueTW[key]) {
            DengueTW[key].forEach(function (val) {
                count += val[1];
            });
        }
        value.setProperty('num', count);
    });

    map.data.setStyle(function (feature) {
        color = ColorBar(feature.getProperty('num'));
        return {
            fillColor: color,
            fillOpacity: 0.6,
            strokeColor: 'gray',
            strokeWeight: 1
        }
    });

    map.data.addListener('mouseover', function (event) {
        var Cunli = event.feature.getProperty('C_Name') + event.feature.getProperty('T_Name') + event.feature.getProperty('V_Name');
        map.data.revertStyle();
        map.data.overrideStyle(event.feature, {fillColor: 'white'});
        $('#content').html('
' + Cunli + ' :' + event.feature.getProperty('num') + ' 例
').removeClass('text-muted');
    });

    map.data.addListener('mouseout', function (event) {
        map.data.revertStyle();
        $('#content').html('在地圖上滑動或點選以顯示數據').addClass('text-muted');
    });

    map.data.addListener('click', function (event) {
        var Cunli = event.feature.getProperty('VILLAGE_ID');
        var CunliTitle = event.feature.getProperty('C_Name') + event.feature.getProperty('T_Name') + event.feature.getProperty('V_Name');
        if ($('#myTab a[name|="' + Cunli + '"]').tab('show').length === 0) {
            $('#myTab').append('
' + CunliTitle +
                    '<button class="close" onclick="closeTab(this.parentNode)">×</button>
');
            $('#myTabContent').append('

');
            $('#myTab a:last').tab('show');
            createStockChart(Cunli, cunli);
            $('#myTab li a:last').click(function (e) {
                $(window).trigger('resize');
            });
        }
    });
    createStockChart('total', cunli);

    $('#playButton1').on('click', function () {
        var maxIndex = DengueTW['total'].length;
        if (false === currentPlayIndex) {
            currentPlayIndex = 0;
        } else {
            currentPlayIndex += 1;
            $(this).addClass('active disabled').find('.glyphicon').show();
        }

        if (currentPlayIndex < maxIndex) {
            showDateMap(new Date(DengueTW['total'][currentPlayIndex][0]), cunli);
            setTimeout(function () {
                $('#playButton1').trigger('click');
            }, 300);
        } else {
            $(this).removeClass('active disabled').find('.glyphicon').hide();
            currentPlayIndex = false;
            $('#title').html('');
        }
        return false;
    });

    $('#playButton2').on('click', function () {
        var maxIndex = DengueTW['total'].length;
        if (false === currentPlayIndex) {
            currentPlayIndex = 0;
        } else {
            currentPlayIndex += 1;
            $(this).addClass('active disabled').find('.glyphicon').show();
        }

        if (currentPlayIndex < maxIndex) {
            showDayMap(new Date(DengueTW['total'][currentPlayIndex][0]), cunli);
            setTimeout(function () {
                $('#playButton2').trigger('click');
            }, 300);
        } else {
            $(this).removeClass('active disabled').find('.glyphicon').hide();
            currentPlayIndex = false;
            $('#title').html('');
        }
        return false;
    });
}

function createStockChart(Cunli, cunli) {
    var series = [];

    for (var i = 0; i < DengueTW[Cunli].length; i++) {
        series.push([new Date(DengueTW[Cunli][i][0]).getTime(), DengueTW[Cunli][i][1]]);
    }

    Highcharts.setOptions({
        lang: {
            months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
            shortMonths: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
            weekdays: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
            loading: '載入中'
        }
    });

    $('#' + Cunli).highcharts('StockChart', {
        chart: {
            alignTicks: false,
            width: $('#myTabContent').width(),
            height: $('#myTabContent').height()
        },
        rangeSelector: {
            enabled: false
        },
        tooltip: {
            enabled: true,
            positioner: function () {
                return {x: 10, y: 30}
            }
        },
        plotOptions: {
            series: {
                cursor: 'pointer',
                point: {
                    events: {
                        click: function () {
                            showDayMap(new Date(this.x), cunli);
                        }
                    }
                },
            }
        },
        series: [{
                type: 'column',
                name: Cunli,
                data: series,
            }]
    });
}

function showDateMap(clickedDate, cunli) {
    var yyyy = clickedDate.getFullYear().toString(),
            mm = (clickedDate.getMonth() + 1).toString(),
            dd = clickedDate.getDate().toString(),
            clickedDateKey = yyyy + '-' + (mm[1] ? mm : '0' + mm[0]) + '-' + (dd[1] ? dd : '0' + dd[0]);

    $('#title').html(clickedDateKey + ' 累積病例');
    cunli.forEach(function (value) {
        var key = value.getProperty('VILLAGE_ID'),
                count = 0;

        if (DengueTW[key]) {
            DengueTW[key].forEach(function (val) {
                var recordDate = new Date(val[0]);
                if (recordDate <= clickedDate) {
                    count += val[1];
                }
            });
        }
        value.setProperty('num', count);
    });
}

function showDayMap(clickedDate, cunli) {
    var yyyy = clickedDate.getFullYear().toString(),
            mm = (clickedDate.getMonth() + 1).toString(),
            dd = clickedDate.getDate().toString(),
            clickedDateKey = yyyy + '-' + (mm[1] ? mm : "0" + mm[0]) + '-' + (dd[1] ? dd : "0" + dd[0]);

    $('#title').html(clickedDateKey + ' 當日病例');
    cunli.forEach(function (value) {
        var key = value.getProperty('VILLAGE_ID'),
                count = 0;

        if (DengueTW[key]) {
            DengueTW[key].forEach(function (val) {
                if (clickedDateKey == val[0]) {
                    count += val[1];
                }
            });
        }
        value.setProperty('num', count);
    });
}

$(window).resize(function () {
    var len = $('#myTabContent > .tab-pane').length;
    for (var i = 0; i < len; i++) {
        $('#myTabContent > .tab-pane').eq(i).highcharts().setSize($('#myTabContent').width(), $('#myTabContent').height());
    }
});

function closeTab(node) {
    var nodename = node.name;
    node.parentNode.remove();
    $('#' + nodename).remove();
    $('#myTab a:first').tab('show');
}

google.maps.event.addDomListener(window, 'load', initialize);

redpajama_set_name: RedPajamaGithub


text:
layout: post
title:  "Checking Sequence File Metrics"
date:   2016-1-1 17:55:47
comments: true
tags: [python, metagenomics]
---

First post of 2016!  Just a quick post about how I measure sequence total, sequence length distribution, and assembly quality (when it's
important).  I wrote a python script that handles both fastas and fastqs to report a variety of metrics.

Here's my code:

{% highlight python %}
#!/usr/bin/python2.7
'''USAGE: fasta_stats.py seqFile
This script calculates various statistics about the provided fasta or fastq file.
'''
import sys
import os

# This function reads in fasta file, appends the length of each sequence to a list, and counts all Gs & Cs.
# It returns a sorted list of sequence lengths with the G+C total as the last element.
def readFasta(FastaFile):

	tempseq = ''
	GC_count = 0
	N_count = 0
	lenList = []

	for line in FastaFile:

		if line.startswith('>'):
			lenList.append(len(tempseq))
			GC_count = GC_count + tempseq.count('C') + tempseq.count('c') + tempseq.count('G') + tempseq.count('g')
			N_count = N_count + tempseq.count('N') + tempseq.count('n')
			tempseq = ''
			continue

		else:
			tempseq = tempseq + line.strip()

	lenList.append(len(tempseq))

	lenList.remove(0)
	lenList.sort()
	lenList.append(GC_count)
	lenList.append(N_count)

	FastaFile.close()

	return lenList

# This function reads in fastq files and returns all sequence lengths in a list
def readFastq(FastqFile):

	GC_count = 0
	N_count = 0
	lenList = []
	line_count = 3

	for line in FastqFile:

		line_count += 1

		if line_count == 5:
			seq = line.strip()
			lenList.append(len(seq))
			GC_count = GC_count + seq.count('C') + seq.count('c') + seq.count('G') + seq.count('g')
			N_count = N_count + seq.count('N') + seq.count('n')
			line_count = 1
			continue

		else:
			continue

	lenList.sort()
	lenList.append(GC_count)
	lenList.append(N_count)

	FastqFile.close()

	return lenList

# This function calculates and returns all the printed statistics.
def calcStats(lengths):

	Ns = lengths[-1]
	del lengths[-1]
	GCs = lengths[-1] # extract saved GC count
	del lengths[-1]

	total_seq = len(lengths) # Total number of sequences
	len_sum = sum(lengths) # Total number of residues
	total_Mb = len_sum/1000000.00 # Total number of residues expressed in Megabases
	GC_content = (float(GCs)/float(len_sum))*100 # GC content as a percent of total residues

	# interquartile range
	if total_seq >= 4:
		median_len = lengths[int(round(total_seq/2))] # Median sequence length
		q1_range = lengths[0:(int(total_seq/2)-1)]
		q1 = q1_range[int(len(q1_range)/2)]
		q3_range = lengths[(int(total_seq/2)+1):-1]
		q3 = q3_range[int(len(q3_range)/2)]
		iqr = int(q3 - q1)
	else:
		iqr = 'Too few sequences to calculate'
		median_len = 'Too few sequences to calculate'

	#n50 calculation loop
	current_bases = 0
	n50 = 0
	n90 = 0
	seqs_1000 = 0
	seqs_5000 = 0
	percent50_bases = int(round(len_sum*0.5))
	percent90_bases = int(round(len_sum*0.1))

	for object in lengths:

		current_bases += object

		if object > 1000:
			seqs_1000 += 1
		if object > 5000:
			seqs_5000 += 1

		if current_bases >= percent50_bases and n50 == 0:
			n50 = object
		if current_bases >= percent90_bases and n90 == 0:
			n90 = object

	if total_seq < 4:
		n50 = 'Too few sequences to calculate'
		n90 = 'Too few sequences to calculate'
		l50 = 'Too few sequences to calculate'
	else:
		l50 = lengths.count(n50)

	return(total_seq, total_Mb, n50, median_len, iqr, GC_content, n90, seqs_1000, seqs_5000, Ns, l50)

if os.stat(str(sys.argv[1])).st_size == 0:
	print('ERROR: Empty input file.')
	sys.exit()

fasta_suffix = ['fasta', 'fa', 'fna', 'faa', 'ffn', 'frn']
fastq_suffix = ['fastq', 'fq']
file_suffix = str(sys.argv[1]).split('.')[-1]

if file_suffix in fasta_suffix:
	file_type = 'Fasta'
	seq_lengths = readFasta(open(sys.argv[1], 'r'))

elif file_suffix in fastq_suffix:
	file_type = 'Fastq'
	seq_lengths = readFastq(open(sys.argv[1], 'r'))

else:
	print('ERROR: Invalid file format provided.')
	sys.exit()

stat_list = calcStats(seq_lengths)

output_string = """# Input file name: {filename}
# File type: {filetype}
# Total sequences: {total_seq}
# Total bases: {total_mb} Mb
# Sequence N50: {n50}
# Sequence L50: {l50}
# Sequence N90: {n90}
# Median sequence length: {median_len}
# Interquartile range: {iqr}
# Shortest sequence length: {short}
# Longest sequence length: {long}
# Sequences > 1 kb: {seqs_1000}
# Sequences > 5 kb: {seqs_5000}
# G-C content: {gc}%
# Ns included: {ns}
""".format(filename = str(sys.argv[1]).split('/')[-1], filetype = file_type, total_seq = stat_list[0], total_mb = "%.2f" % stat_list[1], n50 = stat_list[2], median_len = stat_list[3], iqr = stat_list[4], short = seq_lengths[0], long = seq_lengths[-1], gc = "%.2f" % stat_list[5], n90 = stat_list[6], seqs_1000 = stat_list[7], seqs_5000 = stat_list[8], ns = stat_list[9], l50 = stat_list[10])

print output_string
{% endhighlight %}

Output is printed to the terminal and appears like this:

	# Input file name: example.fasta
	# File type: Fasta
	# Total sequences: 2362551
	# Total bases: 1462.60 Mb
	# Sequence N50: 682
	# Sequence L50: 2575
	# Sequence N90: 394
	# Median sequence length: 532
	# Interquartile range: 331
	# Shortest sequence length: 251
	# Longest sequence length: 190893
	# Sequences > 1 kb: 260467
	# Sequences > 5 kb: 632
	# G-C content: 42.76%
	# Ns included: 0

Pretty straight forward, but I haven't found any others like it that give all of these stats together.  It makes read
QC and evaluating assemblies a lot more convenient.  So if you like it, give it a try!  I've also made a Github repo
for the scripts I use in this blog and linked it on the resources page.


text:
import { Plugin, Server, ServerOptions } from "@hapi/hapi";

export interface Options {
  relativeTo: string;
  preConnections?: (Server: Server, next: (err: any) => void) => void;
  preRegister?: (Server: Server, next: (err: any) => void) => void;
}

export interface PluginObject {
  plugin: string | Plugin<any>;
  options?: any;
  routes?: any;
}

export interface Manifest {
  server: ServerOptions;
  register?: {
    plugins: string[] | PluginObject[] | Array<(string|PluginObject)>
  };
}

export function compose(manifest: Manifest, options?: Options): Promise<Server>;


text:
Change Log
##########

Version 3.0.4
=============

Release Date: Jan 13, 2016

-   Housekeeping

    -   Updated copyright dates for 2016.

-   New Translations

    -   armenian
    -   greek
    -   slovenian

-   Updated Translations

    -   filipino
    -   vietnamese

Version 3.0.3
=============

Release Date: Oct 31, 2015

- No changes. Updated version # to sync with framework.

Version 3.0.2
=============

Release Date: Oct 8, 2015

-   Enhancements

    -   MY_Lang (optional) can provide automatic translation fallbacks.

-   Updated Translations

    -   arabic
    -   german
    -   hindi
    -   persian
    -   portuguese-brazilian
    -   romanian
    -   simplified-chinese
    -   thai
    -   vietnamese

-   New Translations

    -   latvian
    -   slovak

Version 3.0.0
=============

Release Date: March 30, 2015

Initial "official" release, with settings consistent with CodeIgniter 3.0.0


text:
"""Sign and send a heartbeat message to a remote service."""

import argparse
import sys

from infra.tools.heartbeat import heartbeat

def parse_options():
  # Gather user options.
  parser = argparse.ArgumentParser()
  parser.add_argument('-u', '--urls', help='URLs to send heartbeat.',
      action='append', default=[
          'https://chrome-heartbeats.appspot.com/heartbeat'])
  parser.add_argument('-n', '--name', help='Override the hostname detector.')
  parser.add_argument('-i', '--ident', help='Override the machine ID.')
  parser.add_argument('-s', '--secret',
                    default='~/.heartbeat.key',
                    help='Key file for authentication')
  args = parser.parse_args()

  secret = heartbeat.get_secret(args.secret)
  return secret, args.name, args.ident, args.urls

def main():
  # Step 1: Get options and secret.
  secret, name, ident, urls = parse_options()

  # Step 2: Create and populate the heartbeat object.
  data = heartbeat.get_heartbeat_data(name, ident)

  # Step 3: Sign heartbeat with key.
  signed_message = heartbeat.get_hashed_message(data, secret)

  # Step 4: Send heartbeat
  result = heartbeat.send(signed_message, urls)
  if result == 402:
    # Unknown user -> need to send key along with request.
    print 'Server does not recognize the hostname. Resending with key.'
    signed_message['key'] = secret
    result = heartbeat.send(signed_message, urls)
  return result

if __name__ == '__main__':
  sys.exit(main())


text:
"use strict";

require('../configure');
var opsgenie = require('../../');

opsgenie.configure({
    'host': 'https://api.opsgenie.com',
    'api_key': "yourApiKey"
});

var addTags_request_identifier = {
    identifier: "5", // should be custom to your created alert
    identifierType : "tiny"
};

var addTags_data = {
    note : "some note for add tags action",
    user : "user@opsgenie.com",
    source : "source of the add tags request",
    tags : ["tag1", "tag2"]
};

opsgenie.alertV2.addTags(addTags_request_identifier, addTags_data, function (error, result) {
    if (error) {
        console.error(error);
    } else {
        console.log("Add Tags to Alert Response");
        console.log(result);
    }
});


text:
using Frankenwiki.Example.NancyWeb;
using Frankenwiki.Example.NancyWeb.Plumbing;
using Microsoft.Owin;
using Microsoft.Owin.Extensions;
using Nancy.Owin;
using Owin;

[assembly: OwinStartup(typeof (Startup))]

namespace Frankenwiki.Example.NancyWeb
{
    public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            var container = IoC.BoomShakalaka();

            appBuilder.UseNancy(new NancyOptions
            {
                Bootstrapper = new Bootstrapper(container)
            });

            appBuilder.UseStageMarker(PipelineStage.MapHandler);
        }
    }
}


text:
<?php

namespace Ngames\Framework;

/**
 * Represents the response from a controller.
 *
 */
class Response
{
    public const HTTP_STATUS_OK = 200;

    public const HTTP_STATUS_CREATED = 201;

    public const HTTP_STATUS_MOVED_PERMANENTLY = 301;

    public const HTTP_STATUS_FOUND = 302;

    public const HTTP_STATUS_NOT_MODIFIED = 304;

    public const HTTP_STATUS_BAD_REQUEST = 400;

    public const HTTP_STATUS_UNAUTHORIZED = 401;

    public const HTTP_STATUS_FORBIDDEN = 403;

    public const HTTP_STATUS_NOT_FOUND = 404;

    public const HTTP_STATUS_INTERNAL_SERVER_ERROR = 500;

    public const HTTP_STATUS_NOT_IMPLEMENTED = 501;

    public const CONTENT_TYPE_HEADER = 'Content-Type';

    public const ERROR_CONTENT_TYPE = 'text/plain; charset=utf-8';

    /**
     *
     * @var int
     */
    protected $statusCode;

    /**
     *
     * @var array
     */
    protected $headers;

    /**
     *
     * @var string|null
     */
    protected $content;

    /**
     * Initializes an empty successful response.
     */
    public function __construct()
    {
        $this->headers = [];
        $this->content = null;
        $this->statusCode = self::HTTP_STATUS_OK;
    }

    /**
     * Outputs the response.
     */
    public function send()
    {
        // Send headers
        foreach ($this->headers as $name => $value) {
            header($name . ': ' . $value);
        }

        // Set response code
        http_response_code($this->statusCode);

        // Send the content
        if ($this->content !== null) {
            echo $this->content;
        }
    }

    /**
     * Changes the response status code
     *
     * @param int $statusCode
     */
    public function setStatusCode($statusCode)
    {
        $this->statusCode = $statusCode;
    }

    /**
     * Adds a new header value
     *
     * @param string $name
     * @param string $value
     */
    public function setHeader($name, $value)
    {
        $this->headers[$name] = $value;
    }

    /**
     * Sets the content type of the response (helper to set a header).
     *
     * @param String $contentType
     * @param String|null $charset
     *            Optional charset
     */
    public function setContentType($contentType, $charset = null)
    {
        $headerValue = $contentType;

        if ($charset !== null) {
            $headerValue .= '; charset=' . $charset;
        }

        $this->setHeader(self::CONTENT_TYPE_HEADER, $headerValue);
    }

    /**
     * Sets the content of the response
     *
     * @param string|null $content
     */
    public function setContent($content)
    {
        $this->content = $content;
    }

    /**
     * Create a successful response
     *
     * @param string|null $content
     * @return Response
     */
    public static function createOkResponse($content = null)
    {
        $response = new self();
        $response->setContent($content);
        $response->setStatusCode(self::HTTP_STATUS_OK);

        return $response;
    }

    /**
     * Create an internal error response
     *
     * @param string|null $message
     * @return Response
     */
    public static function createInternalErrorResponse($message = null)
    {
        $response = new self();
        $response->setHeader(self::CONTENT_TYPE_HEADER, self::ERROR_CONTENT_TYPE);
        $response->setContent($message !== null ? $message : 'Internal server error.');
        $response->setStatusCode(self::HTTP_STATUS_INTERNAL_SERVER_ERROR);

        return $response;
    }

    /**
     * Create an unauthorized response
     *
     * @param string|null $message
     * @return Response
     */
    public static function createUnauthorizedResponse($message = null)
    {
        $response = new self();
        $response->setHeader(self::CONTENT_TYPE_HEADER, self::ERROR_CONTENT_TYPE);
        $response->setContent($message !== null ? $message : 'Unauthorized.');
        $response->setStatusCode(self::HTTP_STATUS_UNAUTHORIZED);

        return $response;
    }

    /**
     * Create a not found response
     *
     * @param string|null $message
     * @return Response
     */
    public static function createNotFoundResponse($message = null)
    {
        $response = new self();
        $response->setHeader(self::CONTENT_TYPE_HEADER, self::ERROR_CONTENT_TYPE);
        $response->setContent($message !== null ? $message : 'File not found.');
        $response->setStatusCode(self::HTTP_STATUS_NOT_FOUND);

        return $response;
    }

    /**
     * Create a bad request response
     *
     * @param string|null $message
     * @return Response
     */
    public static function createBadRequestResponse($message = null)
    {
        $response = new self();
        $response->setHeader(self::CONTENT_TYPE_HEADER, self::ERROR_CONTENT_TYPE);
        $response->setContent($message !== null ? $message : 'Bad request.');
        $response->setStatusCode(self::HTTP_STATUS_BAD_REQUEST);

        return $response;
    }

    /**
     * Create a redirect response
     *
     * @param string $url
     * @return Response
     */
    public static function createRedirectResponse($url)
    {
        $response = new self();
        $response->setStatusCode(self::HTTP_STATUS_MOVED_PERMANENTLY);
        $response->setHeader('Location', $url);

        return $response;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Gallio.Framework.Pattern;
using Gallio.Common.Reflection;

namespace MbUnit.Framework
{
    /// <summary>
    /// Specifies the maximum number of concurrent threads to use when tests are run in parallel
    /// for all tests in the test assembly.
    /// </summary>
    /// <remarks>
    /// <para>
    /// Defaults to <see cref="Environment.ProcessorCount" /> or 2, whichever is greater.
    /// </para>
    /// </remarks>
    /// <seealso cref="TestAssemblyExecutionParameters.DegreeOfParallelism"/>
    [AttributeUsage(PatternAttributeTargets.TestAssembly, AllowMultiple = true, Inherited = true)]
    public class DegreeOfParallelismAttribute : TestAssemblyDecoratorPatternAttribute
    {
        private readonly int degreeOfParallelism;

        /// <summary>
        /// Specifies the maximum number of concurrent threads to use when tests are run in parallel.
        /// </summary>
        /// <param name="degreeOfParallelism">The degree of parallelism.</param>
        /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="degreeOfParallelism"/> is less than 1.</exception>
        public DegreeOfParallelismAttribute(int degreeOfParallelism)
        {
            if (degreeOfParallelism < 1)
                throw new ArgumentOutOfRangeException("degreeOfParallelism", "Degree of parallelism must be at least 1.");

            this.degreeOfParallelism = degreeOfParallelism;
        }

        /// <summary>
        /// Gets the degree of parallelism.
        /// </summary>
        public int DegreeOfParallelism
        {
            get { return degreeOfParallelism; }
        }

        /// <inheritdoc />
        protected override void DecorateAssemblyTest(IPatternScope assemblyScope, IAssemblyInfo assembly)
        {
            assemblyScope.TestBuilder.TestActions.InitializeTestChain.After(state =>
            {
                TestAssemblyExecutionParameters.DegreeOfParallelism = degreeOfParallelism;
            });
        }
    }
}


text:
package org.sakaiproject.nakamura.profile;

import static org.sakaiproject.nakamura.api.profile.ProfileConstants.USER_PROFILE_RT;
import static org.sakaiproject.nakamura.api.profile.ProfileConstants.GROUP_PROFILE_RT;
import static org.sakaiproject.nakamura.api.user.UserConstants.GROUP_DESCRIPTION_PROPERTY;
import static org.sakaiproject.nakamura.api.user.UserConstants.GROUP_TITLE_PROPERTY;
import static org.sakaiproject.nakamura.api.user.UserConstants.USER_RESPONSE_CACHE;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.ReferenceStrategy;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.wrappers.ValueMapDecorator;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.sakaiproject.nakamura.api.http.cache.DynamicContentResponseCache;
import org.sakaiproject.nakamura.api.lite.StorageClientException;
import org.sakaiproject.nakamura.api.lite.StorageClientUtils;
import org.sakaiproject.nakamura.api.lite.accesscontrol.AccessControlManager;
import org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException;
import org.sakaiproject.nakamura.api.lite.authorizable.Authorizable;
import org.sakaiproject.nakamura.api.lite.authorizable.AuthorizableManager;
import org.sakaiproject.nakamura.api.lite.authorizable.User;
import org.sakaiproject.nakamura.api.lite.content.Content;
import org.sakaiproject.nakamura.api.lite.content.ContentManager;
import org.sakaiproject.nakamura.api.profile.ProfileConstants;
import org.sakaiproject.nakamura.api.profile.ProfileProvider;
import org.sakaiproject.nakamura.api.profile.ProfileService;
import org.sakaiproject.nakamura.api.profile.ProviderSettings;
import org.sakaiproject.nakamura.api.resource.lite.LiteJsonImporter;
import org.sakaiproject.nakamura.api.user.BasicUserInfoService;
import org.sakaiproject.nakamura.util.LitePersonalUtils;
import org.sakaiproject.nakamura.util.PathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.jcr.RepositoryException;
import javax.jcr.Session;

/**
 *
 */
@Component(immediate = true, metatype = true, specVersion="1.1")
@Service
@Reference(name = "ProfileProviders", referenceInterface = ProfileProvider.class, policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, strategy = ReferenceStrategy.EVENT, bind = "bindProfileProvider", unbind = "unbindProfileProvider")
public class ProfileServiceImpl implements ProfileService {

  private Map<String, ProfileProvider> providers = new ConcurrentHashMap<String, ProfileProvider>();
  private ProviderSettingsFactory providerSettingsFactory = new ProviderSettingsFactory();
  public static final Logger LOG = LoggerFactory.getLogger(ProfileServiceImpl.class);

  @Property
  static final String EMAIL_LOCATION = "sakai.profile.email.location";
  private String emailLocation;

  @Property(boolValue = false)
  static final String SCAN_PROVIDER = "should-scan-for-providers";
  private Boolean shouldScanForProviders;

  @Reference
  private BasicUserInfoService basicUserInfoService;

  @Reference
  private DynamicContentResponseCache responseCache;

  @Activate @Modified
  protected void activate(Map<?, ?> props) {
    emailLocation = PropertiesUtil.toString(props.get(EMAIL_LOCATION), null);
    shouldScanForProviders = PropertiesUtil.toBoolean(props.get(SCAN_PROVIDER), false);
  }

  public String getEmailLocation() {
    return emailLocation;
  }

  /**
   * {@inheritDoc}
   * @throws AccessDeniedException
   * @throws StorageClientException
   *
   * @see org.sakaiproject.nakamura.api.profile.ProfileService#getCompactProfileMap(org.apache.jackrabbit.api.security.user.Authorizable,
   *      javax.jcr.Session)
   * @deprecated Replaced with {@link BasicUserInfoService#getProperties(Authorizable)} in user bundle
   */
  public ValueMap getCompactProfileMap(Authorizable authorizable, Session session)
      throws RepositoryException, StorageClientException, AccessDeniedException {
    return new ValueMapDecorator(basicUserInfoService.getProperties(authorizable));
  }
  /**
   * {@inheritDoc}
   * @see org.sakaiproject.nakamura.api.profile.ProfileService#getCompactProfileMap(org.sakaiproject.nakamura.api.lite.authorizable.Authorizable, javax.jcr.Session)
   * @deprecated Replaced with {@link BasicUserInfoService#getProperties(Authorizable)} in user bundle
   */
  public ValueMap getCompactProfileMap(
      org.apache.jackrabbit.api.security.user.Authorizable authorizable, Session session) throws RepositoryException {
    org.sakaiproject.nakamura.api.lite.Session sparseSession = StorageClientUtils.adaptToSession(session);
    try {
      return  new ValueMapDecorator(basicUserInfoService.getProperties(sparseSession.getAuthorizableManager().findAuthorizable(authorizable.getID())));
    } catch (StorageClientException e) {
      throw new RepositoryException(e.getMessage(), e);
    } catch (AccessDeniedException e) {
      throw new RepositoryException(e.getMessage(), e);
    }
  }

  public ValueMap getProfileMap(
      org.apache.jackrabbit.api.security.user.Authorizable authorizable, Session session) throws RepositoryException {
    org.sakaiproject.nakamura.api.lite.Session sparseSession = StorageClientUtils.adaptToSession(session);
    try {
      return getProfileMap(sparseSession.getAuthorizableManager().findAuthorizable(authorizable.getID()), session);
    } catch (StorageClientException e) {
      throw new RepositoryException(e.getMessage(), e);
    } catch (AccessDeniedException e) {
      throw new RepositoryException(e.getMessage(), e);
    }
  }

  public ValueMap getProfileMap(Content profileContent, Session session)
      throws RepositoryException {
    try {
      org.sakaiproject.nakamura.api.lite.Session sparseSession = StorageClientUtils
          .adaptToSession(session);
      AuthorizableManager authorizableManager = sparseSession.getAuthorizableManager();
      Authorizable authorizable = authorizableManager.findAuthorizable(PathUtils
          .getAuthorizableId(profileContent.getPath()));
      return getProfileMap(
          sparseSession.getAuthorizableManager().findAuthorizable(authorizable.getId()),
          session);
    } catch (StorageClientException e) {
      throw new RepositoryException(e.getMessage(), e);
    } catch (AccessDeniedException e) {
      throw new RepositoryException(e.getMessage(), e);
    }
  }

  /**
   * {@inheritDoc}
   * @throws StorageClientException
   * @throws AccessDeniedException
   *
   * @see org.sakaiproject.nakamura.api.profile.ProfileService#getProfileMap(org.apache.jackrabbit.api.security.user.Authorizable,
   *      javax.jcr.Session)
   */
  public ValueMap getProfileMap(Authorizable authorizable, Session session)
      throws RepositoryException, StorageClientException, AccessDeniedException {
    if (User.ANON_USER.equals(authorizable.getId())) {
      return new ValueMapDecorator(basicUserInfoService.getProperties(authorizable));
    }
    String profilePath = LitePersonalUtils.getProfilePath(authorizable.getId());
    org.sakaiproject.nakamura.api.lite.Session sparseSession = StorageClientUtils.adaptToSession(session);
    ContentManager contentManager = sparseSession.getContentManager();
    ValueMap profileMap = new ValueMapDecorator(new HashMap<String, Object>());

    if (contentManager.exists(profilePath)) {
      Content profileContent = contentManager.get(profilePath);
      profileMap.putAll(getResolvedProfileMap(authorizable, profileContent, session));
    }

    profileMap.putAll(basicUserInfoService.getProperties(authorizable));
    return profileMap;
  }

  /**
   * {@inheritDoc}
   * @param jcrSession
   *
   * @see org.sakaiproject.nakamura.api.profile.ProfileService#getProfileMap(javax.jcr.Node)
   */
  public ValueMap getResolvedProfileMap(Authorizable authorizable, Content profileContent, Session jcrSession) throws RepositoryException {
    // Get the data from our external providers.
    Map<String, Future<Map<String, Object>>> providedNodeData = new HashMap<String, Future<Map<String, Object>>>();
    if (shouldScanForProviders) {
      Map<String, List<ProviderSettings>> providersMap = scanForProviders(profileContent, jcrSession);
      for (Entry<String, List<ProviderSettings>> e : providersMap.entrySet()) {
        ProfileProvider pp = providers.get(e.getKey());
        if (pp != null) {
          providedNodeData.putAll(pp.getProvidedMap(e.getValue()));
        }
      }
    }
    try {
      // Return it as a ValueMap.
      ValueMap map = new ValueMapDecorator(new HashMap<String, Object>());
      handleNode(profileContent, providedNodeData, map);
      final String resourceType = (String) profileContent
          .getProperty("sling:resourceType");
      if (ProfileConstants.USER_PROFILE_RT.equals(resourceType)) {
        map.put("userid", PathUtils.getAuthorizableId(profileContent.getPath()));
      } else if (ProfileConstants.GROUP_PROFILE_RT.equals(resourceType)) {
        map.put("groupid", PathUtils.getAuthorizableId(profileContent.getPath()));
      }
      return map;
    } catch (InterruptedException e) {
      throw new RuntimeException(e.getMessage(),e);
    } catch (ExecutionException e) {
      throw new RuntimeException(e.getMessage(),e);
    }
  }

  /**
   * Fills the provided map with the JCR info and the external information.
   *
   * @param profileContent
   *          The node that should be merged with the external info. The entire nodetree
   *          will be checked.
   * @param baseMap
   *          The map that contains the external information.
   * @param map
   *          The map that should be filled.
   * @throws RepositoryException
   * @throws InterruptedException
   * @throws ExecutionException
   */
  protected void handleNode(Content profileContent, Map<String, Future<Map<String, Object>>> baseMap,
      Map<String, Object> map) throws RepositoryException, InterruptedException,
      ExecutionException {
    // If our map contains this node, that means one of the providers had some information
    // for it. We will use this provider.
    if (!baseMap.isEmpty() && baseMap.containsKey(profileContent.getPath())) {
      map.putAll(baseMap.get(profileContent.getPath()).get());
    } else {

      // The node wasn't found in the baseMap.
      // We just dump the Sparse properties excluding any system properties.
      for ( Entry<String, Object> e : profileContent.getProperties().entrySet()) {
        String k = e.getKey();
        if ( !k.startsWith("_") &&  !k.startsWith(":") ) {
          map.put(k,e.getValue());
        }
      }
      map.put("_path", PathUtils.translateAuthorizablePath(profileContent.getPath()));

      // We loop over the child nodes, but each node get checked against the baseMap
      // again.
      for (Content childProfile : profileContent.listChildren()) {
        ValueMap childMap = new ValueMapDecorator(new HashMap<String, Object>());
        handleNode(childProfile, baseMap, childMap);
        map.put(StorageClientUtils.getObjectName(childProfile.getPath()), childMap);
      }
    }
  }

  /**
   * Loops over an entire profile and checks if some of the nodes are marked as external.
   * If there is a node found that has it's sakai:source property set to external, we'll
   * look for a ProfileProvider that matches that path.
   *
   * @param profileContent
   *          The top node of a profile.
   * @param jcrSession
   * @return
   * @throws RepositoryException
   */
  private Map<String, List<ProviderSettings>> scanForProviders(Content profileContent, Session jcrSession)
      throws RepositoryException {
    Map<String, List<ProviderSettings>> providerMap = new HashMap<String, List<ProviderSettings>>();
    if (!shouldScanForProviders){
      return providerMap;
    }
    return scanForProviders("", profileContent, providerMap, jcrSession);
  }

  /**
   * @param path
   * @param profileContent
   * @param providerMap
   * @param jcrSession
   * @return
   * @throws RepositoryException
   */
  private Map<String, List<ProviderSettings>> scanForProviders(String path, Content profileContent,
      Map<String, List<ProviderSettings>> providerMap, Session jcrSession) throws RepositoryException {
    ProviderSettings settings = providerSettingsFactory.newProviderSettings(path, profileContent, jcrSession);
    if (settings == null) {
      for (Content childProfileContent : profileContent.listChildren()) {
        scanForProviders(StorageClientUtils.newPath(path, StorageClientUtils.getObjectName(childProfileContent.getPath())), childProfileContent, providerMap, jcrSession);
      }
    } else {

      List<ProviderSettings> l = providerMap.get(settings.getProvider());

      if (l == null) {
        l = new ArrayList<ProviderSettings>();
        providerMap.put(settings.getProvider(), l);
      }
      l.add(settings);
    }
    return providerMap;
  }

  protected void bindProfileProvider(ProfileProvider provider,
      Map<String, Object> properties) {
    String name = (String) properties.get(ProfileProvider.PROVIDER_NAME);
    System.err.println("Bound reference with name: " + name);
    if (name != null) {
      providers.put(name, provider);
    }
  }

  protected void unbindProfileProvider(ProfileProvider provider,
      Map<String, Object> properties) {
    String name = (String) properties.get(ProfileProvider.PROVIDER_NAME);
    System.err.println("Unbound reference with name: " + name);
    if (name != null) {
      providers.remove(name);
    }
  }

  public void update(org.sakaiproject.nakamura.api.lite.Session session, String profilePath,
      JSONObject json, boolean replace, boolean replaceProperties, boolean removeTree)
      throws StorageClientException, AccessDeniedException, JSONException {
    responseCache.invalidate(USER_RESPONSE_CACHE, session.getUserId());
    String objectName = PathUtils.lastElement(profilePath);
    ContentManager contentManager = session.getContentManager();
    String authorizableId = PathUtils.getAuthorizableId(profilePath);
    // update the authorizable
    if (authorizableId != null) {
      AuthorizableManager authorizableManager = session.getAuthorizableManager();
      Authorizable a = authorizableManager.findAuthorizable(authorizableId);
      if (a != null) {
        // only treat "basic" special if it has the root profile node as its parent
        // this allows for a "basic" section to exist anywhere in the tree but only
        // have special meaning at the root

        if ("basic".equals(objectName) && isProfile(PathUtils.removeLastElement(profilePath), contentManager)) {
          processBasic(json, a);
          json = null;
        } else {
          if (json.has("basic") && isProfile(profilePath, contentManager)) {
            JSONObject basic = json.getJSONObject("basic");
            processBasic(basic, a);

            // KERN-1835, "basic" subtree data is stored in Authorizable object above,
            // therefore removing "basic" subtree data, before updating the content tree.
            // Content tree update strategy is "Partial update (with @Delete instructions where needed)"
            json.remove("basic");
          }
          if (json.has(GROUP_TITLE_PROPERTY)) {
            a.setProperty(GROUP_TITLE_PROPERTY, json.get(GROUP_TITLE_PROPERTY));
          }
          if (json.has(GROUP_DESCRIPTION_PROPERTY)) {
            a.setProperty(GROUP_DESCRIPTION_PROPERTY, json.get(GROUP_DESCRIPTION_PROPERTY));
          }
        }
        authorizableManager.updateAuthorizable(a);
      }
    }
    // update the profile content
    if (json != null && json.length() > 0) {
      AccessControlManager accessControlManger = session.getAccessControlManager();
      LiteJsonImporter importer = new LiteJsonImporter();
      importer.importContent(contentManager, json, profilePath, replace, replaceProperties,
          removeTree, accessControlManger);
    }
  }

  private void processBasic(JSONObject basic, Authorizable a)
      throws StorageClientException, AccessDeniedException, JSONException {
    if (basic.has("elements")) {
      JSONObject elements = basic.getJSONObject("elements");
      for (String element : basicUserInfoService.getBasicProfileElements()) {
        if (elements.has(element)) {
          JSONObject elementObject = elements.getJSONObject(element);
          if (elementObject.has("value")) {
            a.setProperty(element, elementObject.get("value"));
          }
        }
      }
      if ( basic.has("access")) {
        a.setProperty("access", basic.get("access"));
      }
    }
  }

  private boolean isProfile(String path, ContentManager contentManager)
      throws StorageClientException, AccessDeniedException {
    boolean retval = false;
    Content profile = contentManager.get(path);
    if (profile != null) {
      String resourceType = String.valueOf(profile.getProperty("sling:resourceType"));
      if (GROUP_PROFILE_RT.equals(resourceType) || USER_PROFILE_RT.equals(resourceType)) {
        return true;
      }
    }
    return retval;
  }
}


text:
using System;
using System.Xml.Serialization;

namespace HoloXPLOR.Data.DataForge
{
    [XmlRoot(ElementName = "CommunicationChannel")]
    public partial class CommunicationChannel
    {
        [XmlAttribute(AttributeName = "name")]
        public String Name { get; set; }

        [XmlAttribute(AttributeName = "minSilence")]
        public Single MinSilence { get; set; }

        [XmlAttribute(AttributeName = "flushSilence")]
        public Single FlushSilence { get; set; }

        [XmlAttribute(AttributeName = "type")]
        public eCommunicationChannelType Type { get; set; }

        [XmlAttribute(AttributeName = "priority")]
        public Int32 Priority { get; set; }

        [XmlAttribute(AttributeName = "minSpeakerSilence")]
        public Single MinSpeakerSilence { get; set; }

        [XmlAttribute(AttributeName = "ignoreSpeakerSilence")]
        public Boolean IgnoreSpeakerSilence { get; set; }

        [XmlElement(ElementName = "subtitles")]
        public CommunicationSubtitleSettings Subtitles { get; set; }

        [XmlArray(ElementName = "audioRTPC")]
        [XmlArrayItem(Type = typeof(CommunicationAudioRTPC))]
        public CommunicationAudioRTPC[] AudioRTPC { get; set; }

        [XmlArray(ElementName = "subChannels")]
        [XmlArrayItem(Type = typeof(CommunicationChannel))]
        public CommunicationChannel[] SubChannels { get; set; }

    }
}


text:
/* origin: OpenBSD /usr/src/lib/libm/src/polevll.c */
/*
 * Copyright (c) 2008 Stephen L. Moshier <steve@moshier.net>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
/*
 *      Evaluate polynomial
 *
 *
 * SYNOPSIS:
 *
 * int N;
 * long double x, y, coef[N+1], polevl[];
 *
 * y = polevll( x, coef, N );
 *
 *
 * DESCRIPTION:
 *
 * Evaluates polynomial of degree N:
 *
 *                     2          N
 * y  =  C  + C x + C x  +...+ C x
 *        0    1     2          N
 *
 * Coefficients are stored in reverse order:
 *
 * coef[0] = C  , ..., coef[N] = C  .
 *            N                   0
 *
 *  The function p1evll() assumes that coef[N] = 1.0 and is
 * omitted from the array.  Its calling arguments are
 * otherwise the same as polevll().
 *
 *
 * SPEED:
 *
 * In the interest of speed, there are no checks for out
 * of bounds arithmetic.  This routine is used by most of
 * the functions in the library.  Depending on available
 * equipment features, the user may wish to rewrite the
 * program in microcode or assembly language.
 *
 */

#include "libm.h"

#if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024
#else
/*
 * Polynomial evaluator:
 *  P[0] x^n  +  P[1] x^(n-1)  +  ...  +  P[n]
 */
long double __polevll(long double x, const long double *P, int n)
{
	long double y;

	y = *P++;
	do {
		y = y * x + *P++;
	} while (--n);

	return y;
}

/*
 * Polynomial evaluator:
 *  x^n  +  P[0] x^(n-1)  +  P[1] x^(n-2)  +  ...  +  P[n]
 */
long double __p1evll(long double x, const long double *P, int n)
{
	long double y;

	n -= 1;
	y = x + *P++;
	do {
		y = y * x + *P++;
	} while (--n);

	return y;
}
#endif


text:
<!DOCTYPE html>

<TITLE>Manpage of POSTKICK</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

POSTKICK

Section: User Commands  (1)
Index
Return to Main Contents

NAME

postkick
-
kick a Postfix service

SYNOPSIS

postkick [-c config_dir] [-v]
class service request

DESCRIPTION

The postkick(1) command sends request to the
specified service over a local transport channel.
This command makes Postfix private IPC accessible
for use in, for example, shell scripts.

Options:

-c config_dir

Read the main.cf configuration file in the named directory
instead of the default configuration directory.

-v

Enable verbose logging for debugging purposes. Multiple -v
options make the software increasingly verbose.

Arguments:

class

Name of a class of local transport channel endpoints,
either public (accessible by any local user) or
private (administrative access only).

service

The name of a local transport endpoint within the named class.

request

A string. The list of valid requests is service-specific.

DIAGNOSTICS

Problems and transactions are logged to the standard error
stream.

ENVIRONMENT

MAIL_CONFIG

Directory with Postfix configuration files.

MAIL_VERBOSE

Enable verbose logging for debugging purposes.

CONFIGURATION PARAMETERS

The following main.cf parameters are especially relevant to
this program.
The text below provides only a parameter summary. See
postconf(5) for more details including examples.

config_directory (see 'postconf -d' output)

The default location of the Postfix main.cf and master.cf
configuration files.

application_event_drain_time (100s)

How long the postkick(1) command waits for a request to enter the
server's input buffer before giving up.

queue_directory (see 'postconf -d' output)

The location of the Postfix top-level queue directory.

FILES

/var/spool/postfix/private, private class endpoints
/var/spool/postfix/public, public class endpoints

SEE ALSO

qmgr(8), queue manager trigger protocol
pickup(8), local pickup daemon
postconf(5), configuration parameters

LICENSE

The Secure Mailer license must be distributed with this software.

AUTHOR(S)

Wietse Venema
IBM T.J. Watson Research
P.O. Box 704
Yorktown Heights, NY 10598, USA

Index

NAME

SYNOPSIS

DESCRIPTION

DIAGNOSTICS

ENVIRONMENT

CONFIGURATION PARAMETERS

FILES

SEE ALSO

LICENSE

AUTHOR(S)

This document was created by
man2html,
using the manual pages.

Time: 05:29:09 GMT, December 24, 2015


text:
'use strict';

// Test directive is used to demo lazy loading external directive in the test project

angular.module('sgAppTest')
  .controller('sgAppTest', function($scope) {
    $scope.clickCount = 0;
    $scope.incrementClicks = function() {
      $scope.clickCount += 1;
    };
  })
  .directive('sgTestDirective', function() {
    return {
      replace: true,
      restrict: 'A',
      templateUrl: 'demo/testDirective.html'
    };
  });


text:
using namespace std;

using CountryInfo = map<string, string>;

void ChangeCapital(CountryInfo& ci, string& country, string& new_capital)
{
	auto c = ci.find(country);
	if(c == ci.end())
	{
		cout << "Introduce new country " << country << " with capital " << new_capital << endl;
		ci.insert(make_pair(country, new_capital));
	}
	else
	{
		if (c->second == new_capital)
		{
			cout << "Country " << country << " hasn't changed its capital" << endl;
		}
		else
		{
			cout << "Country " << country << " has changed its capital from " << c->second << " to " << new_capital << endl;
			c->second = new_capital;
		}
	}
}

void Rename(CountryInfo& ci, string& old_country_name, string& new_country_name)
{
	auto co = ci.find(old_country_name);
	auto cn = ci.find(new_country_name);
	if (co == ci.end() || old_country_name == new_country_name || cn != ci.end())
	{
		cout << "Incorrect rename, skip" << endl;
	}
	else
	{
		string capital = co->second;
		cout << "Country " << old_country_name << " with capital " << capital << " has been renamed to " << new_country_name << endl;
		ci.erase(old_country_name);
		ci[new_country_name] = capital;
	}
}

void About(CountryInfo& ci, string& country)
{
	auto c = ci.find(country);
	if (c != ci.end())
	{
		cout << "Country " << country << " has capital " << c->second << endl;
	}
	else
	{
		cout << "Country " << country << " doesn't exist" << endl;
	}
}

void Dump(CountryInfo& ci)
{
	if (ci.size() == 0)
	{
		cout << "There are no countries in the world" << endl;
	}
	else
	{
		for(auto& c : ci)
		{
			cout << c.first << "/" << c.second << " ";
		}
		cout << endl;
	}
}

int main02_12()
{
	int q;
	cin >> q;
	CountryInfo ci;
	for(int i = 0; i < q; i++)
	{
		string command;
		cin >> command;
		if(command == "CHANGE_CAPITAL")
		{
			string country, new_capital;
			cin >> country >> new_capital;
			ChangeCapital(ci, country, new_capital);
		}
		else if (command == "RENAME")
		{
			string old_country_name, new_country_name;
			cin >> old_country_name >> new_country_name;
			Rename(ci, old_country_name, new_country_name);
		}
		else if (command == "ABOUT")
		{
			string country;
			cin >> country;
			About(ci, country);
		}
		else if (command == "DUMP")
		{
			Dump(ci);
		}
		else
		{
			cout << "Invalid command" << endl;
		}
	}
	return 0;
}


text:
package org.devocative.metis;

import org.devocative.demeter.entity.IPrivilegeKey;

public enum MetisPrivilegeKey implements IPrivilegeKey {
	DBConnectionGroupAdd, DBConnectionGroupEdit,
	DBConnectionAdd, DBConnectionEdit, DBConnectionCloseAll,
	DataGroupAdd, DataGroupEdit,
	ReportAdd, ReportEdit,
	DataViewExport,
	DataViewImport,
	DBConnectionAliasAdd, DBConnectionAliasEdit,
	ReportExport,
	ReportImport;

	private String name;

	@Override
	public String getName() {
		return name;
	}

	@Override
	public void setModule(String module) {
		name = String.format("%s.%s", module, name());
	}
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using ZyGames.Framework.Cache;
using ZyGames.Framework.Common;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Service;
using ZyGames.Tianjiexing.BLL.Base;
using ZyGames.Tianjiexing.BLL.Combat;
using ZyGames.Tianjiexing.Component;
using ZyGames.Tianjiexing.Model;
using ZyGames.Tianjiexing.Model.Config;
using ZyGames.Tianjiexing.Model.Enum;

namespace ZyGames.Tianjiexing.BLL.Action
{

    /// <summary>
    /// 1257_附魔符培养界面接口
    /// </summary>
    public class Action1257 : BaseAction
    {
        private string userEnchantID;
        private string abilityNum;
        private decimal matureNum;
        private decimal maxMature;
        private UserEnchantInfo userEnchant = null;
        private EnchantInfo enchantInfo = null;
        private List<EnchantCulTure> enchantList = new List<EnchantCulTure>();

        public Action1257(ZyGames.Framework.Game.Contract.HttpGet httpGet)
            : base(ActionIDDefine.Cst_Action1257, httpGet)
        {

        }

        public override void BuildPacket()
        {
            this.PushIntoStack(enchantInfo == null ? string.Empty : enchantInfo.EnchantName.ToNotNullString());
            this.PushIntoStack(enchantInfo == null ? string.Empty : enchantInfo.HeadID.ToNotNullString());
            this.PushIntoStack(userEnchant == null ? (short)0 : (short)userEnchant.EnchantLv);
            this.PushIntoStack(enchantInfo == null ? (short)0 : (short)enchantInfo.ColorType);
            this.PushIntoStack(matureNum.ToNotNullString());
            this.PushIntoStack(TrumpHelper.GetTransformData(maxMature).ToNotNullString());
            this.PushIntoStack(enchantInfo == null ? (short)0 : (short)enchantInfo.AbilityType);
            this.PushIntoStack(abilityNum.ToNotNullString());
            this.PushIntoStack(enchantList.Count);
            foreach (var culTure in enchantList)
            {
                DataStruct dsItem = new DataStruct();
                dsItem.PushIntoStack((short)culTure.CultureType);
                dsItem.PushIntoStack(culTure.MoJingNum);
                dsItem.PushIntoStack(culTure.GoldNum);
                dsItem.PushIntoStack((int)culTure.UpMature);
                dsItem.PushIntoStack(culTure.SuccessNum.ToNotNullString());
                dsItem.PushIntoStack(IsMeet(ContextUser, culTure) ? (short)1 : (short)0);
                this.PushIntoStack(dsItem);
            }
        }

        public override bool GetUrlElement()
        {
            if (httpGet.GetString("UserEnchantID", ref userEnchantID))
            {
                return true;
            }
            return false;
        }

        public override bool TakeAction()
        {
            var package = UserEnchant.Get(ContextUser.UserID);
            if (package != null)
            {
                userEnchant = package.EnchantPackage.Find(m => m.UserEnchantID == userEnchantID);
                if (userEnchant != null)
                {
                    matureNum = (decimal)userEnchant.MaxMature / GameConfigSet.MaxEnchantMature;
                    maxMature = CombatHelper.EnchantFinalNum(userEnchant);
                    enchantInfo = new ConfigCacheSet<EnchantInfo>().FindKey(userEnchant.EnchantID);
                    EnchantLvInfo enchantLvInfo = new ConfigCacheSet<EnchantLvInfo>().FindKey(userEnchant.EnchantID,
                                                                                userEnchant.EnchantLv);
                    if (enchantLvInfo != null)
                    {
                        abilityNum = TrumpHelper.GetTransformData(enchantLvInfo.Num);
                    }
                }
            }
            enchantList = EnchantHelper.EnchantCultureList();
            return true;
        }

        /// <summary>
        /// 是否满足培养条件
        /// </summary>
        /// <param name="user"></param>
        /// <param name="culTure"></param>
        /// <returns></returns>
        public static bool IsMeet(GameUser user, EnchantCulTure culTure)
        {
            if ((culTure.CultureType == EnchantCultureType.Ordinary && user.UserExtend != null && user.UserExtend.MoJingNum >= culTure.MoJingNum)
                || (user.GoldNum >= culTure.GoldNum && culTure.CultureType != EnchantCultureType.Ordinary))
            {
                return true;
            }
            return false;
        }
    }
}


text:
require 'beaker-rspec/spec_helper'
require 'beaker-rspec/helpers/serverspec'
require 'beaker/puppet_install_helper'

run_puppet_install_helper

RSpec.configure do |c|
  # Project root
  proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))

  # Readable test descriptions
  c.formatter = :documentation

  # Configure all nodes in nodeset
  c.before :suite do
    # Install module and dependencies
    puppet_module_install(source: proj_root, module_name: 'bind')
    hosts.each do |host|
      on host, puppet('module', 'install', 'puppetlabs-stdlib'), acceptable_exit_codes: [0]
      on host, puppet('module', 'install', 'puppetlabs-concat'), acceptable_exit_codes: [0]
    end
  end
end


text:
class Hooks::ViewProjectsFormHook < Redmine::Hook::ViewListener
  render_on :view_projects_form,
            :partial => 'hooks/timelines/view_projects_form'

end


text:
@interface BZInvalidValuesModel : NSObject
@property (nonatomic,assign) Class vclass;
@property (nonatomic,assign) SEL vsel;
@end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mitteil. Thür. Bot. Ver. , N. F. 28: 64 (1911)

#### Original name
Schroeteria bornmuelleri Magnus, 1911

### Remarks
null


text:
'use strict';

/**
 * Read-write endpoint of the failover group instance.
 *
 */
class FailoverGroupReadWriteEndpoint {
  /**
   * Create a FailoverGroupReadWriteEndpoint.
   * @member {string} failoverPolicy Failover policy of the read-write endpoint
   * for the failover group. If failoverPolicy is Automatic then
   * failoverWithDataLossGracePeriodMinutes is required. Possible values
   * include: 'Manual', 'Automatic'
   * @member {number} [failoverWithDataLossGracePeriodMinutes] Grace period
   * before failover with data loss is attempted for the read-write endpoint.
   * If failoverPolicy is Automatic then failoverWithDataLossGracePeriodMinutes
   * is required.
   */
  constructor() {
  }

  /**
   * Defines the metadata of FailoverGroupReadWriteEndpoint
   *
   * @returns {object} metadata of FailoverGroupReadWriteEndpoint
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'FailoverGroupReadWriteEndpoint',
      type: {
        name: 'Composite',
        className: 'FailoverGroupReadWriteEndpoint',
        modelProperties: {
          failoverPolicy: {
            required: true,
            serializedName: 'failoverPolicy',
            type: {
              name: 'String'
            }
          },
          failoverWithDataLossGracePeriodMinutes: {
            required: false,
            serializedName: 'failoverWithDataLossGracePeriodMinutes',
            type: {
              name: 'Number'
            }
          }
        }
      }
    };
  }
}

module.exports = FailoverGroupReadWriteEndpoint;


text:
require 'test/unit'
require "-test-/class"

class Test_Class < Test::Unit::TestCase
  class Test_Class2Name < superclass
    def test_toplevel_class
      assert_equal("Object", Bug::Class.class2name(::Object))
    end

    def test_toplevel_module
      assert_equal("Kernel", Bug::Class.class2name(::Kernel))
    end

    def test_singleton_class
      assert_equal("Object", Bug::Class.class2name(::Object.new.singleton_class))
    end
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

    <title>boxsdk.network.default_network — boxsdk 1.1.6 documentation</title>

    <link rel="stylesheet" href="../../../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />

    <link rel="top" title="boxsdk 1.1.6 documentation" href="../../../index.html" />
    <link rel="up" title="Module code" href="../../index.html" />

Navigation

          index

          modules |

boxsdk 1.1.6 documentation »

Module code »

Source code for boxsdk.network.default_network

# coding: utf-8

from __future__ import unicode_literals

import requests
import time

from .network_interface import Network, NetworkResponse

[docs]class DefaultNetwork(Network):
    """Implementation of the network interface using the requests library."""

    def __init__(self):
        super(DefaultNetwork, self).__init__()
        self._session = requests.Session()

[docs]    def request(self, method, url, access_token, **kwargs):
        """Base class override.
        Make a network request using a requests.Session.
        """
        return DefaultNetworkResponse(self._session.request(method, url, **kwargs), access_token)

[docs]    def retry_after(self, delay, request_method, *args, **kwargs):
        """Base class override.
        Retry after sleeping for delay seconds.
        """
        time.sleep(delay)
        return request_method(*args, **kwargs)

[docs]class DefaultNetworkResponse(NetworkResponse):
    """Implementation of the network interface using the requests library."""

    def __init__(self, request_response, access_token_used):
        self._request_response = request_response
        self._access_token_used = access_token_used

[docs]    def json(self):
        """Base class override."""
        return self._request_response.json()

    @property
    def content(self):
        """Base class override."""
        return self._request_response.content

    @property
    def status_code(self):
        """Base class override."""
        return self._request_response.status_code

    @property
    def ok(self):
        """Base class override."""
        # pylint:disable=invalid-name
        return self._request_response.ok

    @property
    def headers(self):
        """Base class override."""
        return self._request_response.headers

    @property
    def response_as_stream(self):
        """Base class override."""
        return self._request_response.raw

    @property
    def access_token_used(self):
        """Base class override."""
        return self._access_token_used

Quick search

    <form class="search" action="../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

boxsdk 1.1.6 documentation »

Module code »

        © Copyright 2014, Box.
      Created using Sphinx 1.3.1.


text:
namespace blink {

void WebMediaStreamAudioSink::AddToAudioTrack(
    WebMediaStreamAudioSink* sink,
    const blink::WebMediaStreamTrack& track) {
  DCHECK(track.Source().GetType() == blink::WebMediaStreamSource::kTypeAudio);
  MediaStreamAudioTrack* native_track = MediaStreamAudioTrack::From(track);
  DCHECK(native_track);
  native_track->AddSink(sink);
}

void WebMediaStreamAudioSink::RemoveFromAudioTrack(
    WebMediaStreamAudioSink* sink,
    const blink::WebMediaStreamTrack& track) {
  MediaStreamAudioTrack* native_track = MediaStreamAudioTrack::From(track);
  DCHECK(native_track);
  native_track->RemoveSink(sink);
}

media::AudioParameters WebMediaStreamAudioSink::GetFormatFromAudioTrack(
    const blink::WebMediaStreamTrack& track) {
  MediaStreamAudioTrack* native_track = MediaStreamAudioTrack::From(track);
  DCHECK(native_track);
  return native_track->GetOutputFormat();
}

}  // namespace blink


text:
<?php
namespace Procure\Domain\PurchaseOrder;

use Application\Domain\Shared\DTOFactory;
use Application\Domain\Shared\SnapshotAssembler;
use Application\Domain\Shared\Assembler\GenericObjectAssembler;
use Application\Domain\Shared\Command\CommandOptions;
use Procure\Application\DTO\Po\PORowDTO;
use Procure\Application\DTO\Po\PORowDetailsDTO;
use Procure\Domain\GenericDoc;
use Procure\Domain\Contracts\ProcureDocType;
use Procure\Domain\Contracts\ProcureTrxStatus;
use Procure\Domain\QuotationRequest\QRRow;
use Webmozart\Assert\Assert;

/**
 * PO Row
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
final class PORow extends BaseRow
{

    /**
     *
     * {@inheritdoc}
     * @see \Procure\Domain\GenericRow::updateRowStatus()
     */
    public function updateRowStatus()
    {
        $openGRQty = $this->getPostedStandardGrQuantity() - $this->getPostedStandardGrQuantity();
        $openAPQty = $this->getPostedStandardGrQuantity() - $this->getPostedStandardApQuantity();
        $openAPAmount = $this->getNetAmount() - $this->getBilledAmount();

        $this->setConfirmedGrBalance($openGRQty);
        $this->setOpenAPQuantity($openAPQty);
        $this->setOpenAPAmount($openAPAmount);

        $this->setTransactionStatus(ProcureTrxStatus::PENDING);

        if ($openGRQty <= 0 and $openAPQty <= 0) {
            $this->setTransactionStatus(ProcureTrxStatus::COMPLETED);
        }
    }

    /**
     *
     * {@inheritdoc}
     * @see \Procure\Domain\GenericRow::createVO()
     */
    protected function createVO(GenericDoc $rootDoc)
    {
        $this->createUomVO();
        $this->createQuantityVO();
        $this->createDocPriceVO($rootDoc);
        $this->createLocalPriceVO($rootDoc);
    }

    public static function cloneFrom(PODoc $rootDoc, PoRow $sourceObj, CommandOptions $options)
    {
        Assert::isInstanceOf($rootDoc, PODoc::class, "PO is required!");
        Assert::isInstanceOf($sourceObj, PoRow::class, "PO row is required!");
        Assert::notNull($options, "No Options is found");

        /**
         *
         * @var PORow $instance
         */
        $instance = new self();

        $exculdedProps = [
            'invoice',
            'po',
            'rowIdentifer'
        ];

        $instance = $sourceObj->convertExcludeFieldsTo($instance, $exculdedProps);
        $instance->initRow($options);
        return $instance;
    }

    /**
     *
     * @param PODoc $rootDoc
     * @param PORowSnapshot $snapshot
     * @return \Procure\Domain\PurchaseOrder\PORow
     */
    public static function createFromSnapshot(PODoc $rootDoc, PORowSnapshot $snapshot)
    {
        Assert::isInstanceOf($rootDoc, PODoc::class, "PO is required!");
        Assert::isInstanceOf($snapshot, PORowSnapshot::class, "PO row snapshot is required!");

        $instance = new self();

        SnapshotAssembler::makeFromSnapshot($instance, $snapshot);
        $instance->createVO($rootDoc);
        return $instance;
    }

    public static function createFromQuoteRow(QRRow $sourceObj, CommandOptions $options)
    {
        Assert::isInstanceOf($sourceObj, QRRow::class, "Quotation document is required!");

        /**
         *
         * @var PORow $instance
         */
        $instance = new self();
        $instance = $sourceObj->convertTo($instance);

        $instance->setDocType(ProcureDocType::PO_FROM_QOUTE); // important.
                                                              // $instance->setQ($sourceObj->getId()); // Important

        $createdDate = new \Datetime();
        $createdBy = $options->getUserId();
        $instance->initRow($options);

        return $instance;
    }

    /**
     *
     * @return \Procure\Domain\PurchaseOrder\PORow
     */
    public static function getInstance()
    {
        if (self::$instance == null) {
            self::$instance = new PORow();
        }
        return self::$instance;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Procure\Domain\GenericRow::makeSnapshot()
     */
    public function makeSnapshot()
    {
        return GenericObjectAssembler::updateAllFieldsFrom(new PORowSnapshot(), $this);
    }

    /**
     *
     * @return NULL|\Procure\Application\DTO\Po\PORowDTO
     */
    public function makeDTO()
    {
        return \Application\Domain\Shared\DTOFactory::createDTOFrom($this, new PORowDTO());
    }

    /**
     *
     * @return NULL|\Procure\Application\DTO\Po\PORowDTO
     */
    public function makeDetailsDTO()
    {
        $dto = new PORowDetailsDTO();
        $dto = DTOFactory::createDTOFrom($this, $dto);
        return $dto;
    }

    /**
     *
     * @return NULL|object
     */
    public function makeDTOForGrid()
    {
        $dto = new PORowDetailsDTO();
        $dto = DTOFactory::createDTOFrom($this, $dto);
        return $dto;
    }

    public static function constructFromDB(PORowSnapshot $snapshot)
    {
        if (! $snapshot instanceof PORowSnapshot) {
            return null;
        }

        $instance = new self();

        GenericObjectAssembler::updateAllFieldsFrom($instance, $snapshot);
        $instance->setConstructedFromDB(TRUE);

        return $instance;
    }

    /**
     *
     * @param PORowSnapshot $snapshot
     */
    public static function makeFromSnapshot(PORowSnapshot $snapshot)
    {
        if (! $snapshot instanceof PORowSnapshot) {
            return null;
        }

        $instance = new self();

        SnapshotAssembler::makeFromSnapshot($instance, $snapshot);
        return $instance;
    }

    /**
     *
     * @param PORowDetailsSnapshot $snapshot
     */
    public static function makeFromDetailsSnapshot(PORowSnapshot $snapshot)
    {
        if (! $snapshot instanceof PORowSnapshot)
            return;

        $instance = new self();
        SnapshotAssembler::makeFromSnapshot($instance, $snapshot);
        return $instance;
    }
}


text:
// +build go1.7 go1.8

package minio

import (
	"crypto/tls"
	"crypto/x509"
	"net"
	"net/http"
	"time"

	"golang.org/x/net/http2"
)

// DefaultTransport - this default transport is similar to
// http.DefaultTransport but with additional param  DisableCompression
// is set to true to avoid decompressing content with 'gzip' encoding.
var DefaultTransport = func(secure bool) (http.RoundTripper, error) {
	tr := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		DialContext: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		}).DialContext,
		MaxIdleConns:          1024,
		MaxIdleConnsPerHost:   1024,
		IdleConnTimeout:       90 * time.Second,
		TLSHandshakeTimeout:   10 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
		// Set this value so that the underlying transport round-tripper
		// doesn't try to auto decode the body of objects with
		// content-encoding set to `gzip`.
		//
		// Refer:
		//    https://golang.org/src/net/http/transport.go?h=roundTrip#L1843
		DisableCompression: true,
	}

	if secure {
		rootCAs, _ := x509.SystemCertPool()
		if rootCAs == nil {
			// In some systems (like Windows) system cert pool is
			// not supported or no certificates are present on the
			// system - so we create a new cert pool.
			rootCAs = x509.NewCertPool()
		}

		// Keep TLS config.
		tlsConfig := &tls.Config{
			RootCAs: rootCAs,
			// Can't use SSLv3 because of POODLE and BEAST
			// Can't use TLSv1.0 because of POODLE and BEAST using CBC cipher
			// Can't use TLSv1.1 because of RC4 cipher usage
			MinVersion: tls.VersionTLS12,
		}
		tr.TLSClientConfig = tlsConfig

		// Because we create a custom TLSClientConfig, we have to opt-in to HTTP/2.
		// See https://github.com/golang/go/issues/14275
		if err := http2.ConfigureTransport(tr); err != nil {
			return nil, err
		}
	}
	return tr, nil
}


text:
package com.eaglesakura.andriders.ui;

import com.eaglesakura.andriders.AcesEnvironment;
import com.eaglesakura.andriders.serialize.CommandProtocol.TweetRequestPayload;
import com.eaglesakura.util.LogUtil;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;

@Deprecated
public class TweetSettingUtil {

    /**
     * ツイート設定用メッセージ
     */
    public static final String EXTRA_TWEETREQUEST_PAYLOAD = "EXTRA_TWEETREQUEST_PAYLOAD";

    /**
     * ツイート設定用Activityを開く
     */
    public static Intent createDefaultTweetSettingActivityIntent(Context context) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(AcesEnvironment.getApplicationPackageName(), "com.eaglesakura.andriders.ui.sns.TweetMessageInputActivity_"));
        return intent;
    }

    /**
     * ツイート設定Activityからツイート設定メッセージを受け取る
     */
    public static TweetRequestPayload getResultTweetRequest(Intent resultIntent) {
        byte[] extra = resultIntent.getByteArrayExtra(EXTRA_TWEETREQUEST_PAYLOAD);
        if (extra == null) {
            return null;
        }

        try {
            return TweetRequestPayload.parseFrom(extra);
        } catch (Exception e) {
            LogUtil.d(e);
            return null;
        }
    }
}


text:
<?php

namespace PhpParser\Builder;

use PhpParser;
use PhpParser\Node;
use PhpParser\Node\Stmt;

abstract class FunctionLike extends Declaration {

    protected $returnByRef = false;
    protected $params = array();

    /**
     * Make the function return by reference.
     *
     * @return $this The builder instance (for fluid interface)
     */
    public function makeReturnByRef() {
        $this->returnByRef = true;

        return $this;
    }

    /**
     * Adds a parameter.
     *
     * @param Node\Param|Param $param The parameter to add
     *
     * @return $this The builder instance (for fluid interface)
     */
    public function addParam($param) {
        $param = $this->normalizeNode($param);

        if (!$param instanceof Node\Param) {
            throw new \LogicException(sprintf('Expected parameter node, got "%s"', $param->getType()));
        }

        $this->params[] = $param;

        return $this;
    }

    /**
     * Adds multiple parameters.
     *
     * @param array $params The parameters to add
     *
     * @return $this The builder instance (for fluid interface)
     */
    public function addParams(array $params) {
        foreach ($params as $param) {
            $this->addParam($param);
        }

        return $this;
    }

}


text:
"""
Demonstrates fetching id3 information for a song

Note: sudo pip install mutagen

eg: ./020-id3.py "data/06 Cliantro Vision.mp3"

"""
import argparse
from mutagen.easyid3 import EasyID3

def main():

	parser = argparse.ArgumentParser(description='Download some videos')
	parser.add_argument('song', type=str, nargs=1, help='The song to read id3 tags from')
	args = parser.parse_args()

	audio = EasyID3(args.song[0])
	print "Album: "+audio["album"][0]
	print "Artist: "+audio["artist"][0]
	print "Title: "+audio["title"][0]

if __name__ == '__main__':
	main()


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>leaflet on Tim Thoughts</title>
    <link>/categories/leaflet/</link>
    <description>Recent content in leaflet on Tim Thoughts</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <copyright>© {2020}</copyright>
    <lastBuildDate>Mon, 20 Jul 2020 00:00:00 +0000</lastBuildDate>

	<atom:link href="/categories/leaflet/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>shiny test</title>
      <link>/blog/shiny-test/</link>
      <pubDate>Mon, 20 Jul 2020 00:00:00 +0000</pubDate>

      <guid>/blog/shiny-test/</guid>
      <description> </description>
    </item>

    <item>
      <title>Back to Florida</title>
      <link>/blog/back-to-florida/</link>
      <pubDate>Fri, 17 Jul 2020 00:00:00 +0000</pubDate>

      <guid>/blog/back-to-florida/</guid>
      <description>Practicing my Leaflet and data cleaning skills!
This is a ethnicity breakdown of Census-tract level data of Florida using the 2014-2018 ACS datasets, focusing on CVAP (citizen voting age population) data.
I&rsquo;ve layered on a dot-density map of renters and internet accessibility.
I&rsquo;ve added 2016 and 2018 election results (using Clinton and Gillum&rsquo;s percentages as a rough benchmark for Democratic Party&rsquo;s &ldquo;blue&rdquo;)
Future iterations of this map will consolidate and cleanup the missing NA&rsquo;s, I got a suspicion we got some consolidated precincts to clean up.</description>
    </item>

  </channel>
</rss>


text:
function l = uniformPriorLogProb(prior, x)

% UNIFORMPRIORLOGPROB Log probability of uniform prior.

% GPMAT

% Compute log prior

l = sum(log((x >= prior.a) .* (x <= prior.b) * 1 / (prior.b - prior.a)));


text:
package rpc

import (
	"fmt"
	"github.com/golang/glog"
	"github.com/nebulaim/telegramd/baselib/grpc_util"
	"github.com/nebulaim/telegramd/baselib/logger"
	"github.com/nebulaim/telegramd/proto/mtproto"
	"golang.org/x/net/context"
)

/*
	if (error.text.equals("PASSWORD_HASH_INVALID")) {
		onPasscodeError(true);
	} else if (error.text.startsWith("FLOOD_WAIT")) {
		int time = Utilities.parseInt(error.text);
		String timeString;
		if (time < 60) {
			timeString = LocaleController.formatPluralString("Seconds", time);
		} else {
			timeString = LocaleController.formatPluralString("Minutes", time / 60);
		}
		needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString));
	} else {
		needShowAlert(LocaleController.getString("AppName", R.string.AppName), error.text);
	}
*/

// 客户端调用auth.signIn时返回SESSION_PASSWORD_NEEDED时会触发

// auth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;
func (s *AuthServiceImpl) AuthCheckPassword(ctx context.Context, request *mtproto.TLAuthCheckPassword) (*mtproto.Auth_Authorization, error) {
	md := grpc_util.RpcMetadataFromIncoming(ctx)
	glog.Infof("auth.checkPassword#a63011e - metadata: %s, request: %s", logger.JsonDebugData(md), logger.JsonDebugData(request))

/*
	var (
		err error
	)

	password := request.GetPassword()

	if len(request.PasswordHash) == 0 {
		err = mtproto.NewRpcError2(mtproto.TLRpcErrorCodes_PASSWORD_HASH_INVALID)
		glog.Error(err)
		return nil, err
	}

	passwordLogic, err := s.AccountModel.MakePasswordData(md.UserId)
	if err != nil {
		glog.Error(err)
		return nil, err
	}

	ok := passwordLogic.CheckPassword(request.PasswordHash)
	if !ok {
		err = mtproto.NewRpcError2(mtproto.TLRpcErrorCodes_PASSWORD_HASH_INVALID)
		glog.Error(err)
		return nil, err
	}

	user := s.UserModel.GetUserById(md.UserId, md.UserId)
	authAuthorization := &mtproto.TLAuthAuthorization{Data2: &mtproto.Auth_Authorization_Data{
		User: user.To_User(),
	}}

	glog.Infof("auth.checkPassword#a63011e - reply: %s\n", logger.JsonDebugData(authAuthorization))
	return authAuthorization.To_Auth_Authorization(), nil
 */

	return nil, fmt.Errorf("not impl auth.checkPassword#d18b4d16")
}


text:
/*	$NetBSD: uipc_mbuf2.c,v 1.30 2013/10/08 19:59:49 christos Exp $	*/
/*	$KAME: uipc_mbuf2.c,v 1.29 2001/02/14 13:42:10 itojun Exp $	*/

/*
 * Copyright (C) 1999 WIDE Project.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * Copyright (c) 1982, 1986, 1988, 1991, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)uipc_mbuf.c	8.4 (Berkeley) 2/14/95
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: uipc_mbuf2.c,v 1.30 2013/10/08 19:59:49 christos Exp $");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>

MALLOC_DEFINE(M_PACKET_TAGS, "packet tags", "Packet-attached information");

/*
 * ensure that [off, off + len) is contiguous on the mbuf chain "m".
 * packet chain before "off" is kept untouched.
 * if offp == NULL, the target will start at <retval, 0> on resulting chain.
 * if offp != NULL, the target will start at <retval, *offp> on resulting chain.
 *
 * on error return (NULL return value), original "m" will be freed.
 *
 * XXX M_TRAILINGSPACE/M_LEADINGSPACE on shared cluster (sharedcluster)
 */
struct mbuf *
m_pulldown(struct mbuf *m, int off, int len, int *offp)
{
	struct mbuf *n, *o;
	int hlen, tlen, olen;
	int sharedcluster;

	/* check invalid arguments. */
	if (m == NULL)
		panic("m == NULL in m_pulldown()");
	if (len > MCLBYTES) {
		m_freem(m);
		return NULL;	/* impossible */
	}

	n = m;
	while (n != NULL && off > 0) {
		if (n->m_len > off)
			break;
		off -= n->m_len;
		n = n->m_next;
	}
	/* be sure to point non-empty mbuf */
	while (n != NULL && n->m_len == 0)
		n = n->m_next;
	if (!n) {
		m_freem(m);
		return NULL;	/* mbuf chain too short */
	}

	sharedcluster = M_READONLY(n);

	/*
	 * the target data is on <n, off>.
	 * if we got enough data on the mbuf "n", we're done.
	 */
	if ((off == 0 || offp) && len <= n->m_len - off && !sharedcluster)
		goto ok;

	/*
	 * when len <= n->m_len - off and off != 0, it is a special case.
	 * len bytes from <n, off> sits in single mbuf, but the caller does
	 * not like the starting position (off).
	 * chop the current mbuf into two pieces, set off to 0.
	 */
	if (len <= n->m_len - off) {
		struct mbuf *mlast;

		o = m_dup(n, off, n->m_len - off, M_DONTWAIT);
		if (o == NULL) {
			m_freem(m);
			return NULL;	/* ENOBUFS */
		}
		KASSERT(o->m_len >= len);
		for (mlast = o; mlast->m_next != NULL; mlast = mlast->m_next)
			;
		n->m_len = off;
		mlast->m_next = n->m_next;
		n->m_next = o;
		n = o;
		off = 0;
		goto ok;
	}

	/*
	 * we need to take hlen from <n, off> and tlen from <n->m_next, 0>,
	 * and construct contiguous mbuf with m_len == len.
	 * note that hlen + tlen == len, and tlen > 0.
	 */
	hlen = n->m_len - off;
	tlen = len - hlen;

	/*
	 * ensure that we have enough trailing data on mbuf chain.
	 * if not, we can do nothing about the chain.
	 */
	olen = 0;
	for (o = n->m_next; o != NULL; o = o->m_next)
		olen += o->m_len;
	if (hlen + olen < len) {
		m_freem(m);
		return NULL;	/* mbuf chain too short */
	}

	/*
	 * easy cases first.
	 * we need to use m_copydata() to get data from <n->m_next, 0>.
	 */
	if ((off == 0 || offp) && M_TRAILINGSPACE(n) >= tlen &&
	    !sharedcluster) {
		m_copydata(n->m_next, 0, tlen, mtod(n, char *) + n->m_len);
		n->m_len += tlen;
		m_adj(n->m_next, tlen);
		goto ok;
	}
	if ((off == 0 || offp) && M_LEADINGSPACE(n->m_next) >= hlen &&
	    !sharedcluster && n->m_next->m_len >= tlen) {
		n->m_next->m_data -= hlen;
		n->m_next->m_len += hlen;
		memcpy(mtod(n->m_next, void *), mtod(n, char *) + off, hlen);
		n->m_len -= hlen;
		n = n->m_next;
		off = 0;
		goto ok;
	}

	/*
	 * now, we need to do the hard way.  don't m_copy as there's no room
	 * on both end.
	 */
	o = m_get(M_DONTWAIT, m->m_type);
	if (o && len > MLEN) {
		MCLGET(o, M_DONTWAIT);
		if ((o->m_flags & M_EXT) == 0) {
			m_free(o);
			o = NULL;
		}
	}
	if (!o) {
		m_freem(m);
		return NULL;	/* ENOBUFS */
	}
	/* get hlen from <n, off> into <o, 0> */
	o->m_len = hlen;
	memcpy(mtod(o, void *), mtod(n, char *) + off, hlen);
	n->m_len -= hlen;
	/* get tlen from <n->m_next, 0> into <o, hlen> */
	m_copydata(n->m_next, 0, tlen, mtod(o, char *) + o->m_len);
	o->m_len += tlen;
	m_adj(n->m_next, tlen);
	o->m_next = n->m_next;
	n->m_next = o;
	n = o;
	off = 0;

ok:
	if (offp)
		*offp = off;
	return n;
}

/*
 * FreeBSD 4.6 introduced m_getcl(), which performs `fast' allocation
 * mbuf clusters from a cache of recently-freed clusters. (If the cache
 * is empty, new clusters are allocated en-masse).
 * On NetBSD, for now, implement the `cache' as a function
 * using normal NetBSD mbuf/cluster allocation macros. Replace this
 * with fast-cache code, if and when NetBSD implements one.
 */
struct mbuf *
m_getcl(int how, int type, int flags)
{
	struct mbuf *mp;

	if ((flags & M_PKTHDR) != 0)
		mp = m_gethdr(how, type);
	else
		mp = m_get(how, type);

	if (mp == NULL)
		return NULL;

	MCLGET(mp, how);
	if ((mp->m_flags & M_EXT) != 0)
		return mp;

	m_free(mp);
	return NULL;
}

/* Get a packet tag structure along with specified data following. */
struct m_tag *
m_tag_get(int type, int len, int wait)
{
	struct m_tag *t;

	if (len < 0)
		return (NULL);
	t = malloc(len + sizeof(struct m_tag), M_PACKET_TAGS, wait);
	if (t == NULL)
		return (NULL);
	t->m_tag_id = type;
	t->m_tag_len = len;
	return (t);
}

/* Free a packet tag. */
void
m_tag_free(struct m_tag *t)
{

	free(t, M_PACKET_TAGS);
}

/* Prepend a packet tag. */
void
m_tag_prepend(struct mbuf *m, struct m_tag *t)
{

	SLIST_INSERT_HEAD(&m->m_pkthdr.tags, t, m_tag_link);
}

/* Unlink a packet tag. */
void
m_tag_unlink(struct mbuf *m, struct m_tag *t)
{

	SLIST_REMOVE(&m->m_pkthdr.tags, t, m_tag, m_tag_link);
}

/* Unlink and free a packet tag. */
void
m_tag_delete(struct mbuf *m, struct m_tag *t)
{

	m_tag_unlink(m, t);
	m_tag_free(t);
}

/* Unlink and free a packet tag chain, starting from given tag. */
void
m_tag_delete_chain(struct mbuf *m, struct m_tag *t)
{
	struct m_tag *p, *q;

	if (t != NULL)
		p = t;
	else
		p = SLIST_FIRST(&m->m_pkthdr.tags);
	if (p == NULL)
		return;
	while ((q = SLIST_NEXT(p, m_tag_link)) != NULL)
		m_tag_delete(m, q);
	m_tag_delete(m, p);
}

/*
 * Strip off all tags that would normally vanish when
 * passing through a network interface.  Only persistent
 * tags will exist after this; these are expected to remain
 * so long as the mbuf chain exists, regardless of the
 * path the mbufs take.
 */
void
m_tag_delete_nonpersistent(struct mbuf *m)
{
	/* NetBSD has no persistent tags yet, so just delete all tags. */
	m_tag_delete_chain(m, NULL);
}

/* Find a tag, starting from a given position. */
struct m_tag *
m_tag_find(const struct mbuf *m, int type, struct m_tag *t)
{
	struct m_tag *p;

	if (t == NULL)
		p = SLIST_FIRST(&m->m_pkthdr.tags);
	else
		p = SLIST_NEXT(t, m_tag_link);
	while (p != NULL) {
		if (p->m_tag_id == type)
			return (p);
		p = SLIST_NEXT(p, m_tag_link);
	}
	return (NULL);
}

/* Copy a single tag. */
struct m_tag *
m_tag_copy(struct m_tag *t)
{
	struct m_tag *p;

	p = m_tag_get(t->m_tag_id, t->m_tag_len, M_NOWAIT);
	if (p == NULL)
		return (NULL);
	memcpy(p + 1, t + 1, t->m_tag_len); /* Copy the data */
	return (p);
}

/*
 * Copy two tag chains. The destination mbuf (to) loses any attached
 * tags even if the operation fails. This should not be a problem, as
 * m_tag_copy_chain() is typically called with a newly-allocated
 * destination mbuf.
 */
int
m_tag_copy_chain(struct mbuf *to, struct mbuf *from)
{
	struct m_tag *p, *t, *tprev = NULL;

	m_tag_delete_chain(to, NULL);
	SLIST_FOREACH(p, &from->m_pkthdr.tags, m_tag_link) {
		t = m_tag_copy(p);
		if (t == NULL) {
			m_tag_delete_chain(to, NULL);
			return (0);
		}
		if (tprev == NULL)
			SLIST_INSERT_HEAD(&to->m_pkthdr.tags, t, m_tag_link);
		else
			SLIST_INSERT_AFTER(tprev, t, m_tag_link);
		tprev = t;
	}
	return (1);
}

/* Initialize tags on an mbuf. */
void
m_tag_init(struct mbuf *m)
{

	SLIST_INIT(&m->m_pkthdr.tags);
}

/* Get first tag in chain. */
struct m_tag *
m_tag_first(struct mbuf *m)
{

	return (SLIST_FIRST(&m->m_pkthdr.tags));
}

/* Get next tag in chain. */
struct m_tag *
m_tag_next(struct mbuf *m, struct m_tag *t)
{

	return (SLIST_NEXT(t, m_tag_link));
}


text:
</div

Copyright © PHPrinciples 2016


text:
#include <aws/networkmanager/model/StartOrganizationServiceAccessUpdateRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

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

StartOrganizationServiceAccessUpdateRequest::StartOrganizationServiceAccessUpdateRequest() :
    m_actionHasBeenSet(false)
{
}

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

  if(m_actionHasBeenSet)
  {
   payload.WithString("Action", m_action);

  }

  return payload.View().WriteReadable();
}


text:
<?php
namespace TYPO3\Flow\Security\Authentication\Token;

use TYPO3\Flow\Annotations as Flow;
use TYPO3\Flow\Mvc\ActionRequest;

/**
 * An authentication token used for functional tests
 */
class TestingToken extends AbstractToken implements SessionlessTokenInterface
{
    /**
     * Simply sets the authentication status to AUTHENTICATION_NEEDED
     *
     * @param ActionRequest $actionRequest The current action request instance
     * @return void
     */
    public function updateCredentials(ActionRequest $actionRequest)
    {
        $this->authenticationStatus = self::AUTHENTICATION_NEEDED;
    }

    /**
     * Returns a string representation of the token for logging purposes.
     *
     * @return string The username credential
     */
    public function __toString()
    {
        return 'Testing token';
    }
}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

//A comment schema declaring the attribute of a comment
var CommentSchema = new Schema ({
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	},
	comment: {
		type: String,
		default: ''
	}
});

//A review schema that stores details about the review
var ReviewSchema = new Schema ({
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	},
	content: {
		type: String,
		default: ''
	},
	posted: {
		type: Date,
		default: Date.now
	},
	comments: [CommentSchema]
});

//A category schema
var CategorySchema = new Schema ({
	category: {
		type: String,
		enum: ['software', 'appliances', 'books', 'devices', 'deviceAddons', 'computers', 'computerAddons', 'electronics', 'Movies']
	}
});

//A product schema that stores attributes of a ptoduct
var ProductSchema = new Schema ({
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	},
	title: {
		required: 'The product being reviewed should have a name, don\'t you think',
		type: String,
		default: ''
	},
	added: {
		type: Date,
		default: Date.now
	},
	category: [CategorySchema],
	reviews: [ReviewSchema]
});

mongoose.model('Product', ProductSchema);