text:
"""

./plot_read_alignment_ratios.py -i /usr/local/projects/aplysia/A1_CNS_reorientation.log -o /usr/local/projects/aplysia/A1_CNS_reorientation.png
Count of ratios < 0.05: 47414
Count of ratios > 0.95: 53006

./plot_read_alignment_ratios.py -i /usr/local/projects/aplysia/A3_digestive_reorientation.log -o /usr/local/projects/aplysia/A3_digestive_reorientation.png
Count of ratios < 0.05: 44087
Count of ratios > 0.95: 49084

./plot_read_alignment_ratios.py -i /usr/local/projects/aplysia/A7_heart_reorientation.log -o /usr/local/projects/aplysia/A7_heart_reorientation.png
Count of ratios < 0.05: 45995
Count of ratios > 0.95: 52188

./plot_read_alignment_ratios.py -i /usr/local/projects/aplysia/A10_gills_reorientation.log -o /usr/local/projects/aplysia/A10_gills_reorientation.png
Count of ratios < 0.05: 49941
Count of ratios > 0.95: 55683

Ranges wanted:
0.125 - 0.875
0.25 - 0.75
0.475 - 0.525

"""

import argparse
import re

import matplotlib
import matplotlib.pyplot as plt
from biocode import utils

matplotlib.use('Agg')
import sys

def main():
    parser = argparse.ArgumentParser( description='Put a description of your script here' )

    ## output file to be written
    parser.add_argument('-i', '--input_file', type=str, required=True, help='Path to an input reorientation log file to be read' )
    parser.add_argument('-o', '--output_file', type=str, required=True, help='Path to an output image file to be created' )
    parser.add_argument('-f', '--fasta_file', type=str, required=True, help='Path to an input FASTA file' )
    parser.add_argument('-rmin', '--ratio_min', type=float, required=False, default=0.05, help='Left bounds of ratio with correctly mapped reads to export' )
    parser.add_argument('-rmax', '--ratio_max', type=float, required=False, default=0.95, help='Right bounds of ratio with correctly mapped reads to export' )
    args = parser.parse_args()

    ratios = list()

    # if set to true, the IDs in the mid-range will be printed to STDOUT
    print_ids = True

    LENGTH_CUTOFF = 350
    ratio_min_count = 0
    ratio_bet_count = 0
    ratio_max_count = 0

    fasta = utils.fasta_dict_from_file(args.fasta_file)

    for line in open(args.input_file):
        # lines are like: comp0_c0_seq1   1-T:6   1-F:0   2-T:0   2-F:5
        m = re.search('(.+)\t1-T:(\d+)\t1-F:(\d+)\t2-T:(\d+)\t2-F:(\d+)', line)
        if m:
            seq_id = m.group(1)

            if seq_id in fasta:
                if len(fasta[seq_id]['s']) < LENGTH_CUTOFF:
                    continue
            else:
                raise Exception("Expected but filed to find seq ID {0} in FASTA file".format(seq_id))

            f_reads_correctly_mapped = int(m.group(2))
            f_reads_incorrectly_mapped = int(m.group(3))
            r_reads_correctly_mapped = int(m.group(5))
            r_reads_incorrectly_mapped = int(m.group(4))
            f_read_count = f_reads_correctly_mapped + f_reads_incorrectly_mapped

            if f_read_count > 0:
                correct_ratio = f_reads_correctly_mapped / f_read_count
                ratios.append(correct_ratio)

                if correct_ratio < args.ratio_min:
                    ratio_min_count += 1
                elif correct_ratio > args.ratio_max:
                    ratio_max_count += 1
                else:
                    ratio_bet_count += 1
                    if print_ids == True:
                        print(seq_id)

                #print("LOG: Fcorrect:{0} Fwrong:{1} Ftotal:{2} ratio:{3}".format(f_reads_correctly_mapped, f_reads_incorrectly_mapped, f_read_count, correct_ratio))

    plt.hist(ratios, bins=100)
    plt.xlabel("Correct read orientation alignment ratio")
    plt.ylabel("Log of transcript count")
    plt.grid(True)
    #plt.ylim(0,5000)
    plt.gca().set_yscale("log")
    plt.savefig(args.output_file)

    sys.stderr.write("Length cutoff: {0} bp\n".format(LENGTH_CUTOFF))
    sys.stderr.write("Count of ratios < {0}: {1}\n".format(args.ratio_min, ratio_min_count))
    sys.stderr.write("Count where {0} > ratio < {1}: {2}\n".format(args.ratio_min, args.ratio_max, ratio_bet_count))
    sys.stderr.write("Count of ratios > {0}: {1}\n".format(args.ratio_max, ratio_max_count))

if __name__ == '__main__':
    main()


text:
'use strict';

var ES = require('es-abstract');
var flagsGetter = require('regexp.prototype.flags');

var RegExpStringIterator = require('./RegExpStringIterator');
var OrigRegExp = RegExp;
var hasFlags = typeof (/a/).flags === 'string';

module.exports = function MatchAllIterator(R, O) {
	if (!ES.IsRegExp(R)) {
		throw new TypeError('MatchAllIterator requires a regex');
	}
	var S = ES.ToString(O);
	var C = ES.SpeciesConstructor(R, OrigRegExp);
	var flags = ES.Get(R, 'flags');

	var matcher;
	var actualFlags = typeof flags === 'string' ? flags : flagsGetter(R);
	if (hasFlags) {
		matcher = new C(R, actualFlags); // ES.Construct(C, [R, actualFlags]);
	} else if (C === OrigRegExp) {
		// workaround for older engines that lack RegExp.prototype.flags
		matcher = new C(R.source, actualFlags); // ES.Construct(C, [R.source, actualFlags]);
	} else {
		matcher = new C(R, actualFlags); // ES.Construct(C, [R, actualFlags]);
	}
	var global = ES.ToBoolean(ES.Get(R, 'global'));
	var fullUnicode = ES.ToBoolean(ES.Get(R, 'unicode'));
	var lastIndex = ES.ToLength(ES.Get(R, 'lastIndex'));
	ES.Set(matcher, 'lastIndex', lastIndex, true);
	return new RegExpStringIterator(matcher, S, global, fullUnicode);
};

redpajama_set_name: RedPajamaGithub


text:
clockin
=====

Track clocking in and out of work.


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

namespace ConsoleToolBox
{
    /// <summary>
    /// Kernel32 holds the imported Kernel32.dll functions and data structures needed to directly access
    /// and modify the console that are not provided from the .net managed platform. Yup we have to reach outside of managed
    /// code to do some of  the fancy console work. I want to keep this all some what seperate since this is platform
    /// dependant and may change in future version of window.
    ///
    /// TODO: This should be refactored a bit at some point but for right now it will work fine
    /// </summary>
    internal class Kernel32
    {
        #region Data Structures & Enums

        public enum StdHandle
        {
            Stdin = -10,
            Stdout = -11,
            Stderr = -12
        };

        internal struct COORD
        {
            public short X;
            public short Y;

        }

        internal struct SMALL_RECT
        {
            public short Left;
            public short Top;
            public short Right;
            public short Bottom;
        }

        [StructLayout(LayoutKind.Explicit)]
        internal struct CHAR_INFO
        {
            [FieldOffset(0)]
            char UnicodeChar;
            [FieldOffset(0)]
            char AsciiChar;
            [FieldOffset(2)] //2 bytes seems to work properly
            UInt16 Attributes;
        }

        //internal struct CONSOLE_SCREEN_BUFFER_INFO
        //{
        //    public COORD dwSize;
        //    public COORD dwCursorPosition;
        //    public short wAttributes;
        //    public SMALL_RECT srWindow;
        //    public COORD dwMaximumWindowSize;
        //}

        //[StructLayout(LayoutKind.Sequential)]
        //internal struct CONSOLE_SCREEN_BUFFER_INFO_EX
        //{
        //    public uint cbSize;
        //    public COORD dwSize;
        //    public COORD dwCursorPosition;
        //    public short wAttributes;
        //    public SMALL_RECT srWindow;
        //    public COORD dwMaximumWindowSize;

        //    public ushort wPopupAttributes;
        //    public bool bFullscreenSupported;
        //    public COLORREF color0;
        //    public COLORREF color1;
        //    public COLORREF color2;
        //    public COLORREF color3;

        //    public COLORREF color4;
        //    public COLORREF color5;
        //    public COLORREF color6;
        //    public COLORREF color7;

        //    public COLORREF color8;
        //    public COLORREF color9;
        //    public COLORREF colorA;
        //    public COLORREF colorB;

        //    public COLORREF colorC;
        //    public COLORREF colorD;
        //    public COLORREF colorE;
        //    public COLORREF colorF;
        //}

        //[StructLayout(LayoutKind.Sequential)]
        //public struct COLORREF
        //{
        //    public uint ColorDWORD;

        //    public COLORREF(System.Drawing.Color color)
        //    {
        //        ColorDWORD = (uint)color.R + (((uint)color.G) << 8) + (((uint)color.B) << 16);
        //    }

        //    public System.Drawing.Color GetColor()
        //    {
        //        return System.Drawing.Color.FromArgb((int)(0x000000FFU & ColorDWORD),
        //           (int)(0x0000FF00U & ColorDWORD) >> 8, (int)(0x00FF0000U & ColorDWORD) >> 16);
        //    }

        //    public void SetColor(System.Drawing.Color color)
        //    {
        //        ColorDWORD = (uint)color.R + (((uint)color.G) << 8) + (((uint)color.B) << 16);
        //    }
        //}

        //[StructLayout(LayoutKind.Sequential)]
        //internal struct CONSOLE_FONT_INFO
        //{
        //    public int nFont;
        //    public COORD dwFontSize;
        //}

        //[StructLayout(LayoutKind.Sequential)]
        //public struct CONSOLE_FONT_INFO_EX
        //{
        //    public uint cbSize;
        //    public uint nFont;
        //    public COORD dwFontSize;
        //    public ushort FontFamily;
        //    public ushort FontWeight;
        //    fixed char FaceName[LF_FACESIZE];

        //    const uint LF_FACESIZE = 32;
        //}

        //[StructLayout(LayoutKind.Explicit)]
        //internal struct INPUT_RECORD
        //{
        //    [FieldOffset(0)]
        //    public ushort EventType;
        //    [FieldOffset(4)]
        //    public KEY_EVENT_RECORD KeyEvent;
        //    [FieldOffset(4)]
        //    public MOUSE_EVENT_RECORD MouseEvent;
        //    [FieldOffset(4)]
        //    public WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent;
        //    [FieldOffset(4)]
        //    public MENU_EVENT_RECORD MenuEvent;
        //    [FieldOffset(4)]
        //    public FOCUS_EVENT_RECORD FocusEvent;
        //};

