text:
package gridsim.parallel.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import gridsim.GridSim;
import gridsim.Gridlet;
import gridsim.net.Link;
import gridsim.parallel.log.LoggerEnum;
import gridsim.parallel.log.Logging;
import gridsim.util.Workload;

/**
 * This class is responsible for reading resource traces from a file and
 * creating a list of jobs.
 *

 * NOTE:
 *

 *
 This class can only take <tt>one</tt> trace file of the following
 *           format: ASCII text, zip, gz.
 *
 If you need to load multiple trace files, then you need to
 *      	 create multiple instances of this class <tt>each with a unique
 *      	 entity name</tt>.
 *
 If size of the trace file is huge or contains lots of traces
 *           please increase the JVM heap size accordingly by using
 *           <tt>java -Xmx</tt> option when running the simulation.
 *
 The default job file size for sending to and receiving from
 *           a resource is {@link gridsim.net.Link#DEFAULT_MTU}.
 *           However, you can specify
 *           the file size by using {@link #setGridletFileSize(int)}.
 *
 A job run time is only for 1 PE <tt>not</tt> the total number of
 *           allocated PEs. Therefore, a Gridlet length is also calculated
 *           for 1 PE.

 *           For example, job #1 in the trace has a run time of 100 seconds
 *           for 2 processors. This means each processor runs
 *           job #1 for 100 seconds, if the processors have the same
 *           specification.
 *

 *

 * By default, this class follows the standard workload format as specified
 * in
 * http://www.cs.huji.ac.il/labs/parallel/workload/

 * However, you can use other format by calling the below methods before
 * running the simulation:
 *

 *
 {@link #setComment(String)}
 *
 {@link #setField(int, int, int, int, int)}
 *

 *
 * @author   Anthony Sulistio and Marcos Dias de Assuncao
 * @since    5.0
 *
 * @see Workload
 */
public class WorkloadFileReader implements WorkloadModel {
	private static Logger logger = Logging.getLogger(LoggerEnum.PARALLEL);

    private String fileName;   			// file name
    private int rating;        			// a PE rating
    private int size = Link.DEFAULT_MTU;  	// job size for sending it through a network
    private ArrayList<WorkloadJob> jobs = null;  // a list for getting all the Gridlets

    // using Standard Workload Format
    private int JOB_NUM = 1 - 1;        // job number
    private int SUBMIT_TIME = 2 - 1;    // submit time of a Gridlet
    private int RUN_TIME = 4 - 1;       // running time of a Gridlet
    private int NUM_PROC = 5 - 1;       // number of processors needed for a Gridlet
    private int REQ_NUM_PROC = 8 - 1;   // required number of processors
    private int REQ_RUN_TIME = 9 - 1;   // required running time
    private int MAX_FIELD = 18;      	// max number of field in the trace file
    private String COMMENT = ";";     	// a string that denotes the start of a comment
    private static final int IRRELEVANT = -1;  // irrelevant number
    private String[] fieldArray = null;       // a temp array storing all the fields

    /**
     * Create a new {@link WorkloadFileReader} object.
     * @param fileName  the workload trace filename in one of the following
     *                  format: ASCII text, zip, gz.
     * @param rating    the resource's PE rating
     * @throws IllegalArgumentException This happens for the following conditions:
     *

     *
the workload trace file name is null or empty
     *
the resource PE rating <= 0
     *

     * @pre fileName != null
     * @pre rating > 0
     * @post $none
     */
    public WorkloadFileReader(String fileName, int rating) {
        if (fileName == null || fileName.length() == 0) {
            throw new IllegalArgumentException("Invalid trace file name.");
        }
        else if (rating <= 0) {
            throw new IllegalArgumentException("Resource PE rating must be > 0.");
        }

        this.fileName = fileName;
        this.rating = rating;
    }

    /**
     * Sets a Gridlet file size (in byte) for sending to/from a resource.
     * @param size  a Gridlet file size (in byte)
     * @return true if it is successful, false otherwise
     * @pre size > 0
     * @post $none
     */
    public boolean setGridletFileSize(int size) {
        if (size < 0) {
            return false;
        }

        this.size = size;
        return true;
    }

    /**
     * Identifies the start of a comment line.
     * @param cmt  a character that denotes the start of a comment, e.g. ";" or "#"
     * @return true if it is successful, false otherwise
     * @pre comment != null
     * @post $none
     */
    public boolean setComment(String cmt) {
        boolean success = false;
        if (cmt != null && cmt.length() > 0) {
            COMMENT = cmt;
            success = true;
        }
        return success;
    }

    /**
     * Tells this class what to look in the trace file.
     * This method should be called before the start of the simulation.
     *

     * By default, this class follows the standard workload format as specified
     * in
     * http://www.cs.huji.ac.il/labs/parallel/workload/

     * However, you can use other format by calling this method.
     *

     * The parameters must be a positive integer number starting from 1.
     * A special case is where <tt>jobNum == -1</tt>, meaning the job or
     * gridlet ID starts at 1.
     *
     * @param maxField  max. number of field/column in one row
     * @param jobNum    field/column number for locating the job ID
     * @param submitTime   field/column number for locating the job submit time
     * @param runTime   field/column number for locating the job run time
     * @param numProc   field/column number for locating the number of PEs
     *                  required to run a job
     * @return true if successful, false otherwise
     * @throws IllegalArgumentException if any of the arguments are not
     * within the acceptable ranges
     * @pre maxField > 0
     * @pre submitTime > 0
     * @pre runTime > 0
     * @pre numProc > 0
     * @post $none
     */
    public boolean setField(int maxField, int jobNum, int submitTime,
                            int runTime, int numProc) {
        // need to subtract by 1 since array starts at 0.
        if (jobNum > 0) {
            JOB_NUM = jobNum - 1;
        } else if (jobNum == 0) {
        	throw new IllegalArgumentException("Invalid job number field.");
        } else {
            JOB_NUM = -1;
        }

        // get the max. number of field
        if (maxField > 0) {
            MAX_FIELD = maxField;
        } else {
        	throw new IllegalArgumentException("Invalid max. number of field.");
        }

        // get the submit time field
        if (submitTime > 0) {
            SUBMIT_TIME = submitTime - 1;
        } else {
        	throw new IllegalArgumentException("Invalid submit time field.");
        }

        // get the run time field
        if (runTime > 0) {
            REQ_RUN_TIME = runTime - 1;
        } else {
        	throw new IllegalArgumentException("Invalid run time field.");
        }

        // get the number of processors field
        if (numProc > 0) {
            REQ_NUM_PROC = numProc - 1;
        } else {
        	throw new IllegalArgumentException("Invalid number of processors field.");
        }

        return true;
    }

    /**
     * Reads job information from a given file.
     * @return the list of gridlets read from the file; null
     * in case of failure.
     */
    public ArrayList<WorkloadJob> generateWorkload() {
    	if(jobs == null) {
	        jobs = new ArrayList<WorkloadJob>();

	        // create a temp array
	        fieldArray = new String[MAX_FIELD];

	        try {
		        if (fileName.endsWith(".gz")) {
		        	readGZIPFile(fileName);
		        }
		        else if (fileName.endsWith(".zip")) {
		            readZipFile(fileName);
		        }
		        else {
		            readFile(fileName);
		        }
			} catch (FileNotFoundException e) {
				logger.log(Level.SEVERE, "File not found", e);
			} catch (IOException e) {
				logger.log(Level.SEVERE, "Error reading file", e);
			}
    	}

        return jobs;
    }

    //------------------- PRIVATE METHODS -------------------

    /**
     * Breaks a line of string into many fields.
     * @param line  a line of string
     * @param lineNum   a line number
     * @pre line != null
     * @pre lineNum > 0
     * @post $none
     */
    private void parseValue(String line, int lineNum) {
        // skip a comment line
        if (line.startsWith(COMMENT)) {
            return;
        }

        String[] sp = line.split("\\s+");  // split the fields based on a space
        int len = 0;        // length of a string
        int index = 0;      // the index of an array

        // check for each field in the array
        for(String elem : sp) {
            len = elem.length();  // get the length of a string

            // if it is empty then ignore
            if (len == 0) {
                continue;
            }
            // if not, then put into the array
            else {
                fieldArray[index] = elem;
                index++;
            }
        }

        if (index == MAX_FIELD) {
            extractField(fieldArray, lineNum);
        }
    }

    /**
     * Extracts relevant information from a given array
     * @param array  an array of String
     * @param line   a line number
     * @pre array != null
     * @pre line > 0
     */
    private void extractField(String[] array, int line) {
        try {
            Integer obj = null;

            // get the job number
            int id = 0;
            if (JOB_NUM == IRRELEVANT) {
                id = jobs.size() + 1;
            }
            else {
                obj = new Integer( array[JOB_NUM].trim() );
                id = obj.intValue();
            }

            // get the submit time
            Long l = new Long( array[SUBMIT_TIME].trim() );
            long submitTime = l.intValue();

            // get the run time
            obj = new Integer( array[REQ_RUN_TIME].trim() );
            int runTime = obj.intValue();

            // if the required run time field is ignored, then use
            // the actual run time
            if (runTime == IRRELEVANT) {
                obj = new Integer( array[RUN_TIME].trim() );
                runTime = obj.intValue();
            }

            // according to the SWF manual, runtime of 0 is possible due
            // to rounding down. E.g. runtime is 0.4 seconds -> runtime = 0
            if (runTime == 0) {
                runTime = 1;    // change to 1 second
            }

            // get the number of allocated processors
            obj = new Integer( array[REQ_NUM_PROC].trim() );
            int numProc = obj.intValue();

            // if the required num of allocated processors field is ignored
            // or zero, then use the actual field
            if (numProc == IRRELEVANT || numProc == 0) {
                obj = new Integer( array[NUM_PROC].trim() );
                numProc = obj.intValue();
            }

            // finally, check if the num of PEs required is valid or not
            if (numProc <= 0) {
            	logger.info("Job #" + id + " at line " + line + " requires " +
            			numProc + " CPU. Change to 1 CPU.");
                numProc = 1;
            }

            createGridlet(id, submitTime, runTime, numProc);
        }
        catch (Exception e) {
        	logger.log(Level.WARNING, "Exception reading file at line #" + line, e);
        }
    }

    /**
     * Creates a Gridlet with the given information and adds to the list
     * @param id  a Gridlet ID
     * @param submitTime  Gridlet's submit time
     * @param runTime     Gridlet's run time
     * @param numProc     number of processors
     * @pre id >= 0
     * @pre submitTime >= 0
     * @pre runTime >= 0
     * @pre numProc > 0
     * @post $none
     */
    private void createGridlet(int id, long submitTime, int runTime, int numProc) {
        // create the gridlet
        int len = runTime * rating;      // calculate a job length for each PE
        Gridlet gl = new Gridlet(id, len, size, size, GridSim.isTraceEnabled());
        gl.setNumPE(numProc);             // set the requested num of proc

        // check the submit time
        if (submitTime < 0) {
            submitTime = 0L;
        }

        WorkloadJob wgl = new WorkloadJob(gl, submitTime);
        jobs.add(wgl);
    }

