text:
import * as React from "react";
import {
  DataToolbarGroup,
  DataToolbarFilter,
  DataToolbarItem,
  DataToolbarChip,
  DataToolbarToggleGroup,
  DataToolbar,
  DataToolbarContent
} from "@patternfly/react-core/dist/js/experimental";
import {
  Dropdown,
  DropdownToggle,
  DropdownItem,
  InputGroup,
  Button,
  ButtonVariant,
  Badge,
  Select,
  SelectVariant,
  SelectOption,
  SelectOptionObject
} from "@patternfly/react-core";
import { FilterIcon, SearchIcon } from "@patternfly/react-icons";
import { ISortBy } from "@patternfly/react-table";
import useWindowDimensions from "components/common/WindowDimension";
import { SortForMobileView } from "components/common/SortForMobileView";
import { useApolloClient } from "@apollo/react-hooks";
import {
  RETURN_ALL_CONTAINER_IDS_OF_ADDRESS_LINKS_FOR_TYPEAHEAD_SEARCH,
  RETURN_ALL_NAMES_OF_ADDRESS_LINK_FOR_TYPEAHEAD_SEARCH
} from "queries";
import {
  ISearchAddressLinkNameResponse,
  ISearchAddressLinkContainerResponse
} from "types/ResponseTypes";
import {
  TypeAheadMessage,
  TYPEAHEAD_REQUIRED_LENGTH,
  MAX_ITEM_TO_DISPLAY_IN_TYPEAHEAD_DROPDOWN,
  NUMBER_OF_RECORDS_TO_DISPLAY_IF_SERVER_HAS_MORE_DATA,
  FetchPolicy
} from "constants/constants";
import { getSelectOptionList, ISelectOption } from "utils";

interface IAddressLinksFilterProps {
  filterValue: string;
  setFilterValue: (value: string) => void;
  filterNames: any[];
  setFilterNames: (value: Array<any>) => void;
  filterContainers: any[];
  setFilterContainers: (value: Array<any>) => void;
  filterRole?: string;
  setFilterRole: (role: string | undefined) => void;
  totalLinks: number;
  sortValue?: ISortBy;
  setSortValue: (value: ISortBy) => void;
  addressName: string;
  addressSpaceName: string;
  namespace: string;
}
export const AddressLinksFilter: React.FunctionComponent<IAddressLinksFilterProps> = ({
  filterValue,
  setFilterValue,
  filterNames,
  setFilterNames,
  filterContainers,
  setFilterContainers,
  filterRole,
  setFilterRole,
  totalLinks,
  sortValue,
  setSortValue,
  addressName,
  addressSpaceName,
  namespace
}) => {
  const { width } = useWindowDimensions();
  const client = useApolloClient();
  const [filterIsExpanded, setFilterIsExpanded] = React.useState<boolean>(
    false
  );
  const [roleIsExpanded, setRoleIsExpanded] = React.useState<boolean>(false);
  const [isSelectNameExpanded, setIsSelectNameExpanded] = React.useState<
    boolean
  >(false);
  const [
    isSelectContainerExpanded,
    setIsSelectContainerExpanded
  ] = React.useState<boolean>(false);
  const [nameSelected, setNameSelected] = React.useState<string>();
  const [containerSelected, setContainerSelected] = React.useState<string>();
  const [nameOptions, setNameOptions] = React.useState<Array<ISelectOption>>();
  const [containerOptions, setContainerOptions] = React.useState<
    Array<ISelectOption>
  >();
  const [nameInput, setNameInput] = React.useState<string>("");
  const [containerInput, setContainerInput] = React.useState<string>("");
  const filterMenuItems = [
    { key: "filterName", value: "Name" },
    { key: "filterContainers", value: "Container" },
    { key: "filterRole", value: "Role" }
  ];

  const roleMenuItems = [
    { key: "roleSender", value: "Sender" },
    { key: "roleReceiver", value: "Receiver" }
  ];

  const sortMenuItems = [
    { key: "name", value: "Name", index: 2 },
    { key: "deliveryRate", value: "DeliveryRate", index: 3 },
    { key: "backlog", value: "Backlog", index: 4 }
  ];

  const onAddInput = (event: any) => {
    if (filterValue && filterValue === "Name") {
      if (nameSelected && nameSelected.trim() !== "")
        if (
          filterNames.map(filter => filter.value).indexOf(nameSelected.trim()) <
          0
        ) {
          setFilterNames([
            ...filterNames,
            { value: nameSelected.trim(), isExact: true }
          ]);
          setNameSelected(undefined);
        }
      if (!nameSelected && nameInput && nameInput.trim() !== "")
        if (
          filterNames.map(filter => filter.value).indexOf(nameInput.trim()) < 0
        )
          setFilterNames([
            ...filterNames,
            { value: nameInput.trim(), isExact: false }
          ]);
    } else if (filterValue && filterValue === "Container") {
      if (containerSelected && containerSelected.trim() !== "")
        if (
          filterContainers
            .map(filter => filter.value)
            .indexOf(containerSelected.trim()) < 0
        ) {
          setFilterContainers([
            ...filterContainers,
            { value: containerSelected.trim(), isExact: true }
          ]);
          setContainerSelected(undefined);
        }
      if (!containerSelected && containerInput && containerInput.trim() !== "")
        if (
          filterContainers
            .map(filter => filter.value)
            .indexOf(containerInput.trim()) < 0
        )
          setFilterContainers([
            ...filterContainers,
            { value: containerInput.trim(), isExact: false }
          ]);
    }
  };

  const onFilterSelect = (event: any) => {
    setFilterValue(event.target.value);
    setFilterIsExpanded(!filterIsExpanded);
  };
  const onRoleSelect = (event: any) => {
    setFilterRole(event.target.value);
    setRoleIsExpanded(!roleIsExpanded);
  };
  const onNameSelectToggle = () => {
    setIsSelectNameExpanded(!isSelectNameExpanded);
  };
  const onContainerSelectToggle = () => {
    setIsSelectContainerExpanded(!isSelectContainerExpanded);
  };
  const onChangeNameData = async (value: string) => {
    setNameOptions(undefined);
    if (value.trim().length < TYPEAHEAD_REQUIRED_LENGTH) {
      setNameOptions([]);
      return;
    }
    const response = await client.query<ISearchAddressLinkNameResponse>({
      query: RETURN_ALL_NAMES_OF_ADDRESS_LINK_FOR_TYPEAHEAD_SEARCH(
        addressName,
        namespace,
        value.trim()
      ),
      fetchPolicy: FetchPolicy.NETWORK_ONLY
    });
    if (
      response &&
      response.data &&
      response.data.addresses &&
      response.data.addresses.addresses &&
      response.data.addresses.addresses.length > 0 &&
      response.data.addresses.addresses[0].links &&
      response.data.addresses.addresses[0].links.links &&
      response.data.addresses.addresses[0].links.links.length > 0
    ) {
      let obtainedList = [];
      obtainedList = response.data.addresses.addresses[0].links.links.map(
        (link: any) => {
          return link.metadata.name;
        }
      );
      //get list of unique records to display in the select dropdown based on total records and 100 fetched objects
      const uniqueList = getSelectOptionList(
        obtainedList,
        response.data.addresses.addresses[0].links.total
      );
      if (uniqueList.length > 0) setNameOptions(uniqueList);
    }
  };
  const onNameSelectFilterChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setNameInput(e.target.value);
    onChangeNameData(e.target.value);
    const options: React.ReactElement[] = nameOptions
      ? nameOptions.map((option, index) => (
          <SelectOption key={index} value={option} />
        ))
      : [];
    return options;
  };

  const onChangeContainerData = async (value: string) => {
    setContainerOptions(undefined);
    if (value.trim().length < TYPEAHEAD_REQUIRED_LENGTH) {
      setContainerOptions([]);
      return;
    }
    const response = await client.query<ISearchAddressLinkContainerResponse>({
      query: RETURN_ALL_CONTAINER_IDS_OF_ADDRESS_LINKS_FOR_TYPEAHEAD_SEARCH(
        addressName,
        namespace,
        value.trim()
      ),
      fetchPolicy: FetchPolicy.NETWORK_ONLY
    });
    if (
      response &&
      response.data &&
      response.data.addresses &&
      response.data.addresses.addresses &&
      response.data.addresses.addresses.length > 0 &&
      response.data.addresses.addresses[0].links &&
      response.data.addresses.addresses[0].links.links &&
      response.data.addresses.addresses[0].links.links.length > 0
    ) {
      let obtainedList = [];
      obtainedList = response.data.addresses.addresses[0].links.links.map(
        (link: any) => {
          return link.spec.connection.spec.containerId;
        }
      );
      //get list of unique records to display in the select dropdown based on total records and 100 fetched objects
      const uniqueList = getSelectOptionList(
        obtainedList,
        response.data.addresses.addresses[0].links.total
      );
      if (uniqueList.length > 0) setContainerOptions(uniqueList);
    }
  };

  const onContainerSelectFilterChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    setContainerInput(e.target.value);
    onChangeContainerData(e.target.value);
    const options: React.ReactElement[] = containerOptions
      ? containerOptions.map((option, index) => (
          <SelectOption key={index} value={option} />
        ))
      : [];
    return options;
  };

  const onNameSelect = (event: any, selection: string | SelectOptionObject) => {
    setNameSelected(selection.toString());
    setIsSelectNameExpanded(false);
  };

  const onContainerSelect = (
    event: any,
    selection: string | SelectOptionObject
  ) => {
    setContainerSelected(selection.toString());
    setIsSelectContainerExpanded(false);
  };

  const onDelete = (
    type: string | DataToolbarChip,
    id: string | DataToolbarChip
  ) => {
    switch (type) {
      case "Name":
        if (filterNames && id) {
          let index = filterNames
            .map(filter => filter.value)
            .indexOf(id.toString());
          if (index >= 0) filterNames.splice(index, 1);
          setFilterNames([...filterNames]);
        }
        break;
      case "Container":
        if (filterContainers && id) {
          let index = filterContainers
            .map(filter => filter.value)
            .indexOf(id.toString());
          if (index >= 0) filterContainers.splice(index, 1);
          setFilterContainers([...filterContainers]);
        }
        break;
      case "Role":
        setFilterRole(undefined);
        break;
    }
  };
  const checkIsFilterApplied = () => {
    if (
      (filterNames && filterNames.length > 0) ||
      (filterContainers && filterContainers.length > 0) ||
      (filterRole && filterRole.trim() !== "")
    ) {
      return true;
    }
    return false;
  };
  const onDeleteAll = () => {
    setFilterValue("Name");
    setFilterNames([]);
    setFilterContainers([]);
    setFilterRole(undefined);
  };

  const toggleGroupItems = (
    <>
      <DataToolbarGroup variant="filter-group">
        <DataToolbarFilter categoryName="Filter">
          <Dropdown
            id="ad-links-filter-dropdown"
            position="left"
            onSelect={onFilterSelect}
            isOpen={filterIsExpanded}
            toggle={
              <DropdownToggle onToggle={setFilterIsExpanded}>
                <FilterIcon />

                {filterValue}
              </DropdownToggle>
            }
            dropdownItems={filterMenuItems.map(option => (
              <DropdownItem
                id={`ad-links-filter-dropdown-item${option.key}`}
                key={option.key}
                value={option.value}
                itemID={option.key}
                component={"button"}
              >
                {option.value}
              </DropdownItem>
            ))}
          />
        </DataToolbarFilter>
        <>
          <DataToolbarItem>
            <DataToolbarFilter
              chips={filterNames.map(filter => filter.value)}
              deleteChip={onDelete}
              categoryName="Name"
            >
              {filterValue && filterValue === "Name" && (
                <InputGroup>
                  <Select
                    id="ad-links-filter-select-name"
                    variant={SelectVariant.typeahead}
                    aria-label="Select a Name"
                    onToggle={onNameSelectToggle}
                    onSelect={onNameSelect}
                    onClear={() => {
                      setNameSelected(undefined);
                      setIsSelectNameExpanded(false);
                    }}
                    maxHeight="200px"
                    selections={nameSelected}
                    onFilter={onNameSelectFilterChange}
                    isExpanded={isSelectNameExpanded}
                    ariaLabelledBy={"typeahead-select-id"}
                    placeholderText="Select name"
                    isDisabled={false}
                    isCreatable={false}
                  >
                    {nameOptions && nameOptions.length > 0 ? (
                      nameOptions.map((option, index) => (
                        <SelectOption
                          key={index}
                          value={option.value}
                          isDisabled={option.isDisabled}
                        />
                      ))
                    ) : nameInput.trim().length < TYPEAHEAD_REQUIRED_LENGTH ? (
                      <SelectOption
                        key={"invalid-input-length"}
                        value={"Enter more characters"}
                        disabled={true}
                      />
                    ) : (
                      <SelectOption
                        key={"no-results-found"}
                        value={"No results found"}
                        disabled={true}
                      />
                    )}
                    {/* {} */}
                  </Select>
                  <Button
                    id="ad-links-filter-search-name"
                    variant={ButtonVariant.control}
                    aria-label="search button for search name"
                    onClick={onAddInput}
                  >
                    <SearchIcon />
                  </Button>
                </InputGroup>
              )}
            </DataToolbarFilter>
          </DataToolbarItem>
          <DataToolbarItem>
            <DataToolbarFilter
              chips={filterContainers.map(filter => filter.value)}
              deleteChip={onDelete}
              categoryName="Container"
            >
              {filterValue && filterValue === "Container" && (
                <InputGroup>
                  <Select
                    id="ad-links-filter-select-container"
                    variant={SelectVariant.typeahead}
                    aria-label="Select a Container"
                    onToggle={onContainerSelectToggle}
                    onSelect={onContainerSelect}
                    onClear={() => {
                      setContainerSelected(undefined);
                      setIsSelectContainerExpanded(false);
                    }}
                    maxHeight="200px"
                    selections={containerSelected}
                    onFilter={onContainerSelectFilterChange}
                    isExpanded={isSelectContainerExpanded}
                    ariaLabelledBy={"typeahead-select-id"}
                    placeholderText="Select container"
                    isDisabled={false}
                    isCreatable={false}
                  >
                    {containerOptions && containerOptions.length > 0 ? (
                      containerOptions.map((option, index) => (
                        <SelectOption
                          key={index}
                          value={option.value}
                          isDisabled={option.isDisabled}
                        />
                      ))
                    ) : containerInput.trim().length <
                      TYPEAHEAD_REQUIRED_LENGTH ? (
                      <SelectOption
                        key={"invalid-input-length"}
                        value={TypeAheadMessage.MORE_CHAR_REQUIRED}
                        disabled={true}
                      />
                    ) : (
                      <SelectOption
                        key={"no-results-found"}
                        value={TypeAheadMessage.NO_RESULT_FOUND}
                        disabled={true}
                      />
                    )}
                    {/* {} */}
                  </Select>
                  <Button
                    id="ad-links-filter-search-container"
                    variant={ButtonVariant.control}
                    aria-label="search button for search containers"
                    onClick={onAddInput}
                  >
                    <SearchIcon />
                  </Button>
                </InputGroup>
              )}
            </DataToolbarFilter>
          </DataToolbarItem>

          <DataToolbarItem>
            <DataToolbarFilter
              chips={filterRole ? [filterRole] : []}
              deleteChip={onDelete}
              categoryName="Role"
            >
              {filterValue === "Role" && (
                <Dropdown
                  id="ad-links-filter-select-role"
                  position="left"
                  onSelect={onRoleSelect}
                  isOpen={roleIsExpanded}
                  toggle={
                    <DropdownToggle onToggle={setRoleIsExpanded}>
                      {filterRole || "Select Role"}
                    </DropdownToggle>
                  }
                  dropdownItems={roleMenuItems.map(option => (
                    <DropdownItem
                      id={`ad-links-filter-select-option-role${option.key}`}
                      key={option.key}
                      value={option.value}
                      itemID={option.key}
                      component={"button"}
                    >
                      {option.value}
                    </DropdownItem>
                  ))}
                />
              )}
            </DataToolbarFilter>
          </DataToolbarItem>
        </>
      </DataToolbarGroup>
    </>
  );

  return (
    <DataToolbar
      id="data-toolbar-with-filter"
      className="pf-m-toggle-group-container"
      collapseListedFiltersBreakpoint="xl"
      clearAllFilters={onDeleteAll}
    >
      <DataToolbarContent>
        <>
          <DataToolbarToggleGroup
            toggleIcon={
              <>
                <FilterIcon />
                {checkIsFilterApplied() && (
                  <Badge key={1} isRead>
                    {totalLinks}
                  </Badge>
                )}
              </>
            }
            breakpoint="xl"
          >
            {toggleGroupItems}
          </DataToolbarToggleGroup>
          {width < 769 && (
            <SortForMobileView
              sortMenu={sortMenuItems}
              sortValue={sortValue}
              setSortValue={setSortValue}
            />
          )}
        </>
      </DataToolbarContent>
    </DataToolbar>
  );
};