        //[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]
        //internal struct KEY_EVENT_RECORD
        //{
        //    [FieldOffset(0), MarshalAs(UnmanagedType.Bool)]
        //    public bool bKeyDown;
        //    [FieldOffset(4), MarshalAs(UnmanagedType.U2)]
        //    public ushort wRepeatCount;
        //    [FieldOffset(6), MarshalAs(UnmanagedType.U2)]
        //    //public VirtualKeys wVirtualKeyCode;
        //    public ushort wVirtualKeyCode;
        //    [FieldOffset(8), MarshalAs(UnmanagedType.U2)]
        //    public ushort wVirtualScanCode;
        //    [FieldOffset(10)]
        //    public char UnicodeChar;
        //    [FieldOffset(12), MarshalAs(UnmanagedType.U4)]
        //    //public ControlKeyState dwControlKeyState;
        //    public uint dwControlKeyState;
        //}

        //[StructLayout(LayoutKind.Sequential)]
        //internal struct MOUSE_EVENT_RECORD
        //{
        //    public COORD dwMousePosition;
        //    public uint dwButtonState;
        //    public uint dwControlKeyState;
        //    public uint dwEventFlags;
        //}

        //internal struct WINDOW_BUFFER_SIZE_RECORD
        //{
        //    public COORD dwSize;

        //    public WINDOW_BUFFER_SIZE_RECORD(short x, short y)
        //    {
        //        dwSize = new COORD();
        //        dwSize.X = x;
        //        dwSize.Y = y;
        //    }
        //}

        //[StructLayout(LayoutKind.Sequential)]
        //internal struct MENU_EVENT_RECORD
        //{
        //    public uint dwCommandId;
        //}

        //[StructLayout(LayoutKind.Sequential)]
        //internal struct FOCUS_EVENT_RECORD
        //{
        //    public uint bSetFocus;
        //}

        //[StructLayout(LayoutKind.Sequential)]
        //internal struct CONSOLE_CURSOR_INFO
        //{
        //    uint Size;
        //    bool Visible;
        //}

        //[StructLayout(LayoutKind.Sequential)]
        //internal struct CONSOLE_HISTORY_INFO
        //{
        //    ushort cbSize;
        //    ushort HistoryBufferSize;
        //    ushort NumberOfHistoryBuffers;
        //    uint dwFlags;
        //}

        //[StructLayout(LayoutKind.Sequential)]
        //internal struct CONSOLE_SELECTION_INFO
        //{
        //    uint Flags;
        //    COORD SelectionAnchor;
        //    SMALL_RECT Selection;

        //    // Flags values:
        //    const uint CONSOLE_MOUSE_DOWN = 0x0008; // Mouse is down
        //    const uint CONSOLE_MOUSE_SELECTION = 0x0004; //Selecting with the mouse
        //    const uint CONSOLE_NO_SELECTION = 0x0000; //No selection
        //    const uint CONSOLE_SELECTION_IN_PROGRESS = 0x0001; //Selection has begun
        //    const uint CONSOLE_SELECTION_NOT_EMPTY = 0x0002; //Selection rectangle is not empty
        //}

        //// Enumerated type for the control messages sent to the handler routine
        //internal enum CtrlTypes : uint
        //{
        //    CTRL_C_EVENT = 0,
        //    CTRL_BREAK_EVENT,
        //    CTRL_CLOSE_EVENT,
        //    CTRL_LOGOFF_EVENT = 5,
        //    CTRL_SHUTDOWN_EVENT
        //}
        #endregion

        #region Kernel32 Console Functions

        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern IntPtr GetStdHandle(
            StdHandle std
            );

        //[DllImport("kernel32.dll", SetLastError = true)]
        //static extern bool SetStdHandle(
        //    uint nStdHandle,
        //    IntPtr hHandle
        //    );

        //[DllImport("kernel32.dll", SetLastError = true)]
        //static extern bool GetConsoleCursorInfo(
        //    IntPtr hConsoleOutput,
        //    out CONSOLE_CURSOR_INFO lpConsoleCursorInfo
        //    );

        //[DllImport("kernel32.dll", SetLastError = true)]
        //static extern bool GetConsoleDisplayMode(
        //    out uint ModeFlags
        //    );

        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern uint GetConsoleTitle(
            [Out] StringBuilder lpConsoleTitle,
            uint nSize
            );

        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern uint GetConsoleOriginalTitle(
            [Out] StringBuilder lpConsoleTitle,
            uint nSize
            );

        //[DllImport("kernel32.dll", SetLastError = true)]
        //internal static extern bool GetConsoleScreenBufferInfo(
        //    IntPtr hConsoleOutput,
        //    [Out] CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
        //    );

        //[DllImport("kernel32.dll", SetLastError = true)]
        //static extern bool GetNumberOfConsoleMouseButtons(
        //    ref uint lpNumberOfMouseButtons
        //    );

        //[DllImport("kernel32.dll", SetLastError = true)]
        //static extern bool PeekConsoleInput(
        //    IntPtr hConsoleInput,
        //    [Out] INPUT_RECORD[] lpBuffer,
        //    uint nLength,
        //    out uint lpNumberOfEventsRead
        //    );

        //[DllImport("kernel32.dll", SetLastError = true)]
        //static extern bool ReadConsole(
        //    IntPtr hConsoleInput,
        //    [Out] StringBuilder lpBuffer,
        //    uint nNumberOfCharsToRead,
        //    out uint lpNumberOfCharsRead,
        //    IntPtr lpReserved
        //    );

        //[DllImport("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
        //static extern bool ReadConsoleInput(
        //    IntPtr hConsoleInput,
        //    [Out] INPUT_RECORD[] lpBuffer,
        //    uint nLength,
        //    out uint lpNumberOfEventsRead
        //    );

        //[DllImport("kernel32.dll", SetLastError = true)]
        //static extern bool ReadConsoleOutput(
        //    IntPtr hConsoleOutput,
        //    [Out] CHAR_INFO[] lpBuffer,
        //    COORD dwBufferSize,
        //    COORD dwBufferCoord,
        //    ref SMALL_RECT lpReadRegion
        //    );

        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern bool ReadConsoleOutputAttribute(
            IntPtr hConsoleOutput,
            [Out] ushort[] lpAttribute,
            uint nLength,
            COORD dwReadCoord,
            out uint lpNumberOfAttrsRead
            );

        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern bool ReadConsoleOutputCharacter(
            IntPtr hConsoleOutput,
            [Out] StringBuilder lpCharacter,
            uint nLength,
            COORD dwReadCoord,
            out uint lpNumberOfCharsRead
            );

        //[DllImport("kernel32.dll", SetLastError = true)]
        //static extern bool SetConsoleCursorInfo(
        //    IntPtr hConsoleOutput,
        //    [In] ref CONSOLE_CURSOR_INFO lpConsoleCursorInfo
        //    );

        //[DllImport("kernel32.dll", SetLastError = true)]
        //internal static extern bool SetConsoleCursorPosition(
        //    IntPtr hConsoleOutput,
        //   COORD dwCursorPosition
        //    );

        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern bool SetConsoleTitle(
            string lpConsoleTitle
            );

        [DllImport("kernel32.dll")]
        internal static extern bool WriteConsoleOutputAttribute(
            IntPtr hConsoleOutput,
            ushort[] lpAttribute,
            uint nLength,
            COORD dwWriteCoord,
            out uint lpNumberOfAttrsWritten
            );

        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern bool WriteConsoleOutputCharacter(
            IntPtr hConsoleOutput,
            string lpCharacter,
            uint nLength,
            COORD dwWriteCoord,
            out uint lpNumberOfCharsWritten
            );

        #endregion
    }
}


text:
const assert = require("chai").assert
// const d = require("debug")("raptorjs:test:workflow")
const util = require("../util")

const newInstanceName = () => "workflow_test" + Math.floor(Date.now() * Math.random())

const create = async(instanceName) => {

    const r = await util.getRaptor()
    await r.Workflow().create(instanceName)
    const list = await r.Workflow().list()

    assert.equal(1, list.filter(((n) => instanceName === n.Name)).length)

    return Promise.resolve()
}

describe("Workflow", function () {

    // before(util.before)
    // after(util.after)

    // spawing node-red containers can take a while
    this.timeout(15000)

    it("should list all workflows", async () => {

        const r = await util.getRaptor()
        const list = await r.Workflow().list()
        assert.isTrue(list instanceof Array)

        return Promise.resolve()
    })

    it("should create a workflow", () => create(newInstanceName()))

    it("should get a workflow", async () => {

        const instanceName = newInstanceName()
        await create(instanceName)

        const r = await util.getRaptor()

        let instance = await r.Workflow().get(instanceName)
        assert.equal(instance.Name, instanceName)

        return Promise.resolve()
    })

    it("should restart a workflow", async () => {

        const r = await util.getRaptor()
        const instanceName = newInstanceName()
        await create(instanceName)

        await r.Workflow().stop(instanceName)
        let instance = await r.Workflow().get(instanceName)
        assert.equal(r.Workflow().states.stopped, instance.Status)

        await r.Workflow().start(instanceName)
        instance = await r.Workflow().get(instanceName)
        assert.equal(r.Workflow().states.started, instance.Status)

        return Promise.resolve()
    })

})


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>compact_specs (Gem::Indexer)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />

# File lib/rubygems/indexer.rb, line 495
  def compact_specs(specs)
    names = {}
    versions = {}
    platforms = {}

    specs.map do |(name, version, platform)|
      names[name] = name unless names.include? name
      versions[version] = version unless versions.include? version
      platforms[platform] = platform unless platforms.include? platform

      [names[name], versions[version], platforms[platform]]
    end
  end


text:
import './Page.scss';
import AuthLogout from '../auth/Logout.react';
import Component from 'react-pure-render/component';
import Helmet from 'react-helmet';
import React, { PropTypes } from 'react';
import { FormattedMessage, defineMessages, injectIntl, intlShape } from 'react-intl';
import { Link } from 'react-router';
import { connect } from 'react-redux';

const messages = defineMessages({
  title: {
    defaultMessage: 'Me',
    id: 'me.page.title'
  },
  welcome: {
    defaultMessage: 'Hi {email}. This is your secret page.',
    id: 'me.page.welcome'
  },
  linkToProfile: {
    defaultMessage: 'Profile',
    id: 'me.page.linkToProfile'
  },
  linkToSettings: {
    defaultMessage: 'Settings',
    id: 'me.page.linkToSettings'
  },
});

class Page extends Component {

  static propTypes = {
    children: PropTypes.object,
    intl: intlShape.isRequired,
    viewer: PropTypes.object
  };

  render() {
    const { children, intl, viewer: { email } } = this.props;
    const title = intl.formatMessage(messages.title);

    return (

        <Helmet title={title} />

<Link activeClassName="active" to="/me/profile">
            <FormattedMessage {...messages.linkToProfile} />
          </Link>

<Link activeClassName="active" to="/me/settings">
            <FormattedMessage {...messages.linkToSettings} />
          </Link>

        {children ||

            <FormattedMessage {...messages.welcome} values={{ email }} />

        }
        <AuthLogout />

    );
  }

}

Page = injectIntl(Page);

export default connect(state => ({
  viewer: state.users.viewer
}))(Page);


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;