    /**
     * Reads a text file one line at the time
     * @param flName a file name
     * @return true if successful, false otherwise.
     * @throws IOException if the there was any error reading the file
     * @throws FileNotFoundException if the file was not found
     */
    private boolean readFile(String flName) throws IOException, FileNotFoundException {
        boolean success = false;
        BufferedReader reader = null;
        try {
            FileInputStream file = new FileInputStream(flName);
            reader = new BufferedReader(new InputStreamReader(file));

            // read one line at the time
            int line = 1;
            while (reader.ready()) {
                parseValue(reader.readLine(), line);
                line++;
            }

            reader.close();
            success = true;
        } finally {
            if (reader != null) {
            	reader.close();
            }
        }

        return success;
    }

    /**
     * Reads a gzip file one line at the time
     * @param flName   a gzip file name
     * @return true if successful; false otherwise.
     * @throws IOException if the there was any error reading the file
     * @throws FileNotFoundException if the file was not found
     */
    private boolean readGZIPFile(String flName)
    					throws IOException, FileNotFoundException {
        boolean success = false;
        BufferedReader reader = null;
        try {
            FileInputStream file = new FileInputStream(flName);
            GZIPInputStream gz =  new GZIPInputStream(file);
            reader = new BufferedReader(new InputStreamReader(gz));

            // read one line at the time
            int line = 1;
            while (reader.ready()) {
                parseValue(reader.readLine(), line);
                line++;
            }

            reader.close();
            success = true;
        } finally {
            if (reader != null) {
            	reader.close();
            }
        }

        return success;
    }

    /**
     * Reads a Zip file.
     * @param flName a zip file name
     * @return true if reading a file is successful;
     * false otherwise.
     * @throws IOException if the there was any error reading the file
     */
    private boolean readZipFile(String flName) throws IOException {
        boolean success = false;
        ZipFile zipFile = null;
        try {
            BufferedReader reader = null;

            // ZipFile offers an Enumeration of all the files in the file
            zipFile = new ZipFile(flName);
            Enumeration<? extends ZipEntry> e = zipFile.entries();
            while (e.hasMoreElements()) {
                success = false;    // reset the value again
                ZipEntry zipEntry = e.nextElement();

                reader = new BufferedReader(
                		new InputStreamReader(zipFile.getInputStream(zipEntry)));

                // read one line at the time
                int line = 1;
                while (reader.ready()) {
                    parseValue(reader.readLine(), line);
                    line++;
                }

                reader.close();
                success = true;
            }
        } finally {
            if (zipFile != null) {
            	zipFile.close();
            }
        }

        return success;
    }
}


text:
'''
Helper functions for string related operation
'''

def cmd_str2dic(cmd_str):
    words = cmd_str.split()
    rst = {}
    if len(words) >= 1:
        begin = 0;
        if words[0][0:1] != '-':                # the first one could be the the name of the command
            rst['cmd_name'] = words[0]
            begin = 1
        curr_word = '...'                       # default parameter
        quoted = False
        curly_braced = False
        for word in words[begin:]:
            if quoted:                          # expecting the reverse double quote
                if word.endswith('"'):
                    quoted = False
                    word = word[:-1]
            elif curly_braced:                  # expecting the reverse curly brace
                if word.endswith('}'):
                    curly_braced = False
            else:
                if word[0:1]=='-':              # a new parameter
                    curr_word = word
                    rst[curr_word] = ''
                    continue
                if word.startswith('"'):        # meet double quote
                    if word.endswith('"'):
                        word = word[1:-1]
                    else:
                        quoted = True
                        word = word[1:]
                elif word.startswith('{'):      # meet curly brace
                    if not word.endswith('}'):
                        curly_braced = True
                                                # append to current parameter
            if len(rst[curr_word]) == 0:        # first value
                rst[curr_word] += word
            else:                               # following value, add a space
                rst[curr_word] += ' '+word
    return rst

redpajama_set_name: RedPajamaGithub


text:
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var ShootR;
(function (ShootR) {
    var ShipMovementController = (function (_super) {
        __extends(ShipMovementController, _super);
        function ShipMovementController(movables) {
            _super.call(this, movables);

            this._moveables = movables;

            this.Mass = ShipMovementController.MASS;
            this.Power = ShipMovementController.ENGINE_POWER;
            this.Forces = eg.Vector2d.Zero;
            this.Controllable = true;
            this._acceleration = eg.Vector2d.Zero;

            this.Moving = {
                Forward: false,
                Backward: false,
                RotatingLeft: false,
                RotatingRight: false
            };

            this._interpolationManager = new ShootR.ShipInterpolationManager(this);

            this.OnMove = new eg.EventHandler1();
        }
        ShipMovementController.prototype.LoadPayload = function (payload, forceMovement) {
            if (!forceMovement) {
                this._interpolationManager.LoadPayload(payload);
            } else {
                this.Position = payload.Position;
                this.Rotation = payload.Rotation;
            }

            if (!this.UserControlled || forceMovement) {
                this.Mass = payload.Mass;
                this.Forces = payload.Forces;
                this.Velocity = payload.Velocity;
                this.Moving = payload.Moving;
            }
        };

        ShipMovementController.prototype.IsMovingInDirection = function (direction) {
            return this.Moving[direction] || false;
        };

        ShipMovementController.prototype.StartMoving = function (direction) {
            this.Move(direction, true);
        };

        ShipMovementController.prototype.StopMoving = function (direction) {
            this.Move(direction, false);
        };

        ShipMovementController.prototype.StopAllMovement = function () {
            for (var i = ShipMovementController.MOVING_DIRECTIONS.length - 1; i >= 0; i--) {
                this.Moving[ShipMovementController.MOVING_DIRECTIONS[i]] = false;
            }
        };

        ShipMovementController.prototype.ApplyForce = function (force) {
            this.Forces = this.Forces.Add(force);
        };

        ShipMovementController.prototype.Update = function (gameTime) {
            var rotationIncrementor, direction = new eg.Vector2d(Math.cos(this.Rotation), Math.sin(this.Rotation)), dragForce, velocityLength;

            this._interpolationManager.Update(gameTime);

            if (!this._interpolationManager.Interpolating) {
                this._acceleration = this.Forces.Divide(this.Mass);

                this.Position = this.Position.Add(this.Velocity.Multiply(gameTime.Elapsed.Seconds).Add(this._acceleration.Multiply(gameTime.Elapsed.Seconds * gameTime.Elapsed.Seconds)));
                this.Velocity = this.Velocity.Add(this._acceleration.Multiply(gameTime.Elapsed.Seconds));
                velocityLength = this.Velocity.Length();

                if (velocityLength < 10) {
                    this.Velocity = eg.Vector2d.Zero;
                } else if (velocityLength > 3000) {
                    this.Velocity = direction.Multiply(600);
                }

                this._acceleration = eg.Vector2d.Zero;
                this.Forces = eg.Vector2d.Zero;

                dragForce = this.Velocity.Multiply(.5).Multiply(this.Velocity.Abs()).Multiply(ShipMovementController.DRAG_COEFFICIENT * ShipMovementController.DRAG_AREA * -1);

                if (this.Moving.Forward) {
                    this.ApplyForce(direction.Multiply(this.Power));
                }
                if (this.Moving.Backward) {
                    this.ApplyForce(direction.Multiply(this.Power * -1));
                }

                this.ApplyForce(dragForce);

                rotationIncrementor = gameTime.Elapsed.Seconds * ShipMovementController.ROTATE_SPEED;

                if (this.Moving.RotatingLeft) {
                    this.Rotation -= rotationIncrementor;
                }
                if (this.Moving.RotatingRight) {
                    this.Rotation += rotationIncrementor;
                }
            }

            for (var i = 0; i < this._moveables.length; i++) {
                this._moveables[i].Position = this.Position;
            }
        };

        ShipMovementController.prototype.Move = function (direction, startMoving) {
            if (this.Controllable) {
                if (typeof this.Moving[direction] !== "undefined") {
                    this.Moving[direction] = startMoving;
                    this.OnMove.Trigger({
                        Direction: direction,
                        StartMoving: startMoving
                    });
                } else {
                    throw new Error(direction + " is an unknown direction.");
                }
            }
        };

        ShipMovementController.prototype.Dispose = function () {
            // Make all active functions no-op
            this.Update = function () {
            };
            this.LoadPayload = function () {
            };
        };
        ShipMovementController.MASS = 50;
        ShipMovementController.ENGINE_POWER = 110000;
        ShipMovementController.DRAG_AREA = 5;
        ShipMovementController.DRAG_COEFFICIENT = .2;
        ShipMovementController.ROTATE_SPEED = Math.PI;
        ShipMovementController.MOVING_DIRECTIONS = ["RotatingLeft", "RotatingRight", "Forward", "Backward"];
        return ShipMovementController;
    })(eg.MovementControllers.MovementController);
    ShootR.ShipMovementController = ShipMovementController;
})(ShootR || (ShootR = {}));
//# sourceMappingURL=ShipMovementController.js.map


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

namespace MMDB.Azure.Management.AzureDto.AzureStorage
{
    public class StorageServiceKeys
    {
        public string Primary { get; set; }
        public string Secondary { get; set; }
    }
}


text:
This explores the idea that iron-ajax could be extended to support server-side
preloading of data. This project contains two ideas:

1. sample-ajax: a simple fork of the iron-ajax component that can support
loading data from its light DOM children. When instantiated, if the component's
`preloaded` attribute is set, it will read its own textContent and process that
as if text were a server response.
2. A simple web server helper called componentDataPreloader. Given an HTML file
that's about to be served (e.g., by Express), this searches for components that
have a `preload="..."` attribute set. If any such components are found, the
preload attribute is taken to be the name of *another* attribute specifying a
URL. That URL will be fetched by the server, and the results spliced into the
HTML content before serving. The component's `preload` attribute will be
replaced with a `preloaded` attribute that triggers the loading behavior
described above.

Significantly, the preloading convention is general, and not specific to a
single type of component like iron-ajax. As long as the component exposes the
URL it will fetch data from as an attribute, the server can preload that data
at that URL.

# Running the demo

* Run `node server/app.js`.
* Open localhost:8000.
* By default, server data is preloaded in the sample-ajax component. In the
  debugger's Network tab, note that the page loads 13 resources. The page source
  will show JSON embedded in the HTML.