text:
function outputArray = tuneFatigue(fileName, baseline, threshold, ...
    fatigueThresholdArray)
% This is the function that runs processFile multiple times using different
% values for baselineF and thresholdF.

n = length(fatigueThresholdArray);

outputArray = zeros(n,4);

for i = 1:n
    outputArray(i,1) = fatigueThresholdArray(i);
    [outputArray(i,2), outputArray(i,3)] =  processFile(fileName, ...
        baseline, threshold, fatigueThresholdArray(i));
    outputArray(i,4) = outputArray(i,3) - outputArray(i,2);
end

redpajama_set_name: RedPajamaGithub


text:
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Microsoft Public License (MS-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
//
//   The terms "reproduce," "reproduction," "derivative works," and
//   "distribution" have the same meaning here as under U.S. copyright law. A
//   "contribution" is the original software, or any additions or changes to
//   the software. A "contributor" is any person that distributes its
//   contribution under this license. "Licensed patents" are a contributor's
//   patent claims that read directly on its contribution.
//
// 2. Grant of Rights
//
//   (A) Copyright Grant- Subject to the terms of this license, including the
//       license conditions and limitations in section 3, each contributor
//       grants you a non-exclusive, worldwide, royalty-free copyright license
//       to reproduce its contribution, prepare derivative works of its
//       contribution, and distribute its contribution or any derivative works
//       that you create.
//
//   (B) Patent Grant- Subject to the terms of this license, including the
//       license conditions and limitations in section 3, each contributor
//       grants you a non-exclusive, worldwide, royalty-free license under its
//       licensed patents to make, have made, use, sell, offer for sale,
//       import, and/or otherwise dispose of its contribution in the software
//       or derivative works of the contribution in the software.
//
// 3. Conditions and Limitations
//
//   (A) No Trademark License- This license does not grant you rights to use
//       any contributors' name, logo, or trademarks.
//
//   (B) If you bring a patent claim against any contributor over patents that
//       you claim are infringed by the software, your patent license from such
//       contributor to the software ends automatically.
//
//   (C) If you distribute any portion of the software, you must retain all
//       copyright, patent, trademark, and attribution notices that are present
//       in the software.
//
//   (D) If you distribute any portion of the software in source code form, you
//       may do so only under this license by including a complete copy of this
//       license with your distribution. If you distribute any portion of the
//       software in compiled or object code form, you may only do so under a
//       license that complies with this license.
//
//   (E) The software is licensed "as-is." You bear the risk of using it. The
//       contributors give no express warranties, guarantees or conditions. You
//       may have additional consumer rights under your local laws which this
//       license cannot change. To the extent permitted under your local laws,
//       the contributors exclude the implied warranties of merchantability,
//       fitness for a particular purpose and non-infringement.
//

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.ClearScript.Util;

namespace Microsoft.ClearScript.Windows
{
    public abstract partial class WindowsScriptEngine
    {
        #region Nested type: DebugDocument

        private class DebugDocument : IDebugDocumentInfo, IDebugDocumentProvider, IDebugDocument, IDebugDocumentText
        {
            private readonly WindowsScriptEngine engine;
            private readonly UIntPtr sourceContext;
            private readonly string name;
            private readonly string code;

            private string[] codeLines;
            private IDebugApplicationNode node;

            public DebugDocument(WindowsScriptEngine engine, UIntPtr sourceContext, string name, string code, bool transient)
            {
                this.engine = engine;
                this.sourceContext = sourceContext;
                this.name = name + (transient ? " [temp]" : "");
                this.code = code;
                Initialize();
            }

            private void Initialize()
            {
                codeLines = code.Split('\n').Select(line => line + '\n').ToArray();

                engine.debugApplication.CreateApplicationNode(out node);
                node.SetDocumentProvider(this);

                IDebugApplicationNode rootNode;
                engine.debugApplication.GetRootNode(out rootNode);
                node.Attach(rootNode);
            }

            public string Code
            {
                get { return code; }
            }

            public void Close()
            {
                node.Detach();
                node.Close();
                node = null;
            }

            #region IDebugDocumentInfo implementation

            public void GetName(DocumentNameType type, out string documentName)
            {
                switch (type)
                {
                    case DocumentNameType.URL:
                        var fullName = Path.HasExtension(name) ? name : Path.ChangeExtension(name, engine.FileNameExtension);
                        documentName = MiscHelpers.FormatInvariant("{0}/{1}", engine.Name, fullName);
                        break;

                    default:
                        documentName = name;
                        break;
                }
            }

            public void GetDocumentClassId(out Guid clsid)
            {
                clsid = Guid.Empty;
            }

            #endregion

            #region IDebugDocumentProvider implementation

            public void GetDocument(out IDebugDocument document)
            {
                document = this;
            }

            #endregion

            #region IDebugDocument implementation

            #endregion

            #region IDebugDocumentText implementation

            public void GetDocumentAttributes(out TextDocAttrs attrs)
            {
                attrs = TextDocAttrs.ReadOnly;
            }

            public void GetSize(out uint numLines, out uint length)
            {
                numLines = (uint)codeLines.Length;
                length = (uint)code.Length;
            }

            public void GetPositionOfLine(uint lineNumber, out uint position)
            {
                if (lineNumber >= codeLines.Length)
                {
                    throw new ArgumentOutOfRangeException("lineNumber");
                }

                position = 0;
                for (var index = 0; index < lineNumber; index++)
                {
                    position += (uint)codeLines[index].Length;
                }
            }

            public void GetLineOfPosition(uint position, out uint lineNumber, out uint offsetInLine)
            {
                if (position >= code.Length)
                {
                    throw new ArgumentOutOfRangeException("position");
                }

                offsetInLine = position;
                for (lineNumber = 0; lineNumber < codeLines.Length; lineNumber++)
                {
                    var lineLength = (uint)codeLines[lineNumber].Length;
                    if (offsetInLine < lineLength)
                    {
                        break;
                    }

                    offsetInLine -= lineLength;
                }
            }

            public void GetText(uint position, IntPtr pChars, IntPtr pAttrs, ref uint length, uint maxChars)
            {
                var codeLength = (uint)code.Length;
                if (position < codeLength)
                {
                    length = Math.Min(codeLength - position, maxChars);

                    if (pChars != IntPtr.Zero)
                    {
                        Marshal.Copy(code.ToCharArray(), (int)position, pChars, (int)length);
                    }

                    if (pAttrs != IntPtr.Zero)
                    {
                        var attrs = Enumerable.Repeat((short)SourceTextAttrs.None, (int)length).ToArray();
                        Marshal.Copy(attrs, 0, pAttrs, (int)length);
                    }
                }
            }

            public void GetPositionOfContext(IDebugDocumentContext context, out uint position, out uint length)
            {
                var documentContext = (DebugDocumentContext)context;
                position = documentContext.Position;
                length = documentContext.Length;
            }

            public void GetContextOfPosition(uint position, uint length, out IDebugDocumentContext context)
            {
                IEnumDebugCodeContexts enumCodeContexts;
                engine.activeScript.EnumCodeContextsOfPosition(sourceContext, position, length, out enumCodeContexts);
                context = new DebugDocumentContext(this, position, length, enumCodeContexts);
            }

            #endregion
        }

        #endregion

        #region Nested type: DebugDocumentMap

        private class DebugDocumentMap : Dictionary<UIntPtr, DebugDocument>
        {
        }

        #endregion

        #region Nested type: DebugDocumentContext

        private class DebugDocumentContext : IDebugDocumentContext
        {
            private readonly DebugDocument document;
            private readonly uint position;
            private readonly uint length;
            private readonly IEnumDebugCodeContexts enumCodeContexts;

            public DebugDocumentContext(DebugDocument document, uint position, uint length, IEnumDebugCodeContexts enumCodeContexts)
            {
                this.document = document;
                this.position = position;
                this.length = length;
                this.enumCodeContexts = enumCodeContexts;
            }

            public uint Position
            {
                get { return position; }
            }

            public uint Length
            {
                get { return length; }
            }

            #region IDebugDocumentContext implementation

            public void GetDocument(out IDebugDocument debugDocument)
            {
                debugDocument = document;
            }

            public void EnumCodeContexts(out IEnumDebugCodeContexts enumContexts)
            {
                enumCodeContexts.Clone(out enumContexts);
            }

            #endregion
        }

        #endregion
    }
}


text:
<?php
/**
 * Welcome English lexicon topic
 *
 * @language en
 * @package modx
 * @subpackage lexicon
 */
$_lang['modx_news'] = 'MODX новини';
$_lang['security_notices'] = 'Известия за сигурност';
$_lang['welcome_messages'] = 'Входящата ви кутия съдържа %d съобщения, от които %s са непрочетени.';
$_lang['welcome_title'] = 'Добре дошли във Вашия MODX Мениджър';
$_lang['yourinfo_message'] = 'Този раздел показва информация за вас:';
$_lang['yourinfo_previous_login'] = 'Твоето последно влизане:';
$_lang['yourinfo_title'] = 'Вашата информация';
$_lang['yourinfo_total_logins'] = 'Общ брой на влизанията:';
$_lang['yourinfo_username'] = 'Влезли сте като:';


text:
<?php

/**
 * Flat sales order shipment item resource
 *
 * @category    Mage
 * @package     Mage_Sales
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Sales_Model_Mysql4_Order_Shipment_Item extends Mage_Sales_Model_Resource_Order_Shipment_Item
{
}


text:
import React, {Component} from 'react';
import {StyleSheet,Image,ActionSheetIOS} from 'react-native';
import NavBar, { NavGroup, NavButton, NavButtonText, NavTitle } from 'react-native-nav'
import Theme from '../utils/Theme'

let BUTTONS = ['夜间模式','粉色模式','设置','取消'];
let CANCEL_INDEX = 3;

export default class HomeNav extends Component {

  title = '首页';
  drawer = false;

  constructor(props) {
    super(props);
  }

  handleDrawer(props){
    this.drawer?props.closeDrawer():props.openDrawer();
    // this.drawer = !this.drawer;
  };

  showActionSheet(props) {
    // BUTTONS[0] = this.props.zhihu.theme==Theme.DARK?'日间模式':'夜间模式';
    ActionSheetIOS.showActionSheetWithOptions({
          options: BUTTONS,
          cancelButtonIndex: CANCEL_INDEX
        },
        (index) => {
          if(index==0){
            props.switchTheme(this.props.zhihu.theme==Theme.DARK?Theme.LIGHT:Theme.DARK);
          } else if (index==1){
            props.switchTheme(Theme.PINK);
          }
        }
    );
  }

  render() {
    let theme = new Theme(this.props.zhihu.theme);
    let title = {
        color: '#rgba(255, 255, 255, 1)',
        left: -70
    };
    let styles = StyleSheet.create({
      statusBar: {
        backgroundColor: theme.colors.statusBar
      },
      navBar: {
        backgroundColor: theme.colors.titleBar,
        height: 50,
        paddingLeft: 15
      },
      buttonText: {
        color: '#rgba(255, 255, 255, 1)'
      },
      navButton:{
        marginTop: 20,
        flex: 1
      },
      icon:{
        width:30,
        height:30
      }
    });
    if (this.props.zhihu.title.length<4) title.left = -100;
    else if (this.props.zhihu.title.length==4) title.left = -80;
    else if (this.props.zhihu.title.length>4) title.left = -60;
    return (
      <NavBar style={styles}>
        <NavButton style={styles.navButton} onPress={()=>{this.handleDrawer(this.props)}}>
          <NavButtonText style={styles.buttonText}>
            <Image style={styles.icon} source={require('../img/ic_menu_white.png')} resizeMode={'contain'}/>
          </NavButtonText>
        </NavButton>
        <NavTitle style={title}>
          {this.props.zhihu.title}
        </NavTitle>
        <NavGroup>
          <NavButton style={styles.navButton}>
            <NavButtonText style={styles.buttonText}>
              <Image style={styles.icon} source={require('../img/ic_message_white.png')} resizeMode={'contain'}/>
            </NavButtonText>
          </NavButton>
          <NavButton style={styles.navButton} onPress={()=>{this.showActionSheet(this.props)}}>
            <NavButtonText style={styles.buttonText}>
              <Image style={styles.icon} source={require('../img/ic_more_white.png')} resizeMode={'contain'}/>
            </NavButtonText>
          </NavButton>
        </NavGroup>
      </NavBar>
    );
  }

}


text:
'use strict';

/* global CloudCmd, DOM*/

CloudCmd.EditFile = exports;

const Format = require('format-io');
const fullstore = require('fullstore');
const exec = require('execon');
const supermenu = require('supermenu');

const Info = DOM.CurrentInfo;

const {
    Dialog,
    Images,
} = DOM;

const {config} = CloudCmd;

let Menu;
let MSG_CHANGED;

const isLoading = fullstore();

const ConfigView = {
    beforeClose: async () => {
        exec.ifExist(Menu, 'hide');
        await isChanged();
    },
};

module.exports.init = async () => {
    isLoading(true);

    await CloudCmd.Edit();

    const editor = CloudCmd.Edit.getEditor();
    authCheck(editor);
    setListeners(editor);

    isLoading(false);
};

function getName() {
    const {name, isDir} = Info;

    if (isDir)
        return `${name}.json`;

    return name;
}

module.exports.show = async (options) => {
    if (isLoading())
        return;

    const optionsEdit = {
        ...ConfigView,
        ...options,
    };

    if (CloudCmd.config('showFileName'))
        optionsEdit.title = Info.name;

    Images.show.load();

    CloudCmd.Edit
        .getEditor()
        .setOption('keyMap', 'default');

    const [error, data] = await Info.getData();

    if (error) {
        Images.hide();
        return CloudCmd.Edit;
    }

    const {path} = Info;
    const name = getName();

    setMsgChanged(name);

    CloudCmd.Edit
        .getEditor()
        .setValueFirst(path, data)
        .setModeForPath(name)
        .enableKey();

    CloudCmd.Edit.show(optionsEdit);

    return CloudCmd.Edit;
};

module.exports.hide = hide;

function hide() {
    CloudCmd.Edit.hide();
}

function setListeners(editor) {
    const element = CloudCmd.Edit.getElement();

    DOM.Events.addOnce('contextmenu', element, setMenu);

    editor.on('save', (value) => {
        DOM.setCurrentSize(Format.size(value));
    });
}

function authCheck(spawn) {
    spawn.emit('auth', config('username'), config('password'));
    spawn.on('reject', () => {
        Dialog.alert('Wrong credentials!');
    });
}

function setMenu(event) {
    const position = {
        x: event.clientX,
        y: event.clientY,
    };

    event.preventDefault();

    if (Menu)
        return;

    const options = {
        beforeShow: (params) => {
            params.x -= 18;
            params.y -= 27;
        },

        afterClick: () => {
            CloudCmd.Edit
                .getEditor()
                .focus();
        },
    };

    const element = CloudCmd.Edit.getElement();

    Menu = supermenu(element, options, getMenuData());

    Menu.addContextMenuListener();
    Menu.show(position.x, position.y);
}

function getMenuData() {
    const editor = CloudCmd.Edit.getEditor();

    return {
        'Save           Ctrl+S' : () => {
            editor.save();
        },
        'Go To Line     Ctrl+G' : () => {
            editor.goToLine();
        },
        'Cut            Ctrl+X' : () => {
            editor.cutToClipboard();
        },
        'Copy           Ctrl+C' : () => {
            editor.copyToClipboard();
        },
        'Paste          Ctrl+V' : () => {
            editor.pasteFromClipboard();
        },
        'Delete         Del'    : () => {
            editor.remove('right');
        },
        'Select All     Ctrl+A' : () => {
            editor.selectAll();
        },
        'Close          Esc'    : hide,
    };
}

function setMsgChanged(name) {
    MSG_CHANGED = 'Do you want to save changes to ' + name + '?';
}

module.exports.isChanged = isChanged;

async function isChanged() {
    const editor = CloudCmd.Edit.getEditor();
    const is = editor.isChanged();

    if (!is)
        return;

    const [cancel] = await Dialog.confirm(MSG_CHANGED);

    if (cancel)
        return;

    editor.save();
}


text:
using System;
using Zyan.InterLinq;
using Zyan.InterLinq.Communication.Remoting;

namespace InterLinq.UnitTests.Server
{
	public class ServerQueryRemotingHandlerObjects : ServerQueryRemotingHandler
	{
		/// <summary>
		/// Initializes this class.
		/// </summary>
		/// <param name="innerHandler">Inner Handler of this Server.</param>
		public ServerQueryRemotingHandlerObjects(IQueryHandler innerHandler) : base(innerHandler) { }
		protected ServerQueryRemotingHandlerObjects() { }

		private static IQueryRemoteHandler registeredService;

		protected override void RegisterService(IQueryRemoteHandler serviceHandler)
		{
			registeredService = serviceHandler;
		}

		protected override IQueryRemoteHandler GetRegisteredService()
		{
			if (registeredService == null)
			{
				throw new Exception("Service could not be found.");
			}
			return registeredService;
		}
	}
}


text:
import re
import os

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc

import csv

from product_spiders.items import Product, ProductLoader
from product_spiders.spiders.BeautifulSoup import BeautifulSoup

class HGVDirectSpider(BaseSpider):
    name = 'hgvdirect.co.uk'
    allowed_domains = ['www.hgvdirect.co.uk']
    start_urls = ('http://www.hgvdirect.co.uk/catalog/allprods.php',)

    def __init__(self, *args, **kwargs):
        super(HGVDirectSpider, self).__init__(*args, **kwargs)

    def parse(self, response):
        if not isinstance(response, HtmlResponse):
            return
        hxs = HtmlXPathSelector(response)

        # pages
        next_page = hxs.select('//a[contains(text(), "Next")]/@href').extract()
        if next_page:
            url = urljoin_rfc(get_base_url(response), next_page[0])
            yield Request(url)
        else:
            soup = BeautifulSoup(response.body)
            next_page = soup.find('a', text=re.compile('.*Next.*'))
            if next_page:
                url = urljoin_rfc(get_base_url(response), next_page.parent['href'])
                yield Request(url)

        # products
        for product in self.parse_product(response):
            yield product

    def parse_product(self, response):
        if not isinstance(response, HtmlResponse):
            return

        hxs = HtmlXPathSelector(response)

        # products
        products = hxs.select('//table[@class="productListing"]/tr')[1:]
        if len(products) < 20: # if the product list can not be parsed using lxml, use BeautifulSoup
            soup = BeautifulSoup(response.body)
            products = soup.find('table', {'class': 'productListing'}).findAll('tr')
            products = products[1:]
            for product in products:
                product_loader = ProductLoader(item=Product(), response=response)
                product = product.findAll('td')
                name = product[1].find('a').contents
                url = product[1].find('a')['href']
                price = product[2].text
                price = re.findall('[0-9\.]+', price)
                product_loader.add_value('name', name)
                product_loader.add_value('url', url)
                product_loader.add_value('price', price[0])
                yield product_loader.load_item()

        else:
            for product in products:
                product_loader = ProductLoader(item=Product(), selector=product)
                product_loader.add_xpath('name', './td[position()=2]/a/text()')
                product_loader.add_xpath('url', './td[position()=2]/a/@href')
                product_loader.add_xpath('price', './td[position()=3]', re='\xa3(.*[0-9])')
                yield product_loader.load_item()


text:
using System;
using System.Text;

class Problem_13
{
    static void Main()
    {
        string inputURL = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
        int indexProtocol = inputURL.IndexOf(':');
        Console.WriteLine("protocol: {0}", inputURL.Substring(0,indexProtocol));
        int indexServer = inputURL.IndexOf('/', indexProtocol + 3);
        Console.WriteLine("server: {0}", inputURL.Substring(indexProtocol + 3, indexServer - indexProtocol - 3));
        Console.WriteLine("resource: {0}", inputURL.Substring(indexServer));
    }
}


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe "rhook examples" do
  describe "log buffer (hack Logger)" do
    require "logger"

    # Captures any messages written to Logger and keep in buffer.
    # You can read captured messages by LogBuffer#get
    # or LogBuffer##pull ( also clears buffer ).
    class LogBuffer
      def initialize
        @buf = ""
        # Any log messages are passed to Logger#format_message. Hack it!!
        Logger._rhook.hack(:format_message) do |inv|
          result = inv.call
          @buf << result
          result
        end
      end

      def clear
        @buf = ""
      end

      def get
        @buf
      end

      def pull
        result = get()
        clear()
        result
      end
    end #/LogBuffer

    # The example application to test.
    # You cannot know whether it success or failed, (by return value or exception)
    # ... it only logs.
    class TargetApp
      def initialize
        @log = Logger.new(STDERR)
      end

      def success
        @log.info "Success!"
      end

      def fail
        @log.error "Failed!"
      end
    end

    example "Use LogBuffer to write test" do
      app = TargetApp.new

      # start to capture log.
      logbuf = LogBuffer.new

      app.success
      logbuf.pull.should match(/Success!/)

      app.fail
      logbuf.pull.should match(/Failed!/)
    end
  end
end


text:
package org.javastack.bouncer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLSocket;

// ============================================ Mux Server

// MuxServer (MUX=IN) Local=MUX, Remote=RAW
class MuxServer {
	final MuxServerMessageRouter router = new MuxServerMessageRouter();
	final HashMap<Integer, MuxServerRemote> mapRemotes = new HashMap<Integer, MuxServerRemote>();
	final ServerContext context;

	MuxServerListenLocal localListen;
	ArrayList<MuxServerListenRemote> remoteListen = new ArrayList<MuxServerListenRemote>(1);
	MuxServerLocal local = null;

	final InboundAddress left;
	final Map<Integer, InboundAddress> right;

	MuxServer(final ServerContext context, final InboundAddress left, final InboundAddress right) {
		this.context = context;
		this.left = left;
		this.right = (right == null ? new HashMap<Integer, InboundAddress>() : //
				Collections.singletonMap(Integer.valueOf(0), right));
	}

	void addRight(final InboundAddress right) {
		this.right.put(right.getOpts().getTunID(), right);
	}

	void listenLocal() throws IOException { // Entry Point
		localListen = new MuxServerListenLocal(left); // Local is MUX
		context.addReloadableAwaiter(localListen);
		context.submitTask(localListen, "MuxInListenLeft[" + left + "]", ClientId.newId());
	}

	void listenRemote() throws IOException {
		for (InboundAddress right : this.right.values()) {
			try {
				final MuxServerListenRemote remoteListen = new MuxServerListenRemote(right); // Remote is RAW
				this.remoteListen.add(remoteListen);
				context.addReloadableAwaiter(remoteListen);
				context.submitTask(remoteListen, "MuxInListenRight[" + left + "|" + right + "]",
						ClientId.newId());
			} catch (IOException e) {
				Log.error(this.getClass().getSimpleName() + "::listenRemote " + e.toString(), e);
			}
		}
	}

	void closeRemote() {
		for (final MuxServerListenRemote remoteListen : this.remoteListen) {
			remoteListen.setShutdown();
		}
	}

	void closeRemote(final int id) {
		// Send FIN
		try {
			final MuxPacket mux = context.allocateMuxPacket();
			mux.fin(id);
			local.sendLocal(mux);
			context.releaseMuxPacket(mux);
		} catch (Exception ign) {
		}
		//
		synchronized (mapRemotes) {
			final MuxServerRemote remote = mapRemotes.remove(id);
			if (remote != null) {
				remote.setShutdown();
			}
		}
	}

	void sendACK(final RawPacket msg) {
		// Send ACK
		try {
			final MuxPacket mux = context.allocateMuxPacket();
			mux.ack(msg.getIdChannel(), msg.getBufferLen());
			local.sendLocal(mux);
			context.releaseMuxPacket(mux);
		} catch (Exception ign) {
		}
	}

	void sendNOP() {
		// Send NOP
		try {
			final MuxPacket mux = context.allocateMuxPacket();
			mux.nop(0);
			local.sendLocal(mux);
			context.releaseMuxPacket(mux);
		} catch (Exception ign) {
		}
	}

	MuxServerRemote getRemote(final int id) {
		synchronized (mapRemotes) {
			return mapRemotes.get(id);
		}
	}

	static void doSleep(final long time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException ie) {
			Thread.currentThread().interrupt();
		}
	}

	// ============================================

	class MuxServerMessageRouter {
		void onReceiveFromLocal(final MuxServerLocal local, final MuxPacket msg) { // Local is MUX
			// Log.debug(this.getClass().getSimpleName() + "::onReceiveFromLocal " + msg);
			if (msg.syn()) { // This is SYN/ACK
				final MuxServerRemote remote = getRemote(msg.getIdChannel());
				if (remote != null)
					remote.unlock(Constants.BUFFER_LEN * Constants.IO_BUFFERS);
			} else if (msg.fin()) { // End SubChannel
				Log.info(this.getClass().getSimpleName() + "::onReceiveFromLocal " + msg);
				final MuxServerRemote remote = getRemote(msg.getIdChannel());
				if (remote != null)
					remote.setShutdown();
			} else if (msg.ack()) { // Flow-Control ACK
				Log.debug(this.getClass().getSimpleName() + "::onReceiveFromLocal " + msg);
				final MuxServerRemote remote = getRemote(msg.getIdChannel());
				if (remote != null)
					remote.unlock(msg.ackSize());
			} else if (msg.nop()) { // NOP
				Log.info(this.getClass().getSimpleName() + "::onReceiveFromLocal " + msg);
			} else { // Data
				Log.debug(this.getClass().getSimpleName() + "::onReceiveFromLocal " + msg);
				try {
					final MuxServerRemote remote = getRemote(msg.getIdChannel());
					if (remote == null)
						return;
					final RawPacket raw = context.allocateRawPacket();
					raw.put(msg.getIdChannel(), msg.getBufferLen(), msg.getBuffer());
					remote.sendQueueRemote(raw);
				} catch (Exception e) {
					Log.error(this.getClass().getSimpleName() + "::onReceiveFromLocal " + e.toString(), e);
				}
			}
		}

		void onReceiveFromRemote(final MuxServerRemote remote, final RawPacket msg) { // Remote is RAW
			Log.debug(this.getClass().getSimpleName() + "::onReceiveFromRemote " + msg);
			try {
				final MuxPacket mux = context.allocateMuxPacket();
				mux.put(msg.getIdChannel(), msg.getBufferLen(), msg.getBuffer());
				local.sendLocal(mux);
				context.releaseMuxPacket(mux);
			} catch (Exception e) {
				Log.error(this.getClass().getSimpleName() + "::onReceiveFromRemote " + e.toString(), e);
			}
		}
	}

	abstract class MuxServerListen implements Awaiter, Runnable { // Local is MUX, Remote is RAW
		final InboundAddress inboundAddress;
		final ServerSocket listen;
		boolean shutdown = false;

		MuxServerListen(final InboundAddress inboundAddress) throws IOException {
			this.inboundAddress = inboundAddress;
			listen = inboundAddress.listen();
		}

		@Override
		public void setShutdown() {
			shutdown = true;
			close();
		}

		void close() {
			context.closeSilent(listen);
		}

		@Override
		public void run() {
			Log.info(this.getClass().getSimpleName() + "::run listen: " + listen);
			while (!shutdown) {
				try {
					final Socket socket = listen.accept();
					try {
						context.registerSocket(socket);
						final Integer pReadTimeout = inboundAddress.getOpts().getInteger(
								Options.P_READ_TIMEOUT);
						if (pReadTimeout != null) {
							socket.setSoTimeout(pReadTimeout.intValue());
						}
						if (socket instanceof SSLSocket) {
							((SSLSocket) socket).startHandshake();
						}
						Log.info(this.getClass().getSimpleName() + " new socket: " + socket + " "
								+ SSLFactory.getSocketProtocol(socket) + " SendBufferSize="
								+ socket.getSendBufferSize() + " ReceiveBufferSize="
								+ socket.getReceiveBufferSize());
						attender(socket);
					} catch (Exception e) {
						Log.error(this.getClass().getSimpleName() + " Exception: " + e.toString(), e);
						context.closeSilent(socket);
					}
				} catch (SocketTimeoutException e) {
					continue;
				} catch (Exception e) {
					if (!shutdown) {
						Log.error(this.getClass().getSimpleName() + " " + e.toString(), e);
					}
					doSleep(1000);
				}
			}
			close();
			Log.info(this.getClass().getSimpleName() + " await end");
			context.awaitShutdown(this);
			Log.info(this.getClass().getSimpleName() + " end");
		}

		//
		protected abstract void attender(Socket socket) throws IOException;
	}

	class MuxServerListenLocal extends MuxServerListen { // Local is MUX
		MuxServerListenLocal(final InboundAddress inboundAddress) throws IOException {
			super(inboundAddress);
		}

		@Override
		protected synchronized void attender(final Socket socket) throws IOException {
			Log.info(this.getClass().getSimpleName() + " attending socket: " + socket);
			if ((local == null) || local.isClosed()) {
				try {
					socket.setSoTimeout(Constants.MUX_READ_TIMEOUT);
				} catch (Exception ign) {
				}
				local = new MuxServerLocal(socket, inboundAddress);
				local.setRouter(router);
				context.addShutdownable(local);
				listenRemote();
				context.submitTask(local, "MuxInLeft[" + left + "|" + IOHelper.socketRemoteToString(socket)
						+ "]", ClientId.newId());
			} else {
				// Only one concurrent client, close the new connection
				Log.error(this.getClass().getSimpleName()
						+ " This listener already connected, closing socket: " + socket);
				sendNOP(); // FIXME: Try to check
				doSleep(1000);
				context.closeSilent(socket);
			}
		}
	}

	class MuxServerListenRemote extends MuxServerListen { // Remote is RAW
		MuxServerListenRemote(final InboundAddress inboundAddress) throws IOException {
			super(inboundAddress);
		}

		@Override
		protected synchronized void attender(final Socket socket) throws IOException {
			Log.info(this.getClass().getSimpleName() + " attending socket: " + socket);
			final MuxServerRemote remote = new MuxServerRemote(socket, inboundAddress);
			remote.setRouter(router);
			mapRemotes.put(remote.getId(), remote);
			context.submitTask(remote, "MuxInRight-Recv[" + socket.getPort() + "|" + left + "|" + right + "|"
					+ IOHelper.socketRemoteToString(socket) + "]",
					(((long) socket.getPort() << 48) | ClientId.newId()));
		}
	}

	abstract class MuxServerConnection implements Shutdownable, Runnable { // Local is MUX, Remote is RAW
		final Socket sock;
		final InboundAddress inboundAddress;
		final InputStream is;
		final OutputStream os;
		MuxServerMessageRouter router;
		boolean shutdown = false;

		//
		MuxServerConnection(final Socket sock, final InboundAddress inboundAddress) throws IOException {
			this.sock = sock;
			this.inboundAddress = inboundAddress;
			is = sock.getInputStream();
			os = sock.getOutputStream();
		}

		void setRouter(final MuxServerMessageRouter router) {
			this.router = router;
		}

		@Override
		public void setShutdown() {
			shutdown = true;
			// Graceful Shutdown: don't call close()
		}

		void close() {
			IOHelper.closeSilent(is);
			IOHelper.closeSilent(os);
			context.closeSilent(sock);
		}

		boolean isClosed() {
			return ((sock == null) || sock.isClosed());
		}
	}

	class MuxServerLocal extends MuxServerConnection implements Awaiter { // Local is MUX
		final SealerAES seal;

		MuxServerLocal(final Socket sock, final InboundAddress inboundAddress) throws IOException {
			super(sock, inboundAddress);
			if (inboundAddress.getOpts().isOption(Options.MUX_AES)) {
				seal = new SealerAES(inboundAddress.getOpts().getString(Options.P_AES), //
						inboundAddress.getOpts().getString(Options.P_AES_ALG), //
						inboundAddress.getOpts().getInteger(Options.P_AES_BITS, Integer.MIN_VALUE), //
						true);
			} else {
				seal = null;
			}
		}

		void sendLocal(final MuxPacket msg) throws IOException, GeneralSecurityException {
			synchronized (os) {
				if (seal != null) {
					// AES encryption
					final ByteArrayOutputStream baos = context.allocateByteArrayOutputStream();
					msg.toWire(baos);
					final byte[] encoded = seal.code(baos.toByteArray(), 0, baos.size());
					baos.reset();
					IOHelper.toWireWithHeader(baos, encoded, encoded.length);
					baos.writeTo(os);
					os.flush();
					context.releaseByteArrayOutputStream(baos);
				} else {
					msg.toWire(os);
				}
			}
			context.getStatistics().incOutMsgs().incOutBytes(msg.getBufferLen());
		}

		@Override
		public void run() {
			Log.info(this.getClass().getSimpleName() + "::run socket: " + sock);
			long muxNopKeepAlive = System.currentTimeMillis();
			while (!shutdown || !mapRemotes.isEmpty()) {
				try {
					final MuxPacket msg = context.allocateMuxPacket();
					if (seal != null) {
						// AES encryption
						final byte[] encoded = IOHelper.fromWireWithHeader(is);
						final byte[] decoded = seal.decode(encoded, 0, encoded.length);
						final ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
						msg.fromWire(bais);
					} else {
						msg.fromWire(is);
					}
					context.getStatistics().incInMsgs().incInBytes(msg.getBufferLen());
					router.onReceiveFromLocal(this, msg);
					context.releaseMuxPacket(msg);
				} catch (SocketTimeoutException e) {
					final long now = System.currentTimeMillis();
					if ((muxNopKeepAlive + Constants.MUX_KEEP_ALIVE) < now) {
						Log.debug(this.getClass().getSimpleName() + " " + e.toString());
						sendNOP();
						muxNopKeepAlive = now;
					}
					continue;
				} catch (EOFException e) {
					break;
				} catch (IOException e) {
					if ((sock != null) && !sock.isClosed() && !shutdown) {
						Log.error(this.getClass().getSimpleName() + " " + e.toString());
					}
					break;
				} catch (GeneralSecurityException e) {
					Log.error(this.getClass().getSimpleName() + " " + e.toString());
					doSleep(1000);
					break;
				} catch (Exception e) {
					Log.error(this.getClass().getSimpleName() + " Generic exception", e);
					break;
				}
			}
			// Close all
			close();
			closeRemote();
			synchronized (mapRemotes) { // Remotes are RAW
				for (MuxServerRemote r : mapRemotes.values()) {
					r.setShutdown();
				}
				mapRemotes.clear();
			}
			Log.info(this.getClass().getSimpleName() + " await end");
			context.awaitShutdown(this);
			Log.info(this.getClass().getSimpleName() + " end");
			local = null;
		}
	}

	class MuxServerRemote extends MuxServerConnection { // Remote is RAW
		final Semaphore isLocked = new Semaphore(0); // Begin Locked
		final ArrayBlockingQueue<RawPacket> queue = new ArrayBlockingQueue<RawPacket>(
				Constants.IO_BUFFERS << 1);
		final int id;
		long keepalive = System.currentTimeMillis();

		MuxServerRemote(final Socket sock, final InboundAddress inboundAddress) throws IOException {
			super(sock, inboundAddress);
			id = sock.getPort();
		}

		void unlock(final int size) {
			isLocked.release(size);
		}

		boolean lock(final int size) throws InterruptedException {
			return isLocked.tryAcquire(size, 3000, TimeUnit.MILLISECONDS);
		}

		int getId() {
			return id;
		}

		void sendQueueRemote(final RawPacket msg) throws IOException {
			try {
				while (!queue.offer(msg, 1000, TimeUnit.MILLISECONDS)) {
					if (shutdown)
						break;
				}
				keepalive = System.currentTimeMillis();
			} catch (InterruptedException e) {
				Log.error(this.getClass().getSimpleName() + "::sendRemote " + e.toString(), e);
			}
		}

		@Override
		public void run() {
			Log.info(this.getClass().getSimpleName() + "::run socket: " + sock);
			// Send SYN
			try {
				final MuxPacket mux = context.allocateMuxPacket();
				final int idEndpoint = inboundAddress.getOpts().getTunID();
				mux.syn(id, idEndpoint, sock.getInetAddress());
				local.sendLocal(mux);
				while (!lock(1)) {
					if (shutdown) {
						close();
						break;
					}
				}
				unlock(1);
				context.releaseMuxPacket(mux);
			} catch (Exception e) {
				Log.error(this.getClass().getSimpleName() + "::syn-send " + e.toString(), e);
			}
			// Send Headers
			if (inboundAddress.getOpts().isOption(Options.PROXY_SEND)) {
				try {
					final MuxPacket mux = context.allocateMuxPacket();
					final byte[] header = ProxyProtocol.getInstance().formatV1(sock).getBytes();
					mux.put(id, header.length, header);
					local.sendLocal(mux);
					while (!lock(header.length)) {
						if (shutdown) {
							close();
							break;
						}
					}
					unlock(header.length);
					context.releaseMuxPacket(mux);
				} catch (Exception e) {
					Log.error(this.getClass().getSimpleName() + "::proxy-send " + e.toString(), e);
				}
			}
			//
			if (!shutdown) {
				context.submitTask(new Runnable() {
					@Override
					public void run() {
						while (!shutdown || !queue.isEmpty()) {
							try {
								final RawPacket msg = queue.poll(1000, TimeUnit.MILLISECONDS);
								if (msg == null)
									continue;
								msg.toWire(os);
								context.getStatistics().incOutMsgs().incOutBytes(msg.getBufferLen());
								sendACK(msg); // Send ACK
								context.releaseRawPacket(msg);
							} catch (IOException e) {
								if ((sock != null) && !sock.isClosed() && !shutdown) {
									Log.error(this.getClass().getName() + "::sendRemote " + e.toString());
								}
							} catch (Exception e) {
								Log.error(this.getClass().getName() + " Exception: " + e, e);
							}
						}
						close();
					}
				}, "MuxInRight-Send[" + id + "|" + inboundAddress + "|" + IOHelper.socketRemoteToString(sock)
						+ "]", ClientId.getId());
			}
			//
			int pkt = 0;
			OUTTER: while (!shutdown) {
				try {
					final RawPacket msg = context.allocateRawPacket();
					msg.fromWire(is);
					msg.setIdChannel(id);
					pkt++;
					while (!lock(msg.getBufferLen())) {
						if (shutdown)
							break OUTTER;
						Log.info(this.getClass().getSimpleName() + " Timeout Locking(" + pkt + "): " + sock);
					}
					context.getStatistics().incInMsgs().incInBytes(msg.getBufferLen());
					router.onReceiveFromRemote(this, msg);
					context.releaseRawPacket(msg);
				} catch (SocketTimeoutException e) {
					Log.info(this.getClass().getSimpleName() + " " + e.toString());
					try {
						// Idle Timeout
						final long now = System.currentTimeMillis();
						if ((sock.getSoTimeout() + keepalive) < now) {
							break;
						}
					} catch (Exception brk) {
						break;
					}
				} catch (EOFException e) {
					break;
				} catch (IOException e) {
					if ((sock != null) && !sock.isClosed() && !shutdown) {
						Log.error(this.getClass().getSimpleName() + " " + e.toString());
					}
					break;
				} catch (Exception e) {
					Log.error(this.getClass().getSimpleName() + " Exception: " + e, e);
					break;
				}
			}
			// Send FIN
			closeRemote(id);
			close();
			Log.info(this.getClass().getSimpleName() + " end");
		}
	}
}