namespace DotNetWebSocket
{
    public class WebSocketListener : IWebSocketListener
    {
        private readonly ConcurrentQueue<WebSocket> newWebSockets = new ConcurrentQueue<WebSocket>();
        private readonly WebSocketServer server;

        public WebSocketListener(IPAddress listenAddress, int port)
        {
            server = new WebSocketServer(listenAddress, port);
        }

        public event EventHandler<EventArgs> NewClientAvailable;

        public event EventHandler<UnhandledExceptionEventArgs> UnhandledException;

        public void Start()
        {
            server.Start();

            BeginAcceptSocket();
        }

        public void Stop()
        {
            server.Stop();
        }

        public void Dispose()
        {
            server.Dispose();
        }

        public IWebSocketClient GetNewClientOrDefault()
        {
            WebSocket webSocket;
            newWebSockets.TryDequeue(out webSocket);
            return new WebSocketClient(webSocket);
        }

        public IEnumerable<IWebSocketClient> GetNewClients()
        {
            List<IWebSocketClient> newClients = null;

            WebSocket socketSession;
            while (newWebSockets.TryDequeue(out socketSession))
            {
                if (newClients == null)
                {
                    newClients = new List<IWebSocketClient>();
                }

                newClients.Add(new WebSocketClient(socketSession));
            }

            return newClients ?? Enumerable.Empty<IWebSocketClient>();
        }

        private void BeginAcceptSocket()
        {
            try
            {
                server.BeginAccept(HandleAcceptSocketCompleted, null);
            }
            catch (ObjectDisposedException)
            {
            }
            catch (Exception ex)
            {
                OnUnhandledException(ex);
            }
        }

        private void HandleAcceptSocketCompleted(IAsyncResult ar)
        {
            try
            {
                var socket = server.EndAccept(ar);
                server.BeginHandshake(socket, HandleHandshakeCompleted, null);

                BeginAcceptSocket();
            }
            catch (ObjectDisposedException)
            {
            }
            catch (SocketException)
            {
                BeginAcceptSocket();
            }
            catch (Exception ex)
            {
                OnUnhandledException(ex);
            }
        }

        private void HandleHandshakeCompleted(IAsyncResult ar)
        {
            try
            {
                var webSocket = server.EndHandshake(ar);
                newWebSockets.Enqueue(webSocket);
                OnNewWebSocketsAvailable();
            }
            catch (ObjectDisposedException)
            {
            }
            catch (HandshakeException)
            {
            }
            catch (Exception ex)
            {
                OnUnhandledException(ex);
            }
        }

        private void OnUnhandledException(Exception ex)
        {
            EventHandler<UnhandledExceptionEventArgs> unhandledException = UnhandledException;
            if (unhandledException != null)
            {
                unhandledException(this, new UnhandledExceptionEventArgs(ex));
            }
        }

        private void OnNewWebSocketsAvailable()
        {
            var newWebSocketsAvailable = NewClientAvailable;
            if (newWebSocketsAvailable != null)
            {
                newWebSocketsAvailable(this, EventArgs.Empty);
            }
        }
    }
}


text:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"View Controller 1";
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)openAnotherView:(id)sender {
    AnotherViewController *anotherVC = [[AnotherViewController alloc] initWithNibName:@"AnotherView"
                                                                               bundle:nil];
    [self.navigationController pushViewController:anotherVC animated:YES];

}

@end


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

namespace ProductsShop.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }

        public int? BuyerId { get; set; }
        public User Buyer { get; set; }

        public int SellerId { get; set; }
        public User Seller { get; set; }

        public ICollection<CategoryProduct> CategoriesProduct { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient android:startColor="#ffbec0c3" android:endColor="#ffcdced1" android:angle="90.0" android:type="linear" />
</shape>
<!-- From: file:/H:/AndroidStuiod_0.8.0/Vanrui_Weather/Vanrui_Weather/app/src/main/res/drawable/contact_search_box_background.xml -->


text:
__author__ = 'max'

import numpy

import theano
import theano.tensor as T
from theano.tensor import as_tensor_variable
from theano.gof import Op, Apply
from theano.tensor.nlinalg import matrix_inverse, matrix_dot

__all__ = [
    "LogAbsDet",
    "logabsdet",
    "theano_logsumexp",
]

class LogAbsDet(Op):
    """
    Computes the logarithm of absolute determinants of a sequence of square
    matrix M, log(abs(det(M))), on CPU. Avoids det(M) overflow/
    underflow.

    TODO: add GPU code!
    """

    def make_node(self, x):
        x = as_tensor_variable(x)
        assert x.ndim == 2
        o = theano.tensor.scalar(dtype=x.dtype)
        return Apply(self, [x], [o])

    def perform(self, node, inputs, outputs, params=None):
        try:
            (x,) = inputs
            (z,) = outputs
            s = numpy.linalg.svd(x, compute_uv=False)
            log_abs_det = numpy.sum(numpy.log(numpy.abs(s)))
            z[0] = numpy.asarray(log_abs_det, dtype=x.dtype)
        except Exception:
            print('Failed to compute logabsdet of {}.'.format(x))
            raise

    def grad(self, inputs, g_outputs):
        [gz] = g_outputs
        [x] = inputs
        return [gz * matrix_inverse(x).T]

    def __str__(self):
        return "LogAbsDet"

logabsdet = LogAbsDet()

def theano_logsumexp(x, axis=None):
    """
    Compute log(sum(exp(x), axis=axis) in a numerically stable
    fashion.
    Parameters
    ----------
    x : tensor_like
        A Theano tensor (any dimension will do).
    axis : int or symbolic integer scalar, or None
        Axis over which to perform the summation. `None`, the
        default, performs over all axes.
    Returns
    -------
    result : ndarray or scalar
        The result of the log(sum(exp(...))) operation.
    """

    xmax = x.max(axis=axis, keepdims=True)
    xmax_ = x.max(axis=axis)
    return xmax_ + T.log(T.exp(x - xmax).sum(axis=axis))


text:
package org.apache.hadoop.hdfs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.log4j.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TestDFSStripedOutputStream {
  public static final Log LOG = LogFactory.getLog(
      TestDFSStripedOutputStream.class);

  static {
    GenericTestUtils.setLogLevel(DFSOutputStream.LOG, Level.ALL);
    GenericTestUtils.setLogLevel(DataStreamer.LOG, Level.ALL);
  }

  private int dataBlocks = StripedFileTestUtil.NUM_DATA_BLOCKS;
  private int parityBlocks = StripedFileTestUtil.NUM_PARITY_BLOCKS;

  private MiniDFSCluster cluster;
  private DistributedFileSystem fs;
  private Configuration conf;
  private final int cellSize = StripedFileTestUtil.BLOCK_STRIPED_CELL_SIZE;
  private final int stripesPerBlock = 4;
  private final int blockSize = cellSize * stripesPerBlock;

  @Before
  public void setup() throws IOException {
    int numDNs = dataBlocks + parityBlocks + 2;
    conf = new Configuration();
    conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
    conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_REPLICATION_CONSIDERLOAD_KEY,
        false);
    conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MAX_STREAMS_KEY, 0);
    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDNs).build();
    cluster.getFileSystem().getClient().setErasureCodingPolicy("/", null);
    fs = cluster.getFileSystem();
  }

  @After
  public void tearDown() {
    if (cluster != null) {
      cluster.shutdown();
      cluster = null;
    }
  }

  @Test
  public void testFileEmpty() throws Exception {
    testOneFile("/EmptyFile", 0);
  }

  @Test
  public void testFileSmallerThanOneCell1() throws Exception {
    testOneFile("/SmallerThanOneCell", 1);
  }

  @Test
  public void testFileSmallerThanOneCell2() throws Exception {
    testOneFile("/SmallerThanOneCell", cellSize - 1);
  }

  @Test
  public void testFileEqualsWithOneCell() throws Exception {
    testOneFile("/EqualsWithOneCell", cellSize);
  }

  @Test
  public void testFileSmallerThanOneStripe1() throws Exception {
    testOneFile("/SmallerThanOneStripe", cellSize * dataBlocks - 1);
  }

  @Test
  public void testFileSmallerThanOneStripe2() throws Exception {
    testOneFile("/SmallerThanOneStripe", cellSize + 123);
  }

  @Test
  public void testFileEqualsWithOneStripe() throws Exception {
    testOneFile("/EqualsWithOneStripe", cellSize * dataBlocks);
  }

  @Test
  public void testFileMoreThanOneStripe1() throws Exception {
    testOneFile("/MoreThanOneStripe1", cellSize * dataBlocks + 123);
  }

  @Test
  public void testFileMoreThanOneStripe2() throws Exception {
    testOneFile("/MoreThanOneStripe2", cellSize * dataBlocks
            + cellSize * dataBlocks + 123);
  }

  @Test
  public void testFileLessThanFullBlockGroup() throws Exception {
    testOneFile("/LessThanFullBlockGroup",
        cellSize * dataBlocks * (stripesPerBlock - 1) + cellSize);
  }

  @Test
  public void testFileFullBlockGroup() throws Exception {
    testOneFile("/FullBlockGroup", blockSize * dataBlocks);
  }

  @Test
  public void testFileMoreThanABlockGroup1() throws Exception {
    testOneFile("/MoreThanABlockGroup1", blockSize * dataBlocks + 123);
  }

  @Test
  public void testFileMoreThanABlockGroup2() throws Exception {
    testOneFile("/MoreThanABlockGroup2",
        blockSize * dataBlocks + cellSize+ 123);
  }

  @Test
  public void testFileMoreThanABlockGroup3() throws Exception {
    testOneFile("/MoreThanABlockGroup3",
        blockSize * dataBlocks * 3 + cellSize * dataBlocks
        + cellSize + 123);
  }

  private void testOneFile(String src, int writeBytes) throws Exception {
    src += "_" + writeBytes;
    Path testPath = new Path(src);

    byte[] bytes = StripedFileTestUtil.generateBytes(writeBytes);
    DFSTestUtil.writeFile(fs, testPath, new String(bytes));
    StripedFileTestUtil.waitBlockGroupsReported(fs, src);

    StripedFileTestUtil.checkData(fs, testPath, writeBytes,
        new ArrayList<DatanodeInfo>(), null);
  }
}


text:
import multiprocessing
import peewee
import re
import traceback
from abjad.tools import sequencetools
from abjad.tools import stringtools
from abjad.tools import systemtools
from playhouse import postgres_ext
from discograph.library.Bootstrapper import Bootstrapper
from discograph.library.PostgresModel import PostgresModel