* If you remove `preload="url"` from the sample-ajax instance in index.html,
  the component will make a separate request to fetch data in the normal way.
  The page will now load 14 resources.


text:
#include "gui/input/scroll.h++"

namespace skui::gui::input
{
  std::ostream& operator<<(std::ostream& os, scroll scroll)
  {
    switch(scroll)
    {
      case input::scroll::down:
        return os << "down";
      case input::scroll::up:
        return os << "up";
      case input::scroll::left:
        return os << "left";
      case input::scroll::right:
        return os << "right";
      default:
        throw 42;
    }
  }
}


text:
package internal

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"path"
	"time"

	"github.com/onsi/gomega/gbytes"
	"github.com/onsi/gomega/gexec"

	"sigs.k8s.io/testing_frameworks/integration/addr"
)

type ProcessState struct {
	DefaultedProcessInput
	Session *gexec.Session
	// Healthcheck Endpoint. If we get http.StatusOK from this endpoint, we
	// assume the process is ready to operate. E.g. "/healthz". If this is set,
	// we ignore StartMessage.
	HealthCheckEndpoint string
	// HealthCheckPollInterval is the interval which will be used for polling the
	// HealthCheckEndpoint.
	// If left empty it will default to 100 Milliseconds.
	HealthCheckPollInterval time.Duration
	// StartMessage is the message to wait for on stderr. If we recieve this
	// message, we assume the process is ready to operate. Ignored if
	// HealthCheckEndpoint is specified.
	//
	// The usage of StartMessage is discouraged, favour HealthCheckEndpoint
	// instead!
	//
	// Deprecated: Use HealthCheckEndpoint in favour of StartMessage
	StartMessage string
	Args         []string
}

type DefaultedProcessInput struct {
	URL              url.URL
	Dir              string
	DirNeedsCleaning bool
	Path             string
	StopTimeout      time.Duration
	StartTimeout     time.Duration
}

func DoDefaulting(
	name string,
	listenUrl *url.URL,
	dir string,
	path string,
	startTimeout time.Duration,
	stopTimeout time.Duration,
) (DefaultedProcessInput, error) {
	defaults := DefaultedProcessInput{
		Dir:          dir,
		Path:         path,
		StartTimeout: startTimeout,
		StopTimeout:  stopTimeout,
	}

	if listenUrl == nil {
		port, host, err := addr.Suggest()
		if err != nil {
			return DefaultedProcessInput{}, err
		}
		defaults.URL = url.URL{
			Scheme: "http",
			Host:   fmt.Sprintf("%s:%d", host, port),
		}
	} else {
		defaults.URL = *listenUrl
	}

	if dir == "" {
		newDir, err := ioutil.TempDir("", "k8s_test_framework_")
		if err != nil {
			return DefaultedProcessInput{}, err
		}
		defaults.Dir = newDir
		defaults.DirNeedsCleaning = true
	}

	if path == "" {
		if name == "" {
			return DefaultedProcessInput{}, fmt.Errorf("must have at least one of name or path")
		}
		defaults.Path = BinPathFinder(name)
	}

	if startTimeout == 0 {
		defaults.StartTimeout = 20 * time.Second
	}

	if stopTimeout == 0 {
		defaults.StopTimeout = 20 * time.Second
	}

	return defaults, nil
}

type stopChannel chan struct{}

func (ps *ProcessState) Start(stdout, stderr io.Writer) (err error) {
	command := exec.Command(ps.Path, ps.Args...)

	ready := make(chan bool)
	timedOut := time.After(ps.StartTimeout)
	var pollerStopCh stopChannel

	if ps.HealthCheckEndpoint != "" {
		healthCheckURL := ps.URL
		healthCheckURL.Path = ps.HealthCheckEndpoint
		pollerStopCh = make(stopChannel)
		go pollURLUntilOK(healthCheckURL, ps.HealthCheckPollInterval, ready, pollerStopCh)
	} else {
		startDetectStream := gbytes.NewBuffer()
		ready = startDetectStream.Detect(ps.StartMessage)
		stderr = safeMultiWriter(stderr, startDetectStream)
	}

	ps.Session, err = gexec.Start(command, stdout, stderr)
	if err != nil {
		return err
	}

	select {
	case <-ready:
		return nil
	case <-timedOut:
		if pollerStopCh != nil {
			close(pollerStopCh)
		}
		if ps.Session != nil {
			ps.Session.Terminate()
		}
		return fmt.Errorf("timeout waiting for process %s to start", path.Base(ps.Path))
	}
}

func safeMultiWriter(writers ...io.Writer) io.Writer {
	safeWriters := []io.Writer{}
	for _, w := range writers {
		if w != nil {
			safeWriters = append(safeWriters, w)
		}
	}
	return io.MultiWriter(safeWriters...)
}

func pollURLUntilOK(url url.URL, interval time.Duration, ready chan bool, stopCh stopChannel) {
	if interval <= 0 {
		interval = 100 * time.Millisecond
	}
	for {
		res, err := http.Get(url.String())
		if err == nil && res.StatusCode == http.StatusOK {
			ready <- true
			return
		}

		select {
		case <-stopCh:
			return
		default:
			time.Sleep(interval)
		}
	}
}

func (ps *ProcessState) Stop() error {
	if ps.Session == nil {
		return nil
	}

	// gexec's Session methods (Signal, Kill, ...) do not check if the Process is
	// nil, so we are doing this here for now.
	// This should probably be fixed in gexec.
	if ps.Session.Command.Process == nil {
		return nil
	}

	detectedStop := ps.Session.Terminate().Exited
	timedOut := time.After(ps.StopTimeout)

	select {
	case <-detectedStop:
		break
	case <-timedOut:
		return fmt.Errorf("timeout waiting for process %s to stop", path.Base(ps.Path))
	}

	if ps.DirNeedsCleaning {
		return os.RemoveAll(ps.Dir)
	}

	return nil
}


text:
from pyspark.ml import pipeline

# feature engineering
from pyspark.ml.stat import  ChiSquareTest,Correlation
from pyspark.ml.feature import VectorIndexer,StandardScaler,StringIndexer,VectorIndexer,IndexToString

# performance tuning
from pyspark.ml.tuning import CrossValidator,TrainValidationSplit

# modeling
from pyspark.ml.classification import RandomForestClassifier
from pyspark.ml.regression import RandomForestRegressor

# evaluation
from pyspark.ml.evaluation import RegressionEvaluator,BinaryClassificationEvaluator

# spark
from pyspark import SparkContext,SparkConf
from pyspark.sql import Row
from pyspark.ml.linalg import Vector,Vectors
import re
import os

from pyspark.sql import SparkSession

from pyspark.mllib.util import MLUtils

def f(x):
    rel = {}
    rel['features'] = Vectors.dense(Vectors.dense(float(x[0]),float(x[1]),float(x[2]),float(x[3])))
    rel['label'] =str(x[6])
    return rel

conf = SparkConf().setAppName("churn").setMaster("local")
sc = SparkContext(conf=conf)
# data =sc.textFile("/Users/qiudebo/PycharmProjects/stanford_cs231/sklearn_example/data/churn.csv").\
#     map(lambda line:line.split(","))
#
spark = SparkSession.builder.\
    appName("Python Spark SQL basic adult")\
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()

data_path=['/Users/qiudebo/PycharmProjects/stanford_cs231/sklearn_example/data']
fileName=["churn.csv"]

filepath = os.sep.join(data_path+fileName)

# data = spark.sparkContext.textFile(filepath).\
#     map(lambda line:line.split(","))
#
# df = spark.read.text(filepath)
# # df = spark.read.text(filepath, wholetext=True)
# df.printSchema()
#
# df2 = spark.read.load(filepath,format="csv", sep=":", inferSchema="true", header="true")
# print(df.dtypes)

# rdd = sc.textFile(filepath)
# df2 = spark.read.csv(rdd)
# print(df2.dtypes)

df3 = spark.read.csv(filepath,header=True)
print("df3:", df3.dtypes)
print(df3.columns)
print(df3.select("_c0").count())

df3.createOrReplaceTempView("churn")
df3.drop("_c0")
# results = spark.sql("ALTER TABLE churn DROP COLUMN _c0")
results = spark.sql("select * from churn limit 10")
results = results.drop("_c0")

print("results:",results.show())
print(results.distinct().count())

print(results.columns)
print(results.dtypes)
# print(results.corr(results.select('start_times'),results.select('is_churn')))
label = results.select("is_churn")
features = results.drop("is_churn")
print("label:", label)
print("features:", label.count())
label.index

# 分别获取标签列和特征列,进行索引,并进行了重命名。
labelIndexer = StringIndexer().setInputCol("label").setOutputCol("indexedLabel").fit(label)

featureIndexer = VectorIndexer().setInputCol("features").setOutputCol("indexedFeatures").fit(features)

# 这里我们设置一个labelConverter,目的是把预测的类别重新转化成字符型的。
labelConverter = IndexToString().setInputCol("prediction").setOutputCol("predictedLabel").setLabels(labelIndexer.labels)

trainingData, testData = data.randomSplit([0.7, 0.3])

#
# (trainingData, testData)=results.randomSplit([0.7,0.3])
#
# rf = RandomForestClassifier(numTrees=500, maxDepth=4, seed=42)
# RandomForestClassifier(featuresCol='features', labelCol='label',
#                        predictionCol='prediction', probabilityCol='probability', rawPredictionCol='rawPrediction',
#                        maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
#                        maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity='gini',
#                        numTrees=500, featureSubsetStrategy='auto', seed=None, subsamplingRate=1.0)
#
# model=rf.fit(trainingData)
#
# temp_path = "./"
# model_path = temp_path + "/rfr"
# model.save(model_path)
# rf2 = RandomForestClassifier.load(model_path)
# ret = model.transform(testData)
# ret.prediction
# ret.probability
# ret.rawPrediction
#

spark.stop()