text:
#region LICENCE

//

#endregion

using System.Collections.Generic;
using System.Linq;
using TileIconifier.Core.Custom.WindowsStoreShellMethod;

namespace TileIconifier.Controls.Custom.WindowsStoreShellMethod
{
    internal class WindowsStoreAppListViewItemLibrary
    {
        private static List<WindowsStoreApp> _windowsStoreApps = new List<WindowsStoreApp>();

        public static List<WindowsStoreAppListViewItemGroup> LibraryAsListViewItems
        {
            get
            {
                RefreshList(false);
                return _windowsStoreApps
                        .Select(windowsStoreApp => new WindowsStoreAppListViewItemGroup(windowsStoreApp))
                        .ToList();
            }
        }

        public static void RefreshList(bool force = true)
        {
            if (force || !_windowsStoreApps.Any())
            {
                _windowsStoreApps =
                    WindowsStoreLibrary.GetAppKeysFromRegistry();
            }
        }
    }
}


text:
@interface LXMeViewController : UIViewController

@end


text:
module Main where

import Options.Applicative
import System.FilePath
import Solver (solver)

-- command line parser arguments

data Config = Config {
                inputFile  :: FilePath
              , outputFile :: Maybe FilePath
              } deriving Show

config :: Parser Config
config = Config <$> strOption
                      (  long "input-file"
                      <> short 'i'
                      <> metavar "INPUT"
                      <> help "Core C or Constraint input file")
                <*> optional
                      (strOption
                         (  long "output-file"
                         <> short 'o'
                         <> metavar "OUTPUT"
                         <> help "Output file with infered typedef's"))