class PostgresEntity(PostgresModel):

    ### CLASS VARIABLES ###

    _strip_pattern = re.compile(r'(\(\d+\)|[^(\w\s)]+)')

    class BootstrapPassTwoWorker(multiprocessing.Process):

        def __init__(self, entity_type, indices):
            multiprocessing.Process.__init__(self)
            self.entity_type = entity_type
            self.indices = indices

        def run(self):
            proc_number = self.name.split('-')[-1]
            corpus = {}
            total = len(self.indices)
            for i, entity_id in enumerate(self.indices):
                with PostgresEntity._meta.database.execution_context():
                    progress = float(i) / total
                    try:
                        PostgresEntity.bootstrap_pass_two_single(
                            entity_type=self.entity_type,
                            entity_id=entity_id,
                            annotation=proc_number,
                            corpus=corpus,
                            progress=progress,
                            )
                    except:
                        print(
                            'ERROR:',
                            self.entity_type,
                            entity_id,
                            proc_number,
                            )
                        traceback.print_exc()

    class BootstrapPassThreeWorker(multiprocessing.Process):

        def __init__(self, entity_type, indices):
            multiprocessing.Process.__init__(self)
            self.entity_type = entity_type
            self.indices = indices

        def run(self):
            proc_name = self.name
            total = len(self.indices)
            for i, entity_id in enumerate(self.indices):
                with PostgresEntity._meta.database.execution_context():
                    progress = float(i) / total
                    try:
                        PostgresEntity.bootstrap_pass_three_single(
                            entity_type=self.entity_type,
                            entity_id=entity_id,
                            annotation=proc_name,
                            progress=progress,
                            )
                    except:
                        print('ERROR:', self.entity_type, entity_id, proc_name)
                        traceback.print_exc()

    ### PEEWEE FIELDS ###

    entity_id = peewee.IntegerField(index=False)
    entity_type = peewee.IntegerField(index=False)
    name = peewee.TextField(index=True)
    relation_counts = postgres_ext.BinaryJSONField(null=True, index=False)
    metadata = postgres_ext.BinaryJSONField(null=True, index=False)
    entities = postgres_ext.BinaryJSONField(null=True, index=False)
    search_content = postgres_ext.TSVectorField(index=True)

    ### PEEWEE META ###

    class Meta:
        db_table = 'entities'
        primary_key = peewee.CompositeKey('entity_type', 'entity_id')

    ### PUBLIC METHODS ###

    @classmethod
    def bootstrap(cls):
        cls.drop_table(True)
        cls.create_table()
        cls.bootstrap_pass_one()
        cls.bootstrap_pass_two()

    @classmethod
    def bootstrap_pass_one(cls):
        PostgresModel.bootstrap_pass_one(
            cls,
            'artist',
            id_attr='entity_id',
            name_attr='name',
            skip_without=['name'],
            )
        PostgresModel.bootstrap_pass_one(
            cls,
            'label',
            id_attr='entity_id',
            name_attr='name',
            skip_without=['name'],
            )

    @classmethod
    def get_entity_iterator(cls, entity_type, pessimistic=False):
        if not pessimistic:
            id_query = cls.select(peewee.fn.Max(cls.entity_id))
            id_query = id_query.where(cls.entity_type == entity_type)
            max_id = id_query.scalar()
            for i in range(1, max_id + 1):
                query = cls.select().where(
                    cls.entity_id == i,
                    cls.entity_type == entity_type,
                    )
                if not query.count():
                    continue
                document = query.get()
                yield document
        else:
            id_query = cls.select(cls.entity_id)
            id_query = id_query.where(cls.entity_type == entity_type)
            for entity in id_query:
                entity_id = entity.entity_id
                entity = cls.select().where(
                    cls.entity_id == entity_id,
                    cls.entity_type == entity_type,
                    ).get()
                yield entity

    @classmethod
    def get_indices(cls, entity_type, pessimistic=False):
        indices = []
        if not pessimistic:
            maximum_id = cls.select(
                peewee.fn.Max(cls.entity_id)).where(
                    cls.entity_type == entity_type
                    ).scalar()
            step = maximum_id // multiprocessing.cpu_count()
            for start in range(0, maximum_id, step):
                stop = start + step
                indices.append(range(start, stop))
        else:
            query = cls.select(cls.entity_id)
            query = query.where(cls.entity_type == entity_type)
            query = query.order_by(cls.entity_id)
            query = query.tuples()
            all_ids = tuple(_[0] for _ in query)
            ratio = [1] * multiprocessing.cpu_count()
            for chunk in sequencetools.partition_sequence_by_ratio_of_lengths(
                all_ids, ratio):
                indices.append(chunk)
        return indices

    @classmethod
    def bootstrap_pass_two(cls, pessimistic=False):
        entity_type = 1
        indices = cls.get_indices(entity_type, pessimistic=pessimistic)
        workers = [cls.BootstrapPassTwoWorker(entity_type, x)
            for x in indices]
        for worker in workers:
            worker.start()
        for worker in workers:
            worker.join()
        for worker in workers:
            worker.terminate()
        entity_type = 2
        indices = cls.get_indices(entity_type, pessimistic=pessimistic)
        workers = [cls.BootstrapPassTwoWorker(entity_type, x)
            for x in indices]
        for worker in workers:
            worker.start()
        for worker in workers:
            worker.join()
        for worker in workers:
            worker.terminate()

    @classmethod
    def bootstrap_pass_three(cls, pessimistic=False):
        entity_type = 1
        indices = cls.get_indices(entity_type, pessimistic=pessimistic)
        workers = [cls.BootstrapPassThreeWorker(entity_type, x)
            for x in indices]
        for worker in workers:
            worker.start()
        for worker in workers:
            worker.join()
        for worker in workers:
            worker.terminate()
        entity_type = 2
        indices = cls.get_indices(entity_type, pessimistic=pessimistic)
        workers = [cls.BootstrapPassThreeWorker(entity_type, _)
            for _ in indices]
        for worker in workers:
            worker.start()
        for worker in workers:
            worker.join()
        for worker in workers:
            worker.terminate()

    @classmethod
    def bootstrap_pass_two_single(
        cls,
        entity_type,
        entity_id,
        annotation='',
        corpus=None,
        progress=None,
        ):
        skipped_template = u'{} (Pass 2) {:.3%} [{}]\t[SKIPPED] (id:{}) [{:.8f}]: {}'
        changed_template = u'{} (Pass 2) {:.3%} [{}]\t          (id:{}) [{:.8f}]: {}'
        query = cls.select().where(
            cls.entity_id == entity_id,
            cls.entity_type == entity_type,
            )
        if not query.count():
            return
        document = query.get()
        corpus = corpus or {}
        with systemtools.Timer(verbose=False) as timer:
            changed = document.resolve_references(corpus)
        if not changed:
            message = skipped_template.format(
                cls.__name__.upper(),
                progress,
                annotation,
                (document.entity_type, document.entity_id),
                timer.elapsed_time,
                document.name,
                )
            print(message)
            return
        document.save()
        message = changed_template.format(
            cls.__name__.upper(),
            progress,
            annotation,
            (document.entity_type, document.entity_id),
            timer.elapsed_time,
            document.name,
            )
        print(message)

    @classmethod
    def bootstrap_pass_three_single(
        cls,
        entity_type,
        entity_id,
        annotation='',
        progress=None,
        ):
        import discograph
        query = cls.select(
            cls.entity_id,
            cls.entity_type,
            cls.name,
            cls.relation_counts,
            ).where(
            cls.entity_id == entity_id,
            cls.entity_type == entity_type,
            )
        if not query.count():
            return
        document = query.get()
        entity_id = document.entity_id
        where_clause = (
            (discograph.PostgresRelation.entity_one_id == entity_id) &
            (discograph.PostgresRelation.entity_one_type == entity_type)
            )
        where_clause |= (
            (discograph.PostgresRelation.entity_two_id == entity_id) &
            (discograph.PostgresRelation.entity_two_type == entity_type)
            )
        query = discograph.PostgresRelation.select().where(where_clause)
        relation_counts = {}
        for relation in query:
            if relation.role not in relation_counts:
                relation_counts[relation.role] = set()
            key = (
                relation.entity_one_type,
                relation.entity_one_id,
                relation.entity_two_type,
                relation.entity_two_id,
                )
            relation_counts[relation.role].add(key)
        for role, keys in relation_counts.items():
            relation_counts[role] = len(keys)
        if not relation_counts:
            return
        document.relation_counts = relation_counts
        document.save()
        message_pieces = [
            cls.__name__.upper(),
            progress,
            annotation,
            (document.entity_type, document.entity_id),
            document.name,
            len(relation_counts),
            ]
        template = u'{} (Pass 3) {:.3%} [{}]\t(id:{}) {}: {}'
        message = template.format(*message_pieces)
        print(message)

    @classmethod
    def element_to_names(cls, names):
        result = {}
        if names is None or not len(names):
            return result
        for name in names:
            name = name.text
            if not name:
                continue
            result[name] = None
        return result

    @classmethod
    def element_to_names_and_ids(cls, names_and_ids):
        result = {}
        if names_and_ids is None or not len(names_and_ids):
            return result
        for i in range(0, len(names_and_ids), 2):
            discogs_id = int(names_and_ids[i].text)
            name = names_and_ids[i + 1].text
            result[name] = discogs_id
        return result

    @classmethod
    def element_to_parent_label(cls, parent_label):
        result = {}
        if parent_label is None or parent_label.text is None:
            return result
        name = parent_label.text.strip()
        if not name:
            return result
        result[name] = None
        return result

    @classmethod
    def element_to_sublabels(cls, sublabels):
        result = {}
        if sublabels is None or not len(sublabels):
            return result
        for sublabel in sublabels:
            name = sublabel.text
            if name is None:
                continue
            name = name.strip()
            if not name:
                continue
            result[name] = None
        return result

    @classmethod
    def fixup_search_content(cls):
        template = 'FIXUP ({}:{}): {} -> {}'
        for document in cls.get_entity_iterator(entity_type=1):
            document.search_content = cls.string_to_tsvector(document.name)
            document.save()
            message = template.format(
                document.entity_type,
                document.entity_id,
                document.name,
                document.search_content,
                )
            print(message)
        for document in cls.get_entity_iterator(entity_type=2):
            document.search_content = cls.string_to_tsvector(document.name)
            document.save()
            message = template.format(
                document.entity_type,
                document.entity_id,
                document.name,
                document.search_content,
                )
            print(message)

    @classmethod
    def from_element(cls, element):
        data = cls.tags_to_fields(element)
        return cls(**data)

    @classmethod
    def preprocess_data(cls, data, element):
        data['metadata'] = {}
        data['entities'] = {}
        for key in (
            'aliases',
            'groups',
            'members',
            'parent_label',
            'sublabels',
            ):
            if key in data:
                data['entities'][key] = data.pop(key)
        for key in (
            'contact_info',
            'name_variations',
            'profile',
            'real_name',
            'urls',
            ):
            if key in data:
                data['metadata'][key] = data.pop(key)
        if 'name' in data and data.get('name'):
            search_content = data.get('name')
            search_content = search_content.lower()
            search_content = stringtools.strip_diacritics(search_content)
            data['search_content'] = peewee.fn.to_tsvector(search_content)
        if element.tag == 'artist':
            data['entity_type'] = 1
        elif element.tag == 'label':
            data['entity_type'] = 2
        return data

    def resolve_references(self, corpus):
        changed = False
        if not self.entities:
            return changed
        if self.entity_type == 1:
            entity_type = 1
            for section in ('aliases', 'groups', 'members'):
                if section not in self.entities:
                    continue
                for entity_name in self.entities[section].keys():
                    key = (entity_type, entity_name)
                    self.update_corpus(corpus, key)
                    if key in corpus:
                        self.entities[section][entity_name] = corpus[key]
                        changed = True
        elif self.entity_type == 2:
            entity_type = 2
            for section in ('parent_label', 'sublabels'):
                if section not in self.entities:
                    continue
                for entity_name in self.entities[section].keys():
                    key = (entity_type, entity_name)
                    self.update_corpus(corpus, key)
                    if key in corpus:
                        self.entities[section][entity_name] = corpus[key]
                        changed = True
        return changed

    def roles_to_relation_count(self, roles):
        count = 0
        relation_counts = self.relation_counts or {}
        for role in roles:
            if role == 'Alias':
                count += len(self.entities.get('aliases', ()))
            elif role == 'Member Of':
                count += len(self.entities.get('groups', ()))
                count += len(self.entities.get('members', ()))
            elif role == 'Sublabel Of':
                count += len(self.entities.get('parent_label', ()))
                count += len(self.entities.get('sublabels', ()))
            else:
                count += relation_counts.get(role, 0)
        return count

    @classmethod
    def search_multi(cls, entity_keys):
        artist_ids, label_ids = [], []
        for entity_type, entity_id in entity_keys:
            if entity_type == 1:
                artist_ids.append(entity_id)
            elif entity_type == 2:
                label_ids.append(entity_id)
        if artist_ids and label_ids:
            where_clause = (
                (
                    (cls.entity_type == 1) &
                    (cls.entity_id.in_(artist_ids))
                    ) | (
                    (cls.entity_type == 2) &
                    (cls.entity_id.in_(label_ids))
                    )
                )
        elif artist_ids:
            where_clause = (
                (cls.entity_type == 1) &
                (cls.entity_id.in_(artist_ids))
                )
        else:
            where_clause = (
                (cls.entity_type == 2) &
                (cls.entity_id.in_(label_ids))
                )
        return cls.select().where(where_clause)

    @classmethod
    def search_text(cls, search_string):
        search_string = search_string.lower()
        search_string = stringtools.strip_diacritics(search_string)
        search_string = ','.join(search_string.split())
        query = PostgresEntity.raw("""
            SELECT entity_type,
                entity_id,
                name,
                ts_rank_cd(search_content, query, 63) AS rank
            FROM entities,
                to_tsquery(%s) query
            WHERE query @@ search_content
            ORDER BY rank DESC
            LIMIT 100
            """, search_string)
        return query

    @classmethod
    def string_to_tsvector(cls, string):
        string = string.lower()
        string = stringtools.strip_diacritics(string)
        string = cls._strip_pattern.sub('', string)
        tsvector = peewee.fn.to_tsvector(string)
        return tsvector

    def structural_roles_to_entity_keys(self, roles):
        entity_keys = set()
        if self.entity_type == 1:
            entity_type = 1
            if 'Alias' in roles:
                for section in ('aliases',):
                    if section not in self.entities:
                        continue
                    for entity_id in self.entities[section].values():
                        if not entity_id:
                            continue
                        entity_keys.add((entity_type, entity_id))
            if 'Member Of' in roles:
                for section in ('groups', 'members'):
                    if section not in self.entities:
                        continue
                    for entity_id in self.entities[section].values():
                        if not entity_id:
                            continue
                        entity_keys.add((entity_type, entity_id))
        elif self.entity_type == 2:
            entity_type = 2
            if 'Sublabel Of' in roles:
                for section in ('parent_label', 'sublabels'):
                    if section not in self.entities:
                        continue
                    for entity_id in self.entities[section].values():
                        if not entity_id:
                            continue
                        entity_keys.add((entity_type, entity_id))
        return entity_keys

    def structural_roles_to_relations(self, roles):
        from discograph import PostgresRelation
        relations = {}
        if self.entity_type == 1:
            entity_type = 1
            role = 'Alias'
            if role in roles and 'aliases' in self.entities:
                for entity_id in self.entities['aliases'].values():
                    if not entity_id:
                        continue
                    ids = sorted((entity_id, self.entity_id))
                    relation = PostgresRelation(
                        entity_one_type=entity_type,
                        entity_one_id=ids[0],
                        entity_two_type=entity_type,
                        entity_two_id=ids[1],
                        role=role,
                        )
                    relations[relation.link_key] = relation
            role = 'Member Of'
            if role in roles:
                if 'groups' in self.entities:
                    for entity_id in self.entities['groups'].values():
                        if not entity_id:
                            continue
                        relation = PostgresRelation(
                            entity_one_type=entity_type,
                            entity_one_id=self.entity_id,
                            entity_two_type=entity_type,
                            entity_two_id=entity_id,
                            role=role,
                            )
                        relations[relation.link_key] = relation
                if 'members' in self.entities:
                    for entity_id in self.entities['members'].values():
                        if not entity_id:
                            continue
                        relation = PostgresRelation(
                            entity_one_type=entity_type,
                            entity_one_id=entity_id,
                            entity_two_type=entity_type,
                            entity_two_id=self.entity_id,
                            role=role,
                            )
                        relations[relation.link_key] = relation
        elif self.entity_type == 2 and 'Sublabel Of' in roles:
            entity_type = 2
            role = 'Sublabel Of'
            if 'parent_label' in self.entities:
                for entity_id in self.entities['parent_label'].values():
                    if not entity_id:
                        continue
                    relation = PostgresRelation(
                        entity_one_type=entity_type,
                        entity_one_id=self.entity_id,
                        entity_two_type=entity_type,
                        entity_two_id=entity_id,
                        role=role,
                        )
                    relations[relation.link_key] = relation
            if 'sublabels' in self.entities:
                for entity_id in self.entities['sublabels'].values():
                    if not entity_id:
                        continue
                    relation = PostgresRelation(
                        entity_one_type=entity_type,
                        entity_one_id=entity_id,
                        entity_two_type=entity_type,
                        entity_two_id=self.entity_id,
                        role=role,
                        )
                    relations[relation.link_key] = relation
        return relations

    @classmethod
    def update_corpus(cls, corpus, key):
        if key in corpus:
            return
        entity_type, entity_name = key
        query = cls.select().where(
            cls.entity_type == entity_type,
            cls.name == entity_name,
            )
        if query.count():
            corpus[key] = query.get().entity_id

    ### PUBLIC PROPERTIES ###

    @property
    def entity_key(self):
        return (self.entity_type, self.entity_id)

    @property
    def json_entity_key(self):
        entity_type, entity_id = self.entity_key
        if entity_type == 1:
            return 'artist-{}'.format(self.entity_id)
        elif entity_type == 2:
            return 'label-{}'.format(self.entity_id)
        raise ValueError(self.entity_key)

    @property
    def size(self):
        if self.entity_type == 1:
            members = self.entities.get('members', ())
        elif self.entity_type == 2:
            members = self.entities.get('sublabels', ())
        return len(members)