text:
/*
 * Created on Mar 1, 2007
 *
 * TODO
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package edu.psu.compbio.seqcode.gse.utils.xml;

import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Vector;

public class XMLTreeElement {

    private static final String istr = "  ";

    public XMLTreeElement parent;
    public String name;
    public Map<String,String> values;
    public String content;

    public Vector<XMLTreeElement> children;

    public XMLTreeElement(String n, XMLTreeElement p) {
        parent = p;
        name = n;
        values = new LinkedHashMap<String,String>();
        content = null;
        children = new Vector<XMLTreeElement>();

        if(parent != null) { parent.children.add(this); }
    }

    public LinkedList<XMLTreeElement> collectElements(String n) {
        LinkedList<XMLTreeElement> elmts = new LinkedList<XMLTreeElement>();
        gatherElements(n, elmts);
        return elmts;
    }

    private void gatherElements(String n, LinkedList<XMLTreeElement> elmts) {
        if(name.equals(n)) { elmts.addLast(this); }
        for(XMLTreeElement child : children) { child.gatherElements(n, elmts); }
    }

    public void printTree(PrintStream ps) {
        printTree(ps, 0);
    }

    private void printTree(PrintStream ps, int indent) {
        StringBuilder idb = new StringBuilder();
        for(int i = 0; i < indent; i++) { idb.append(istr); }
        String indentStr = idb.toString();

        ps.println(indentStr + name + " {" + content + "} --> " + children.size() + " children.");
        for(String key : values.keySet()) {
            ps.println(indentStr + istr + key + "=>\"" + values.get(key) + "\"");
        }
        for(int i = 0; i < children.size(); i++) {
            children.get(i).printTree(ps, indent+1);
        }
    }
}


text:
layout: page
subheadline:  ""
title: "香芋蕃薯焖鹅"
teaser:  ""
breadcrumb: true
category: MenuCuisine/all
permalink: /MenuCuisine/all/xiangyufanshumene/
---

{% include cuisine-template.html item=site.data.goose.xiangyufanshumene %}


text: <!DOCTYPE html>


text:
'use strict';

var express = require('express');
var braintree = require('braintree');
var router = express.Router(); // eslint-disable-line new-cap
var gateway = require('../lib/gateway');
var db = require('../lib/firebasedb');
var moment = require('moment');

var TRANSACTION_SUCCESS_STATUSES = [
  braintree.Transaction.Status.Authorizing,
  braintree.Transaction.Status.Authorized,
  braintree.Transaction.Status.Settled,
  braintree.Transaction.Status.Settling,
  braintree.Transaction.Status.SettlementConfirmed,
  braintree.Transaction.Status.SettlementPending,
  braintree.Transaction.Status.SubmittedForSettlement
];

function formatErrors(errors) {
  var formattedErrors = '';

  for (var i in errors) { // eslint-disable-line no-inner-declarations, vars-on-top
    if (errors.hasOwnProperty(i)) {
      formattedErrors += 'Error: ' + errors[i].code + ': ' + errors[i].message + '\n';
    }
  }
  return formattedErrors;
}

function createResultObject(transaction) {
  var result;
  var status = transaction !== null ?transaction.status : -1;

  if (TRANSACTION_SUCCESS_STATUSES.indexOf(status) !== -1) {
    result = {
      header: 'Sweet Success!',
      icon: 'success',
      message: 'Your test transaction has been successfully processed. See the Braintree API response and try again.'
    };
  } else {
    result = {
      header: 'Transaction Failed',
      icon: 'fail',
      message: 'Your test transaction has a status of ' + status + '. See the Braintree API response and try again.'
    };
  }

  return result;
}

router.get('/', function (req, res) {
  res.redirect('/checkouts/landing');
});
router.get('/checkouts/landing', function(req,res){
  var ref = db.ref("/");
    ref.on("value", function(snapshot) {
        res.render('checkouts/landing', {totalamount : snapshot.val().totalamount , users: snapshot.val().Users});
      }, function (errorObject) {
        console.log("The read failed: " + errorObject.code);
      });
})

router.get('/checkouts/new', function (req, res) {
  gateway.clientToken.generate({}, function (err, response) {
    var totalamount = db.ref("/totalamount");
    totalamount.on("value", function(snapshot) {
        res.render('checkouts/new', {clientToken: response.clientToken, totalamount : snapshot.val(), messages: req.flash('error')});
      }, function (errorObject) {
        console.log("The read failed: " + errorObject.code);
      });

  });
});

router.get('/checkouts/:id', function (req, res) {
  var result;
  var transactionId = req.params.id;

  gateway.transaction.find(transactionId, function (err, transaction) {
    result = createResultObject(transaction);
    res.render('checkouts/show', {transaction: transaction, result: result});
  });
});

router.post('/checkouts', function (req, res) {
  var transactionErrors;
  var amount = req.body.amount; // In production you should not take amounts directly from clients
  var nonce = req.body.payment_method_nonce;
  var fn = req.body.fullName;
  var email = req.body.email;
  gateway.transaction.sale({
    amount: amount,
    paymentMethodNonce: nonce,
    customer: {
    firstName : fn,
    email : email
    },
    options: {
      storeInVaultOnSuccess: true
    }
  }, function (err, result) {
    if (result.success || result.transaction) {
      var totalamount = db.ref("/totalamount");
      totalamount.transaction(function (current_value) {
        return (current_value || 0) + parseInt(req.body.amount);
      });
      var userref = db.ref('/Users');
      var newuserref = userref.push();
      var date = moment(new Date()).format('DD/MM/YYYY MM:HH A');
      console.log(date);
      newuserref.set({name:req.body.fullName , email: req.body.email,amount : req.body.amount , time: date})
      res.redirect('checkouts/' + result.transaction.id);
    } else {
      transactionErrors = result.errors.deepErrors();
      req.flash('error', {msg: formatErrors(transactionErrors)});
      res.redirect('checkouts/new');
    }
  });
});

module.exports = router;


text:
Template.superhighSaturatedFatPercentFood.helpers({
	'superhighSaturatedFatPercentFood': function () {
	  return Foods.find(
	      {totalFatPercentDVQuotient: {$gt: 1.5}},
	      {sort: {totalFatPercentDVQuotient: -1}}
	      );
	},
});


text:
/*
    Python3 definition file to consistently map the code to Python 2.6 or
    Python 3.

    PyInt and PyLong were merged into PyLong in Python 3, so all PyInt functions
    are mapped to PyLong.

    PyString, on the other hand, was split into PyBytes and PyUnicode. We map
    both back onto PyString, so use PyBytes or PyUnicode where appropriate. The
    only exception to this is _imagingft.c, where PyUnicode is left alone.
*/

#if PY_VERSION_HEX >= 0x03000000
#define PY_ARG_BYTES_LENGTH             "y#"

/* Map PyInt -> PyLong */
#define PyInt_AsLong                PyLong_AsLong
#define PyInt_Check                 PyLong_Check
#define PyInt_FromLong              PyLong_FromLong
#define PyInt_AS_LONG               PyLong_AS_LONG
#define PyInt_FromSsize_t           PyLong_FromSsize_t

#else   /* PY_VERSION_HEX < 0x03000000 */
#define PY_ARG_BYTES_LENGTH             "s#"

#if !defined(KEEP_PY_UNICODE)
/* Map PyUnicode -> PyString */
#undef PyUnicode_AsString
#undef PyUnicode_AS_STRING
#undef PyUnicode_Check
#undef PyUnicode_FromStringAndSize
#undef PyUnicode_FromString
#undef PyUnicode_FromFormat
#undef PyUnicode_DecodeFSDefault

#define PyUnicode_AsString          PyString_AsString
#define PyUnicode_AS_STRING         PyString_AS_STRING
#define PyUnicode_Check             PyString_Check
#define PyUnicode_FromStringAndSize PyString_FromStringAndSize
#define PyUnicode_FromString        PyString_FromString
#define PyUnicode_FromFormat        PyString_FromFormat
#define PyUnicode_DecodeFSDefault   PyString_FromString
#endif

/* Map PyBytes -> PyString */
#define PyBytesObject               PyStringObject
#define PyBytes_AsString            PyString_AsString
#define PyBytes_AS_STRING           PyString_AS_STRING
#define PyBytes_Check               PyString_Check
#define PyBytes_AsStringAndSize     PyString_AsStringAndSize
#define PyBytes_FromStringAndSize   PyString_FromStringAndSize
#define PyBytes_FromString          PyString_FromString
#define _PyBytes_Resize             _PyString_Resize

#endif  /* PY_VERSION_HEX < 0x03000000 */


text:
<!doctype html>
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE
The complete set of authors may be found at http://polymer.github.io/AUTHORS
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS
-->
<html>
<head>
  <meta charset="UTF-8">
  <title>iron-list test</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

  <script src="../../webcomponentsjs/webcomponents-lite.js"></script>
  <script src="../../web-component-tester/browser.js"></script>
  <script src="../../iron-test-helpers/mock-interactions.js"></script>

  <link rel="import" href="helpers.html">
  <link rel="import" href="x-list.html">

</head>
<body>

  <test-fixture id="trivialList">
    <template>
      <x-list item-height="0" pre></x-list>
    </template>
  </test-fixture>

  <script>

    suite('Dynamic item size', function() {
      var list, container;

      setup(function() {
        container = fixture('trivialList');
        list = container.list;
      });

      test('update size using item index', function(done) {
        list.items = buildDataSet(100);

        flush(function() {
          var firstItem = getFirstItemFromList(list);
          var initHeight = firstItem.offsetHeight;

          list.set('items.0.index', '1\n2\n3\n4');
          list.updateSizeForItem(0);
          assert.isAbove(firstItem.offsetHeight, initHeight*3);

          list.set('items.0.index', '1');
          list.updateSizeForItem(0);
          assert.equal(firstItem.offsetHeight, initHeight);

          done();
        });
      });

      test('update size using item object', function(done) {
        list.items = buildDataSet(100);

        flush(function() {
          var firstItem = getFirstItemFromList(list);
          var initHeight = firstItem.offsetHeight;

          list.set('items.0.index', '1\n2\n3\n4');
          list.updateSizeForItem(list.items[0]);
          assert.isAbove(firstItem.offsetHeight, initHeight*3);

          list.set('items.0.index', '1');
          list.updateSizeForItem(list.items[0]);
          assert.equal(firstItem.offsetHeight, initHeight);

          done();
        });
      });

      test('ignore items that are not rendered', function(done) {
        list.items = buildDataSet(100);

        flush(function() {
          list.updateSizeForItem(list.items[list.items.length - 1]);
          done();
        });
      });

      test('throw if the item is invalid', function(done) {
        list.items = buildDataSet(100);

        flush(function() {
          var firstItem = getFirstItemFromList(list);
          var initHeight = firstItem.offsetHeight;
          var throws = 0;

          try {
            list.updateSizeForItem(100);
          } catch (error) {
            throws++;
          }

          try {
            list.updateSizeForItem({});
          } catch (error) {
            throws++;
          }

          assert.equal(throws, 2);
          done();
        });
      });

    });

  </script>

</body>
</html>


text:
#if defined(G_DISABLE_SINGLE_INCLUDES) && !defined (__GLIB_H_INSIDE__) && !defined (GLIB_COMPILATION)
#error "Only <glib.h> can be included directly."
#endif

#ifndef __G_KEY_FILE_H__
#define __G_KEY_FILE_H__

#include <glib/gerror.h>

G_BEGIN_DECLS

