text:
package magpie.data.materials;

import java.io.BufferedReader;
import java.io.LineNumberReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.*;
import magpie.attributes.generators.BaseAttributeGenerator;
import magpie.attributes.generators.composition.*;
import magpie.data.BaseEntry;
import magpie.data.materials.util.CompositionDatasetOutput;
import magpie.data.materials.util.LookupData;
import magpie.data.materials.util.PropertyLists;
import magpie.utility.tools.OxidationStateGuesser;

/**
 * This class stores entries that describe a material based solely on its
 * composition.
 *
 *
Some of the available features include:
 *

 *
Generate attributes based on composition only

 *
Read in data from specially-formatted input file

 *
Store multiple properties for a each entry

 *

 *
 * When reading data in from text using the importText function,
 * the data must be whitespace-delimited with a header row giving property names
 * and the composition of the material as the first row:
 *
 *

 * Composition property_1{class1,class2} property_2 ... property_N

 * As,0.2,B,0.8, class1 0.4 0.8 ...

 * AsB4, class2 0.9 none ...

 * Cu2Zr,4, class1 0.1 10.8 ...

 * <as many entries as you desire>

 *
 *

 * A few things to know about this format:
 *
 *

 *
Format of composition doesn't matter too much. Only real requirement is that
 * element names are capitalized.
 *
If a property has discrete classes, you can specify what the allowed values
 * are in the header by adding them to the property name surrounded by "{}"s and separated
 * by commas.
 *
If the measured value of a property is not known, put down "None"
 *
For entries with duplicate compositions: Either select the values from
 * lowest-energy duplicate entry or, if energy is not available, the average
 * value of continuous properties or the lowest-index class value (i.e. which
 * ever one is listed first in the header of the input file)
 *

 *
 *
Attributes
 *
 * Generates several categories of attributes by default, which are described
 * in {@linkplain #CompositionDataset(boolean) }.
 *
 *
Implemented Commands:
 *
 * <command>
attributes composition <true|false> -
 *  Set whether to use composition as attributes
 *
<pr>true|false - Whether to use composition as attributes
 *
By default, this class does not use composition (by itself) as attributes</command>
 *
 * <command>
attributes properties - List which elemental properties are used to generate attributes</command>
 *
 * <command>
attributes properties add <names...> - Add elemental properties to use when generating attributes</command>
 *
<pr>name...: Name of a elemental properties</command>
 *
 * <command>
attributes properties add set <name> - Add in all elemental properties from a pre-defined set
 *
<pr>name: Name of the pre-defined set</command>
 *
 * <command>
attributes properties remove <names...> - Remove properties from list of those used when generating attributes
 *
<pr>names...: Name of properties to remove</command>
 *
 * <command>
attributes properties <directory> - Specify directory that contains the elemental property lookup files
 *
<pr>directory: Desired directory</command>
 *
 *
Implemented Save Formats
 *
 * <save>
comp - All properties with composition written by element fraction
 *
Very similar to the "prop" format"</save>
 *
 * @author Logan Ward
 * @version 0.2
 */
public class CompositionDataset extends magpie.data.MultiPropertyDataset {

    /**
     * List of element names
     */
    public String[] ElementNames = LookupData.ElementNames;
    /**
     * Order in which elements are sorted (used when printing)
     */
    protected int[] SortingOrder = LookupData.SortingOrder;
    /**
     * Location of lookup date files
     */
    public String DataDirectory = "./Lookup Data";
    /**
     * List of properties used when generating attributes
     */
    protected List<String> ElementalProperties = new ArrayList<>();
    /**
     * Map of elemental property names to values
     */
    public Map<String, double[]> PropertyData = LookupData.ElementalProperties;
	/** Oxidation states of every element */
	protected double[][] OxidationStates = LookupData.OxidationStates;

    /**
     * Create a dataset using the default set of attribute generators.
     */
    public CompositionDataset() {
        this(true);
    }