PostgresEntity._tags_to_fields_mapping = {
    'aliases': ('aliases', PostgresEntity.element_to_names),
    'contact_info': ('contact_info', Bootstrapper.element_to_string),
    'groups': ('groups', PostgresEntity.element_to_names),
    'id': ('entity_id', Bootstrapper.element_to_integer),
    'members': ('members', PostgresEntity.element_to_names_and_ids),
    'name': ('name', Bootstrapper.element_to_string),
    'namevariations': ('name_variations', Bootstrapper.element_to_strings),
    'parentLabel': ('parent_label', PostgresEntity.element_to_parent_label),
    'profile': ('profile', Bootstrapper.element_to_string),
    'realname': ('real_name', Bootstrapper.element_to_string),
    'sublabels': ('sublabels', PostgresEntity.element_to_sublabels),
    'urls': ('urls', Bootstrapper.element_to_strings),
    }


text:
package com.google.cloud.websecurityscanner.v1alpha.samples;

// [START websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanRuns_Paged_async]
import com.google.cloud.websecurityscanner.v1alpha.ListScanRunsRequest;
import com.google.cloud.websecurityscanner.v1alpha.ListScanRunsResponse;
import com.google.cloud.websecurityscanner.v1alpha.ScanConfigName;
import com.google.cloud.websecurityscanner.v1alpha.ScanRun;
import com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerClient;
import com.google.common.base.Strings;

public class AsyncListScanRunsPaged {

  public static void main(String[] args) throws Exception {
    asyncListScanRunsPaged();
  }

  public static void asyncListScanRunsPaged() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.create()) {
      ListScanRunsRequest request =
          ListScanRunsRequest.newBuilder()
              .setParent(ScanConfigName.of("[PROJECT]", "[SCAN_CONFIG]").toString())
              .setPageToken("pageToken873572522")
              .setPageSize(883849137)
              .build();
      while (true) {
        ListScanRunsResponse response =
            webSecurityScannerClient.listScanRunsCallable().call(request);
        for (ScanRun element : response.getScanRunsList()) {
          // doThingsWith(element);
        }
        String nextPageToken = response.getNextPageToken();
        if (!Strings.isNullOrEmpty(nextPageToken)) {
          request = request.toBuilder().setPageToken(nextPageToken).build();
        } else {
          break;
        }
      }
    }
  }
}
// [END websecurityscanner_v1alpha_generated_WebSecurityScanner_ListScanRuns_Paged_async]


text:
<?php

/**
 * @package modx
 * @subpackage rest
 */
require_once realpath(dirname(__FILE__).'/modrestcontroller.class.php');
/**
 * A MODX-powered REST service class for dynamic REST API applications. Uses controller classes to handle routing
 * requests. Also supports xml/json/qs formats, and path/to/object/id routes.
 *
 * @package modx
 * @subpackage rest
 */
class modRestService {
    /** @var modX $modx A reference to the modX instance */
    public $modx;
    /** @var array $config The configuration array */
    public $config = array();
    /** @var modRestServiceRequest $request The REST request object for this service */
	public $request;
	/** @var modRestServiceResponse $response The REST response object for this service */
	public $response;
	/** @var int|string $requestPrimaryKey The primary key requested on the object/id route */
    public $requestPrimaryKey;

	/**
     * @param modX $modx
     * @param array $config
	 */
	public function __construct(modX &$modx,array $config = array()) {
		$this->modx =& $modx;
		$this->config = array_merge(array(
            'basePath' => $this->modx->getOption('base_path',null,MODX_BASE_PATH),
            'collectionResultsKey' => 'results',
            'collectionTotalKey' => 'total',
            'controllerClassPrefix' => 'modRestController',
            'controllerClassSeparator' => '',
            'defaultAction' => 'index',
            'defaultResponseFormat' => 'json',
            'defaultFailureStatusCode' => 200,
            'defaultSuccessStatusCode' => 200,
            'errorMessageSeparator' => ' ',
            'exitOnResponse' => true,
            'propertyLimit' => 'limit',
            'propertyOffset' => 'start',
            'propertySearch' => 'search',
            'propertySort' => 'sort',
            'propertySortDir' => 'dir',
            'requestParameter' => '_rest',
            'responseErrorsKey' => 'errors',
            'responseMessageKey' => 'message',
            'responseObjectKey' => 'object',
            'responseSuccessKey' => 'success',
            'trimParameters' => false,
            'xmlRootNode' => 'response',
		),$config);
		$this->modx->getService('lexicon','modLexicon');
        if ($this->modx->lexicon) {
            $this->modx->lexicon->load('rest');
        }
	}