typedef enum
{
  G_KEY_FILE_ERROR_UNKNOWN_ENCODING,
  G_KEY_FILE_ERROR_PARSE,
  G_KEY_FILE_ERROR_NOT_FOUND,
  G_KEY_FILE_ERROR_KEY_NOT_FOUND,
  G_KEY_FILE_ERROR_GROUP_NOT_FOUND,
  G_KEY_FILE_ERROR_INVALID_VALUE
} GKeyFileError;

#define G_KEY_FILE_ERROR g_key_file_error_quark()

GQuark g_key_file_error_quark (void);

typedef struct _GKeyFile GKeyFile;

typedef enum
{
  G_KEY_FILE_NONE              = 0,
  G_KEY_FILE_KEEP_COMMENTS     = 1 << 0,
  G_KEY_FILE_KEEP_TRANSLATIONS = 1 << 1
} GKeyFileFlags;

GKeyFile *g_key_file_new                    (void);
void      g_key_file_free                   (GKeyFile             *key_file);
void      g_key_file_set_list_separator     (GKeyFile             *key_file,
					     gchar                 separator);
gboolean  g_key_file_load_from_file         (GKeyFile             *key_file,
					     const gchar          *file,
					     GKeyFileFlags         flags,
					     GError              **error);
gboolean  g_key_file_load_from_data         (GKeyFile             *key_file,
					     const gchar          *data,
					     gsize                 length,
					     GKeyFileFlags         flags,
					     GError              **error);
gboolean g_key_file_load_from_dirs          (GKeyFile             *key_file,
					     const gchar	  *file,
					     const gchar	 **search_dirs,
					     gchar		 **full_path,
					     GKeyFileFlags         flags,
					     GError              **error);
gboolean g_key_file_load_from_data_dirs     (GKeyFile             *key_file,
					     const gchar          *file,
					     gchar               **full_path,
					     GKeyFileFlags         flags,
					     GError              **error);
gchar    *g_key_file_to_data                (GKeyFile             *key_file,
					     gsize                *length,
					     GError              **error) G_GNUC_MALLOC;
gchar    *g_key_file_get_start_group        (GKeyFile             *key_file) G_GNUC_MALLOC;
gchar   **g_key_file_get_groups             (GKeyFile             *key_file,
					     gsize                *length) G_GNUC_MALLOC;
gchar   **g_key_file_get_keys               (GKeyFile             *key_file,
					     const gchar          *group_name,
					     gsize                *length,
					     GError              **error) G_GNUC_MALLOC;
gboolean  g_key_file_has_group              (GKeyFile             *key_file,
					     const gchar          *group_name);
gboolean  g_key_file_has_key                (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     GError              **error);
gchar    *g_key_file_get_value              (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     GError              **error) G_GNUC_MALLOC;
void      g_key_file_set_value              (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     const gchar          *value);
gchar    *g_key_file_get_string             (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     GError              **error) G_GNUC_MALLOC;
void      g_key_file_set_string             (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     const gchar          *string);
gchar    *g_key_file_get_locale_string      (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     const gchar          *locale,
					     GError              **error) G_GNUC_MALLOC;
void      g_key_file_set_locale_string      (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     const gchar          *locale,
					     const gchar          *string);
gboolean  g_key_file_get_boolean            (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     GError              **error);
void      g_key_file_set_boolean            (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     gboolean              value);
gint      g_key_file_get_integer            (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     GError              **error);
void      g_key_file_set_integer            (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     gint                  value);
gint64    g_key_file_get_int64              (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     GError              **error);
void      g_key_file_set_int64              (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     gint64                value);
guint64   g_key_file_get_uint64             (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     GError              **error);
void      g_key_file_set_uint64             (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     guint64               value);
gdouble   g_key_file_get_double             (GKeyFile             *key_file,
                                             const gchar          *group_name,
                                             const gchar          *key,
                                             GError              **error);
void      g_key_file_set_double             (GKeyFile             *key_file,
                                             const gchar          *group_name,
                                             const gchar          *key,
                                             gdouble               value);
gchar   **g_key_file_get_string_list        (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     gsize                *length,
					     GError              **error) G_GNUC_MALLOC;
void      g_key_file_set_string_list        (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     const gchar * const   list[],
					     gsize                 length);
gchar   **g_key_file_get_locale_string_list (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     const gchar          *locale,
					     gsize                *length,
					     GError              **error) G_GNUC_MALLOC;
void      g_key_file_set_locale_string_list (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     const gchar          *locale,
					     const gchar * const   list[],
					     gsize                 length);
gboolean *g_key_file_get_boolean_list       (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     gsize                *length,
					     GError              **error) G_GNUC_MALLOC;
void      g_key_file_set_boolean_list       (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     gboolean              list[],
					     gsize                 length);
gint     *g_key_file_get_integer_list       (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     gsize                *length,
					     GError              **error) G_GNUC_MALLOC;
void      g_key_file_set_double_list        (GKeyFile             *key_file,
                                             const gchar          *group_name,
                                             const gchar          *key,
                                             gdouble               list[],
                                             gsize                 length);
gdouble  *g_key_file_get_double_list        (GKeyFile             *key_file,
                                             const gchar          *group_name,
                                             const gchar          *key,
                                             gsize                *length,
                                             GError              **error) G_GNUC_MALLOC;
void      g_key_file_set_integer_list       (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     gint                  list[],
					     gsize                 length);
gboolean  g_key_file_set_comment            (GKeyFile             *key_file,
                                             const gchar          *group_name,
                                             const gchar          *key,
                                             const gchar          *comment,
                                             GError              **error);
gchar    *g_key_file_get_comment            (GKeyFile             *key_file,
                                             const gchar          *group_name,
                                             const gchar          *key,
                                             GError              **error) G_GNUC_MALLOC;

gboolean  g_key_file_remove_comment         (GKeyFile             *key_file,
                                             const gchar          *group_name,
                                             const gchar          *key,
					     GError              **error);
gboolean  g_key_file_remove_key             (GKeyFile             *key_file,
					     const gchar          *group_name,
					     const gchar          *key,
					     GError              **error);
gboolean  g_key_file_remove_group           (GKeyFile             *key_file,
					     const gchar          *group_name,
					     GError              **error);

/* Defines for handling freedesktop.org Desktop files */
#define G_KEY_FILE_DESKTOP_GROUP                "Desktop Entry"

#define G_KEY_FILE_DESKTOP_KEY_TYPE             "Type"
#define G_KEY_FILE_DESKTOP_KEY_VERSION          "Version"
#define G_KEY_FILE_DESKTOP_KEY_NAME             "Name"
#define G_KEY_FILE_DESKTOP_KEY_GENERIC_NAME     "GenericName"
#define G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY       "NoDisplay"
#define G_KEY_FILE_DESKTOP_KEY_COMMENT          "Comment"
#define G_KEY_FILE_DESKTOP_KEY_ICON             "Icon"
#define G_KEY_FILE_DESKTOP_KEY_HIDDEN           "Hidden"
#define G_KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN     "OnlyShowIn"
#define G_KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN      "NotShowIn"
#define G_KEY_FILE_DESKTOP_KEY_TRY_EXEC         "TryExec"
#define G_KEY_FILE_DESKTOP_KEY_EXEC             "Exec"
#define G_KEY_FILE_DESKTOP_KEY_PATH             "Path"
#define G_KEY_FILE_DESKTOP_KEY_TERMINAL         "Terminal"
#define G_KEY_FILE_DESKTOP_KEY_MIME_TYPE        "MimeType"
#define G_KEY_FILE_DESKTOP_KEY_CATEGORIES       "Categories"
#define G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY   "StartupNotify"
#define G_KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS "StartupWMClass"
#define G_KEY_FILE_DESKTOP_KEY_URL              "URL"

#define G_KEY_FILE_DESKTOP_TYPE_APPLICATION     "Application"
#define G_KEY_FILE_DESKTOP_TYPE_LINK            "Link"
#define G_KEY_FILE_DESKTOP_TYPE_DIRECTORY       "Directory"

G_END_DECLS

#endif /* __G_KEY_FILE_H__ */


text:
<TITLE>SanCube.com</TITLE>

        Is Your System Fast Enough?

This Site is Optimized For:

            Operating System
            RAM
            Browser
            System Processor
            Internet Connection

            Macintosh System 7.5 or higher
            64 MB+
            Microsoft Internet Explorer 4.5+ or
              Netscape 4.0+
            333Mhz or Higher
            ISDN or Higher

            Windows 9x/NT/2000
            64 MB+
            Microsoft Internet Explorer 4.0+ or
              Netscape 4.0+
            333Mhz or Higher
            ISDN or Higher

        back to top


text:
package com.p6spy.engine.spy;

public interface SpyDotPropertiesReloadChangedListener {

  void setAutoReload(boolean isEnabled, long secs);
}


text:
'use strict';

const logger = require('../../utils/logger');
const Promise = require('../../promise');
const AbstractQuery = require('../abstract/query');
const sequelizeErrors = require('../../errors');
const parserStore = require('../parserStore')('mssql');
const _ = require('lodash');
const debug = logger.getLogger().debugContext('sql:mssql');

class Query extends AbstractQuery {
  constructor(connection, sequelize, options) {
    super();
    this.connection = connection;
    this.instance = options.instance;
    this.model = options.model;
    this.sequelize = sequelize;
    this.options = Object.assign({
      logging: console.log,
      plain: false,
      raw: false
    }, options || {});

    this.checkLoggingOption();
  }

  getInsertIdField() {
    return 'id';
  }

  getSQLTypeFromJsType(value, TYPES) {
    const paramType = { type: TYPES.VarChar, typeOptions: {} };
    paramType.type = TYPES.NVarChar;
    if (typeof value === 'number') {
      if (Number.isInteger(value)) {
        paramType.type = TYPES.Int;
      } else {
        paramType.type = TYPES.Numeric;
        //Default to a reasonable numeric precision/scale pending more sophisticated logic
        paramType.typeOptions = { precision: 30, scale: 15 };
      }
    }
    if (Buffer.isBuffer(value)) {
      paramType.type = TYPES.VarBinary;
    }
    return paramType;
  }