    /**
     * Create a blank dataset. Default attribute generator set:
     *
     *

     *
{@linkplain StoichiometricAttributeGenerator}: Generate attributes
     * based on fractions of elements. Does not depend on what the elements actually
     * are. Will use p = 2, 3, 5, 7, 10 norms.
     *
{@linkplain ValenceShellAttributeGenerator}: Attributes based on the
     * valence shell electrons of the constituent elements
     *
{@linkplain ElementalPropertyAttributeGenerator}: Generate attributes
     * based on properties of constituent elements. Use the list of attributes
     * provided through "attributes properties add" or
     * {@linkplain #addElementalProperty(java.lang.String) } operations for
     * the commandline and Java interfaces, respectively.
     *
{@linkplain IonicityAttributeGenerator}: Attributes designed to represent
     * the "ionicity" of a compound.
     *

     * @param useDefaultGenerators [in] Whether to use default generators
     */
    public CompositionDataset(boolean useDefaultGenerators) {
        if (!useDefaultGenerators) {
            return;
        }

        try {
            // Add stoichiometric generator
            StoichiometricAttributeGenerator sgen = new StoichiometricAttributeGenerator();
            sgen.addPNorm(2); sgen.addPNorm(3);
            sgen.addPNorm(5); sgen.addPNorm(7); sgen.addPNorm(10);
            addAttribueGenerator(sgen);

            // Add elemental property generator
            ElementalPropertyAttributeGenerator pgen;
            pgen = new ElementalPropertyAttributeGenerator();
            addAttribueGenerator(pgen);

            // Add valence shell attributes
            ValenceShellAttributeGenerator vgen = new ValenceShellAttributeGenerator();
            addAttribueGenerator(vgen);

            // Add ionicity attributes
            IonicityAttributeGenerator igen = new IonicityAttributeGenerator();
            addAttribueGenerator(igen);
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    @Override
    public CompositionDataset emptyClone() {
        CompositionDataset x = (CompositionDataset) super.emptyClone();
        x.ElementNames = ElementNames.clone();
        return x;
    }

    @Override
    public CompositionEntry getEntry(int index) {
        return (CompositionEntry) super.getEntry(index);
    }

	@Override
	public CompositionEntry addEntry(String input) throws Exception {
		CompositionEntry toAdd = new CompositionEntry(input);
		addEntry(toAdd);
		return toAdd;
	}

    /**
     * Get the order in which elements are sorted when storing a composition. Sorting
     * makes it faster to detect whether compounds are equal
     * @return Sorting order
     */
    public int[] getSortingOrder() {
        return SortingOrder.clone();
    }

    /**
     * Read in an dataset from file. See documentation for format information.
     *
     * @param filename Path of file to be imported
     * @throws java.lang.Exception
     */
    @Override
    @SuppressWarnings("empty-statement")
    public void importText(String filename, Object[] options) throws Exception {
        // Clear out entry data
        clearData();

        // Count the number of lines (1 per entry + 1 header)
        // Thanks to: http://stackoverflow.com/questions/453018/number-of-lines-in-a-file-in-java
        LineNumberReader lr = new LineNumberReader(new FileReader(filename));
        while (lr.skip(Long.MAX_VALUE) > 0) {
        };
        int Entry_Count = lr.getLineNumber() + 1;
        lr.close();

        // Define the reader
        BufferedReader is = Files.newBufferedReader(Paths.get(filename), Charset.forName("US-ASCII"));
        String line;
        String[] words;

        // Read in properties from header
        line = is.readLine().trim();
		importPropertyNames(line);

        // Determine which property is the energy ("energy_pa")
        int energy_id = getPropertyIndex("energy_pa");

        // Read in each entry
        TreeMap<BaseEntry, CompositionEntry> acceptedEntries = new TreeMap<>();
        TreeMap<BaseEntry, List<double[]>> duplicateProperties = new TreeMap<>();
        CompositionEntry Entry;
        for (int e = 0; e < Entry_Count; e++) {
            double[] properties;
            // Read a line and tokenize it
            line = is.readLine();
            if (line == null) {
                break;
            }
            words = line.trim().split("\\s+");
            if (words.length < 2) {
                continue;
            }

            // Read properties
            properties = importEntryProperties(words);

            // Make an entry
            try {
                Entry = new CompositionEntry(words[0]);
            } catch (Exception ex) {
                continue; // Skip if fails to parse
            }
            Entry.setMeasuredProperties(properties);

            // Add if the set does not already have it
            if (!acceptedEntries.containsKey(Entry)) {
                acceptedEntries.put(Entry, Entry);
            } else {
                // If the entries have a "energy_pa" as a property, supplant the existing
                //   entry if it is higher in energy
                if (energy_id != -1) {
                    CompositionEntry oldBest = (CompositionEntry) acceptedEntries.get(Entry);
                    if (oldBest.getMeasuredProperty(energy_id)
                            > Entry.getMeasuredProperty(energy_id)) {
                        acceptedEntries.remove(oldBest);
                        acceptedEntries.put(Entry, Entry);
                    }
                } else {
                    // Add to list of entries to duplicate properties if there is no "energy" property
                    if (!duplicateProperties.containsKey(Entry)) {
                        // Add in the property data of the accepted entry
                        double[] props = acceptedEntries.get(Entry).getMeasuredProperties();
                        List<double[]> newList = new LinkedList<>();
                        newList.add(props);
                        duplicateProperties.put(Entry, newList);
                    }
                    duplicateProperties.get(Entry).add(Entry.getMeasuredProperties());
                }
            }
        }

        // If we have any duplicate properties, average them
        Iterator<BaseEntry> Eiter = duplicateProperties.keySet().iterator();
        while (Eiter.hasNext()) {
            CompositionEntry E = (CompositionEntry) Eiter.next();
            CompositionEntry accepted = acceptedEntries.get(E);
            List<double[]> dupProps = duplicateProperties.get(E);
            for (int p = 0; p < NProperties(); p++) {
                if (getPropertyClassCount(p) == 1) {
                    double sum = 0, count = 0;
                    for (double[] props : dupProps) {
                        double toAdd = props[p];
                        if (! Double.isNaN(toAdd)) {
                            sum += toAdd; count++;
                        }
                    }
                    if (count > 0) {
                        accepted.setMeasuredProperty(p, sum / count);
                    }
                } else {
                    double value = Double.MAX_VALUE;
                    boolean wasFound = false;
                    for (double[] props : dupProps) {
                        if (! Double.isNaN(props[p])) {
                            wasFound = true;
                            if (props[p] < value) {
                               value = props[p];
                            }
                        }
                    }
                    if (wasFound) {
                        accepted.setMeasuredProperty(p, value);
                    }
                }
            }
        }

        // Close the file
        is.close();

        // Copy the entries
        this.Entries = new ArrayList<>(acceptedEntries.keySet());
    }

    /**
     * Set whether to use composition (i.e. fraction of each element present) as attributes.
     *
     *
By default: This class does not use fractions as attributes.
     * @param decision Whether to use it or not
     */
    public void useCompositionAsAttributes(boolean decision) {
        boolean found = false;
        Iterator<BaseAttributeGenerator> iter = Generators.iterator();
        while (iter.hasNext()) {
            if (iter.next() instanceof ElementFractionAttributeGenerator) {
                // Remove it, if user wants to
                if (!decision) {
                    iter.remove();
                    return;
                } else {
                    return;
                }
            }
        }

        // Add in, if desired
        if (!found && decision) {
            Generators.add(0, new ElementFractionAttributeGenerator());
        }
    }

    /**
     * Define whether to look for elemental property lookup tables.
     *
     *

     * Elemental property tables should have the properties for each element on
     * a separate line, sorted by Atomic Number. If the property is not known,
     * write "None". You will be alerted if that property was needed generating
     * attributes.
     *
     * @param directory Path to the elemental property lookup directory
     * @throws java.lang.Exception
     */
    public void setDataDirectory(String directory) throws Exception {
        if (! Files.isDirectory(Paths.get(directory))) {
            throw new Exception("No such directory: " + directory);
        }
        this.DataDirectory = directory;
    }

    /**
     * Define a new elemental property to use when generating attributes.
     *
     * @param Name Name of property
     */
    public void addElementalProperty(String Name) {
        if (! ElementalProperties.contains(Name)) {
            ElementalProperties.add(Name);
        }
    }

    /**
     * Get list of elemental properties currently being used to generate attributes.
     * @return List of elemental properties
     */
    public List<String> getElementalProperties() {
        return new ArrayList<>(ElementalProperties);
    }

    /**
     * Remove an elemental property from the list used when generating
     * attributes
     *
     * @param Name Name of property
     * @return Whether the property was found and removed
     */
    public boolean removeElementalProperty(String Name) {
        if (ElementalProperties.contains(Name)) {
            ElementalProperties.remove(Name);
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void calculateAttributes() {
        // Nothing to do
    }

    /**
     * Reads in a data file that contains properties for each element.
     * MeasuredProperty list should be contained in a file named
     * PropertyName.table
     *
     * @param PropertyName MeasuredProperty of interest
     * @return That property for each element
     * @throws java.lang.Exception
     */
    public double[] getPropertyLookupTable(String PropertyName) throws Exception {
        // Check if it has been loaded in yet
        if (PropertyData.containsKey(PropertyName)) {
            return PropertyData.get(PropertyName);
        }

        double[] table = LookupData.loadPropertyLookupTable(DataDirectory, PropertyName);
        PropertyData.put(PropertyName, table);
        return table;
    }

    /**
     * Get the list of known oxidation states
     * @return List of oxidation states
     */
    public double[][] getOxidationStates() {
        if (OxidationStates == null) {
            readOxidationStates();
        }
        return OxidationStates;
    }

    /**
     * Reads in a data file that contains known oxidation states for each
     * element. List should be contained in a file named OxidationStates.table
     */
    protected void readOxidationStates() {
        // Open the file for reading
        Path datafile = Paths.get(DataDirectory);
        BufferedReader is;
        try {
            is = Files.newBufferedReader(
                    datafile.resolve("OxidationStates.table"), Charset.forName("US-ASCII"));

            // Read the file
            int i, j; // Counters
            OxidationStates = new double[ElementNames.length][];
            for (i = 0; i < ElementNames.length; i++) {
                String[] States = is.readLine().split(" ");
                if (States[0].isEmpty()) {
                    OxidationStates[i] = new double[0];
                } else {
                    OxidationStates[i] = new double[States.length];
                    for (j = 0; j < OxidationStates[i].length; j++) {
                        OxidationStates[i][j] = Double.parseDouble(States[j]);
                    }
                }
            }
            is.close();
        } catch (IOException | NumberFormatException e) {
            throw new Error("Oxidation states failed to read due to " + e);
        }
    }

    /**
     * Whether a composition can form a neutral compound assuming each element
     * takes only a single oxidation state.
     * @param entry Composition to be assessed
     * @return Whether it can form an ionic compound
     */
    public boolean compositionCanFormIonic(CompositionEntry entry) {
        OxidationStateGuesser g = new OxidationStateGuesser();

        try {
            g.setElectronegativity(getPropertyLookupTable("Electronegativity"));
            g.setOxidationStates(getOxidationStates());
        } catch (Exception e) {
            throw new Error(e);
        }

        return ! g.getPossibleStates(entry).isEmpty();
    }

    @Override
    public Object runCommand(List<Object> Command) throws Exception {
		if (Command.isEmpty()) return super.runCommand(Command);
        String Action = Command.get(0).toString();
        switch (Action.toLowerCase()) {
            default:
                return super.runCommand(Command);
        }

    }

    @Override
    protected Object runAttributeCommand(List<Object> Command) throws Exception {
        if (Command.isEmpty()) {
            return super.runAttributeCommand(Command);
        }
        String Action = Command.get(0).toString().toLowerCase();
        switch (Action) {
            case "properties": case "prop": {
                return runPropertyCommand(Command.subList(1, Command.size()));
            }
            case "composition": {
                boolean useComp;
                try {
                    switch (Command.get(1).toString().toLowerCase()) {
                        case "true": useComp = true; break;
                        case "false": useComp = false; break;
                        default: throw new Exception();
                    }
                } catch (Exception e) {
                    throw new Exception("Usage: <dataset> attributes composition <true|false>");
                }
                useCompositionAsAttributes(useComp);
                if (useComp) {
                    System.out.println("\tSet dataset to use composition as attributes");
                } else {
                    System.out.println("\tSet dataset to not use composition as attributes");
                }
                return null;
            }
            default:
                return super.runAttributeCommand(Command);
        }
    }

    /**
     * Run commands that control which elemental properties are used when
     * generating attributes
     *
     * @param Command Command to act on
     * @return Any output from operation (null if no output)
     * @throws Exception
     */
    protected Object runPropertyCommand(List<Object> Command) throws Exception {
        if (Command.isEmpty()) {
            Iterator<String> iter = ElementalProperties.iterator();
            int count = 0;
            while (iter.hasNext()) {
                count++;
                System.out.print("\t" + iter.next());
                if (count % 5 == 0) {
                    System.out.println();
                }
            }
            if (count % 5 != 0) {
                System.out.println();
            }
            return null;
        }
        String Action = Command.get(0).toString();
        switch (Action.toLowerCase()) {
            case "add": {
                // Usage: add <name> or add set <name>
                if (Command.size() < 2) {
                    throw new Exception("Usage: \"<dataset> attributes properties add set <set name>\""
                            + " or properties add <property names...>");
                }
                // Add in new properties
                int originalSize = ElementalProperties.size();
                if (Command.get(1).toString().equalsIgnoreCase("set")) {
                    // Add properties from a known set
                    String[] Properties = PropertyLists.getPropertySet(Command.get(2).toString());
                    for (String p : Properties) {
                        addElementalProperty(p);
                    }
                } else {
                    // Add in properties one by one
                    for (int i = 1; i < Command.size(); i++) {
                        addElementalProperty(Command.get(i).toString());
                    }
                }
                System.out.println("\tAdded " + (ElementalProperties.size() - originalSize)
                    + " new properties.");
            }
            break;
            case "remove": {
                // Usage: remove <names...>
                if (Command.size() < 2) {
                    throw new Exception("Usage: <dataset> attributes properties remove <property names...>");
                }
                // Remove those property from the set
                String output = "\tRemoved properties:";
                int nRemoved = 0;
                for (int i = 1; i < Command.size(); i++) {
                    boolean wasRemoved = removeElementalProperty(Command.get(i).toString());
                    if (wasRemoved) {
                        output += " " + Command.get(i).toString();
                        nRemoved++;
                    }
                }
                if (nRemoved > 0) {
                    System.out.println(output);
                } else {
                    System.out.println("\tWARNING: No attributes were removed.");
                }
                break;
            }
            case "directory": {
                // Define the lookup directory
                if (Command.size() < 2) {
                    throw new Exception("Usage: <dataset> attributes properties directory <directory name>");
                }
                DataDirectory = Command.get(1).toString();
                for (int i = 2; i < Command.size(); i++) {
                    DataDirectory += " " + Command.get(i).toString();
                }
            }
            break;
            default:
                throw new Exception("ERROR: Property command not recognized: " + Action);
        }
        return null;
    }

    @Override
    public String saveCommand(String Basename, String Format) throws Exception {
        String filename;
        switch (Format.toLowerCase()) {
            case "comp":
                filename = Basename + ".csv";
                CompositionDatasetOutput.saveCompositionProperties(this,
                        filename);
                return filename;
            default:
                return super.saveCommand(Basename, Format);
        }
    }

    @Override
    public String printEntryDescription(boolean htmlFormat) {
        return "List of elements and their relative proportions";
    }

}


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

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

# File lib/rubygems/local_remote_options.rb, line 18
  def accept_uri_http
    OptionParser.accept URI::HTTP do |value|
      begin
        uri = URI.parse value
      rescue URI::InvalidURIError
        raise OptionParser::InvalidArgument, value
      end

      unless ['http', 'https', 'file'].include?(uri.scheme)
         raise OptionParser::InvalidArgument, value
      end

      value
    end
  end

redpajama_set_name: RedPajamaGithub


text:
package com.endercrest.uwaterlooapi.api.models;

import java.util.List;

/**
 * Created by Thomas Cordua-von Specht on 12/6/2016.
 */
public class ApiChangelog {

    private String date;
    private List<String> changes;

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public List<String> getChanges() {
        return changes;
    }

    public void setChanges(List<String> changes) {
        this.changes = changes;
    }
}


text:
layout: post
title: Python Notes
category: 技术
tags: Python
keywords: Python Pip Numpy Scipy Pillow Matplotlib iPython iPython-Notebook
---

---
## Python

### Python 应用

- iPython iPython-Notebook

sudo apt insall ipython ipython-notebook

>启动ipython[notebook] 终端输入以下命令: $ ipython notebook

- Cocos2d

sudo pip install Cocos2d

## Pip

### 安装 Pip

sudo apt insall pip # python-pip

### 安装 Python 包

sudo pip install pip --upgrade
sudo pip install numpy scipy pillow mtplotlib --upgrade

sudo pip install control filterpy pykalman # Enginering


text:
import time
from bing import *
import urllib
from os.path import expanduser

# the directory in which to store bing image
image_store_dir = expanduser("~") + '/Pictures/'

def test_network():
    code = urllib.urlopen("http://www.bing.com/").getcode()
    if code != 200:
        return False
    return True

def check_dir(path):
    if not os.path.exists(path):
        os.makedirs(path)

if __name__ == "__main__":
    try_times = 0
    while True:
        ok = test_network()
        if ok:
            enjoy = EnjoyBing(image_store_dir)
            enjoy.set_wallpaper()
            enjoy.pop_up_story_window()
            break
        time.sleep(60)
        try_times += 1
        if try_times == 10:
            break


text:
'''A Robot Framework listener that sends information to a socket in JSON format

This requires Python 2.6+
'''

import os
import socket
import sys
import json
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler

PORT = 8910
HOST = "localhost"

# Robot expects the class to be the same as the filename, so
# we can't use the convention of capitalizing the class name
class socket_listener(object):
    """Pass all listener events to a remote listener

    If called with one argument, that argument is a port
    If called with two, the first is a hostname, the second is a port
    """
    ROBOT_LISTENER_API_VERSION = 2

    def __init__(self, *args):
        self.port = PORT
        self.host = HOST
        self.sock = None
        if len(args) == 1:
            self.port = int(args[0])
        elif len(args) >= 2:
            self.host = args[0]
            self.port = int(args[1])
        self._connect()
        self._send_pid()

    def _send_pid(self):
        self._send_socket("pid", os.getpid())

    def start_test(self, name, attrs):
        self._send_socket("start_test", name, attrs)

    def end_test(self, name, attrs):
        self._send_socket("end_test", name, attrs)

    def start_suite(self, name, attrs):
        self._send_socket("start_suite", name, attrs)

    def end_suite(self, name, attrs):
        self._send_socket("end_suite", name, attrs)

    def start_keyword(self, name, attrs):
        self._send_socket("start_keyword", name, attrs)

    def end_keyword(self, name, attrs):
        self._send_socket("end_keyword", name, attrs)

    def message(self, message):
        self._send_socket("message", message)

    def log_message(self, message):
        self._send_socket("log_message", message)

    def log_file(self, path):
        self._send_socket("log_file", path)

    def output_file(self, path):
        self._send_socket("output_file", path)

    def report_file(self, path):
        self._send_socket("report_file", path)

    def summary_file(self, path):
        self._send_socket("summary_file", path)

    def debug_file(self, path):
        self._send_socket("debug_file", path)

    def close(self):
        self._send_socket("close")
        if self.sock:
            self.filehandler.close()
            self.sock.close()

    def _connect(self):
        '''Establish a connection for sending JSON data'''
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.connect((self.host, self.port))
            self.filehandler = self.sock.makefile('w')
        except socket.error, e:
            print 'unable to open socket to "%s:%s" error: %s' % (self.host, self.port, str(e))
            self.sock = None

    def _send_socket(self, name, *args):
        if self.sock:
            try:
                packet = json.dumps([name,] + list(args)) + "\n"
                self.filehandler.write(packet)
                self.filehandler.flush()
            except Exception, e:
                print "writing to the socket failed:", e


text:
using System;
using System.Xml;

namespace VersionOne.SDK.APIClient
{
    [Obsolete("This interface has been deprecated. Please use V1Connector instead.")]
    public interface ICentral
    {
        IServices Services { get; }
        IMetaModel MetaModel { get; }
        ILocalizer Loc { get; }
    }

    [Obsolete("This class has been deprecated. Please use V1Connector instead.")]
    public class V1Central : ICentral
    {
        public V1Central(XmlNode config)
        {
            _applicationUrl = config["ApplicationUrl"].InnerText;

            if (_applicationUrl == null)
            {
                _applicationUrl = string.Empty;
            }
            else if (!_applicationUrl.EndsWith(@"/"))
            {
                _applicationUrl += @"/";
            }

            _username = config["Username"].InnerText;
            _password = config["Password"].InnerText;
            _apiVersion = config["APIVersion"].InnerText;
            _integratedAuth = false;
            bool.TryParse(config["IntegratedAuth"].InnerText, out _integratedAuth);

            //proxy settings
            if (config["ProxySettings"] != null)
            {
                _proxyDisabled = IsProxyDisabled(config["ProxySettings"].GetAttribute("disabled"));
                _proxyUrl = new Uri(SafeGetInnerText(config["ProxySettings"], "Url"));
                _proxyUserName = SafeGetInnerText(config["ProxySettings"], "UserName");
                _proxyPassword = SafeGetInnerText(config["ProxySettings"], "Password");
                _proxyDomain = SafeGetInnerText(config["ProxySettings"], "Domain");
            }
        }

        private string SafeGetInnerText(XmlNode parent, string childNodeName)
        {
            var childNode = parent[childNodeName];
            return childNode != null ? childNode.InnerText : null;
        }

        private bool IsProxyDisabled(string status)
        {
            return status != "0";
        }

        private IServices _services;

        public IServices Services
        {
            get { return _services ?? (_services = new Services(MetaModel, GetConnector("rest-1.v1/", false))); }
        }

        private IMetaModel _metamodel;

        public IMetaModel MetaModel
        {
            get { return _metamodel ?? (_metamodel = new MetaModel(GetConnector("meta.v1/", true))); }
        }

        private ILocalizer _localizer;

        public ILocalizer Loc
        {
            get { return _localizer ?? (_localizer = new Localizer(GetConnector("loc.v1/", true))); }
        }

        private IAPIConnector GetConnector(string path, bool anonymous)
        {
            var connector = new VersionOneAPIConnector(ApplicationUrl + path, proxyProvider: Proxy);

            if (anonymous)
                return connector;

            connector.WithVersionOneUsernameAndPassword(_username, _password);
            if (_integratedAuth)
                connector.WithWindowsIntegratedAuthentication();

            return connector;

        }

        private ProxyProvider Proxy
        {
            get
            {
                return _proxyDisabled ? null : new ProxyProvider(_proxyUrl, _proxyUserName, _proxyPassword, _proxyDomain);
            }
        }

        private readonly bool _integratedAuth;
        private readonly string _apiVersion;
        private readonly string _applicationUrl = "http://localhost/VersionOne.Web/";
        private readonly string _username = "admin";
        private readonly string _password = "admin";
        private readonly bool _proxyDisabled = true;
        private readonly Uri _proxyUrl = new Uri("http://proxy:123");
        private readonly string _proxyUserName = "user";
        private readonly string _proxyPassword = "password";
        private readonly string _proxyDomain = "DOMAIN";

        private bool _isValidKnown;
        private bool _isValid;

        public bool IsValid
        {
            get
            {
                if (!_isValidKnown)
                {
                    _isValidKnown = true;

                    try
                    {
                        Validate();
                        _isValid = true;
                    }
                    catch (ConnectionException)
                    {
                        _isValid = false;
                    }
                }

                return _isValid;
            }
        }

        public void Validate()
        {
            new V1ConnectionValidator(ApplicationUrl, _username, _password, _integratedAuth, Proxy).Test(_apiVersion);
        }

        public string ApplicationUrl
        {
            get { return _applicationUrl; }
        }
    }
}


text:
        <input name='name' type="text" class="form-control search-name" ng-model="nameFilter" placeholder="Search by name..." />

        <button type="button" class="btn btn-md show_filters" ng-click="showHideFilters()" title="Show Or Hide Filters"></button>
        <button type="button" class="btn btn-md btn-danger" ng-click="clearFilters()" title="Clear Applied Side Filters"></button>

              <input name='teams' type="checkbox" rel="Teams" />
              Teams

              <input name='designations' type="checkbox" rel="Designations" />
              Designations

                    <input type="checkbox" rel="{{i}}" ng-model="teamFilter[i]" ng-true-value="'{{i}}'" ng-false-value="''"/> {{i}}

                    <input type="checkbox" rel="{{i}}" ng-model="designationFilter[i]" ng-true-value="'{{i}}'" ng-false-value="''"/> {{i}}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace SimpleLauncher.Properties {

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

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

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

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

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

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

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

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


text:
package com.tom.recipes;

import java.util.Iterator;
import java.util.List;

import javax.annotation.Nonnull;

import net.minecraft.block.Block;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;

import net.minecraftforge.oredict.OreDictionary;

import com.tom.api.item.IWrench;

public class WrenchShapelessCraftingRecipe implements IRecipe {
	@Nonnull
	protected ItemStack output = ItemStack.EMPTY;
	protected NonNullList<Object> input = NonNullList.create();

	public WrenchShapelessCraftingRecipe(Block result, Object... recipe) {
		this(new ItemStack(result), recipe);
	}

	public WrenchShapelessCraftingRecipe(Item result, Object... recipe) {
		this(new ItemStack(result), recipe);
	}

	public WrenchShapelessCraftingRecipe(@Nonnull ItemStack result, Object... recipe) {
		output = result.copy();
		for (Object in : recipe) {
			if (in instanceof ItemStack) {
				input.add(((ItemStack) in).copy());
			} else if (in instanceof Item) {
				input.add(new ItemStack((Item) in));
			} else if (in instanceof Block) {
				input.add(new ItemStack((Block) in));
			} else if (in instanceof String) {
				input.add(OreDictionary.getOres((String) in));
			} else {
				String ret = "Invalid shapeless ore recipe: ";
				for (Object tmp : recipe) {
					ret += tmp + ", ";
				}
				ret += output;
				throw new RuntimeException(ret);
			}
		}
		input.add(OreDictionary.getOres("tomsmodwrench"));
	}

	@Override
	@Nonnull
	public ItemStack getRecipeOutput() {
		return output;
	}

	/**
	 * Returns an Item that is the result of this recipe
	 */
	@Override
	@Nonnull
	public ItemStack getCraftingResult(@Nonnull InventoryCrafting var1) {
		return output.copy();
	}

	/**
	 * Used to check if a recipe matches current crafting inventory
	 */
	@SuppressWarnings("unchecked")
	@Override
	public boolean matches(InventoryCrafting var1, World world) {
		NonNullList<Object> required = NonNullList.create();
		required.addAll(input);

		for (int x = 0;x < var1.getSizeInventory();x++) {
			ItemStack slot = var1.getStackInSlot(x);

			if (!slot.isEmpty()) {
				boolean inRecipe = false;
				Iterator<Object> req = required.iterator();

				while (req.hasNext()) {
					boolean match = false;

					Object next = req.next();

					if (next instanceof ItemStack) {
						match = OreDictionary.itemMatches((ItemStack) next, slot, false);
					} else if (next instanceof List) {
						Iterator<ItemStack> itr = ((List<ItemStack>) next).iterator();
						while (itr.hasNext() && !match) {
							match = OreDictionary.itemMatches(itr.next(), slot, false);
						}
					}

					if (match) {
						inRecipe = true;
						required.remove(next);
						break;
					}
				}

				if (!inRecipe) { return false; }
			}
		}

		return required.isEmpty();
	}

	@Override
	public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) {
		NonNullList<ItemStack> nonnulllist = NonNullList.<ItemStack>withSize(inv.getSizeInventory(), ItemStack.EMPTY);

		for (int i = 0;i < nonnulllist.size();++i) {
			ItemStack itemstack = inv.getStackInSlot(i);
			if (itemstack.getItem() instanceof IWrench) {
				nonnulllist.set(i, itemstack.copy());
			} else {
				nonnulllist.set(i, net.minecraftforge.common.ForgeHooks.getContainerItem(itemstack));
			}
		}

		return nonnulllist;
	}

	/**
	 * Returns the input for this recipe, any mod accessing this value should
	 * never manipulate the values in this array as it will effect the recipe
	 * itself.
	 *
	 * @return The recipes input vales.
	 */
	public NonNullList<Object> getInput() {
		return this.input;
	}

	@Override
	public IRecipe setRegistryName(ResourceLocation name) {
		return null;
	}

	@Override
	public ResourceLocation getRegistryName() {
		return null;
	}

	@Override
	public Class<IRecipe> getRegistryType() {
		return null;
	}

	@Override
	public boolean canFit(int width, int height) {
		return (width == 2 && height == 1) || (height == 2 && width == 1);
	}
}


text:
/*
 * The method is present in: Otsu, N (1979), "A threshold selection method from gray-level histograms", IEEE Trans. Sys., Man., Cyber. 9: 62-66
 * The Otsu implementation is based on: https://en.wikipedia.org/wiki/Otsu's_method
 * @param histogram - the histogram of the image
 * @returns {number} - the threshold
 */

export function otsu(histogramCounts: number[], total: number): number {
  let sumB = 0;
  let wB = 0;
  let maximum = 0;
  let level = 0;

  let sum1 = 0;
  for (let i = 0; i < histogramCounts.length; i++) {
    sum1 += i * histogramCounts[i];
  }

  for (let ii = 0; ii < histogramCounts.length; ii++) {
    wB = wB + histogramCounts[ii];
    const wF = total - wB;
    if (wB === 0 || wF === 0) {
      continue;
    }
    sumB = sumB + ii * histogramCounts[ii];
    const mF = (sum1 - sumB) / wF;
    const between = wB * wF * (sumB / wB - mF) * (sumB / wB - mF);
    if (between >= maximum) {
      level = ii;
      maximum = between;
    }
  }

  return level;
}


text:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Utils;

namespace Math
{
    /// <summary>
    /// Implementation of MathService server
    /// </summary>
    public class MathServiceImpl : Math.MathBase
    {
        public override Task<DivReply> Div(DivArgs request, ServerCallContext context)
        {
            return Task.FromResult(DivInternal(request));
        }

        public override async Task Fib(FibArgs request, IServerStreamWriter<Num> responseStream, ServerCallContext context)
        {
            var limit = request.Limit > 0 ? request.Limit : long.MaxValue;
            var fibEnumerator = FibInternal(limit).GetEnumerator();

            // Keep streaming the sequence until the call is cancelled.
            // Use CancellationToken from ServerCallContext to detect the cancellation.
            while (!context.CancellationToken.IsCancellationRequested && fibEnumerator.MoveNext())
            {
                await responseStream.WriteAsync(fibEnumerator.Current);
                await Task.Delay(100);
            }
        }

        public override async Task<Num> Sum(IAsyncStreamReader<Num> requestStream, ServerCallContext context)
        {
            long sum = 0;
            await requestStream.ForEachAsync(num =>
            {
                sum += num.Num_;
                return TaskUtils.CompletedTask;
            });
            return new Num { Num_ = sum };
        }

        public override async Task DivMany(IAsyncStreamReader<DivArgs> requestStream, IServerStreamWriter<DivReply> responseStream, ServerCallContext context)
        {
            await requestStream.ForEachAsync(async divArgs => await responseStream.WriteAsync(DivInternal(divArgs)));
        }

        static DivReply DivInternal(DivArgs args)
        {
            if (args.Divisor == 0)
            {
                // One can finish the RPC with non-ok status by throwing RpcException instance.
                // Alternatively, resulting status can be set using ServerCallContext.Status
                throw new RpcException(new Status(StatusCode.InvalidArgument, "Division by zero"));
            }

            long quotient = args.Dividend / args.Divisor;
            long remainder = args.Dividend % args.Divisor;
            return new DivReply { Quotient = quotient, Remainder = remainder };
        }

        static IEnumerable<Num> FibInternal(long n)
        {
            long a = 1;
            yield return new Num { Num_ = a };

            long b = 1;
            for (long i = 0; i < n - 1; i++)
            {
                long temp = a;
                a = b;
                b = temp + b;
                yield return new Num { Num_ = a };
            }
        }
    }
}


text:
from setuptools import setup

VERSION = "0.5.1"

base_url = "http://github.com/wharris/dougrain/"

setup(
    name='dougrain',
    version=VERSION,
    description='HAL JSON parser and generator',
    author='Will Harris',
    author_email='will@greatlibrary.net',
    url=base_url,
    packages=['dougrain'],
    provides=['dougrain'],
    long_description=open("README.rst").read(),
    install_requires=['uritemplate >= 0.6'],
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Operating System :: POSIX',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ]
)


text:
module Gitlab
  module GonHelper
    def add_gon_variables
      gon.api_version            = API::API.version
      gon.default_avatar_url     = URI::join(Gitlab.config.gitlab.url, ActionController::Base.helpers.image_path('no_avatar.png')).to_s
      gon.max_file_size          = current_application_settings.max_attachment_size
      gon.relative_url_root      = Gitlab.config.gitlab.relative_url_root
      gon.shortcuts_path         = help_page_path('shortcuts')
      gon.user_color_scheme      = Gitlab::ColorSchemes.for_user(current_user).css_class
      gon.award_menu_url         = emojis_path

      if current_user
        gon.current_user_id = current_user.id
      end
    end
  end
end


text:
#ifndef TCLAP_VISITOR_H
#define TCLAP_VISITOR_H

namespace TCLAP
{

/**
 * A base class that defines the interface for visitors.
 */
class Visitor
{
  public:

    /**
     * Constructor. Does nothing.
     */
    Visitor() { }

    /**
     * Destructor. Does nothing.
     */
    virtual ~Visitor() { }

    /**
     * Does nothing. Should be overridden by child.
     */
    virtual void visit() { }
};

}

#endif


text:
Goal: Try an experiment with dat

Unchanging data such as countries of the world with data such as

* dial codes
* tax rates


text:
GridFS, which stands for "Grid File Store," is a specification for storing large files in MongoDB. It works by dividing a file into manageable chunks and storing each of those chunks as a separate document. GridFS requires two collections to achieve this: one collection stores each file's metadata (e.g., name, size, etc.) and another stores the chunks themselves. If you're interested in more details, check out the [GridFS Specification](http://www.mongodb.org/display/DOCS/GridFS+Specification).

### The Grid class

The [Grid class](Mongo/Grid.html) represents the core GridFS implementation. Grid gives you a simple file store, keyed on a unique ID. This means that duplicate filenames aren't a problem. To use the Grid class, first make sure you have a database, and then instantiate a Grid:

    @db = Mongo::Connection.new.db('social_site')
    @grid = Grid.new(@db)

#### Saving files
Once you have a Grid object, you can start saving data to it. The data can be either a string or an IO-like object that responds to a #read method:

    # Saving string data
    id = @grid.put("here's some string / binary data")

    # Saving IO data and including the optional filename
    image = File.open("me.jpg")
    id2   = @grid.put(image, :filename => "me.jpg")

Grid#put returns an object id, which you can use to retrieve the file:

    # Get the string we saved
    file = @grid.get(id)

    # Get the file we saved
    image = @grid.get(id2)

#### File metadata

There are accessors for the various file attributes:

    image.filename
    # => "me.jpg"

    image.content_type
    # => "image/jpg"

    image.file_length
    # => 502357

    image.upload_date
    # => Mon Mar 01 16:18:30 UTC 2010

    # Read all the image's data at once
    image.read

    # Read the first 100k bytes of the image
    image.read(100 * 1024)

When putting a file, you can set many of these attributes and write arbitrary metadata:

    # Saving IO data
    file = File.open("me.jpg")
    id2  = @grid.put(file,
             :filename     => "my-avatar.jpg"
             :content_type => "application/jpg",
             :_id          => 'a-unique-id-to-use-in-lieu-of-a-random-one',
             :chunk_size   => 100 * 1024,
             :metadata     => {'description' => "taken after a game of ultimate"})

#### Safe mode

A kind of safe mode is built into the GridFS specification. When you save a file, and MD5 hash is created on the server. If you save the file in safe mode, an MD5 will be created on the client for comparison with the server version. If the two hashes don't match, an exception will be raised.

    image = File.open("me.jpg")
    id2   = @grid.put(image, "my-avatar.jpg", :safe => true)

#### Deleting files

Deleting a file is as simple as providing the id:

    @grid.delete(id2)

### The GridFileSystem class

[GridFileSystem](http://api.mongodb.org/ruby/current/Mongo/GridFileSystem.html) is a light emulation of a file system and therefore has a couple of unique properties. The first is that filenames are assumed to be unique. The second, a consequence of the first, is that files are versioned. To see what this means, let's create a GridFileSystem instance:

#### Saving files

    @db = Mongo::Connection.new.db("social_site")
    @fs = GridFileSystem.new(@db)

Now suppose we want to save the file 'me.jpg.' This is easily done using a filesystem-like API:

    image = File.open("me.jpg")
    @fs.open("me.jpg", "w") do |f|
      f.write image
    end

We can then retrieve the file by filename:

    image = @fs.open("me.jpg", "r") {|f| f.read }

No problems there. But what if we need to replace the file? That too is straightforward:

    image = File.open("me-dancing.jpg")
    @fs.open("me.jpg", "w") do |f|
      f.write image
    end

But a couple things need to be kept in mind. First is that the original 'me.jpg' will be available until the new 'me.jpg' saves. From then on, calls to the #open method will always return the most recently saved version of a file. But, and this the second point, old versions of the file won't be deleted. So if you're going to be rewriting files often, you could end up with a lot of old versions piling up. One solution to this is to use the :delete_old options when writing a file:

    image = File.open("me-dancing.jpg")
    @fs.open("me.jpg", "w", :delete_old => true) do |f|
      f.write image
    end

This will delete all but the latest version of the file.

#### Deleting files

When you delete a file by name, you delete all versions of that file:

    @fs.delete("me.jpg")

#### Metadata and safe mode

All of the options for storing metadata and saving in safe mode are available for the GridFileSystem class:

    image = File.open("me.jpg")
    @fs.open('my-avatar.jpg', w,
               :content_type => "application/jpg",
               :metadata     => {'description' => "taken on 3/1/2010 after a game of ultimate"},
               :_id          => 'a-unique-id-to-use-instead-of-the-automatically-generated-one',
               :safe         => true) { |f| f.write image }

### Advanced Users

Astute code readers will notice that the Grid and GridFileSystem classes are merely thin wrappers around an underlying [GridIO class](http://api.mongodb.org/ruby/current/Mongo/GridIO.html). This means that it's easy to customize the GridFS implementation presented here; just use GridIO for all the low-level work, and build the API you need in an external manager class similar to Grid or GridFileSystem.


text:
package main

import (
	"bytes"
	"net/http"

	"github.com/tsuru/tsuru/cmd"
	"gopkg.in/check.v1"
)

func (s *S) TestInstallInfo(c *check.C) {
	c.Assert((&install{}).Info(), check.NotNil)
}

func (s *S) TestInstall(c *check.C) {
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	client := cmd.NewClient(&http.Client{}, nil, manager)
	command := install{}
	command.Run(&context, client)
	c.Assert(stdout.String(), check.Equals, "")
}

func (s *S) TestUninstallInfo(c *check.C) {
	c.Assert((&uninstall{}).Info(), check.NotNil)
}

func (s *S) TestUninstall(c *check.C) {
	var stdout, stderr bytes.Buffer
	context := cmd.Context{
		Stdout: &stdout,
		Stderr: &stderr,
	}
	client := cmd.NewClient(&http.Client{}, nil, manager)
	command := uninstall{}
	command.Run(&context, client)
	c.Assert(stdout.String(), check.Equals, "")
}


text:
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define EIGEN_USE_GPU

#include "tensorflow/core/kernels/tile_functor.h"
#include "tensorflow/core/kernels/tile_functor_gpu.h"

namespace tensorflow {
namespace functor {
using Eigen::GpuDevice;

template struct Tile<GpuDevice, int16, int32>;
template struct Tile<GpuDevice, int16, int64>;
}  // namespace functor
}  // namespace tensorflow

#endif  // GOOGLE_CUDA || TENSORFLOW_USE_ROCM


text:
\hypertarget{dir_8bfd91d3d000cd817c64e9671be9a379}{\section{devel/lib/python2.7/dist-\/packages/nubot\-\_\-common/msg Directory Reference}
\label{dir_8bfd91d3d000cd817c64e9671be9a379}\index{devel/lib/python2.\-7/dist-\/packages/nubot\-\_\-common/msg Directory Reference@{devel/lib/python2.\-7/dist-\/packages/nubot\-\_\-common/msg Directory Reference}}
}
\subsection*{Files}
\begin{DoxyCompactItemize}
\item
file \hyperlink{nubot__common_2msg_2____init_____8py}{\-\_\-\-\_\-init\-\_\-\-\_\-.\-py}
\item
file \hyperlink{__VelCmd_8py}{\-\_\-\-Vel\-Cmd.\-py}
\end{DoxyCompactItemize}


text:
import os
from django.utils import timezone
from datetime import datetime
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
from .local_settings import *

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'lots_client',
    'lots_admin',
    'raven.contrib.django.raven_compat',
    'bootstrap_pagination',
    'debug_toolbar',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
)

ROOT_URLCONF = 'lots.urls'

WSGI_APPLICATION = 'lots.wsgi.application'

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/Chicago'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "lots", "static"),
)

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'lots_admin.context.extra_context',
            ],
        },
    },
]

SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_QUERYSTRING_AUTH = False


text:
% Version 2.2.0
% greg
% 07/11/2014

Release 2.2.0
=============

Date: 2014-07-11

New features:

* Job timeout: specify a maximum duration for a job. If the job execution exceeds this duration, it will be halted (as if killed manually). You can use a simple format like "120m" (120 minutes) or "2h" (2 hours).  You can specify the timeout via a job option by setting it to `${option.name}`.  This only affects the job when executed directly, not when run as a job reference.
* Job retry: specify a maximum retry attempt for a job.  If the job fails or is timed out, it will be retried.  The maximum value can be specified via a job option if set to `${option.name}`.
* Delete executions: delete executions individually or in bulk. Requires a 'delete_execution' action allowed via aclpolicy.

Some bug fixes are included, as well as some pull requests to enhance the LDAP login module:

* Support nested LDAP group membership (see [Added support for nested groups in JettyCachingLdapLoginModule.](https://github.com/rundeck/rundeck/pull/829))
* Support a "supplementalRoles" setting, which can help avoid the `!role` issue. See [Login Module Configuration](../administration/authenticating-users.html#login-module-configuration).

*Upgrade notes:*

Several domain fields were added. Mysql and H2 should upgrade in place without issue.

## Contributors

* jdmulloy
* Greg Schueler (gschueler)
* Alex Honor (ahonor)
* new23d
* Bart van der Schans (schans)
* Andreas Knifh (knifhen)

## Issues

* [Server listening port number defined in profile instead of service start script](https://github.com/rundeck/rundeck/pull/845)
* [Install fails when /etc/rundeck is a symlink](https://github.com/rundeck/rundeck/pull/842)
* [Multiple Recepient E-mail Notification](https://github.com/rundeck/rundeck/issues/834)
* [Added support for nested groups in JettyCachingLdapLoginModule.](https://github.com/rundeck/rundeck/pull/829)
* [Add Job retry behavior](https://github.com/rundeck/rundeck/pull/825)
* [Job's references are reported as Killed](https://github.com/rundeck/rundeck/issues/821)
* [Ace editor cursor position bug on mac retina display](https://github.com/rundeck/rundeck/issues/820)
* [add a Job Timeout behavior](https://github.com/rundeck/rundeck/issues/815)
* [Added support for the supplementalRoles option to the LDAP Module](https://github.com/rundeck/rundeck/pull/803)
* [Ansi 256 color support doesn't work](https://github.com/rundeck/rundeck/issues/797)
* [Delete executions](https://github.com/rundeck/rundeck/pull/767)


text:
package com.cardpay.pccredit.report.web;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cardpay.pccredit.Sx.model.SxOutputData;
import com.cardpay.pccredit.Sx.service.SxService;
import com.cardpay.pccredit.report.filter.ReportFilter;
import com.cardpay.pccredit.report.model.BjjdktjbbForm;
import com.cardpay.pccredit.report.service.CustomerTransferFlowService;
import com.wicresoft.jrad.base.auth.JRadModule;
import com.wicresoft.jrad.base.auth.JRadOperation;
import com.wicresoft.jrad.base.database.model.QueryResult;
import com.wicresoft.jrad.base.web.JRadModelAndView;
import com.wicresoft.jrad.base.web.controller.BaseController;
import com.wicresoft.jrad.base.web.result.JRadPagedQueryResult;
import com.wicresoft.util.spring.mvc.mv.AbstractModelAndView;

@Controller
@RequestMapping("/refuse/loan/*")
@JRadModule("refuse.loan")
public class RefuseLoanController extends BaseController{
	@Autowired
	private SxService service;
	@Autowired
	private CustomerTransferFlowService customerTransferFlowService;

	/**
	 * 被拒绝贷款统计查询
	 * @param filter
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "queryRefuseLoan.page", method = { RequestMethod.GET })
	@JRadOperation(JRadOperation.BROWSE)
	public AbstractModelAndView queryHaveBeenLoan(@ModelAttribute ReportFilter filter,HttpServletRequest request) {
		JRadModelAndView mv = new JRadModelAndView("/report/refuseLoan/refuseLoan", request);
		filter.setRequest(request);
		String name=request.getParameter("custManagerName");
		String custManagerName;
		if(name!=null && name!=""){
			try {
				//String custManagerName=URLDecoder.decode(name, "UTF-8");
				custManagerName=new String(name.getBytes("iso-8859-1"),"utf-8");
				filter.setCustManagerName(custManagerName);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// 查询团队
		List<SxOutputData> team = service.findteam();
	    QueryResult<BjjdktjbbForm> result =  customerTransferFlowService.findbjjdktjbbFormList(filter);
		JRadPagedQueryResult<BjjdktjbbForm> pagedResult = new JRadPagedQueryResult<BjjdktjbbForm>(filter, result);
		mv.addObject(PAGED_RESULT, pagedResult);
		mv.addObject("team", team);
		return mv;
	}

	/**
	 * 导出被拒绝贷款统计查询
	 */
	@ResponseBody
	@RequestMapping(value = "exportAll.page", method = { RequestMethod.GET })
	public void exportAll(@ModelAttribute ReportFilter filter, HttpServletRequest request,HttpServletResponse response){
		filter.setRequest(request);
		List<BjjdktjbbForm> list = customerTransferFlowService.getbjjdktjbbFormList(filter);
		create(list,response);
	}

	public void create(List<BjjdktjbbForm> list,HttpServletResponse response){
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("被拒绝贷款统计统报表");
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		//第一行  合并单元格 并且设置标题
		/*HSSFRow row0 = sheet.createRow((int) 0);
		row0.createCell(0).setCellValue("基本资料");
		row0.createCell(0).setCellStyle(style);
		sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) 6));*/
		sheet.setColumnWidth(0, 3500);
		sheet.setColumnWidth(1, 8000);
		sheet.setColumnWidth(2, 8000);
		sheet.setColumnWidth(3, 8000);
		sheet.setColumnWidth(4, 8000);
		sheet.setColumnWidth(5, 5000);
		//==========================
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCell cell = row.createCell((short) 0);
		cell.setCellValue("序号");
		cell.setCellStyle(style);
		cell = row.createCell((short) 1);
		cell.setCellValue("客户名称");
		cell.setCellStyle(style);
		cell = row.createCell((short) 2);
		cell.setCellValue("客户证件号码");
		cell.setCellStyle(style);
		cell = row.createCell((short) 3);
		cell.setCellValue("所属产品");
		cell.setCellStyle(style);
		cell = row.createCell((short) 4);
		cell.setCellValue("申请日期");
		cell.setCellStyle(style);
		cell = row.createCell((short) 5);
		cell.setCellValue("申请金额");
		cell.setCellStyle(style);
		cell = row.createCell((short) 6);
		cell.setCellValue("拒绝日期");
		cell.setCellStyle(style);
		cell = row.createCell((short) 7);
		cell.setCellValue("拒绝原因");
		cell.setCellStyle(style);
		cell = row.createCell((short) 8);
		cell.setCellValue("所属客户经理");
		cell.setCellStyle(style);
		cell = row.createCell((short) 9);
		cell.setCellValue("所属机构");
		cell.setCellStyle(style);

		for(int i = 0; i < list.size(); i++){
			BjjdktjbbForm move = list.get(i);
			row = sheet.createRow((int) i+1);
			row.createCell((short) 0).setCellValue(move.getRowIndex());
			row.createCell((short) 1).setCellValue(move.getCname());
			row.createCell((short) 2).setCellValue(move.getCardtype());
			row.createCell((short) 3).setCellValue(move.getProdName());
			row.createCell((short) 4).setCellValue(move.getAppdate());
			row.createCell((short) 5).setCellValue(move.getReqlmt());
			row.createCell((short) 6).setCellValue(move.getRefuseDate());
			row.createCell((short) 7).setCellValue(move.getRefuseReason());
			row.createCell((short) 8).setCellValue(move.getBusimanager());
			row.createCell((short) 9).setCellValue(move.getName());
		}
		String fileName = "被拒绝贷款统计报表";
		try{
			response.setHeader("Content-Disposition", "attachment;fileName="+new String(fileName.getBytes("gbk"),"iso8859-1")+".xls");
			response.setHeader("Connection", "close");
			response.setHeader("Content-Type", "application/vnd.ms-excel");
			OutputStream os = response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
}


text:
<% include shared/header.html %>
<%-body%>
<% include shared/footer.html%>


text:
require "abstract_unit"
require "template/resolver_shared_tests"

class FileSystemResolverTest < ActiveSupport::TestCase
  include ResolverSharedTests

  def resolver
    ActionView::FileSystemResolver.new(tmpdir)
  end
end


text:
App.InboxController = Marrionette.Controller.extend({

});


text:
this.foo = 3;
function log(n) {
    return n;
}
log(this.foo).toString();


text:
//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// logcabin_kvstore.cpp
//
// Identification: src/backend/kvstore/logcabin_kvstore.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "logcabin_kvstore.h"
#include <iostream>

namespace peloton {
namespace kvstore {

/**
 * @brief Enters an object of type 'KVSEntry' in the Key Value Store
 *
 * @return True or false based on success of entry input.
 */
bool LogcabinKVStore::PutEntry(KVStoreKey *key, KVStoreEntry *entry) {
	std::cout << "PutEntry() called" << std::endl;
}

/**
 * @brief Fetches an entry from the Key Value Store
 *
 * @return Object of type Entry.
 */
KVStoreEntry* LogcabinKVStore::GetEntry(KVStoreKey *key) {
	std::cout << "GetEntry() called" << std::endl;
	KVStoreEntry *entry = new KVStoreEntry();
	return entry;
}

/**
 * @brief Removes an entry from the Key Value Store
 *
 * @return True or false based on binding.
 */
bool LogcabinKVStore::RemoveEntry(KVStoreKey *key) {
	std::cout << "RemoveEntry() called" << std::endl;
}

/**
 * @brief Checks if an entry exists in Key Value Store
 *
 * @return True or false based on existence of entry
 */
bool LogcabinKVStore::ContainsEntry(KVStoreKey *key) {
	std::cout << "ContainsEntry() called" << std::endl;
}

}  // End kvstore namespace
}  // End peloton namespace


text:
namespace blink {
PLATFORM_EXPORT void RGBAtoRGBScalar(const unsigned char* pixels,
                                     unsigned pixelCount,
                                     unsigned char* output);
#ifdef __ARM_NEON__
PLATFORM_EXPORT void RGBAtoRGBNeon(const unsigned char* input,
                                   const unsigned pixelCount,
                                   unsigned char* output);
#endif

}  // namespace blink

#endif


text:
<!DOCTYPE refentry [ <!ENTITY % mathent SYSTEM "math.ent"> %mathent; ]>

<!-- Converted by db4-upgrade version 1.1 -->

<refentry xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="glGetActiveAtomicCounterBufferiv">
    <info>
        <copyright>
            <year>2011-2014</year>
            <holder>Khronos Group.</holder>
        </copyright>
    </info>
    <refmeta>
        <refentrytitle>glGetActiveAtomicCounterBufferiv</refentrytitle>
        <manvolnum>3G</manvolnum>
    </refmeta>
    <refnamediv>
        <refname>glGetActiveAtomicCounterBufferiv</refname>
        <refpurpose>retrieve information about the set of active atomic counter buffers for a program</refpurpose>
    </refnamediv>
    <refsynopsisdiv><title>C Specification</title>
        <funcsynopsis>
            <funcprototype>
                <funcdef>void <function>glGetActiveAtomicCounterBufferiv</function></funcdef>
                <paramdef>GLuint <parameter>program</parameter></paramdef>
                <paramdef>GLuint <parameter>bufferIndex</parameter></paramdef>
                <paramdef>GLenum <parameter>pname</parameter></paramdef>
                <paramdef>GLint *<parameter>params</parameter></paramdef>
            </funcprototype>
        </funcsynopsis>
    </refsynopsisdiv>
    <refsect1 xml:id="parameters"><title>Parameters</title>
        <variablelist>
        <varlistentry>
            <term><parameter>program</parameter></term>
            <listitem>
                <para>
                    The name of a program object from which to retrieve information.
                </para>
            </listitem>
        </varlistentry>
        <varlistentry>
            <term><parameter>bufferIndex</parameter></term>
            <listitem>
                <para>
                    Specifies index of an active atomic counter buffer.
                </para>
            </listitem>
        </varlistentry>
        <varlistentry>
            <term><parameter>pname</parameter></term>
            <listitem>
                <para>
                    Specifies which parameter of the atomic counter buffer to retrieve.
                </para>
            </listitem>
        </varlistentry>
        <varlistentry>
            <term><parameter>params</parameter></term>
            <listitem>
                <para>
                    Specifies the address of a variable into which to write the retrieved information.
                </para>
            </listitem>
        </varlistentry>
        </variablelist>
    </refsect1>
    <refsect1 xml:id="description"><title>Description</title>
        <para>
            <function>glGetActiveAtomicCounterBufferiv</function> retrieves information about the set of active
            atomic counter buffers for a program object. <parameter>program</parameter> is the name of a program
            object for which the command <citerefentry><refentrytitle>glLinkProgram</refentrytitle></citerefentry>
            has been issued in the past. It is not necessary for <parameter>program</parameter> to have been linked
            successfully. The link may have failed because the number of active atomic counters exceeded the limits.
        </para>
        <para>
            <parameter>bufferIndex</parameter> specifies the index of an active atomic counter buffer and must be in
            the range zero to the value of <constant>GL_ACTIVE_ATOMIC_COUNTER_BUFFERS</constant> minus one. The value
            of <constant>GL_ACTIVE_ATOMIC_COUNTER_BUFFERS</constant> for <parameter>program</parameter> indicates the
            number of active atomic counter buffer and can be queried with
            <citerefentry><refentrytitle>glGetProgram</refentrytitle></citerefentry>.
        </para>
        <para>
            If no error occurs, the parameter(s) specified by <parameter>pname</parameter> are returned in <parameter>params</parameter>.
            If an error is generated, the contents of <parameter>params</parameter> are not modified.
        </para>
        <para>
            If <parameter>pname</parameter> is <constant>GL_ATOMIC_COUNTER_BUFFER_BINDING</constant>, then the index of the
            counter buffer binding point associated with the active atomic counter buffer <parameter>bufferIndex</parameter>
            for <parameter>program</parameter> is returned.
        </para>
        <para>
            If <parameter>pname</parameter> is <constant>GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE</constant>, then the implementation-dependent
            minimum total buffer object size, in baseic machine units, required to hold all active atomic counters in the
            atomic counter binding point identified by <parameter>bufferIndex</parameter> is returned.
        </para>
        <para>
            If <parameter>pname</parameter> is <constant>GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS</constant>, then the number of active
            atomic counters for the atomic counter buffer identified by <parameter>bufferIndex</parameter> is returned.
        </para>
        <para>
            If <parameter>pname</parameter> is <constant>GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES</constant>,
            then a list of the active atomic counter indices for the atomic counter buffer identified by <parameter>bufferIndex</parameter>
            is returned. The number of elements that will be written into <parameter>params</parameter> is the value of
            <constant>GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS</constant> for <parameter>bufferIndex</parameter>.
        </para>
        <para>
            If <parameter>pname</parameter> is <constant>GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER</constant>,
            <constant>GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER</constant>,
            <constant>GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER</constant>,
            <constant>GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER</constant>,
            <constant>GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER</constant>,
            <constant>GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER</constant> then a boolean value indicating
            whether the atomic counter buffer identified by <parameter>bufferIndex</parameter> is referenced by the vertex,
            tessellation control, tessellation evaluation, geometry, fragment or compute processing stages of <parameter>program</parameter>,
            respectively, is returned.
        </para>
    </refsect1>
    <refsect1 xml:id="notes"><title>Notes</title>
        <para>
            <function>glGetActiveAtomicCounterBufferiv</function> is available only if the
            GL version is 4.2 or higher.
        </para>
        <para>
            <constant>GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER</constant> is available
            only of the GL version is 4.3 or higher.
        </para>
    </refsect1>
    <refsect1 xml:id="errors"><title>Errors</title>
        <para>
            <constant>GL_INVALID_VALUE</constant> is generated if <parameter>program</parameter> is not the name of a program
            object for which <citerefentry><refentrytitle>glLinkProgram</refentrytitle></citerefentry> has been called in the past.
        </para>
        <para>
            <constant>GL_INVALID_VALUE</constant> is generated if <parameter>bufferIndex</parameter> is greater than or equal to
            the value of <constant>GL_ACTIVE_ATOMIC_COUNTER_BUFFERS</constant> for <parameter>program</parameter>.
        </para>
        <para>
            <constant>GL_INVALID_ENUM</constant> is generated if <parameter>pname</parameter> is not one of the accepted tokens.
        </para>
    </refsect1>
    <refsect1 xml:id="versions"><title>Version Support</title>
        <informaltable>
            <tgroup cols="13" align="left">
                <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apifunchead.xml" xpointer="xpointer(/*/*)"/>
                <tbody>
                    <row>
                        <entry><function>glGetActiveAtomicCounterBufferiv</function></entry>
                        <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apiversion.xml" xpointer="xpointer(/*/*[@role='42']/*)"/>
                    </row>
                </tbody>
            </tgroup>
        </informaltable>
    </refsect1>
    <refsect1 xml:id="seealso"><title>See Also</title>
        <para>
            <citerefentry><refentrytitle>glGetProgram</refentrytitle></citerefentry>,
            <citerefentry><refentrytitle>glGetActiveSubroutineUniform</refentrytitle></citerefentry>,
            <citerefentry><refentrytitle>glGetActiveSubroutineUniformName</refentrytitle></citerefentry>,
            <citerefentry><refentrytitle>glGetUniformLocation</refentrytitle></citerefentry>
        </para>
    </refsect1>
    <refsect1 xml:id="Copyright"><title>Copyright</title>
        <para>
            Copyright <trademark class="copyright"/> 2011-2014 Khronos Group.
            This material may be distributed subject to the terms and conditions set forth in
            the Open Publication License, v 1.0, 8 June 1999.
            <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://opencontent.org/openpub/">http://opencontent.org/openpub/</link>.
        </para>
    </refsect1>
</refentry>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using VAPPCT.DA;

/// <summary>
/// Properties that pertain to an temportal state entry
/// </summary>
public class CTemporalStateDataItem
{
    public string TSLabel { get; set; }
    public long TSDefinitionID { get; set; }
    public long TSID { get; set; }

    private k_TRUE_FALSE_ID m_lIsActive;
    public bool IsActive
    {
        get { return (m_lIsActive == k_TRUE_FALSE_ID.True) ? true : false; }
        set { m_lIsActive = (value == true) ? k_TRUE_FALSE_ID.True : k_TRUE_FALSE_ID.False; }
    }

    private k_TRUE_FALSE_ID m_lIsDefault;
    public bool IsDefault
    {
        get { return (m_lIsDefault == k_TRUE_FALSE_ID.True) ? true : false; }
        set { m_lIsDefault = (value == true) ? k_TRUE_FALSE_ID.True : k_TRUE_FALSE_ID.False; }
    }

    public CTemporalStateDataItem()
    {
    }

    public CTemporalStateDataItem(DataSet ds)
	{
        if (!CDataUtils.IsEmpty(ds))
        {
            TSLabel = CDataUtils.GetDSStringValue(ds, "TS_LABEL");
            TSDefinitionID = CDataUtils.GetDSLongValue(ds, "TS_DEFINITION_ID");
            TSID = CDataUtils.GetDSLongValue(ds, "TS_ID");
            IsActive = (CDataUtils.GetDSLongValue(ds, "IS_ACTIVE") == (long)k_TRUE_FALSE_ID.True) ? true : false;
            IsDefault = (CDataUtils.GetDSLongValue(ds, "IS_DEFAULT") == (long)k_TRUE_FALSE_ID.True) ? true : false;
        }
	}
}


text:
<?php

	$vs_file_path = $this->getVar('version_path');
	$o_zip = $this->getVar('zip');

	header("Content-type: application/zip");
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
	header("Cache-Control: no-store, no-cache, must-revalidate");
	header("Cache-Control: post-check=0, pre-check=0", false);
	header("Pragma: no-cache");
	header("Cache-control: private");

	header("Content-Disposition: attachment; filename=".$this->getVar('version_download_name'));

	readfile($o_zip->output(ZIPFILE_FILEPATH));
	;
?>


text:
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------

<#
.SYNOPSIS
Tests getting the logs associated to a correlation Id.
#>
function Test-GetAzureCorrelationIdLog
{
    # Setup
    $correlation = '/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.insights/alertrules/checkrule3-4b135401-a30c-4224-ae21-fa53a5bd253d/incidents/L3N1YnNjcmlwdGlvbnMvYTkzZmIwN2MtNmM5My00MGJlLWJmM2ItNGYwZGViYTEwZjRiL3Jlc291cmNlR3JvdXBzL0RlZmF1bHQtV2ViLUVhc3RVUy9wcm92aWRlcnMvbWljcm9zb2Z0Lmluc2lnaHRzL2FsZXJ0cnVsZXMvY2hlY2tydWxlMy00YjEzNTQwMS1hMzBjLTQyMjQtYWUyMS1mYTUzYTViZDI1M2QwNjM1NjA5MjE5ODU0NzQ1NDI0'

    try
    {
        # Test
        $actual = Get-AzureRmLog -CorrelationId $correlation -starttime 2015-03-02T18:00:00Z -endtime 2015-03-02T20:00:00Z -detailedOutput

        # Assert TODO add more asserts
		Assert-AreEqual $actual.Count 2
    }
    finally
    {
        # Cleanup
        # No cleanup needed for now
    }
}

<#
.SYNOPSIS
Tests getting the logs associated to a resource group.
#>
function Test-GetAzureResourceGroupLog
{
    # Setup
    $rgname = 'Default-Web-EastUS'

    try
    {
	    $actual = Get-AzureRmLog -ResourceGroup $rgname -starttime 2015-01-15T12:30:00Z -endtime 2015-01-15T20:30:00Z

        # Assert TODO add more asserts
		Assert-AreEqual $actual.Count 2
    }
    finally
    {
        # Cleanup
        # No cleanup needed for now
    }
}

<#
.SYNOPSIS
Tests getting the logs associated to a resource Id.
#>
function Test-GetAzureResourceLog
{
    # Setup
    $rname = '/subscriptions/a93fb07c-6c93-40be-bf3b-4f0deba10f4b/resourceGroups/Default-Web-EastUS/providers/microsoft.insights/alertrules/checkrule3-4b135401-a30c-4224-ae21-fa53a5bd253d'

    try
    {
		$actual = Get-AzureRmLog -ResourceId $rname -startTime 2015-03-03T15:42:50Z -endTime 2015-03-03T16:42:50Z

        # Assert TODO add more asserts
		# Assert-Throws { Set-AzureResourceGroup -Name $rgname -Tags @{"testtag" = "testval"} } "Invalid tag format. Expect @{Name = `"tagName`"} or @{Name = `"tagName`"; Value = `"tagValue`"}"
		Assert-AreEqual $actual.Count 2
    }
    finally
    {
        # Cleanup
        # No cleanup needed for now
    }
}

<#
.SYNOPSIS
Tests getting the logs associated to a resource provider.
#>
function Test-GetAzureResourceProviderLog
{
    # Setup
    $rpname = 'microsoft.insights'

    try
    {
		$actual = Get-AzureRmLog -ResourceProvider $rpname -startTime 2015-03-03T15:42:50Z -endTime 2015-03-03T16:42:50Z

        # Assert
		Assert-AreEqual $actual.Count 2
    }
    finally
    {
        # Cleanup
        # No cleanup needed for now
    }
}

<#
.SYNOPSIS
Tests getting the logs for a subscription Id.
#>
function Test-GetAzureSubscriptionIdLog
{
    # No Setup needed

    try
    {
        # Test
        $actual = Get-AzureRmLog -starttime 2015-01-15T12:30:00Z -endtime 2015-01-15T20:30:00Z

        # Assert
        Assert-AreEqual $actual.Count 1
    }
    finally
    {
        # Cleanup
        # No cleanup needed for now
    }
}


text:
<!DOCTYPE html>
<body>
  <script src=/resources/testharness.js></script>
  <script src=/resources/testharnessreport.js></script>
  <script src=/permissions-policy/resources/permissions-policy.js></script>
  <!-- Permissions-Policy: fullscreen=self wildcard_origin; -->
  <script>
  'use strict';
  var same_origin = 'https://{{domains[]}}:{{ports[https][0]}}';
  var wildcard_origin = 'https://*.{{domains[]}}:{{ports[https][0]}}';
  var cross_origin = 'https://{{domains[www]}}:{{ports[https][0]}}';
  var cross_origin1 = 'https://{{domains[www1]}}:{{ports[https][0]}}';
  var same_origin_src = '/permissions-policy/resources/permissions-policy-allowedfeatures.html';
  var cross_origin_src = cross_origin + same_origin_src;
  var cross_origin_src1 = cross_origin1 + same_origin_src;
  var header_policy = `Permissions-Policy: fullscreen=("${wildcard_origin}")`;

  // Test that fullscreen's allowlist is [self wildcard_origin].
  test(function() {
    assert_array_equals(
      document.featurePolicy.getAllowlistForFeature('fullscreen').sort(),
      [wildcard_origin, same_origin].sort());
  }, header_policy + ' -- test allowlist is [self wildcard_origin].');

  // Test that fullscreen is allowed on same-origin subframes with or without an allow attribute.
  test_allowed_feature_for_subframe(
    header_policy + ' -- test fullscreen is allowed on same-origin subframe',
    'fullscreen',
    same_origin_src);
  test_allowed_feature_for_subframe(
    header_policy + ' -- test fullscreen is allowed on same-origin subframe even with allow attribute',
    'fullscreen',
    same_origin_src,
    "fullscreen " + same_origin);

  // Test that fullscreen is disallowed on cross-origin subframes without an allow attribute.
  test_disallowed_feature_for_subframe(
    header_policy + ' -- test fullscreen is disallowed on cross-origin subframe',
    'fullscreen',
    cross_origin_src);
  test_allowed_feature_for_subframe(
    header_policy + ' -- test fullscreen is allowed on cross-origin subframe allow attribute',
    'fullscreen',
    cross_origin_src,
    "fullscreen " + cross_origin);
  test_disallowed_feature_for_subframe(
    header_policy + ' -- test fullscreen is disallowed on another cross-origin subframe',
    'fullscreen',
    cross_origin_src1);
  test_allowed_feature_for_subframe(
    header_policy + ' -- test fullscreen is allowed on another cross-origin subframe allow attribute',
    'fullscreen',
    cross_origin_src1,
    "fullscreen " + cross_origin1);

  // Test that wildcard allow attribute isn't supported.
  test_disallowed_feature_for_subframe(
    header_policy + ' -- test fullscreen is disallowed on cross-origin subframe with wildcard allow attribute',
    'fullscreen',
    cross_origin_src,
    "fullscreen " + wildcard_origin);
  test_disallowed_feature_for_subframe(
    header_policy + ' -- test fullscreen is disallowed on another cross-origin subframe with wildcard allow attribute',
    'fullscreen',
    cross_origin_src1,
    "fullscreen " + wildcard_origin);
  </script>
</body>


text:
#ifndef MODULES_AUDIO_CODING_AUDIO_NETWORK_ADAPTOR_CHANNEL_CONTROLLER_H_
#define MODULES_AUDIO_CODING_AUDIO_NETWORK_ADAPTOR_CHANNEL_CONTROLLER_H_

#include <stddef.h>

#include "absl/types/optional.h"
#include "modules/audio_coding/audio_network_adaptor/controller.h"
#include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
#include "rtc_base/constructor_magic.h"

namespace webrtc {

class ChannelController final : public Controller {
 public:
  struct Config {
    Config(size_t num_encoder_channels,
           size_t intial_channels_to_encode,
           int channel_1_to_2_bandwidth_bps,
           int channel_2_to_1_bandwidth_bps);
    size_t num_encoder_channels;
    size_t intial_channels_to_encode;
    // Uplink bandwidth above which the number of encoded channels should switch
    // from 1 to 2.
    int channel_1_to_2_bandwidth_bps;
    // Uplink bandwidth below which the number of encoded channels should switch
    // from 2 to 1.
    int channel_2_to_1_bandwidth_bps;
  };

  explicit ChannelController(const Config& config);

  ~ChannelController() override;

  void UpdateNetworkMetrics(const NetworkMetrics& network_metrics) override;

  void MakeDecision(AudioEncoderRuntimeConfig* config) override;

 private:
  const Config config_;
  size_t channels_to_encode_;
  absl::optional<int> uplink_bandwidth_bps_;
  RTC_DISALLOW_COPY_AND_ASSIGN(ChannelController);
};

}  // namespace webrtc

#endif  // MODULES_AUDIO_CODING_AUDIO_NETWORK_ADAPTOR_CHANNEL_CONTROLLER_H_