    /**
     * Get a configuration option for this service
     *
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    public function getOption($key,$default = null) {
        return array_key_exists($key,$this->config) ? $this->config[$key] : $default;
    }

    /**
     * Check permissions for the request.
     *
     * @return boolean
     */
	public function checkPermissions() {
        return true;
	}

    /**
     * Prepare the request object, setting the method, headers, format and parameters
     */
	public function prepare() {
	    $requestParameter = $this->getOption('requestParameter','_rest');
	    $this->request = new modRestServiceRequest($this);
	    $this->request->setAction();
	    $this->request->setFormat($this->getOption('defaultResponseFormat','json'));
	    $this->request->checkForSuffix();
		unset($_GET[$requestParameter]);
		$this->request->setMethod();
		$this->request->setHeaders();
		$this->request->setRequestParameters();
	}

	/**
     * Process the request, creating the controller and response objects, and then sending the processed
     * response back to the client. The controller is determined by the path passed to the request parameter, and
     * the controller's method is determined by the HTTP request method sent.
	 */
	public function process() {
		try	{
			$controllerName = $this->getController();
			if(null == $controllerName) {
				throw new Exception('Method not allowed', 405);
			}
			/** @var modRestController $controller */
			$controller = new ReflectionClass($controllerName);
			if (!$controller->isInstantiable()) {
				throw new Exception('Bad Request', 400);
			}
            $controller->properties = $this->request->parameters;
            $controller->headers = $this->request->headers;
			try {
			    /** @var ReflectionMethod $method */
				$method = $controller->getMethod($this->request->method);
			} catch (ReflectionException $e) {
				throw new Exception('Unsupported HTTP method ' . $this->request->method, 405);
			}
			if (!$method->isStatic()) {
				$controller = $controller->newInstance($this->modx,$this->request,$this->config);
			    $controller->setProperties($this->request->parameters);
			    $controller->setHeaders($this->request->headers);
			    if ($controller->isProtected()) {
                    if (!$controller->verifyAuthentication()) {
                        throw new Exception('Unauthorized', 401);
                    }
                }
			    if (!empty($this->requestPrimaryKey)) {
			        $controller->setProperty($controller->primaryKeyField,$this->requestPrimaryKey);
                }
				$controller->initialize();
				$method->invoke($controller);
				$this->response = new modRestServiceResponse($this,$controller->getResponse(),$controller->getResponseStatus());
			} else {
				throw new Exception('Static methods not supported in Controllers', 500);
			}
			if (empty($this->response)) {
				throw new Exception('Method not allowed', 405);
			}
		} catch (Exception $error)	{
		    $this->response = new modRestServiceResponse($this,array(
			    'success' => false,
                'message' => $error->getMessage(),
                'object' => array(),
                'code' => $error->getCode(),
            ),$error->getCode());
		}
		$contentType = $this->getResponseContentType($this->request->format);
		$this->response->setContentType($contentType);
		$this->response->prepare();
		return $this->response->send();
	}

    /**
     * Get the Response content type based on the format passed
     *
     * @param string $format
     * @return string
     */
    public function getResponseContentType($format = 'json') {
        $supportedFormats = $this->getOption('supportedFormats','xml,json,qs');
        $supportedFormats = explode(',',$supportedFormats);
        if (!in_array($format,$supportedFormats)) {
             $contentType = $this->getOption('defaultResponseFormat','json');
        } else {
            $contentType = $format;
        }
        return trim($contentType);
    }

    /**
     * Get the correct controller path for the class
     *
     * @return string
     */
	protected function getController() {
		$expectedFile = trim($this->request->action,'/');
		$basePath = $this->getOption('basePath');
		$controllerClassPrefix = $this->getOption('controllerClassPrefix','modController');
		$controllerClassSeparator = $this->getOption('controllerClassSeparator','_');
		$controllerClassFilePostfix = $this->getOption('controllerClassFilePostfix','.php');

        /* handle [object]/[id] pathing */
        $expectedArray = explode('/',$expectedFile);
        if (empty($expectedArray)) $expectedArray = array(rtrim($expectedFile,'/').'/');
        $id = array_pop($expectedArray);
        if (!file_exists($basePath.$expectedFile.$controllerClassFilePostfix) && intval($id) > 0) {
            $expectedFile = implode('/',$expectedArray);
            if (empty($expectedFile)) {
                $expectedFile = $id;
                $id = null;
            }
            $this->requestPrimaryKey = $id;
        }

		foreach ($this->iterateDirectories($basePath.'/*'.$controllerClassFilePostfix, GLOB_NOSORT) as $controller) {
            $controller = $basePath != '/' ? str_replace($basePath,'',$controller) : $controller;
            $controller = trim($controller,'/');
            $controllerFile = str_replace(array($controllerClassFilePostfix),array(''),$controller);
            $controllerClass = str_replace(array('/',$controllerClassFilePostfix),array($controllerClassSeparator,''),$controller);
			if (strnatcasecmp($expectedFile, $controllerFile) == 0) {
			    require_once $basePath.$controller;
				return $controllerClassPrefix . $controllerClassSeparator . $controllerClass;
			}
		}
		$this->modx->log(modX::LOG_LEVEL_INFO,'Could not find expected controller: '.$expectedFile);
		return null;
	}

    /**
     * Iterate across directories looking for files based on a pattern
     *
     * @param string $pattern
     * @param int $flags
     * @return array
     */
    public function iterateDirectories($pattern, $flags = 0) {
        $files = glob($pattern, $flags);
        $dirs = glob(dirname($pattern) . '/*', GLOB_ONLYDIR|GLOB_NOSORT);

        if ($dirs) {
            foreach ($dirs as $dir) {
                $files = array_merge($files, $this->iterateDirectories($dir . '/' . basename($pattern), $flags));
            }
        }

        return $files;
    }

    /**
     * Send either to the unauthorized page or exit out with a 401
     * @param bool $exit
     */
    public function sendUnauthorized($exit = true) {
        if (!$exit) {
            $this->modx->sendUnauthorizedPage();
        } else {
            header('HTTP/1.1 401 Unauthorized');
            @session_write_close();
            exit(0);
        }
    }
}

/**
 * Request class for REST Service, which abstracts the incoming request
 *
 * @package modx
 * @subpackage rest
 */
class modRestServiceRequest {
    /** @var \modRestService $service */
    public $service;
    /** @var string $action The action for the request */
    public $action = 'index';
    /** @var string $format The format the request is asking for */
    public $format = 'json';
    /** @var string $method The HTTP method the  */
    public $method = 'GET';
    /** @var array $headers The HTTP headers on the request */
    public $headers = array();
    /** @var array $parameters The request parameters on the request */
    public $parameters = array();

    /**
     * @param modRestService $service A reference to the modRestService instance
     */
    function __construct(modRestService &$service) {
        $this->service = &$service;
    }

    /**
     * Set or determine the target action (controller) for this request
     *
     * @param string $action
     */
    public function setAction($action = '') {
        if (empty($action)) {
            $requestParameter = $this->service->getOption('requestParameter','_rest');
            $defaultAction = $this->service->getOption('defaultAction','index');
            $action = !empty($_GET[$requestParameter]) ? $_GET[$requestParameter] : $defaultAction;
        }
		$this->_trimString($action);
        $this->action = $action;
    }

    /**
     * Set the response format for this request
     *
     * @param string $format
     */
    public function setFormat($format = 'json') {
		$this->_trimString($format);
		$this->format = $format;
    }

    /**
     * Check for a format suffix (.json, .xml, etc) on the request, properly setting the format if found
     */
    public function checkForSuffix() {
		$formatPos = strpos($this->action,'.');
		if ($formatPos !== false) {
		    $this->format = substr($this->action,$formatPos+1);
		    $this->action = substr($this->action,0,$formatPos);
		}
    }

    /**
     * Set or determine the HTTP request method for this request
     *
     * @param string $method
     */
    public function setMethod($method = '') {
        if (empty($method)) {
		    $method = strtolower($_SERVER['REQUEST_METHOD']);
        }
		$this->_trimString($method);
		$this->method = $method;
    }

    /**
     * Set or collect the headers for this request
     *
     * @param array $headers
     */
    public function setHeaders(array $headers = array()) {
        if (empty($headers)) {
            if (function_exists('apache_request_headers')) {
                $this->headers = apache_request_headers();
            }
            $headers = array();
            $keys = preg_grep('{^HTTP_}i', array_keys($_SERVER));
            foreach ($keys as $val) {
                $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($val, 5)))));
                $headers[$key] = $_SERVER[$val];
            }
        }
        array_walk_recursive($headers,array('modRestServiceRequest','_trimString'));
        $this->headers = $headers;
    }

    /**
     * Set the REQUEST parameters for this request
     */
    public function setRequestParameters() {
		switch ($this->method) {
			case 'get':
				$this->parameters = $_GET;
				break;
			case 'post':
			    $this->parameters = array_merge($_POST,$_GET,$this->_collectRequestParameters());
			    $_REQUEST = $this->parameters;
				break;
			case 'put':
			    $this->parameters = array_merge($_POST,$this->_collectRequestParameters());
			    $_REQUEST = $this->parameters;
            	break;
			case 'delete':
			    $this->parameters = array_merge($_GET,$this->_collectRequestParameters());
			    $_REQUEST = $this->parameters;
				break;
			default:
				break;
		}
    }

    /**
     * Properly get request parameters for various HTTP methods and content types
     * @return array
     */
	protected function _collectRequestParameters() {
	    $data = @file_get_contents('php://input');
	    $params = array();
	    $contentType = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';
	    $spPos = strpos($contentType,';');
	    if ($spPos !== false) {
	        $contentType = substr($contentType,0,$spPos);
	    }
        switch ($contentType) {
            case 'application/xml':
            case 'text/xml':
                $xml = simplexml_load_string($data);
                $params = $this->_xml2Array($xml);
                break;
            case 'application/json':
            case 'text/json':
                $params = $this->service->modx->fromJSON($data);
                break;
            case 'application/x-www-form-urlencoded':
            default:
                parse_str($data, $params);
                break;
        }
        if ($this->service->getOption('trimParameters',false)) {
		    array_walk_recursive($this->parameters,array('modRestServiceRequest','_trimString'));
        }
        if (empty($params)) $params = array();
        return $params;
	}

	/**
     * Trim a value, assuming it is a string
     *
     * @static
     * @param mixed $value
     */
	public static function _trimString(&$value) {
        if (is_string($value)) {
            $value = trim($value);
        }
	}

    /**
     * Convert a SimpleXMLElement object to a multi-dimensional array
     *
     * @param SimpleXMLElement $xml
     * @param mixed $attributesKey
     * @param mixed $childrenKey
     * @param mixed $valueKey
     * @return array|null|string
     */
    protected function _xml2array(SimpleXMLElement $xml,$attributesKey=null,$childrenKey=null,$valueKey=null) {
        if ($childrenKey && !is_string($childrenKey)) $childrenKey = '@children';
        if ($attributesKey && !is_string($attributesKey)) $attributesKey = '@attributes';
        if ($valueKey && !is_string($valueKey)) $valueKey = '@values';

        $return = array();
        $name = $xml->getName();
        $_value = trim((string)$xml);
        if (!strlen($_value)) $_value = null;

        if ($_value !== null){
            if ($valueKey) {
                $return[$valueKey] = $_value;
            } else{
                $return = $_value;
            }
        }

        $children = array();
        $first = true;
        foreach ($xml->children() as $elementName => $child){
            $value = $this->_xml2array($child,$attributesKey, $childrenKey,$valueKey);
            if (isset($children[$elementName])) {
                if (is_array($children[$elementName])) {
                    if ($first) {
                        $temp = $children[$elementName];
                        unset($children[$elementName]);
                        $children[$elementName][] = $temp;
                        $first = false;
                    }
                    $children[$elementName][] = $value;
                } else {
                    $children[$elementName] = array($children[$elementName],$value);
                }
            } else {
                $children[$elementName] = $value;
            }
        }
        if ($children) {
            if ($childrenKey) {
                $return[$childrenKey] = $children;
            } else {
                $return = array_merge($return,$children);
            }
        }
        $attributes = array();
        foreach ($xml->attributes() as $name => $value) {
            $attributes[$name] = trim($value);
        }
        if ($attributes) {
            if ($attributesKey) {
                $return[$attributesKey] = $attributes;
            }
            else if (is_array($attributes) && is_array($return)) {
                $return = array_merge($return, $attributes);
            }
        }
        return $return;
    }
}