  _run(connection, sql, parameters) {
    this.sql = sql;

    //do we need benchmark for this query execution
    const benchmark = this.sequelize.options.benchmark || this.options.benchmark;
    let queryBegin;
    if (benchmark) {
      queryBegin = Date.now();
    } else {
      this.sequelize.log(`Executing (${this.connection.uuid || 'default'}): ${this.sql}`, this.options);
    }

    debug(`executing(${this.connection.uuid || 'default'}) : ${this.sql}`);

    return new Promise((resolve, reject) => {
      // TRANSACTION SUPPORT
      if (this.sql.startsWith('BEGIN TRANSACTION')) {
        return connection.beginTransaction(err => {
          if (err) {
            reject(this.formatError(err));
            return;
          }
          resolve(this.formatResults());
        }, this.options.transaction.name, connection.lib.ISOLATION_LEVEL[this.options.isolationLevel]);
      }
      if (this.sql.startsWith('COMMIT TRANSACTION')) {
        return connection.commitTransaction(err => {
          if (err) {
            reject(this.formatError(err));
            return;
          }
          resolve(this.formatResults());
        });
      }
      if (this.sql.startsWith('ROLLBACK TRANSACTION')) {
        return connection.rollbackTransaction(err => {
          if (err) {
            reject(this.formatError(err));
          }
          resolve(this.formatResults());
        }, this.options.transaction.name);
        return;
      }
      if (this.sql.startsWith('SAVE TRANSACTION')) {
        return connection.saveTransaction(err => {
          if (err) {
            reject(this.formatError(err));
            return;
          }
          resolve(this.formatResults());
        }, this.options.transaction.name);
      }
      const results = [];
      const request = new connection.lib.Request(this.sql, (err, rowCount) => {

        debug(`executed(${this.connection.uuid || 'default'}) : ${this.sql}`);

        if (benchmark) {
          this.sequelize.log(`Executed (${this.connection.uuid || 'default'}): ${this.sql}`, Date.now() - queryBegin, this.options);
        }

        if (err) {
          err.sql = sql;
          reject(this.formatError(err));
        } else {
          resolve(this.formatResults(results, rowCount));
        }
      });

      if (parameters) {
        _.forOwn(parameters, (value, key) => {
          const paramType = this.getSQLTypeFromJsType(value, connection.lib.TYPES);
          request.addParameter(key, paramType.type, value, paramType.typeOptions);
        });
      }

      request.on('row', columns => {
        const row = {};
        for (const column of columns) {
          const typeid = column.metadata.type.id;
          const parse = parserStore.get(typeid);
          let value = column.value;

          if (value !== null & !!parse) {
            value = parse(value);
          }
          row[column.metadata.colName] = value;
        }

        results.push(row);
      });

      connection.execSql(request);
    });
  }

  run(sql, parameters) {
    return Promise.using(this.connection.lock(), connection => this._run(connection, sql, parameters));
  }

  static formatBindParameters(sql, values, dialect) {
    const bindParam = {};
    const replacementFunc = (match, key, values) => {
      if (values[key] !== undefined) {
        bindParam[key] = values[key];
        return `@${key}`;
      }
      return undefined;
    };
    sql = AbstractQuery.formatBindParameters(sql, values, dialect, replacementFunc)[0];

    return [sql, bindParam];
  }

  /**
   * High level function that handles the results of a query execution.
   *
   *
   * Example:
   *  query.formatResults([
   *    {
   *      id: 1,              // this is from the main table
   *      attr2: 'snafu',     // this is from the main table
   *      Tasks.id: 1,        // this is from the associated table
   *      Tasks.title: 'task' // this is from the associated table
   *    }
   *  ])
   *
   * @param {Array} data - The result of the query execution.
   * @private
   */
  formatResults(data, rowCount) {
    let result = this.instance;
    if (this.isInsertQuery(data)) {
      this.handleInsertQuery(data);

      if (!this.instance) {
        if (this.options.plain) {
          // NOTE: super contrived. This just passes the newly added query-interface
          //       test returning only the PK. There isn't a way in MSSQL to identify
          //       that a given return value is the PK, and we have no schema information
          //       because there was no calling Model.
          const record = data[0];
          result = record[Object.keys(record)[0]];
        } else {
          result = data;
        }
      }
    }

    if (this.isShowTablesQuery()) {
      return this.handleShowTablesQuery(data);
    }
    if (this.isDescribeQuery()) {
      result = {};
      for (const _result of data) {
        if (_result.Default) {
          _result.Default = _result.Default.replace("('", '').replace("')", '').replace(/'/g, '');
        }

        result[_result.Name] = {
          type: _result.Type.toUpperCase(),
          allowNull: _result.IsNull === 'YES' ? true : false,
          defaultValue: _result.Default,
          primaryKey: _result.Constraint === 'PRIMARY KEY',
          autoIncrement: _result.IsIdentity === 1,
          comment: _result.Comment
        };

        if (
          result[_result.Name].type.includes('VARCHAR')
          && _result.Length
        ) {
          result[_result.Name].type += `(${_result.Length})`;
        }

      }
    }
    if (this.isSelectQuery()) {
      return this.handleSelectQuery(data);
    }
    if (this.isShowIndexesQuery()) {
      return this.handleShowIndexesQuery(data);
    }
    if (this.isUpsertQuery()) {
      return data[0];
    }
    if (this.isCallQuery()) {
      return data[0];
    }
    if (this.isBulkUpdateQuery()) {
      return data.length;
    }
    if (this.isBulkDeleteQuery()) {
      return data[0] && data[0].AFFECTEDROWS;
    }
    if (this.isVersionQuery()) {
      return data[0].version;
    }
    if (this.isForeignKeysQuery()) {
      return data;
    }
    if (this.isInsertQuery() || this.isUpdateQuery()) {
      return [result, rowCount];
    }
    if (this.isShowConstraintsQuery()) {
      return this.handleShowConstraintsQuery(data);
    }
    if (this.isRawQuery()) {
      // MSSQL returns row data and metadata (affected rows etc) in a single object - let's standarize it, sorta
      return [data, data];
    }

    return result;
  }

  handleShowTablesQuery(results) {
    return results.map(resultSet => {
      return {
        tableName: resultSet.TABLE_NAME,
        schema: resultSet.TABLE_SCHEMA
      };
    });
  }

  handleShowConstraintsQuery(data) {
    //Convert snake_case keys to camelCase as it's generated by stored procedure
    return data.slice(1).map(result => {
      const constraint = {};
      for (const key in result) {
        constraint[_.camelCase(key)] = result[key];
      }
      return constraint;
    });
  }

  formatError(err) {
    let match;

    match = err.message.match(/Violation of (?:UNIQUE|PRIMARY) KEY constraint '((.|\s)*)'. Cannot insert duplicate key in object '.*'.(:? The duplicate key value is \((.*)\).)?/);
    match = match || err.message.match(/Cannot insert duplicate key row in object .* with unique index '(.*)'/);
    if (match && match.length > 1) {
      let fields = {};
      const uniqueKey = this.model && this.model.uniqueKeys[match[1]];
      let message = 'Validation error';

      if (uniqueKey && !!uniqueKey.msg) {
        message = uniqueKey.msg;
      }
      if (match[4]) {
        const values = match[4].split(',').map(part => part.trim());
        if (uniqueKey) {
          fields = _.zipObject(uniqueKey.fields, values);
        } else {
          fields[match[1]] = match[4];
        }
      }

      const errors = [];
      _.forOwn(fields, (value, field) => {
        errors.push(new sequelizeErrors.ValidationErrorItem(
          this.getUniqueConstraintErrorMessage(field),
          'unique violation', // sequelizeErrors.ValidationErrorItem.Origins.DB,
          field,
          value,
          this.instance,
          'not_unique'
        ));
      });

      return new sequelizeErrors.UniqueConstraintError({ message, errors, parent: err, fields });
    }

    match = err.message.match(/Failed on step '(.*)'.Could not create constraint. See previous errors./) ||
      err.message.match(/The DELETE statement conflicted with the REFERENCE constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./) ||
      err.message.match(/The (?:INSERT|MERGE|UPDATE) statement conflicted with the FOREIGN KEY constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./);
    if (match && match.length > 0) {
      return new sequelizeErrors.ForeignKeyConstraintError({
        fields: null,
        index: match[1],
        parent: err
      });
    }

    match = err.message.match(/Could not drop constraint. See previous errors./);
    if (match && match.length > 0) {
      let constraint = err.sql.match(/(?:constraint|index) \[(.+?)\]/i);
      constraint = constraint ? constraint[1] : undefined;
      let table = err.sql.match(/table \[(.+?)\]/i);
      table = table ? table[1] : undefined;

      return new sequelizeErrors.UnknownConstraintError({
        message: match[1],
        constraint,
        table,
        parent: err
      });
    }

    return new sequelizeErrors.DatabaseError(err);
  }

  isShowOrDescribeQuery() {
    let result = false;

    result = result || this.sql.toLowerCase().startsWith("select c.column_name as 'name', c.data_type as 'type', c.is_nullable as 'isnull'");
    result = result || this.sql.toLowerCase().startsWith('select tablename = t.name, name = ind.name,');
    result = result || this.sql.toLowerCase().startsWith('exec sys.sp_helpindex @objname');

    return result;
  }

  isShowIndexesQuery() {
    return this.sql.toLowerCase().startsWith('exec sys.sp_helpindex @objname');
  }

  handleShowIndexesQuery(data) {
    // Group by index name, and collect all fields
    data = data.reduce((acc, item) => {
      if (!(item.index_name in acc)) {
        acc[item.index_name] = item;
        item.fields = [];
      }

      item.index_keys.split(',').forEach(column => {
        let columnName = column.trim();
        if (columnName.includes('(-)')) {
          columnName = columnName.replace('(-)', '');
        }

        acc[item.index_name].fields.push({
          attribute: columnName,
          length: undefined,
          order: column.includes('(-)') ? 'DESC' : 'ASC',
          collate: undefined
        });
      });
      delete item.index_keys;
      return acc;
    }, {});

    return _.map(data, item => ({
      primary: item.index_name.toLowerCase().startsWith('pk'),
      fields: item.fields,
      name: item.index_name,
      tableName: undefined,
      unique: item.index_description.toLowerCase().includes('unique'),
      type: undefined
    }));
  }

  handleInsertQuery(results, metaData) {
    if (this.instance) {
      // add the inserted row id to the instance
      const autoIncrementAttribute = this.model.autoIncrementAttribute;
      let id = null;
      let autoIncrementAttributeAlias = null;

      if (this.model.rawAttributes.hasOwnProperty(autoIncrementAttribute) &&
        this.model.rawAttributes[autoIncrementAttribute].field !== undefined)
        autoIncrementAttributeAlias = this.model.rawAttributes[autoIncrementAttribute].field;

      id = id || results && results[0][this.getInsertIdField()];
      id = id || metaData && metaData[this.getInsertIdField()];
      id = id || results && results[0][autoIncrementAttribute];
      id = id || autoIncrementAttributeAlias && results && results[0][autoIncrementAttributeAlias];

      this.instance[autoIncrementAttribute] = id;
    }
  }
}

module.exports = Query;
module.exports.Query = Query;
module.exports.default = Query;


text:
package com.ruesga.rview.text;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.style.ReplacementSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class TagSpan extends ReplacementSpan {
    private final int mBackgroundColor;
    private final int mForegroundColor;

    private final float mMarginLeftRight;
    private final float mMarginTopBottom;
    private final float mRadius;

    private final RectF mRect = new RectF();

    public TagSpan(Context context, @ColorInt int backgroundColor, @ColorInt int foregroundColor) {
        mBackgroundColor = backgroundColor;
        mForegroundColor = foregroundColor;

        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        mMarginLeftRight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, metrics);
        mMarginTopBottom = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, metrics);
        mRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, metrics);
    }

    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end,
            @Nullable Paint.FontMetricsInt fm) {
        return Math.round(paint.measureText(text, start, end) + (mMarginLeftRight * 2));
    }

    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end,
            float x, int top, int y, int bottom, @NonNull Paint paint) {
        // Draw background
        mRect.set(
                x,
                top - mMarginTopBottom,
                x + paint.measureText(text, start, end) + (mMarginLeftRight * 2),
                bottom + mMarginTopBottom);
        paint.setColor(mBackgroundColor);
        canvas.drawRoundRect(mRect, mRadius, mRadius, paint);

        // Draw foreground
        float tx = x + mMarginLeftRight;
        paint.setColor(mBackgroundColor);
        paint.setColor(mForegroundColor);
        paint.setAntiAlias(true);
        paint.setFakeBoldText(true);
        canvas.drawText(text, start, end, tx, y, paint);
    }
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="execution">
        <roleset framnet="execution" id="execution.01" name="kill" source="verb-execute.01" vncls="42.1">
            <roles>

                <role descr="killer" f="" n="0">
                    <vnrole vncls="42.1" vntheta="agent"/>
                </role>

                <role descr="corpse" f="ppt" n="1">
                    <vnrole vncls="42.1" vntheta="patient"/>
                </role>

                <role descr="instrument" f="mnr" n="2">
                    <vnrole vncls="42.1" vntheta="instrument"/>
                </role>

                <note/>
            </roles>

            <example name="Arg 1 only" src="" type="">
                <text>the execution of mass-murderer Ted Bundy</text>
                <rel f="">execution</rel>
                <arg f="" n="1">of mass-murderer Ted Bundy</arg>
                <note/>
            </example>

            <example name="Arg 0" src="" type="">
                <text>The last federal execution before the Supreme Court 's 1972 ruling banning the death penalty</text>
                <arg f="" n="0">federal</arg>
                <rel f="">execution</rel>
                <arg f="tmp" n="m">before the Supreme Court 's 1972 ruling banning the death penalty</arg>
                <note/>
            </example>

            <note>Based on sentences in nouns-00040. Comparison to 'execute.01' Vn class murder-42.1. Fn class execution. Framed by Katie.</note>
            <example name="One more arg 1" src="" type="">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>The execution of six British commandos in WWII</text>
                <note/>
                <rel f="">execution</rel>
                <arg f="" n="1">of six British commandos</arg>
                <arg f="tmp" n="m">in WWII</arg>
            </example>
        </roleset>
        <roleset framnet="" id="execution.02" name="enact" source="verb-execute.02" vncls="">
            <roles>

                <role descr="agent, doer" f="" n="0"/>

                <role descr="thing done" f="ppt" n="1"/>

                <role descr="beneficiary, done for or about" f="gol" n="2"/>

                <role descr="instrumental" f="mnr" n="3"/>

                <note/>
            </roles>

            <example name="Args 0 and 1" src="" type="">
                <text>the president 's execution of the law</text>
                <arg f="" n="0">the president 's</arg>
                <rel f="">execution</rel>
                <arg f="" n="1">of the law</arg>
                <note/>
            </example>

            <example name="arg 1 only" src="" type="">
                <text>The day-to-day execution of policies</text>

                <arg f="mnr" n="m">day-to-day</arg>
                <rel f="">execution</rel>
                <arg f="" n="1">of policies</arg>
                <note/>
            </example>

            <note>Based on sentences in nouns-00040. Comparison to 'execute.02' No VN or FN classes. Framed by Katie.</note>
            <example name="Args 0 in a PP" src="" type="">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>The execution of contracts by foreign investment enterprises</text>
                <note/>
                <rel f="">execution</rel>
                <arg f="" n="1">of contracts</arg>
                <arg f="" n="0">by foreign investment enterprises</arg>
            </example>
        </roleset>
        <note/>
    </predicate>
    <note/>