opts :: ParserInfo Config
opts = info (config <**> helper)
            ( fullDesc
            <> progDesc "Infer missing typedef's for a constraint in INPUT file"
            <> header "Constraint solver for typedef inference" )

-- writing results of the solver

makeFileName :: FilePath -> FilePath
makeFileName p = p -<.> "tdef"

writeResults :: Config -> [String] -> IO ()
writeResults (Config inp Nothing) ts = do
                                       writeFile (makeFileName inp)
                                                 (concat ts)
                                       mapM_ putStrLn ts
writeResults (Config _ (Just o)) ts = writeFile o (concat ts)

-- main function

main :: IO ()
main = do
         cfg <- execParser opts
         c <- readFile (inputFile cfg)
         ts <- solver c (inputFile cfg)
         either putStrLn (writeResults cfg) ts


text:
1、[华丽的动效控件库](https://github.com/codeestX/ENViews)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture1.gif)

2、[Badge风格的TextView,支持Shadow和Elevation](https://github.com/matrixxun/MaterialBadgeTextView)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture2.jpg)

3、[原弧形的布局](https://github.com/florent37/ArcLayout)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture3.jpg)

4、[各种二维码生成样式](https://github.com/vivian8725118/ZXingDemo/)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture4.jpg)

5、[验证码图片](https://github.com/jineshfrancs/CaptchaImageView)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture5.gif)

6、[Github贡献图](https://github.com/barryhappy/TContributionsView)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture6.jpg)

7、[仿斗鱼端的滑动验证码](https://github.com/mcxtzhang/SwipeCaptcha)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture7.gif)

8、[数字增加动画](https://github.com/Bakumon/NumberAnimTextView)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture8.gif)

9、[支持多方向滑动](https://github.com/Kelin-Hong/ScrollablePanel)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture9.gif)

10、[Adblock WebView支持屏蔽广告](https://github.com/AmniX/AdBlockedWebView-Android)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture10.jpg)

11、[守望先锋动画加载效果](https://github.com/zhangyuChen1991/OverWatchLoading)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture11.gif)

12、[可展开的Tab](https://github.com/JoaquimLey/faboptions)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture12.gif)

13、[引导页](https://github.com/codemybrainsout/ahoy-onboarding)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture13.gif)

14、[Android平台下的Markdown解析器](https://github.com/zzhoujay/Markdown)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture14.jpg)

15、[优惠券效果](https://github.com/dongjunkun/CouponView)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture15.jpg)

16、[两个ImageView的转场动画](https://github.com/vikramkakkar/ImageTransition)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture16.gif)

17、[ViewPager底部Indicator动画](https://github.com/romandanylyk/PageIndicatorView)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture17.gif)

18、[轻量级的引导库](https://github.com/binIoter/GuideView)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture18.jpg)

19、[BigBang](https://github.com/baoyongzhang/BigBang)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture19.gif)

20、[让你的view实现3D](https://github.com/githubwing/ThreeDLayout)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture20.gif)

21、[BottomDialog支持动画弹出底部弹窗,支持任意布局](https://github.com/shaohui10086/BottomDialog)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture21.gif)

22、[滑动渐变顶部颜色](https://github.com/ToDou/appbarlayout-spring-behavior)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture22.gif)

23、[浮动的视图](https://github.com/UFreedom/FloatingView)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture23.gif)

24、[3D翻页效果](https://github.com/eschao/android-PageFlip)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture24.jpg)

25、[实现签名模板](https://github.com/ww6015132/SilkySignature)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture25.jpg)

26、[爆炸式展开菜单](https://github.com/Nightonke/BoomMenu)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture26.gif)

27、[翻页的库](https://github.com/xenione/tab-digit)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture27.gif)

28、[3D视差效果的多选按钮](https://github.com/gjiazhe/MultiChoicesCircleButton)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture28.gif)

29、[MD风格的EditText](https://github.com/bufferapp/BufferTextInputLayout)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture29.gif)

30、[可任意拖拽的视频播放方案](https://github.com/hejunlin2013/DragVideo)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture30.gif)

31、[礼物雨](https://github.com/Luolc/EmojiRain)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture31.gif)

32、[有趣的下载进度条](https://github.com/Ajian-studio/GADownloading)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture32.gif)

33、[有创意的底部导航](https://github.com/thelong1EU/SpaceTabLayout)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture33.gif)

34、[快速实现跑马灯效果的library](https://github.com/gongwen/MarqueeViewLibrary)
----------
![image](https://github.com/jaysonn/OpenEffect/blob/master/img1/picture34.gif)


text:
//
//  AKVariableFrequencyResponseBandPassFilter.h
//  AudioKit
//
//  Auto-generated on 2/19/15.
//  Customized by Aurelius Prochazka to add type helpers
//  Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//

#import "AKAudio.h"
#import "AKParameter+Operation.h"

/** A second-order resonant filter.

 This is a second-order filter defined by a center frequency which is the frequency position of the peak response, and a bandwidth which is the frequency difference between the upper and lower half-power points.
 */

NS_ASSUME_NONNULL_BEGIN
@interface AKVariableFrequencyResponseBandPassFilter : AKAudio

// Type Helpers

/// No scaling of the output
+ (AKConstant *)scalingFactorNone;

/// Signifies a peak response factor of 1, i.e. all frequencies other than the cutoffFrequency are attenuated in accordance with the (normalized) response curve.
+ (AKConstant *)scalingFactorPeak;

/// Raises the response factor so that its overall RMS value equals 1. This intended equalization of input and output power assumes all frequencies are physically present; hence it is most applicable to white noise.
+ (AKConstant *)scalingFactorRMS;

/// Instantiates the variable frequency response band pass filter with all values
/// @param audioSource The input signal to be filtered. [Default Value: ]
/// @param cutoffFrequency Cutoff or resonant frequency of the filter, measured in Hz. Updated at Control-rate. [Default Value: 1000]
/// @param bandwidth Bandwidth of the filter (the Hz difference between the upper and lower half-power points). Updated at Control-rate. [Default Value: 10]
/// @param scalingFactor There are three scaling factors possible, 'None' (Default, 0), 'Peak' or 1, and 'RMS' or 2.  All are accessibly through class function 'scalingFactor...'   'Peak' signifies a peak response factor of 1, i.e. all frequencies other than the cutoffFrequency are attenuated in accordance with the (normalized) response curve. 'RMS' raises the response factor so that its overall RMS value equals 1. This intended equalization of input and output power assumes all frequencies are physically present; hence it is most applicable to white noise.   [Default Value: 0]
- (instancetype)initWithAudioSource:(AKParameter *)audioSource
                    cutoffFrequency:(AKParameter *)cutoffFrequency
                          bandwidth:(AKParameter *)bandwidth
                      scalingFactor:(AKConstant *)scalingFactor;

/// Instantiates the variable frequency response band pass filter with default values
/// @param audioSource The input signal to be filtered.
- (instancetype)initWithAudioSource:(AKParameter *)audioSource;

/// Instantiates the variable frequency response band pass filter with default values
/// @param audioSource The input signal to be filtered.
+ (instancetype)filterWithAudioSource:(AKParameter *)audioSource;

/// Cutoff or resonant frequency of the filter, measured in Hz. [Default Value: 1000]
@property (nonatomic) AKParameter *cutoffFrequency;

/// Set an optional cutoff frequency
/// @param cutoffFrequency Cutoff or resonant frequency of the filter, measured in Hz. Updated at Control-rate. [Default Value: 1000]
- (void)setOptionalCutoffFrequency:(AKParameter *)cutoffFrequency;

/// Bandwidth of the filter (the Hz difference between the upper and lower half-power points). [Default Value: 10]
@property (nonatomic) AKParameter *bandwidth;

/// Set an optional bandwidth
/// @param bandwidth Bandwidth of the filter (the Hz difference between the upper and lower half-power points). Updated at Control-rate. [Default Value: 10]
- (void)setOptionalBandwidth:(AKParameter *)bandwidth;

/// There are three scaling factors possible, 'None' (Default, 0), 'Peak' or 1, and 'RMS' or 2.  All are accessibly through class function 'scalingFactor...'   'Peak' signifies a peak response factor of 1, i.e. all frequencies other than the cutoffFrequency are attenuated in accordance with the (normalized) response curve. 'RMS' raises the response factor so that its overall RMS value equals 1. This intended equalization of input and output power assumes all frequencies are physically present; hence it is most applicable to white noise.   [Default Value: 0]
@property (nonatomic) AKConstant *scalingFactor;

/// Set an optional scaling factor
/// @param scalingFactor There are three scaling factors possible, 'None' (Default, 0), 'Peak' or 1, and 'RMS' or 2.  All are accessibly through class function 'scalingFactor...'   'Peak' signifies a peak response factor of 1, i.e. all frequencies other than the cutoffFrequency are attenuated in accordance with the (normalized) response curve. 'RMS' raises the response factor so that its overall RMS value equals 1. This intended equalization of input and output power assumes all frequencies are physically present; hence it is most applicable to white noise.   [Default Value: 0]
- (void)setOptionalScalingFactor:(AKConstant *)scalingFactor;

@end
NS_ASSUME_NONNULL_END


text:
import os
import numpy as np
from scipy import misc
import shutil
import subprocess

def save_as_png(img, file_name):
	''' Given a (48x48) image in the form of a (2304x1) vector, this method
	will save it as a png to the given location.
	'''
	misc.imsave(file_name, np.reshape(img, (48,48)))

def load_from_png(file_name):
	''' Returns the image from the given file_name in a (2304x1) vector.
	'''
	img = misc.imread(file_name)
	return np.reshape(img, (2304,))

def create_image_rotations(img, interval):
	''' Given an image vector (2304x1), this method will rotate it 360
	degrees with the given interval. Returns a list of (2304x1) arrays
	containing the original image followed by its rotations.
	'''
	# Create a working directory.
	os.mkdir('temp_rotations')
	os.chdir('temp_rotations')
	# Save the original image.
	ret_images = []
	ret_images.append(img)
	save_as_png(img, 'orig.png')
	# Rotate the image between 0 and 360.
	for i in xrange(0, 359, interval):
		subprocess.call('convert orig.png -virtual-pixel Tile -distort SRT ' + str(i) + ' temp_'+str(i)+'.png', shell=True)
		im = load_from_png('temp_'+str(i)+'.png')
		ret_images.append(im)

	# Return to the original directory and clean temporary files.
	os.chdir('../')
	shutil.rmtree('temp_rotations')
	return ret_images


text:
package com.amazonaws.services.devopsguru.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.devopsguru.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * LogAnomalyShowcaseMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class LogAnomalyShowcaseMarshaller {

    private static final MarshallingInfo<List> LOGANOMALYCLASSES_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("LogAnomalyClasses").build();

    private static final LogAnomalyShowcaseMarshaller instance = new LogAnomalyShowcaseMarshaller();

    public static LogAnomalyShowcaseMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(LogAnomalyShowcase logAnomalyShowcase, ProtocolMarshaller protocolMarshaller) {

        if (logAnomalyShowcase == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(logAnomalyShowcase.getLogAnomalyClasses(), LOGANOMALYCLASSES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
<!DOCTYPE html>

    <title>Public Meetings & Hearings</title>

    <meta charset="utf-8">
	<meta name="description" content="Public meetings and hearings">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="x-ua-compatible" content="ie=edge">
	<link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico" />

    <link rel="stylesheet" href="css/font-awesome-all.css">
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/mdb.min.css" rel="stylesheet">
    <link href="css/style.min.css" rel="stylesheet">

Engaged Citizens

			Meetings Home
			Upcoming Meetings

This is an experimental project that only works with the Google Chrome and Mozilla Firefox web browsers.
		 Please send your feedback and suggestions!


text:
static char spss_type_strings[][16] = {
    [SPSS_FORMAT_TYPE_A] = "A",
    [SPSS_FORMAT_TYPE_AHEX] = "AHEX",
    [SPSS_FORMAT_TYPE_COMMA] = "COMMA",
    [SPSS_FORMAT_TYPE_DOLLAR] = "DOLLAR",
    [SPSS_FORMAT_TYPE_F] = "F",
    [SPSS_FORMAT_TYPE_IB] = "IB",
    [SPSS_FORMAT_TYPE_PIBHEX] = "PIBHEX",
    [SPSS_FORMAT_TYPE_P] = "P",
    [SPSS_FORMAT_TYPE_PIB] = "PIB",
    [SPSS_FORMAT_TYPE_PK] = "PK",
    [SPSS_FORMAT_TYPE_RB] = "RB",
    [SPSS_FORMAT_TYPE_RBHEX] = "RBHEX",
    [SPSS_FORMAT_TYPE_Z] = "Z",
    [SPSS_FORMAT_TYPE_N] = "N",
    [SPSS_FORMAT_TYPE_E] = "E",
    [SPSS_FORMAT_TYPE_DATE] = "DATE",
    [SPSS_FORMAT_TYPE_TIME] = "TIME",
    [SPSS_FORMAT_TYPE_DATETIME] = "DATETIME",
    [SPSS_FORMAT_TYPE_ADATE] = "ADATE",
    [SPSS_FORMAT_TYPE_JDATE] = "JDATE",
    [SPSS_FORMAT_TYPE_DTIME] = "DTIME",
    [SPSS_FORMAT_TYPE_WKDAY] = "WKDAY",
    [SPSS_FORMAT_TYPE_MONTH] = "MONTH",
    [SPSS_FORMAT_TYPE_MOYR] = "MOYR",
    [SPSS_FORMAT_TYPE_QYR] = "QYR",
    [SPSS_FORMAT_TYPE_WKYR] = "WKYR",
    [SPSS_FORMAT_TYPE_PCT] = "PCT",
    [SPSS_FORMAT_TYPE_DOT] = "DOT",
    [SPSS_FORMAT_TYPE_CCA] = "CCA",
    [SPSS_FORMAT_TYPE_CCB] = "CCB",
    [SPSS_FORMAT_TYPE_CCC] = "CCC",
    [SPSS_FORMAT_TYPE_CCD] = "CCD",
    [SPSS_FORMAT_TYPE_CCE] = "CCE",
    [SPSS_FORMAT_TYPE_EDATE] = "EDATE",
    [SPSS_FORMAT_TYPE_SDATE] = "SDATE",
    [SPSS_FORMAT_TYPE_MTIME] = "MTIME",
    [SPSS_FORMAT_TYPE_YMDHMS] = "YMDHMS",
};

int spss_format(char *buffer, size_t len, spss_format_t *format) {
    if (format->type < 0
            || format->type >= sizeof(spss_type_strings)/sizeof(spss_type_strings[0])
            || spss_type_strings[format->type][0] == '\0') {
        return 0;
    }
    char *string = spss_type_strings[format->type];

    if (format->decimal_places || format->type == SPSS_FORMAT_TYPE_F) {
        snprintf(buffer, len, "%s%d.%d", string, format->width, format->decimal_places);
    } else if (format->width) {
        snprintf(buffer, len, "%s%d", string, format->width);
    } else {
        snprintf(buffer, len, "%s", string);
    }

    return 1;
}

int spss_varinfo_compare(const void *elem1, const void *elem2) {
    int offset = *(int *)elem1;
    const spss_varinfo_t *v = *(const spss_varinfo_t **)elem2;
    if (offset < v->offset)
        return -1;
    return (offset > v->offset);
}

void spss_varinfo_free(spss_varinfo_t *info) {
    if (info) {
        if (info->label)
            free(info->label);
        free(info);
    }
}

uint64_t spss_64bit_value(readstat_value_t value) {
    double dval = readstat_double_value(value);
    uint64_t special_val;
    memcpy(&special_val, &dval, sizeof(double));

    if (isinf(dval)) {
        if (dval < 0.0) {
            special_val = SAV_LOWEST_DOUBLE;
        } else {
            special_val = SAV_HIGHEST_DOUBLE;
        }
    } else if (isnan(dval)) {
        special_val = SAV_MISSING_DOUBLE;
    }
    return special_val;
}

static readstat_value_t spss_boxed_double_value(double fp_value) {
    readstat_value_t value = {
        .type = READSTAT_TYPE_DOUBLE,
        .v = { .double_value = fp_value },
        .is_system_missing = isnan(fp_value)
    };
    return value;
}

static readstat_value_t spss_boxed_string_value(const char *string) {
    readstat_value_t value = {
        .type = READSTAT_TYPE_STRING,
        .v = { .string_value = string }
    };
    return value;
}

static readstat_value_t spss_boxed_missing_value(spss_varinfo_t *info, int i) {
    if (info->type == READSTAT_TYPE_DOUBLE) {
        return spss_boxed_double_value(info->missing_double_values[i]);
    }
    return spss_boxed_string_value(info->missing_string_values[i]);
}

readstat_missingness_t spss_missingness_for_info(spss_varinfo_t *info) {
    readstat_missingness_t missingness;
    memset(&missingness, '\0', sizeof(readstat_missingness_t));

    if (info->missing_range) {
        missingness.missing_ranges_count++;
        missingness.missing_ranges[0] = spss_boxed_missing_value(info, 0);
        missingness.missing_ranges[1] = spss_boxed_missing_value(info, 1);

        if (info->n_missing_values == 3) {
            missingness.missing_ranges_count++;
            missingness.missing_ranges[2] = missingness.missing_ranges[3] = spss_boxed_missing_value(info, 2);
        }
    } else if (info->n_missing_values > 0) {
        missingness.missing_ranges_count = info->n_missing_values;
        int i=0;
        for (i=0; i<info->n_missing_values; i++) {
            missingness.missing_ranges[2*i] = missingness.missing_ranges[2*i+1] = spss_boxed_missing_value(info, i);
        }
    }
    return missingness;
}

readstat_variable_t *spss_init_variable_for_info(spss_varinfo_t *info, int index_after_skipping,
        iconv_t converter) {
    readstat_variable_t *variable = calloc(1, sizeof(readstat_variable_t));

    variable->index = info->index;
    variable->index_after_skipping = index_after_skipping;
    variable->type = info->type;
    if (info->string_length) {
        variable->storage_width = info->string_length;
    } else {
        variable->storage_width = 8 * info->width;
    }

    if (info->longname[0]) {
        readstat_convert(variable->name, sizeof(variable->name),
                info->longname, sizeof(info->longname), converter);
    } else {
        readstat_convert(variable->name, sizeof(variable->name),
                info->name, sizeof(info->name), converter);
    }
    if (info->label) {
        snprintf(variable->label, sizeof(variable->label), "%s", info->label);
    }

    spss_format(variable->format, sizeof(variable->format), &info->print_format);

    variable->missingness = spss_missingness_for_info(info);
    variable->measure = info->measure;
    if (info->display_width) {
        variable->display_width = info->display_width;
    } else {
        variable->display_width = info->print_format.width;
    }

    return variable;
}

uint32_t spss_measure_from_readstat_measure(readstat_measure_t measure) {
    uint32_t sav_measure = SAV_MEASURE_UNKNOWN;
    if (measure == READSTAT_MEASURE_NOMINAL) {
        sav_measure = SAV_MEASURE_NOMINAL;
    } else if (measure == READSTAT_MEASURE_ORDINAL) {
        sav_measure = SAV_MEASURE_ORDINAL;
    } else if (measure == READSTAT_MEASURE_SCALE) {
        sav_measure = SAV_MEASURE_SCALE;
    }
    return sav_measure;
}

readstat_measure_t spss_measure_to_readstat_measure(uint32_t sav_measure) {
    if (sav_measure == SAV_MEASURE_NOMINAL)
        return READSTAT_MEASURE_NOMINAL;
    if (sav_measure == SAV_MEASURE_ORDINAL)
        return READSTAT_MEASURE_ORDINAL;
    if (sav_measure == SAV_MEASURE_SCALE)
        return READSTAT_MEASURE_SCALE;
    return READSTAT_MEASURE_UNKNOWN;
}

uint32_t spss_alignment_from_readstat_alignment(readstat_alignment_t alignment) {
    uint32_t sav_alignment = 0;
    if (alignment == READSTAT_ALIGNMENT_LEFT) {
        sav_alignment = SAV_ALIGNMENT_LEFT;
    } else if (alignment == READSTAT_ALIGNMENT_CENTER) {
        sav_alignment = SAV_ALIGNMENT_CENTER;
    } else if (alignment == READSTAT_ALIGNMENT_RIGHT) {
        sav_alignment = SAV_ALIGNMENT_RIGHT;
    }
    return sav_alignment;
}

readstat_alignment_t spss_alignment_to_readstat_alignment(uint32_t sav_alignment) {
    if (sav_alignment == SAV_ALIGNMENT_LEFT)
        return READSTAT_ALIGNMENT_LEFT;
    if (sav_alignment == SAV_ALIGNMENT_CENTER)
        return READSTAT_ALIGNMENT_CENTER;
    if (sav_alignment == SAV_ALIGNMENT_RIGHT)
        return READSTAT_ALIGNMENT_RIGHT;
    return READSTAT_ALIGNMENT_UNKNOWN;
}

readstat_error_t spss_format_for_variable(readstat_variable_t *r_variable,
        spss_format_t *spss_format) {
    readstat_error_t retval = READSTAT_OK;

    memset(spss_format, 0, sizeof(spss_format_t));

    if (r_variable->type == READSTAT_TYPE_STRING) {
        spss_format->type = SPSS_FORMAT_TYPE_A;
        if (r_variable->display_width) {
            spss_format->width = r_variable->display_width;
        } else if (r_variable->user_width) {
            spss_format->width = r_variable->user_width;
        } else {
            spss_format->width = r_variable->storage_width;
        }
    } else {
        spss_format->type = SPSS_FORMAT_TYPE_F;
        if (r_variable->display_width) {
            spss_format->width = r_variable->display_width;
        } else {
            spss_format->width = 8;
        }
        if (r_variable->type == READSTAT_TYPE_DOUBLE ||
                r_variable->type == READSTAT_TYPE_FLOAT) {
            spss_format->decimal_places = 2;
        }
    }

    if (r_variable->format[0]) {
        spss_format->decimal_places = 0;
        const char *fmt = r_variable->format;
        if (spss_parse_format(fmt, strlen(fmt), spss_format) != READSTAT_OK) {
            retval = READSTAT_ERROR_BAD_FORMAT_STRING;
            goto cleanup;
        }
    }

cleanup:
    return retval;
}


text:
//
//  $Id$
//
//  SPTableTriggersDelegate.m
//  sequel-pro
//
//  Created by Stuart Connolly (stuconnolly.com) on February 21, 2013.
//  Copyright (c) 2013 Stuart Connolly. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person
//  obtaining a copy of this software and associated documentation
//  files (the "Software"), to deal in the Software without
//  restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following
//  conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//  OTHER DEALINGS IN THE SOFTWARE.

#import "SPTableTriggersDelegate.h"
#import "SPDatabaseDocument.h"

@interface SPTableTriggers ()

- (void)_editTriggerAtIndex:(NSInteger)index;
- (void)_toggleConfirmAddTriggerButtonEnabled;

@end

@implementation SPTableTriggers (SPTableTriggersDelegate)

#pragma mark -
#pragma mark Tableview delegate methods

/**
 * Called whenever the triggers table view selection changes.
 */
- (void)tableViewSelectionDidChange:(NSNotification *)notification
{
	[removeTriggerButton setEnabled:([triggersTableView numberOfSelectedRows] > 0)];
}

/**
 * Alter the colour of cells displaying NULL values
 */
- (void)tableView:(NSTableView *)tableView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)rowIndex
{
	if (![cell respondsToSelector:@selector(setTextColor:)]) {
		return;
	}

	id value = [[triggerData objectAtIndex:rowIndex] objectForKey:[tableColumn identifier]];

	[cell setTextColor:[value isNSNull] ? [NSColor lightGrayColor] : [NSColor blackColor]];
}

/**
 * Double-click action on table cells - for the time being, return NO to disable editing.
 */
- (BOOL)tableView:(NSTableView *)tableView shouldEditTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)rowIndex
{
	if ([tableDocumentInstance isWorking]) return NO;

	// Start Edit panel
	if (((NSInteger)[triggerData count] > rowIndex) && [triggerData objectAtIndex:rowIndex]) {
		[self _editTriggerAtIndex:rowIndex];
	}

	return NO;
}

/**
 * Disable row selection while the document is working.
 */
- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)rowIndex
{
	return (![tableDocumentInstance isWorking]);
}

#pragma mark -
#pragma mark Textfield delegate methods

/**
 * Toggles the enabled state of confirm add trigger button based on the editing of the trigger's name.
 */
- (void)controlTextDidChange:(NSNotification *)notification
{
	[self _toggleConfirmAddTriggerButtonEnabled];
}

@end


text:
var gear_menu = (function () {

var exports = {};

// We want to remember how far we were scrolled on each 'tab'.
// To do so, we need to save away the old position of the
// scrollbar when we switch to a new tab (and restore it
// when we switch back.)
var scroll_positions = {};

exports.initialize = function () {
    admin.show_or_hide_menu_item();

    $('#gear-menu a[data-toggle="tab"]').on('show', function (e) {
        // Save the position of our old tab away, before we switch
        var old_tab = $(e.relatedTarget).attr('href');
        scroll_positions[old_tab] = viewport.scrollTop();
    });
    $('#gear-menu a[data-toggle="tab"]').on('shown', function (e) {
        var target_tab = $(e.target).attr('href');
        resize.resize_bottom_whitespace();
        // Hide all our error messages when switching tabs
        $('.alert-error').hide();
        $('.alert-success').hide();
        $('.alert-info').hide();
        $('.alert').hide();

        // Set the URL bar title to show the sub-page you're currently on.
        var browser_url = target_tab;
        if (browser_url === "#home") {
            browser_url = "";
        }
        hashchange.changehash(browser_url);

        // After we show the new tab, restore its old scroll position
        // (we apparently have to do this after setting the hash,
        // because otherwise that action may scroll us somewhere.)
        if (scroll_positions.hasOwnProperty(target_tab)) {
            viewport.scrollTop(scroll_positions[target_tab]);
        } else {
            if (target_tab === '#home') {
                navigate.scroll_to_selected();
            } else {
                viewport.scrollTop(0);
            }
        }
    });

    // The admin and settings pages are generated client-side through
    // templates.
};

return exports;
}());

if (typeof module !== 'undefined') {
    module.exports = gear_menu;
}


text:
/* This module provides the necessary stubs for when dynamic loading is
   not present. */

#include "Python.h"
#include "importdl.h"

#include "dlk.h"

const struct filedescr _PyImport_DynLoadFiletab[] = {
    {"/pyd", "rb", C_EXTENSION},
    {0, 0}
};

void dynload_init_dummy()
{
}

dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
                                    char *pathname, FILE *fp)
{
    int err;
    char errstr[256];
    void (*init_function)(void);

    err = dlk_load_no_init(pathname, &init_function);
    if (err) {
        PyOS_snprintf(errstr, sizeof(errstr), "dlk failure %d", err);
        PyErr_SetString(PyExc_ImportError, errstr);
    }
    return init_function;
}


text:
package eu.luminis.elastic.search.response.aggregations.bucket;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import eu.luminis.elastic.search.response.aggregations.Aggregation;

import java.util.HashMap;
import java.util.Map;

/**
 * Default Bucket that can be used by most other buckets besides the ones with a non-string key.
 */
public class BaseBucket implements Bucket {
    @JsonProperty("key")
    private String key;

    @JsonProperty("doc_count")
    private Long docCount;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Long getDocCount() {
        return docCount;
    }

    public void setDocCount(Long docCount) {
        this.docCount = docCount;
    }

    private Map<String, Aggregation> aggregations = new HashMap<>();

    @JsonAnySetter
    public void add(String key, Aggregation aggregation) {
        int position = key.indexOf('#');
        if (position != -1) {
            aggregations.put(key.substring(position + 1), aggregation);
        } else {
            aggregations.put(key, aggregation);
        }
    }

    @JsonAnyGetter
    public Map<String, Aggregation> getAggregations() {
        return aggregations;
    }

    public void setAggregations(Map<String, Aggregation> aggregations) {
        this.aggregations = aggregations;
    }

}