/**
 * The REST response class for the service
 *
 * @package modx
 * @subpackage rest
 */
class modRestServiceResponse {
    /** @var string $body The data body of the response */
    public $body;
    /** @var int $status The status code of the response */
    public $status;
    /** @var string $contentType The string content type of the response */
    public $contentType = 'json';
    /** @var array $payload The data payload being sent as the response */
    protected $payload = array();

    /**
     * Map of formats to their parallel content types
     * @var array
     */
	protected static $contentTypes = array(
        'xml'   => 'application/xml',
        'json'  => 'application/json',
        'qs'    => 'text/plain'
    );
    /**
     * Dictionary of response codes and their text descriptions
     * @var array
     */
	protected static $responseCodes = array(
        100 => 'Continue',
        101 => 'Switching Protocols',
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        306 => '(Unused)',
        307 => 'Temporary Redirect',
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
    );

    /**
     * @param modRestService $service A reference to the modRestService instance
     * @param string $body The actual body of the response
     * @param string|int $status The status code for the response
     */
    function __construct(modRestService &$service,$body,$status) {
        $this->service = &$service;
        $this->body = $body;
        $this->status = $status;
    }

    /**
     * Set the content type for this response
     *
     * @param string $contentType
     */
    public function setContentType($contentType) {
        $this->contentType = $contentType;
    }

    /**
     * Prepare the response, properly formatting the body and generating the payload
     */
    public function prepare() {
		if (!empty($this->body)) {
			$this->payload = array('status' => $this->status, 'body' => $this->getFormattedBody());
		} else {
			$this->contentType = 'qs';
			$this->payload = array('status' => $this->status, 'body' => $this->body);
		}
    }

    /**
     * Format the body based on the content type of the response
     *
     * @access protected
     * @return string
     */
	protected function getFormattedBody() {
	    switch ($this->contentType) {
            case 'xml':
                $data = $this->toXml($this->body);
                break;
            case 'qs':
                $data = http_build_query($this->body);
                break;
            case 'json':
            case 'js':
            default:
                $data = $this->service->modx->toJSON($this->body);
                break;
        }
        return $data;
	}

    /**
     * Send the response back to the client.
     */
	public function send() {
        $contentType = $this->getResponseContentType($this->contentType);
        $status = !empty($this->payload['status']) ? $this->payload['status'] : 200;
        $body = empty($this->payload['body']) ? '' : $this->payload['body'];

		$headers = 'HTTP/1.1 ' . $status . ' ' . $this->getResponseCodeMessage($status);
		header($headers);
		header('Content-Type: ' . $contentType);
		echo $body;
		if ($this->service->getOption('exitOnResponse',true)) {
            @session_write_close();
            exit(0);
        }
	}

    /**
     * Get the proper response code message for the passed status code
     *
     * @param int $status
     * @return string
     */
	protected function getResponseCodeMessage($status) {
        return (isset(self::$responseCodes[$status])) ? self::$responseCodes[$status] : self::$responseCodes[500];
    }

    /**
     * Get the proper HTTP content type for the passed format
     *
     * @param string $format
     * @return string
     */
	protected function getResponseContentType($format = 'json') {
		return self::$contentTypes[$format];
	}

    /**
     * Convert an array to XML output
     *
     * @param array $data
     * @param string $version
     * @param string $encoding
     * @return string
     */
	protected function toXml($data, $version = '1.0', $encoding = 'UTF-8') {
		$xml = new XMLWriter;
		$xml->openMemory();
		$xml->startDocument($version, $encoding);
		$xml->startElement($this->service->getOption('xmlRootNode','response'));
		$this->_xml($xml, $data);
		$xml->endElement();
		return $xml->outputMemory(true);
	}

    /**
     * Helper method for converting an array to XML output
     *
     * @param XMLWriter $xml
     * @param mixed $data
     * @param string $old_key
     */
	protected function _xml(XMLWriter $xml, $data, $old_key = null) {
        foreach ($data as $key => $value){
            if (is_array($value)){
                if (!is_int($key)) {
                    $xml->startElement($key);
                } else {
                    $singleKey = trim($old_key,'s');
                    $xml->startElement($singleKey);
                }
                $this->_xml($xml, $value, $key);
                $xml->endElement();
                continue;
            }
            $key = (is_int($key)) ? $old_key.$key : $key;
            if (!is_object($value)) {
                $xml->writeElement($key, $value);
            }
        }
    }
}


text:
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Stratageme15.Core.JavascriptCodeDom.Statements;
using Stratageme15.Core.Translation;
using Stratageme15.Core.Translation.Reactors;
using Stratageme15.Core.Translation.TranslationContexts;
using Stratageme15.Reactors.Basic.Utility;

namespace Stratageme15.Reactors.Basic.Statements.Switch
{
    public class SwitchStatementSyntaxReactor : BasicReactorBase<SwitchStatementSyntax>
    {
        protected override void HandleNode(SwitchStatementSyntax node, TranslationContextWrapper context,
                                           TranslationResult result)
        {
            result.Strategy = TranslationStrategy.TraverseChildrenAndNotifyMe;
            result.PrepareForManualPush(context.Context);
            var sw = new SwitchStatement();
            context.Context.TargetNode.CollectSymbol(sw);
            context.Context.PushTranslated(sw);
            if (node.Sections != null)
            {
                foreach (SwitchSectionSyntax source in node.Sections.Reverse())
                {
                    context.Context.TranslationStack.Push(source);
                }
            }
            context.Context.TranslationStack.Push(SyntaxFactory.ParenthesizedExpression(node.Expression));
        }

        public override void OnAfterChildTraversal(TranslationContextWrapper context, SwitchStatementSyntax originalNode)
        {
            base.OnAfterChildTraversal(context, originalNode);
            context.Context.PopTranslated();
        }
    }
}


text:
//
//  BeaconHandler.h
//  Colors
//
//  Created by Lukasz Stocki on 22.01.2015.
//  Copyright (c) 2015 ACME. All rights reserved.
//

@import Foundation;
@import CoreLocation;
@import UIKit;

#import "Beacon.h"
#import "BeaconRegion.h"

@class BeaconHandler;

@protocol BeaconEventHandler <NSObject>

/**
 *  Called on BeaconHandler delegate when some beacons were updated.
 *
 *  @param handler BeaconHandler instance that updated it's beacons.
 *  @param beacons NSArray of Beacon instances that were updated.
 */
- (void)beaconHandler:(BeaconHandler *)handler
     didUpdateBeacons:(NSArray *)beacons;

@end

/**
 *  Class that encapsulates logic required for beacon magic to work.
 */
@interface BeaconHandler : NSObject

@property (nonatomic, weak) id <BeaconEventHandler> delegate;

/**
 *  Designated initalizer for creating a BeaconManager.
 *
 *  @param regions  NSArray of BeaconRegion instancess defining regions in whitch this manager should handle beacons.
 *  @param delegate Delegate that will be notified about updated beacons.
 *
 *  @return Instance of BeaconHandler.
 */
- (instancetype)initWithBeaconRegions:(NSArray *)regions
                             delegate:(id <BeaconEventHandler>)delegate NS_DESIGNATED_INITIALIZER;

/**
 *  Starts monitoring for beacons in defined regions.
 */
- (void)start;

@end


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"/>
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="apple-mobile-web-app-status-bar-style" content="black"/>
<meta name="format-detection" content="telephone=no"/>
<title>定增拼单</title>
<meta name="description" content=""/>
<meta name="keywords" content=""/>
<link href="__CSS__/communal.css" rel="stylesheet"/>

<link href="__CSS__/style.css" rel="stylesheet"/>

                

定增拼单


text:
class AddAccessCountToPosts < ActiveRecord::Migration
  def change
    add_column Refinery::Blog::Post.table_name, :access_count, :integer, :default => 0

    add_index Refinery::Blog::Post.table_name, :access_count

  end
end


text:
namespace CSharpMath.Rendering.FrontEnd {
  public abstract class Path : Typography.OpenFont.IGlyphTranslator, System.IDisposable {
    // Don't depend on contourCount, it is zero when reading a CFF glyph
    void Typography.OpenFont.IGlyphTranslator.BeginRead(int contourCount) { }
    void Typography.OpenFont.IGlyphTranslator.EndRead() => Dispose();
    public abstract void MoveTo(float x0, float y0);
    public abstract void LineTo(float x1, float y1);
    public abstract void Curve3(float x1, float y1, float x2, float y2);
    public abstract void Curve4(float x1, float y1, float x2, float y2, float x3, float y3);
    public abstract void CloseContour();
    public abstract void Dispose();
    public abstract System.Drawing.Color? Foreground { get; set; }
  }
}


text:
class A {
    #name: string;
    constructor(name: string) {
        this.#name = name;
    }
}

//// [privateNameField.js]
"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {
    if (!privateMap.has(receiver)) {
        throw new TypeError("attempted to set private field on non-instance");
    }
    privateMap.set(receiver, value);
    return value;
};
var _name;
class A {
    constructor(name) {
        _name.set(this, void 0);
        __classPrivateFieldSet(this, _name, name);
    }
}
_name = new WeakMap();