</frameset>


text:
<?php

namespace Rds\Request\V20140815;

class DescribeSQLLogFilesRequest extends \RpcAcsRequest
{
	function  __construct()
	{
		parent::__construct("Rds", "2014-08-15", "DescribeSQLLogFiles", "rds", "openAPI");
		$this->setMethod("POST");
	}

	private  $resourceOwnerId;

	private  $fileName;

	private  $resourceOwnerAccount;

	private  $ownerAccount;

	private  $pageSize;

	private  $dBInstanceId;

	private  $ownerId;

	private  $pageNumber;

	public function getResourceOwnerId() {
		return $this->resourceOwnerId;
	}

	public function setResourceOwnerId($resourceOwnerId) {
		$this->resourceOwnerId = $resourceOwnerId;
		$this->queryParameters["ResourceOwnerId"]=$resourceOwnerId;
	}

	public function getFileName() {
		return $this->fileName;
	}

	public function setFileName($fileName) {
		$this->fileName = $fileName;
		$this->queryParameters["FileName"]=$fileName;
	}

	public function getResourceOwnerAccount() {
		return $this->resourceOwnerAccount;
	}

	public function setResourceOwnerAccount($resourceOwnerAccount) {
		$this->resourceOwnerAccount = $resourceOwnerAccount;
		$this->queryParameters["ResourceOwnerAccount"]=$resourceOwnerAccount;
	}

	public function getOwnerAccount() {
		return $this->ownerAccount;
	}

	public function setOwnerAccount($ownerAccount) {
		$this->ownerAccount = $ownerAccount;
		$this->queryParameters["OwnerAccount"]=$ownerAccount;
	}

	public function getPageSize() {
		return $this->pageSize;
	}

	public function setPageSize($pageSize) {
		$this->pageSize = $pageSize;
		$this->queryParameters["PageSize"]=$pageSize;
	}

	public function getDBInstanceId() {
		return $this->dBInstanceId;
	}

	public function setDBInstanceId($dBInstanceId) {
		$this->dBInstanceId = $dBInstanceId;
		$this->queryParameters["DBInstanceId"]=$dBInstanceId;
	}

	public function getOwnerId() {
		return $this->ownerId;
	}

	public function setOwnerId($ownerId) {
		$this->ownerId = $ownerId;
		$this->queryParameters["OwnerId"]=$ownerId;
	}

	public function getPageNumber() {
		return $this->pageNumber;
	}

	public function setPageNumber($pageNumber) {
		$this->pageNumber = $pageNumber;
		$this->queryParameters["PageNumber"]=$pageNumber;
	}

}


text:
DIR=$(dirname "${BASH_SOURCE[0]}")

. "$DIR"/common.sh

PORT=$(($$ + 1024)) # PID + 1024

dub remove maven-dubpackage --non-interactive --version=* 2>/dev/null || true

"$DUB" build --single "$DIR"/test_registry.d
"$DIR"/test_registry --folder="$DIR/issue1416-maven-repo-pkg-supplier" --port=$PORT &
PID=$!
sleep 1
trap 'kill $PID 2>/dev/null || true' exit

echo "Trying to download maven-dubpackage (1.0.5)"
"$DUB" fetch maven-dubpackage --version=1.0.5 --skip-registry=all --registry=mvn+http://localhost:$PORT/maven/release/dubpackages

if ! dub remove maven-dubpackage --non-interactive --version=1.0.5 2>/dev/null; then
    die 'DUB did not install package from maven registry.'
fi

echo "Trying to download maven-dubpackage (latest)"
"$DUB" fetch maven-dubpackage --skip-registry=all --registry=mvn+http://localhost:$PORT/maven/release/dubpackages

if ! dub remove maven-dubpackage --non-interactive --version=1.0.6 2>/dev/null; then
    die 'DUB fetch did not install latest package from maven registry.'
fi

echo "Trying to search (exact) maven-dubpackage"
"$DUB" search maven-dubpackage --skip-registry=all --registry=mvn+http://localhost:$PORT/maven/release/dubpackages | grep -c "maven-dubpackage (1.0.6)"


text:
import sys, json, pprint

# Load JSON data into a Python variable and print
if len(sys.argv) == 2:
	with open(sys.argv[1]) as data_file:
		jsonData = json.load(data_file)

	# working off of Reddit JSON formatted data and get urls
	for child in jsonData['data']['children']:
		pprint.pprint(child['data']['url'])

else:
	print('Usage: jsonParse.py <json_file_to_load>')


text:
Spring 2016 Semester Project

http://videogamedev.club

#####Try out the web version of the game: http://videogamedev.club/VacuumBuild/