text:
module EV
  class EventSource
    def initialize(events)
      events.each { |event| apply_without_changes(event) }
    end

    def version
      @version || 0
    end

    def changes
      return [] unless @changes
      @changes.dup
    end

    def initial_version
      version - changes.size
    end

    def dirty?
      changes.size > 0
    end

    def commit
      @changes.clear if @changes
    end

    protected

    def handle(event)
      raise NotImplementedError
    end

    def apply(event)
      apply_without_changes(event)
      @changes ||= []
      @changes << event
    end

    private

    def apply_without_changes(event)
      handle(event)
      @version = version.next
    end
  end
end


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<LEOSimulation version="2.5.0">
	<STELAVersion>2.5.1</STELAVersion>
	<SpaceObject>
		<mass unit="kg">7.0</mass>
		<dragArea>0.065</dragArea>
		<reflectingArea>0.26</reflectingArea>
		<reflectivityCoefficient>1.5</reflectivityCoefficient>
		<orbitType>LEO</orbitType>
		<ConstantDragCoef>
			<cstDragCoef>2.1</cstDragCoef>
		</ConstantDragCoef>
		<name>EVPDLVPG</name>
	</SpaceObject>
	<EphemerisManager version="2.5.0">
		<initState>
			<bulletin version="2.5.0">
				<date>2014-07-14T15:03:14.000</date>
				<Type2PosVel>
					<frame>CELESTIAL_MEAN_OF_DATE</frame>
					<nature>MEAN</nature>
					<semiMajorAxis unit="m">7000000.0</semiMajorAxis>
					<eccentricity>0.001</eccentricity>
					<inclination unit="rad">1.74532925199</inclination>
					<rAAN unit="rad">0.0</rAAN>
					<argOfPerigee unit="rad">0.0</argOfPerigee>
					<meanAnomaly unit="rad">0.0</meanAnomaly>
				</Type2PosVel>
			</bulletin>
		</initState>
		<finalState>
			<bulletin version="2.5.0">
				<date>2035-07-13T21:46:24.448</date>
				<Type2PosVel>
					<frame>CELESTIAL_MEAN_OF_DATE</frame>
					<nature>MEAN</nature>
					<semiMajorAxis unit="m">6496176.8780872235</semiMajorAxis>
					<eccentricity>2.3378032056186197E-4</eccentricity>
					<inclination unit="rad">1.7438888381360966</inclination>
					<rAAN unit="rad">1.4176571169579901</rAAN>
					<argOfPerigee unit="rad">3.6709498616005947</argOfPerigee>
					<meanAnomaly unit="rad">3.4691117970802408</meanAnomaly>
				</Type2PosVel>
			</bulletin>
		</finalState>
	</EphemerisManager>
	<author>CNES</author>
	<comment>LEO example simulation</comment>
	<simulationDuration unit="years">100.0</simulationDuration>
	<ephemerisStep unit="s">86400.0</ephemerisStep>
	<ttMinusUT1 unit="s">67.184</ttMinusUT1>
	<srpSwitch>true</srpSwitch>
	<sunSwitch>true</sunSwitch>
	<moonSwitch>true</moonSwitch>
	<extrapolationDuration>16813</extrapolationDuration>
	<warningFlag>false</warningFlag>
	<iterativeMode>false</iterativeMode>
	<GTOIntegrator>
		<Integrator>
			<effective_duration unit="years">20.99802869828504</effective_duration>
			<LOSCriteria1 version="2.5.0">
				<status_criteria1>1</status_criteria1>
				<comment_criteria1>Lifetime :21 years</comment_criteria1>
			</LOSCriteria1>
			<LOSCriteria2 version="2.5.0">
				<status_criteria2>3</status_criteria2>
			</LOSCriteria2>
			<LOSCriteria3 version="2.5.0">
				<status_criteria3>3</status_criteria3>
			</LOSCriteria3>
			<LOSCriteria4 version="2.5.0">
				<status_criteria4>3</status_criteria4>
			</LOSCriteria4>
		</Integrator>
	</GTOIntegrator>
	<modelType>GTO</modelType>
	<atmosModel>NRLMSISE-00</atmosModel>
	<VariableSolarActivity>
		<solActType>VARIABLE</solActType>
	</VariableSolarActivity>
	<integrationStep unit="s">86400.0</integrationStep>
	<dragSwitch>true</dragSwitch>
	<dragQuadPoints>33</dragQuadPoints>
	<atmosDragRecomputeStep>1</atmosDragRecomputeStep>
	<srpQuadPoints>11</srpQuadPoints>
	<reentryAltitude unit="m">120000.0</reentryAltitude>
	<iterationData>
		<funcValueAccuracy unit="days">10.0</funcValueAccuracy>
		<expDuration unit="years">24.75</expDuration>
		<simMinusExpDuration unit="years">75.25</simMinusExpDuration>
		<iterationMethod>FrozenOrbit</iterationMethod>
	</iterationData>
	<nbIntegrationStepTesseral>5.0</nbIntegrationStepTesseral>
	<zonalOrder>7</zonalOrder>
</LEOSimulation>


text:
/*!
 * \file   support/xpressive.hpp
 * \author Andrey Semashev
 * \date   18.07.2009
 *
 * This header enables Boost.Xpressive support for Boost.Log.
 */

#ifndef BOOST_LOG_SUPPORT_XPRESSIVE_HPP_INCLUDED_
#define BOOST_LOG_SUPPORT_XPRESSIVE_HPP_INCLUDED_

#include <string>
#include <boost/xpressive/basic_regex.hpp>
#include <boost/xpressive/regex_constants.hpp>
#include <boost/xpressive/regex_algorithms.hpp>
#include <boost/log/detail/config.hpp>
#include <boost/log/utility/functional/matches.hpp>
#include <boost/log/detail/header.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace aux {

//! This tag type is used if an expression is recognized as a Boost.Xpressive expression
struct boost_xpressive_expression_tag;

//! The metafunction detects the matching expression kind and returns a tag that is used to specialize \c match_traits
template< typename T >
struct matching_expression_kind< xpressive::basic_regex< T > >
{
    typedef boost_xpressive_expression_tag type;
};

//! The matching function implementation
template< typename ExpressionT >
struct match_traits< ExpressionT, boost_xpressive_expression_tag >
{
    typedef ExpressionT compiled_type;
    static compiled_type compile(ExpressionT const& expr) { return expr; }

    template< typename StringT, typename T >
    static bool matches(StringT const& str, xpressive::basic_regex< T > const& expr, xpressive::regex_constants::match_flag_type flags = xpressive::regex_constants::match_default)
    {
        return xpressive::regex_match(str, expr, flags);
    }

    template< typename CharT, typename TraitsT, typename AllocatorT >
    static bool matches(std::basic_string< CharT, TraitsT, AllocatorT > const& str, xpressive::basic_regex< const CharT* > const& expr, xpressive::regex_constants::match_flag_type flags = xpressive::regex_constants::match_default)
    {
        const CharT* p = str.c_str();
        return xpressive::regex_match(p, p + str.size(), expr, flags);
    }
};

} // namespace aux

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#include <boost/log/detail/footer.hpp>

#endif // BOOST_LOG_SUPPORT_XPRESSIVE_HPP_INCLUDED_


text:
@interface CRJHUDDemoVC : CRProductionBaseVC

@end


text:
using namespace Yap;
using namespace std;

NiumagFidWriter::NiumagFidWriter(void) :
	ProcessorImpl(L"NiumagFidWriter")
{
	LOG_TRACE(L"NiumagFidWriter constructor called.", L"BasicRecon");
	AddInput(L"Input", YAP_ANY_DIMENSION, DataTypeComplexFloat);

	AddProperty<const wchar_t * const>(L"ExportFolder", L"", L"Set folder used to write FID.");
	AddProperty<const wchar_t * const>(L"FileName", L"", L"Set file name.");
	AddProperty<const wchar_t * const>(L"SavePath", L"", L"Full Path (folder and file name) used to write FID");
}

NiumagFidWriter::NiumagFidWriter(const NiumagFidWriter& rhs) :
	ProcessorImpl(rhs)
{
	LOG_TRACE(L"NiumagFidWriter constructor called.", L"BasicRecon");
}

NiumagFidWriter::~NiumagFidWriter()
{
	LOG_TRACE(L"NiumagFidWriter destructor called.", L"BasicRecon");
}

bool Yap::NiumagFidWriter::Input(const wchar_t * name, IData * data)
{
	assert((data != nullptr) && (GetDataArray<complex<float>>(data) != nullptr));

	auto file_path = GetProperty<const wchar_t * const>(L"SavePath");
	if (!file_path)
	{
		auto output_folder = GetProperty<const wchar_t * const>(L"ExportFolder");
		auto output_name = GetProperty<const wchar_t * const>(L"FileName");
		file_path = GetFilePath(output_folder, output_name).c_str();
	}

	// write data
	int file_version = 1;
	int section1size = 100;
	int section2size = 100;
	int section3size = 100;
	int section4size = 100;
	int section5size = 100; // fid

	int section5_offset = 4 * 6 + 400;

	DataHelper data_helper(data);

	auto dimension_count = data_helper.GetDimensionCount();

	int dim1 = data_helper.GetWidth();
	int dim2 = data_helper.GetHeight();
	int dim3 = data_helper.GetSliceCount();
	int dim4 = data_helper.GetDim4();

	unsigned buffer_size = dim1 * dim2 * dim3 * dim4;
	complex<float> * fid_data = GetDataArray<complex<float>>(data);

	ofstream file(file_path, ios::binary);

	file.write(reinterpret_cast<char*>(&file_version), 4);
	file.write(reinterpret_cast<char*>(&section1size), 4);
	file.write(reinterpret_cast<char*>(&section2size), 4);
	file.write(reinterpret_cast<char*>(&section3size), 4);
	file.write(reinterpret_cast<char*>(&section4size), 4);
	file.write(reinterpret_cast<char*>(&section5size), 4);

	file.seekp(section5_offset, ios::beg);
	file.write(reinterpret_cast<char*>(&dim1), 4);
	file.write(reinterpret_cast<char*>(&dim2), 4);
	file.write(reinterpret_cast<char*>(&dim3), 4);
	file.write(reinterpret_cast<char*>(&dim4), 4);
	file.write(reinterpret_cast<char*>(fid_data), buffer_size * sizeof(complex<float>));
	file.close();

	return true;
}

std::wstring Yap::NiumagFidWriter::GetFilePath(const wchar_t * output_folder, const wchar_t * output_name)
{
	wstring file_path = output_folder;
	if (wcslen(output_folder) > 3)
	{
		file_path += L"\\";
	}

	if (wcslen(output_name) > 0)
	{
		file_path += output_name;
		file_path += L".";
	}

	time_t t = time(0);
	char tmp[64];
	strftime(tmp, sizeof(tmp), "%Y%m%d-%H%M%S", localtime(&t));
	string str(tmp);
	std::wstring wstr;
	wstr.assign(str.begin(), str.end());
	file_path += wstr;

	file_path += L".fid";

	return file_path;
}