[Join the VGDC Telegram group](https://telegram.me/joinchat/Bluy8QIW4BoaQBZs2t3CGA).

***

<!-- TOC depthFrom:1 depthTo:6 withLinks:1 updateOnSave:1 orderedList:0 -->

# Table of Contents

- [Getting Started on the Project](#getting-started-on-the-project)

	- [1. Download Unity 5.3.1f1.](#1-download-unity-531f1)

	- [2. Read or watch some Unity tutorials.](#2-read-or-watch-some-unity-tutorials)

	- [3. Familiarize yourself with the documentation and project standards.](#3-familiarize-yourself-with-the-documentation-and-project-standards)

	- [4. Learn how to use Git and GitHub.](#4-learn-how-to-use-git-and-github)

	- [5. Find out how to contribute.](#5-find-out-how-to-contribute)

- [Extra Stuff](#extra-stuff)

	- [Install ZenHub for integrated to-do lists on GitHub.](#install-zenhub-for-integrated-to-do-lists-on-github)

	- [Go through a Photon tutorial.](#go-through-a-photon-tutorial)

- [Project Standards](#project-standards)

- [Programming Conventions](#programming-conventions)

<!-- /TOC -->

***

### Getting Started on the Project

#### 1. Download Unity 5.3.1f1.
5.3.1f1 is the version being used for this project. Get it with these links.

- [Unity for Mac](https://unity3d.com/get-unity/download?thank-you=update&download_nid=24110&os=Mac)

- [Unity for Windows](https://unity3d.com/get-unity/download?thank-you=update&download_nid=24110&os=Win)

#### 2. Read or watch some Unity tutorials.

Unity can take a while to download, so pass the time by getting down the basics.

- [Getting Started with Unity](http://docs.unity3d.com/Manual/GettingStarted.html)

- [Introduction to Unity's UI](https://unity3d.com/learn/tutorials/topics/interface-essentials)

- [Scripting in C#](https://unity3d.com/learn/tutorials/topics/scripting)

- [More Unity Tutorials](https://unity3d.com/learn/tutorials)

#### 3. Familiarize yourself with the documentation and project standards.

- Project Documentation:
  - [Mockup Object Model Diagram](http://videogamedev.club/?page=GamePlans)
- Project standards and programming conventions can be found at the end of this document.

#### 4. Learn how to use Git and GitHub.

- [GitHub Desktop](https://desktop.github.com) (Recommended App)

- [Set Up Git](https://help.github.com/articles/set-up-git/)

- [Make a Fork](https://guides.github.com/activities/forking/)

- [Different Ways of Contributing](https://guides.github.com/activities/contributing-to-open-source/#contributing)

- [More GitHub Tutorials](https://guides.github.com)

#### 5. Find out how to contribute.
There are many ways to contribute to the project, such as play-testing, contributing to the project's source code, creating assets and art, and finding and reporting bugs.

- To contribute to the project's source code, [create a fork](http://imgur.com/a/D5Ee6), modify your fork, and [submit a pull request](https://help.github.com/articles/using-pull-requests/). Things currently being worked on or needing attention can be found in the [Issues section](https://github.com/VideoGameDevClub/VacuumCleanSupreme/issues).

- Creation of assets and art encompasses multiple things, including creation of 3D models, textures, sound effects, particle effects, interface elements, and animations. There are many free and paid utilities that may be used for producing each of these things. Below are some recommended apps that can be downloaded for free.
	- For 3D models, [SketchUp (Windows, Mac)](http://www.sketchup.com) or [Blender (Windows, Mac, GNU/Linux)](https://www.blender.org)
	- For creating textures, [Gimp (Windows, Mac, GNU/Linux)] (https://www.gimp.org/downloads/) or [Pixelmator (Mac)](http://www.pixelmator.com/mac/try/) (free for 30 days)
	- For sound effects, [Audacity (Windows, Mac, GNU/Linux)](http://audacityteam.org) or [GarageBand (Mac)](http://www.apple.com/mac/garageband/)
	- Particle effects, interface elements, and animations can be created within Unity on [Mac](http://unity3d.com/get-unity/download?thank-you=update&download_nid=24110&os=Mac) and [Windows](http://unity3d.com/get-unity/download?thank-you=update&download_nid=24110&os=Win).

- If you find a bug or problem, first go to the [Issues section](https://github.com/VideoGameDevClub/VacuumCleanSupreme/issues) of the repository to check if the bug or problem has already been reported. If it has not already been reported, [open a new issue](https://github.com/VideoGameDevClub/VacuumCleanSupreme/issues/new) and give a detailed explanation of the issue and any suggestions for a solution.

If you need any further assistance, contact ecd157@msstate.edu or post in the [VGDC Telegram group](https://telegram.me/joinchat/Bluy8QIW4BoaQBZs2t3CGA).

***

### Extra Stuff

#### Install ZenHub for integrated to-do lists on GitHub.
Zenhub changes the format of the Issues section for a new way of organizing your issues and tracking stats. This extension is not required to be able to work on this project.

- Add ZenHub here: https://zenhub.io/

- After adding ZenHub, check out the new Issues and Boards page here: https://github.com/VideoGameDevClub/VacuumCleanSupreme/issues

#### Go through a Photon tutorial.
This project utilizes the networking features of a Unity plugin you can find on their asset store called Photon. This plugin/service allows us to keep things simple by not having to set up our own server for listening and sending calls. This plugin also makes writing network code *extremely* simple.

I suggest creating an empty project on your machine and just going through their [Marco Polo tutorial](https://doc.photonengine.com/en/pun/current/tutorials/tutorial-marco-polo).  This tutorial takes no longer than an hour, and afterwords you'll have a good idea of what's going on whenever you see/write networking code.

***

### Project Standards
These are just a few standards that we would like contributions to follow for consistency throughout the project.  When you submit a PR we will make sure your changes follow these standards and, if needed, recommend appropriate changes so that they do.

* All code written will be under the Scripts folder.
* Folders, file names, enums, and enum constants should be done in camel case beggining in a capital letter
  * ex: ```DemoAssets```
  * ex: ```EnemyBehavior```
  * ex: ```enum EnemyState { Searching, Pursuing, Attacking, Fleeing }```
* Function names are declared camel case and with starting letter lower case
  * ex: ```killSelf()```
* If an enum is made public it should be put in its own file that is named the enum
  * ex: ```public enum EnemyState``` will be put in ```EnemyState.cs```, which only contains the enum decleration and using statements.
  * This is to make finding where the enum is declared easier, as well as an attempt at making merge conflicts easier.
* When you plan to have a class extend from monobehavior (such as a class meant for controlling camera movement), end the name of the class in ```Behavior```
  * ex: ```CameraControlBehavior.cs```
* Document every class and function!
  * To quickly add a summary to a class or function, move the cursor to above the declaration of a class slash function and enter '```///```'.  This in both Mono and VS start a nice body for the description of the class / function.
* **0 public variables.**  To get a variable's value or set it create the appropriate getter and setter methods (otherwise known as accessor and mutator methods).
* Namespace convention: Preface with VGDC, and every parent folder the script is contained in will come after. (Ignoring the Script folder)
  * Ex: If script x is under Scripts > GameManagement, then the script's namespace will be ```VGDC.GameManagement```
  * Ex. If script y is under Scripts > Characters > Player > Weapons, then the script's namespace will be ```VGDC.Characters.Player.Weapons```

***

### Programming Conventions
These are just suggestions that have made our time coding in Unity easier.
* When having a function being called inside of one of [MonoBehavior's messages](http://docs.unity3d.com/ScriptReference/MonoBehaviour.html) ( ex: ```Update()``` ), then that function should end in that message's name.
  * This makes programming state machine's easier.  The ```Update()``` contains a switch statement that calls the appropriate function based on the state.
  * ex: In ```Flee``` state, ```FleeUpdate()``` is a method that is called inside of [Update](http://docs.unity3d.com/ScriptReference/MonoBehaviour.Update.html).
  * ex: In ```Flee``` state, ```FleeOnCollisionEnter()``` is a method that is called inside of [OnCollisionEnter](http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter.html)
* Initialize ```Vector3``` variables to ```Vector3.zero;```
* If you want to edit a script's variable in monobehavior add the ```[SerializeField]``` line above the variable decleration.
* You should most likely be using a ```CharacterController``` rather than a rigid body for agent movement.
* Don't use ```Destroy( gameObject )``` for removing the gameobject in the scene.  If there comes a time that you need to remove a gameobject from the scene localize that ```Destroy()``` statement to its own method that can be called. Similar to destructors.


text:
<?php

declare(strict_types=1);

namespace Gedmo\Tests\Loggable\Fixture\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\ODM\MongoDB\Types\Type;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Tests\Loggable\Fixture\Document\Log\Comment as CommentLog;

/**
 * @ODM\Document
 * @Gedmo\Loggable(logEntryClass="Gedmo\Tests\Loggable\Fixture\Document\Log\Comment")
 */
#[ODM\Document]
#[Gedmo\Loggable(logEntryClass: CommentLog::class)]
class Comment
{
    /**
     * @var string|null
     * @ODM\Id
     */
    #[ODM\Id]
    private $id;

    /**
     * @var string|null
     * @Gedmo\Versioned
     * @ODM\Field(type="string")
     */
    #[ODM\Field(type: Type::STRING)]
    #[Gedmo\Versioned]
    private $subject;

    /**
     * @var string|null
     * @Gedmo\Versioned
     * @ODM\Field(type="string")
     */
    #[ODM\Field(type: Type::STRING)]
    #[Gedmo\Versioned]
    private $message;

    /**
     * @var RelatedArticle|null
     * @Gedmo\Versioned
     * @ODM\ReferenceOne(targetDocument="Gedmo\Tests\Loggable\Fixture\Document\RelatedArticle", inversedBy="comments")
     */
    #[ODM\ReferenceOne(targetDocument: RelatedArticle::class, inversedBy: 'comments')]
    #[Gedmo\Versioned]
    private $article;

    /**
     * @var Author|null
     * @ODM\EmbedOne(targetDocument="Gedmo\Tests\Loggable\Fixture\Document\Author")
     * @Gedmo\Versioned
     */
    #[ODM\EmbedOne(targetDocument: Author::class)]
    #[Gedmo\Versioned]
    private $author;

    public function setArticle(?RelatedArticle $article): void
    {
        $this->article = $article;
    }

    public function getArticle(): ?RelatedArticle
    {
        return $this->article;
    }

    public function getId(): ?string
    {
        return $this->id;
    }

    public function setSubject(?string $subject): void
    {
        $this->subject = $subject;
    }

    public function getSubject(): ?string
    {
        return $this->subject;
    }

    public function setMessage(?string $message): void
    {
        $this->message = $message;
    }

    public function getMessage(): ?string
    {
        return $this->message;
    }

    public function setAuthor(?Author $author): void
    {
        $this->author = $author;
    }

    public function getAuthor(): ?Author
    {
        return $this->author;
    }
}


text:
package com.sromku.simple.fb.utils;

import java.util.Locale;

public class Errors {
    public static enum ErrorMsg {
        LOGIN("You are not logged in"),
        CANCEL_WEB_LOGIN("User canceled the login web dialog"),
        PERMISSIONS_PUBLISH("Publish permission: '%s' wasn't set by SimpleFacebookConfiguration"),
        CANCEL_PERMISSIONS_PUBLISH("Publish permissions: '%s' weren't accepted by user");

        private String mMsg;

        private ErrorMsg(String msg) {
            mMsg = msg;
        }

        public String message() {
            return mMsg;
        }
    }

    /**
     * Get final error message
     *
     * @param errorMsg
     * @param params
     * @return
     */
    public static String getError(ErrorMsg errorMsg, Object... params) {
        if (params == null) {
            return errorMsg.message();
        }
        else {
            return String.format(Locale.US, errorMsg.message(), params);
        }
    }

    public static String getError(ErrorMsg errorMsg) {
        return errorMsg.message();
    }
}


text:
import '@testing-library/jest-dom/extend-expect';

import { render } from '@testing-library/react';
import React from 'react';

import App from './App';

test('renders learn react link', () => {
  const { getByText } = render(<App />);
  const linkElement = getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});


text:
import { Component, OnInit } from '@angular/core';
import { Service327Service } from '../../services/service-327.service';

@Component({
  selector: 'app-comp-327',
  templateUrl: './comp-327.component.html',
  styleUrls: ['./comp-327.component.css']
})
export class Comp327Component implements OnInit {

  constructor(private _service: Service327Service) { }

  ngOnInit() {
  }

}