text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.apache.nutch.protocol.Content (apache-nutch 1.9 API)</title>
<meta name="date" content="2014-08-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.nutch.protocol.Content

Packages that use Content

Package
Description

org.apache.nutch.analysis.lang

Text document language identifier.

org.apache.nutch.crawl

Crawl control code and tools to run the crawler.

org.apache.nutch.microformats.reltag

A microformats Rel-Tag
Parser/Indexer/Querier plugin.

org.apache.nutch.parse

The Parse interface and related classes.

org.apache.nutch.parse.ext

Parse wrapper to run external command to do the parsing.

org.apache.nutch.parse.feed

Parse RSS feeds.

org.apache.nutch.parse.headings

Parse filter to extract headings (h1, h2, etc.) from DOM parse tree.

org.apache.nutch.parse.html

An HTML document parsing plugin.

org.apache.nutch.parse.js

Parser and parse filter plugin to extract all (possible) links
 from JavaScript files and embedded JavaScript code snippets.

org.apache.nutch.parse.metatags

Parse filter to extract meta tags: keywords, description, etc.

org.apache.nutch.parse.swf

Parse Flash SWF files.

org.apache.nutch.parse.tika

Parse various document formats with help of
 Apache Tika.

org.apache.nutch.parse.zip

Parse ZIP files: embedded files are recursively passed to appropriate parsers.

org.apache.nutch.protocol

Classes related to the Protocol interface,
 see also org.apache.nutch.net.protocols.

org.apache.nutch.protocol.file

Protocol plugin which supports retrieving local file resources.

org.apache.nutch.protocol.ftp

Protocol plugin which supports retrieving documents via the ftp protocol.

org.apache.nutch.scoring

The ScoringFilter interface.

org.apache.nutch.scoring.depth

Scoring filter to stop crawling at a configurable depth
 (number of "hops" from seed URLs).

org.apache.nutch.scoring.link

Scoring filter used in conjunction with
 WebGraph.

org.apache.nutch.scoring.opic

Scoring filter implementing a variant of the Online Page Importance Computation
 (OPIC) algorithm.

org.apache.nutch.scoring.tld

Top Level Domain Scoring plugin.

org.apache.nutch.scoring.urlmeta

      URL Meta Tag Scoring Plugin

org.apache.nutch.segment

A segment stores all data from on generate/fetch/update cycle:
 fetch list, protocol status, raw content, parsed content, and extracted outgoing links.

org.apache.nutch.util

Miscellaneous utility classes.

org.creativecommons.nutch

Sample plugins that parse and index Creative Commons medadata.

Uses of Content in org.apache.nutch.analysis.lang

Methods in org.apache.nutch.analysis.lang with parameters of type Content

Modifier and Type
Method and Description

ParseResult
HTMLLanguageParser.filter(Content content,
      ParseResult parseResult,
      HTMLMetaTags metaTags,
      DocumentFragment doc)

Scan the HTML document looking at possible indications of content
 language

 1.

Uses of Content in org.apache.nutch.crawl

Methods in org.apache.nutch.crawl with parameters of type Content

Modifier and Type
Method and Description

byte[]
TextProfileSignature.calculate(Content content,
         Parse parse)

abstract byte[]
Signature.calculate(Content content,
         Parse parse)

byte[]
MD5Signature.calculate(Content content,
         Parse parse)

Uses of Content in org.apache.nutch.microformats.reltag

Methods in org.apache.nutch.microformats.reltag with parameters of type Content

Modifier and Type
Method and Description

ParseResult
RelTagParser.filter(Content content,
      ParseResult parseResult,
      HTMLMetaTags metaTags,
      DocumentFragment doc)

Scan the HTML document looking at possible rel-tags

Uses of Content in org.apache.nutch.parse

Methods in org.apache.nutch.parse with parameters of type Content

Modifier and Type
Method and Description

ParseResult
HtmlParseFilters.filter(Content content,
      ParseResult parseResult,
      HTMLMetaTags metaTags,
      DocumentFragment doc)

Run all defined filters.

ParseResult
HtmlParseFilter.filter(Content content,
      ParseResult parseResult,
      HTMLMetaTags metaTags,
      DocumentFragment doc)

Adds metadata or otherwise modifies a parse of HTML content, given
 the DOM tree of a page.

ParseResult
Parser.getParse(Content c)

 This method parses the given content and returns a map of
 <key, parse> pairs.

static boolean
ParseSegment.isTruncated(Content content)

Checks if the page's content is truncated.

void
ParseSegment.map(org.apache.hadoop.io.WritableComparable<?> key,
   Content content,
   org.apache.hadoop.mapred.OutputCollector<org.apache.hadoop.io.Text,ParseImpl> output,
   org.apache.hadoop.mapred.Reporter reporter)

ParseResult
ParseUtil.parse(Content content)

Performs a parse by iterating through a List of preferred Parsers
 until a successful parse is performed and a Parse object is
 returned.

ParseResult
ParseUtil.parseByExtensionId(String extId,
                  Content content)

Method parses a Content object using the Parser specified
 by the parameter extId, i.e., the Parser's extension ID.

Uses of Content in org.apache.nutch.parse.ext

Methods in org.apache.nutch.parse.ext with parameters of type Content

Modifier and Type
Method and Description

ParseResult
ExtParser.getParse(Content content)

Uses of Content in org.apache.nutch.parse.feed

Methods in org.apache.nutch.parse.feed with parameters of type Content

Modifier and Type
Method and Description

ParseResult
FeedParser.getParse(Content content)

Parses the given feed and extracts out and parsers all linked items within
 the feed, using the underlying ROME feed parsing library.

Uses of Content in org.apache.nutch.parse.headings

Methods in org.apache.nutch.parse.headings with parameters of type Content

Modifier and Type
Method and Description

ParseResult
HeadingsParseFilter.filter(Content content,
      ParseResult parseResult,
      HTMLMetaTags metaTags,
      DocumentFragment doc)

Uses of Content in org.apache.nutch.parse.html

Methods in org.apache.nutch.parse.html with parameters of type Content

Modifier and Type
Method and Description

ParseResult
HtmlParser.getParse(Content content)

Uses of Content in org.apache.nutch.parse.js

Methods in org.apache.nutch.parse.js with parameters of type Content

Modifier and Type
Method and Description

ParseResult
JSParseFilter.filter(Content content,
      ParseResult parseResult,
      HTMLMetaTags metaTags,
      DocumentFragment doc)

ParseResult
JSParseFilter.getParse(Content c)

Uses of Content in org.apache.nutch.parse.metatags

Methods in org.apache.nutch.parse.metatags with parameters of type Content

Modifier and Type
Method and Description

ParseResult
MetaTagsParser.filter(Content content,
      ParseResult parseResult,
      HTMLMetaTags metaTags,
      DocumentFragment doc)

Uses of Content in org.apache.nutch.parse.swf

Methods in org.apache.nutch.parse.swf with parameters of type Content

Modifier and Type
Method and Description

ParseResult
SWFParser.getParse(Content content)

Uses of Content in org.apache.nutch.parse.tika

Methods in org.apache.nutch.parse.tika with parameters of type Content

Modifier and Type
Method and Description

ParseResult
TikaParser.getParse(Content content)

Uses of Content in org.apache.nutch.parse.zip

Methods in org.apache.nutch.parse.zip with parameters of type Content

Modifier and Type
Method and Description

ParseResult
ZipParser.getParse(Content content)

Uses of Content in org.apache.nutch.protocol

Methods in org.apache.nutch.protocol that return Content

Modifier and Type
Method and Description

Content
ProtocolOutput.getContent()

static Content
Content.read(DataInput in)

Methods in org.apache.nutch.protocol with parameters of type Content

Modifier and Type
Method and Description

void
ProtocolOutput.setContent(Content content)

Constructors in org.apache.nutch.protocol with parameters of type Content

Constructor and Description

ProtocolOutput(Content content)

ProtocolOutput(Content content,
              ProtocolStatus status)

Uses of Content in org.apache.nutch.protocol.file

Methods in org.apache.nutch.protocol.file that return Content

Modifier and Type
Method and Description

Content
FileResponse.toContent()

Uses of Content in org.apache.nutch.protocol.ftp

Methods in org.apache.nutch.protocol.ftp that return Content

Modifier and Type
Method and Description

Content
FtpResponse.toContent()

Uses of Content in org.apache.nutch.scoring

Methods in org.apache.nutch.scoring with parameters of type Content

Modifier and Type
Method and Description

void
ScoringFilters.passScoreAfterParsing(org.apache.hadoop.io.Text url,
                     Content content,
                     Parse parse)

void
ScoringFilter.passScoreAfterParsing(org.apache.hadoop.io.Text url,
                     Content content,
                     Parse parse)

Currently a part of score distribution is performed using only data coming
 from the parsing process.

void
AbstractScoringFilter.passScoreAfterParsing(org.apache.hadoop.io.Text url,
                     Content content,
                     Parse parse)

void
ScoringFilters.passScoreBeforeParsing(org.apache.hadoop.io.Text url,
                      CrawlDatum datum,
                      Content content)

void
ScoringFilter.passScoreBeforeParsing(org.apache.hadoop.io.Text url,
                      CrawlDatum datum,
                      Content content)

This method takes all relevant score information from the current datum
 (coming from a generated fetchlist) and stores it into
 Content metadata.

void
AbstractScoringFilter.passScoreBeforeParsing(org.apache.hadoop.io.Text url,
                      CrawlDatum datum,
                      Content content)

Uses of Content in org.apache.nutch.scoring.depth

Methods in org.apache.nutch.scoring.depth with parameters of type Content

Modifier and Type
Method and Description

void
DepthScoringFilter.passScoreAfterParsing(org.apache.hadoop.io.Text url,
                     Content content,
                     Parse parse)

void
DepthScoringFilter.passScoreBeforeParsing(org.apache.hadoop.io.Text url,
                      CrawlDatum datum,
                      Content content)

Uses of Content in org.apache.nutch.scoring.link

Methods in org.apache.nutch.scoring.link with parameters of type Content

Modifier and Type
Method and Description

void
LinkAnalysisScoringFilter.passScoreAfterParsing(org.apache.hadoop.io.Text url,
                     Content content,
                     Parse parse)

void
LinkAnalysisScoringFilter.passScoreBeforeParsing(org.apache.hadoop.io.Text url,
                      CrawlDatum datum,
                      Content content)

Uses of Content in org.apache.nutch.scoring.opic

Methods in org.apache.nutch.scoring.opic with parameters of type Content

Modifier and Type
Method and Description

void
OPICScoringFilter.passScoreAfterParsing(org.apache.hadoop.io.Text url,
                     Content content,
                     Parse parse)

Copy the value from Content metadata under Fetcher.SCORE_KEY to parseData.

void
OPICScoringFilter.passScoreBeforeParsing(org.apache.hadoop.io.Text url,
                      CrawlDatum datum,
                      Content content)

Store a float value of CrawlDatum.getScore() under Fetcher.SCORE_KEY.

Uses of Content in org.apache.nutch.scoring.tld

Methods in org.apache.nutch.scoring.tld with parameters of type Content

Modifier and Type
Method and Description

void
TLDScoringFilter.passScoreAfterParsing(org.apache.hadoop.io.Text url,
                     Content content,
                     Parse parse)

void
TLDScoringFilter.passScoreBeforeParsing(org.apache.hadoop.io.Text url,
                      CrawlDatum datum,
                      Content content)

Uses of Content in org.apache.nutch.scoring.urlmeta

Methods in org.apache.nutch.scoring.urlmeta with parameters of type Content

Modifier and Type
Method and Description

void
URLMetaScoringFilter.passScoreAfterParsing(org.apache.hadoop.io.Text url,
                     Content content,
                     Parse parse)

Takes the metadata, which was lumped inside the content, and replicates it
 within your parse data.

void
URLMetaScoringFilter.passScoreBeforeParsing(org.apache.hadoop.io.Text url,
                      CrawlDatum datum,
                      Content content)

Takes the metadata, specified in your "urlmeta.tags" property, from the
 datum object and injects it into the content.

Uses of Content in org.apache.nutch.segment

Methods in org.apache.nutch.segment with parameters of type Content

Modifier and Type
Method and Description

boolean
SegmentMergeFilters.filter(org.apache.hadoop.io.Text key,
      CrawlDatum generateData,
      CrawlDatum fetchData,
      CrawlDatum sigData,
      Content content,
      ParseData parseData,
      ParseText parseText,
      Collection<CrawlDatum> linked)

Iterates over all SegmentMergeFilter extensions and if any of them
 returns false, it will return false as well.

boolean
SegmentMergeFilter.filter(org.apache.hadoop.io.Text key,
      CrawlDatum generateData,
      CrawlDatum fetchData,
      CrawlDatum sigData,
      Content content,
      ParseData parseData,
      ParseText parseText,
      Collection<CrawlDatum> linked)

The filtering method which gets all information being merged for a given
 key (URL).

Uses of Content in org.apache.nutch.util

Methods in org.apache.nutch.util with parameters of type Content

Modifier and Type
Method and Description

void
EncodingDetector.autoDetectClues(Content content,
               boolean filter)

String
EncodingDetector.guessEncoding(Content content,
             String defaultValue)

Guess the encoding with the previously specified list of clues.

Uses of Content in org.creativecommons.nutch

Methods in org.creativecommons.nutch with parameters of type Content

Modifier and Type
Method and Description

ParseResult
CCParseFilter.filter(Content content,
      ParseResult parseResult,
      HTMLMetaTags metaTags,
      DocumentFragment doc)

Adds metadata or otherwise modifies a parse of an HTML document, given
 the DOM tree of a page.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 The Apache Software Foundation


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../libc/constant.CLOCK_THREAD_CPUTIME_ID.html">

Redirecting to ../../../libc/constant.CLOCK_THREAD_CPUTIME_ID.html...

redpajama_set_name: RedPajamaGithub


text:
// load the soundcloud api
var scr = document.createElement('script'),
    head = document.head || document.getElementsByTagName('head')[0];
scr.async = false;
scr.type = "text/javascript";
scr.src = "https://w.soundcloud.com/player/api.js";
head.insertBefore(scr, head.firstChild);

var soundCloudInstance;

/**
 * BaseMusicPlayer for Soundcloud
 */
class SoundCloudPlayer extends BaseMusicPlayer{
    /**
     * @constructor
     * @param name {string} plugin name (
     */
    constructor() {
        super("soundcloud")
        const self = this;
        this.settings = {playing: false, volume: 100}
        this.widget = null;
        this.ready = false;
        this.time = 0;
        this.duration = 0;
        this.stopped = false;
        this.loadLater = null;
        // create and load the iframe
        this.element = $('');
        this.element.appendTo("body");

        var widgetIframe = document.getElementById('soundcloud-frame');
        const seconds = new Date().getTime() / 1000;

        /**
         * Load the player (can only be done after soundcloud api is finished loading)
         * (-> dirty bugfix, but it seems there is no other way...)
         */
        const load = function(){
            if(typeof SC == 'undefined' || SC == null){
                if(seconds + 5 < (new Date().getTime() / 1000)){
                    Log.error("could not load soundcloud api");
                    return;
                }
                window.setTimeout(load, 500);
            }else {
                soundCloudInstance.widget = SC.Widget(widgetIframe);

                soundCloudInstance.ready = false;
                soundCloudInstance.widget.bind(SC.Widget.Events.READY, function () {
                    soundCloudInstance.ready = true;
                    soundCloudInstance.setVolume(soundCloudInstance.settings.volume);
                    if (soundCloudInstance.settings.playing) {
                        soundCloudInstance.play();
                    }
                    Central.getPlayer().addPlugin(soundCloudInstance);
                    soundCloudInstance.widget.unbind(SC.Widget.Events.READY);
                });

                soundCloudInstance.widget.bind(SC.Widget.Events.FINISH, function () {
                    Central.getPlayer().nextSong();
                })
                self.element.hide();
            }
        }
        window.setTimeout(load, 100);

    }

    /**
     * Play the currently loaded song
     * @override
     */
    play() {
        this.settings.playing = true;
        if (this.ready) {
            this.widget.play();
        }
    }

    /**
     * Pause the current song
     * @override
     */
    pause() {
        this.settings.playing = false;
        if (this.ready) {
            this.widget.pause();
        }
    }

    /**
     * Load a soundcloud URL
     * @param url {string}
     * @override
     */
    load(url) {
        // first has to finish loading the last song -> if not, this is done later
        if (this.ready) {
            // player settings
            url += '&auto_play=false&liking=false&buying=false&sharing=false&'
                + 'hide_related=true&show_comments=false&download=false&'
                + 'show_user=false&show_reposts=false&visual=true';

            this.ready = false;
            this.stopped = false;

            // unload old listeners
            this.widget.unbind(SC.Widget.Events.READY);
            this.widget.unbind(SC.Widget.Events.PAUSE);
            this.widget.unbind(SC.Widget.Events.PLAY);

            soundCloudInstance.element.show();
            this.widget.load(url);

            this.widget.bind(SC.Widget.Events.READY, function () {
                soundCloudInstance.ready = true;

                // if between loading and the ready event an other song was loaded, load this one
                if(soundCloudInstance.loadLater != null){
                    soundCloudInstance.load(soundCloudInstance.loadLater);
                    soundCloudInstance.loadLater = null;
                    return;
                }
                if(soundCloudInstance.stopped){
                    soundCloudInstance.element.hide();
                    return;
                }

                soundCloudInstance.setVolume(soundCloudInstance.settings.volume);
                if (soundCloudInstance.settings.playing) {
                    soundCloudInstance.play();
                }
                // get the duration of the new song
                soundCloudInstance.widget.getDuration(function(aw){
                    soundCloudInstance.duration = aw/1000;
                });

                const getTime = function(aw){
                    soundCloudInstance.time = aw/1000;
                }

                // check the time of the song every second
                const checkTime = function(){
                    if(soundCloudInstance.ready){
                        soundCloudInstance.widget.getPosition(getTime);
                        window.setTimeout(checkTime, 1000);
                    }
                }
                checkTime();
            });

            // if the pause button inside the widget is clicked, also reset the pause button of the player
            this.widget.bind(SC.Widget.Events.PAUSE, function(){
                soundCloudInstance.settings.playing = false;
                var song = Central.getPlayer().getCurrentSong();
                Central.getPlayer().getPlayQueue().notifyListeners(song);
            });

            this.widget.bind(SC.Widget.Events.PLAY, function(){
                soundCloudInstance.settings.playing = true;
                var song = Central.getPlayer().getCurrentSong();
                Central.getPlayer().getPlayQueue().notifyListeners(song);
            })

        }else{ // if not ready, load later
            this.loadLater = url;
            this.element.show();
        }
    }

    /**
     * Stop the player and hide it
     * @override
     */
    stop() {
        this.settings.playing = false;
        this.widget.pause();
        this.element.hide();
        this.stopped = true;
    }

    /**
     * Set the volume
     * @param volume {number} 0-100
     * @override
     */
    setVolume(volume) {
        if (this.ready) {
            this.widget.setVolume(volume);
            this.settings.volume = volume;
        }
    }

    /**
     * Get the current time of the song
     * @return {number} in sectonds
     * @override
     */
    getTime() {
        return this.time;
    }

    /**
     * Get the duration of the current song
     * @return {number} in seconds
     * @override
     */
    getDuration() {
        return this.duration;
    }

    // TODO: tryLoadSource
}

soundCloudInstance = new SoundCloudPlayer();

/**
 * BaseUrlPreview for Soundcloud URLs
 * see /js/models/PluginBase.js for more detail
 */
class SoundCloudPreview extends BaseUrlPreview {
    /**
     * @constructor
     */
    constructor(){
        super("soundcloud");
    }

    /**
     * Checks if the url contains "soundcloud.com"
     * @param url {string}
     * @return {boolean} supported or not
     */
    supportsUrl(url) {
        return (url.search("soundcloud.com") >= 0);
    }

    /**
     * Previews an URL inside an jQuery HTMLElement
     * @param element {HTMLElement} jQuery HTMLElement to render into
     * @param url {string}
     * @param callback {function(object)}
     */
    preview(element, url, callback) {
        const self = this;
        this.element = element;

        if (url.startsWith("www")) {
            url = "https://" + url;
        }
        if (url.startsWith("http://")) {
            url = "https://" + url.substring(7);
        }

        const iframe = $('');

        const title = $('
loading title...
');
        title.appendTo(this.element);
        iframe.appendTo(this.element);

        // Load the html of the page using the backend
        LocalComm.newMessage({command: "get url", url: url},
            Message.Components.GUI, function (data) {
                if (typeof data.answer !== 'undefined' && data.answer !== null) {
                    var html = data.answer;
                    // TODO: remove everything but the header (rest is not needed)
                    const doc = document.implementation.createHTMLDocument('sc');
                    doc.documentElement.innerHTML = html;

                    var trackname = doc.title;
                    var pos = 0;
                    // remove "by user | Listen on Soundcloud"
                    for (var i = trackname.length; i > 0 && pos == 0; i--) {
                        if (trackname.charAt(i) == 'y' && trackname.charAt(i - 1) == 'b') {
                            pos = i - 1;
                        }
                    }
                    trackname = trackname.substring(0, pos);

                    title.html(trackname);

                    var song = {title: trackname, type: "soundcloud", value: url};
                    var split = trackname.split("-");
                    if (split.length >= 2) {
                        song.artist = split[0].trim();
                        song.title = split[1].trim();
                    }

                    callback(song);
                } else {
                    Log.error("SoundCloud: invalid answer from GUI: " + JSON.stringify(data));
                }
            });
    }
}

Central.getUrlPreview().addPlugin(new SoundCloudPreview());


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PatanHospital.Account
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
        }
    }
}


text:
package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"github.com/docker/docker/pkg/archive"
	"github.com/go-check/check"
)

type fileType uint32

const (
	ftRegular fileType = iota
	ftDir
	ftSymlink
)

type fileData struct {
	filetype fileType
	path     string
	contents string
}

func (fd fileData) creationCommand() string {
	var command string

	switch fd.filetype {
	case ftRegular:
		// Don't overwrite the file if it already exists!
		command = fmt.Sprintf("if [ ! -f %s ]; then echo %q > %s; fi", fd.path, fd.contents, fd.path)
	case ftDir:
		command = fmt.Sprintf("mkdir -p %s", fd.path)
	case ftSymlink:
		command = fmt.Sprintf("ln -fs %s %s", fd.contents, fd.path)
	}

	return command
}

func mkFilesCommand(fds []fileData) string {
	commands := make([]string, len(fds))

	for i, fd := range fds {
		commands[i] = fd.creationCommand()
	}

	return strings.Join(commands, " && ")
}

var defaultFileData = []fileData{
	{ftRegular, "file1", "file1"},
	{ftRegular, "file2", "file2"},
	{ftRegular, "file3", "file3"},
	{ftRegular, "file4", "file4"},
	{ftRegular, "file5", "file5"},
	{ftRegular, "file6", "file6"},
	{ftRegular, "file7", "file7"},
	{ftDir, "dir1", ""},
	{ftRegular, "dir1/file1-1", "file1-1"},
	{ftRegular, "dir1/file1-2", "file1-2"},
	{ftDir, "dir2", ""},
	{ftRegular, "dir2/file2-1", "file2-1"},
	{ftRegular, "dir2/file2-2", "file2-2"},
	{ftDir, "dir3", ""},
	{ftRegular, "dir3/file3-1", "file3-1"},
	{ftRegular, "dir3/file3-2", "file3-2"},
	{ftDir, "dir4", ""},
	{ftRegular, "dir4/file3-1", "file4-1"},
	{ftRegular, "dir4/file3-2", "file4-2"},
	{ftDir, "dir5", ""},
	{ftSymlink, "symlink1", "target1"},
	{ftSymlink, "symlink2", "target2"},
}

func defaultMkContentCommand() string {
	return mkFilesCommand(defaultFileData)
}

func makeTestContentInDir(c *check.C, dir string) {
	for _, fd := range defaultFileData {
		path := filepath.Join(dir, filepath.FromSlash(fd.path))
		switch fd.filetype {
		case ftRegular:
			if err := ioutil.WriteFile(path, []byte(fd.contents+"\n"), os.FileMode(0666)); err != nil {
				c.Fatal(err)
			}
		case ftDir:
			if err := os.Mkdir(path, os.FileMode(0777)); err != nil {
				c.Fatal(err)
			}
		case ftSymlink:
			if err := os.Symlink(fd.contents, path); err != nil {
				c.Fatal(err)
			}
		}
	}
}

type testContainerOptions struct {
	addContent bool
	readOnly   bool
	volumes    []string
	workDir    string
	command    string
}

func makeTestContainer(c *check.C, options testContainerOptions) (containerID string) {
	if options.addContent {
		mkContentCmd := defaultMkContentCommand()
		if options.command == "" {
			options.command = mkContentCmd
		} else {
			options.command = fmt.Sprintf("%s && %s", defaultMkContentCommand(), options.command)
		}
	}

	if options.command == "" {
		options.command = "#(nop)"
	}

	args := []string{"run", "-d"}

	for _, volume := range options.volumes {
		args = append(args, "-v", volume)
	}

	if options.workDir != "" {
		args = append(args, "-w", options.workDir)
	}

	if options.readOnly {
		args = append(args, "--read-only")
	}

	args = append(args, "busybox", "/bin/sh", "-c", options.command)

	out, status := dockerCmd(c, args...)
	if status != 0 {
		c.Fatalf("failed to run container, status %d: %s", status, out)
	}

	containerID = strings.TrimSpace(out)

	out, status = dockerCmd(c, "wait", containerID)
	if status != 0 {
		c.Fatalf("failed to wait for test container container, status %d: %s", status, out)
	}

	if exitCode := strings.TrimSpace(out); exitCode != "0" {
		logs, status := dockerCmd(c, "logs", containerID)
		if status != 0 {
			logs = "UNABLE TO GET LOGS"
		}
		c.Fatalf("failed to make test container, exit code (%s): %s", exitCode, logs)
	}

	return
}

func makeCatFileCommand(path string) string {
	return fmt.Sprintf("if [ -f %s ]; then cat %s; fi", path, path)
}

func cpPath(pathElements ...string) string {
	localizedPathElements := make([]string, len(pathElements))
	for i, path := range pathElements {
		localizedPathElements[i] = filepath.FromSlash(path)
	}
	return strings.Join(localizedPathElements, string(filepath.Separator))
}

func cpPathTrailingSep(pathElements ...string) string {
	return fmt.Sprintf("%s%c", cpPath(pathElements...), filepath.Separator)
}

func containerCpPath(containerID string, pathElements ...string) string {
	joined := strings.Join(pathElements, "/")
	return fmt.Sprintf("%s:%s", containerID, joined)
}

func containerCpPathTrailingSep(containerID string, pathElements ...string) string {
	return fmt.Sprintf("%s/", containerCpPath(containerID, pathElements...))
}

func runDockerCp(c *check.C, src, dst string) (err error) {
	c.Logf("running `docker cp %s %s`", src, dst)

	args := []string{"cp", src, dst}

	out, _, err := runCommandWithOutput(exec.Command(dockerBinary, args...))
	if err != nil {
		err = fmt.Errorf("error executing `docker cp` command: %s: %s", err, out)
	}

	return
}

func startContainerGetOutput(c *check.C, cID string) (out string, err error) {
	c.Logf("running `docker start -a %s`", cID)

	args := []string{"start", "-a", cID}

	out, _, err = runCommandWithOutput(exec.Command(dockerBinary, args...))
	if err != nil {
		err = fmt.Errorf("error executing `docker start` command: %s: %s", err, out)
	}

	return
}

func getTestDir(c *check.C, label string) (tmpDir string) {
	var err error

	if tmpDir, err = ioutil.TempDir("", label); err != nil {
		c.Fatalf("unable to make temporary directory: %s", err)
	}

	return
}

func isCpNotExist(err error) bool {
	return strings.Contains(err.Error(), "no such file or directory") || strings.Contains(err.Error(), "cannot find the file specified")
}

func isCpDirNotExist(err error) bool {
	return strings.Contains(err.Error(), archive.ErrDirNotExists.Error())
}

func isCpNotDir(err error) bool {
	return strings.Contains(err.Error(), archive.ErrNotDirectory.Error()) || strings.Contains(err.Error(), "filename, directory name, or volume label syntax is incorrect")
}

func isCpCannotCopyDir(err error) bool {
	return strings.Contains(err.Error(), archive.ErrCannotCopyDir.Error())
}

func isCpCannotCopyReadOnly(err error) bool {
	return strings.Contains(err.Error(), "marked read-only")
}

func isCannotOverwriteNonDirWithDir(err error) bool {
	return strings.Contains(err.Error(), "cannot overwrite non-directory")
}

func fileContentEquals(c *check.C, filename, contents string) (err error) {
	c.Logf("checking that file %q contains %q\n", filename, contents)

	fileBytes, err := ioutil.ReadFile(filename)
	if err != nil {
		return
	}

	expectedBytes, err := ioutil.ReadAll(strings.NewReader(contents))
	if err != nil {
		return
	}

	if !bytes.Equal(fileBytes, expectedBytes) {
		err = fmt.Errorf("file content not equal - expected %q, got %q", string(expectedBytes), string(fileBytes))
	}

	return
}

func containerStartOutputEquals(c *check.C, cID, contents string) (err error) {
	c.Logf("checking that container %q start output contains %q\n", cID, contents)

	out, err := startContainerGetOutput(c, cID)
	if err != nil {
		return err
	}

	if out != contents {
		err = fmt.Errorf("output contents not equal - expected %q, got %q", contents, out)
	}

	return
}

func defaultVolumes(tmpDir string) []string {
	if SameHostDaemon.Condition() {
		return []string{
			"/vol1",
			fmt.Sprintf("%s:/vol2", tmpDir),
			fmt.Sprintf("%s:/vol3", filepath.Join(tmpDir, "vol3")),
			fmt.Sprintf("%s:/vol_ro:ro", filepath.Join(tmpDir, "vol_ro")),
		}
	}

	// Can't bind-mount volumes with separate host daemon.
	return []string{"/vol1", "/vol2", "/vol3", "/vol_ro:/vol_ro:ro"}
}


text:
This document covers using the [OAuth2](https://oauth.net/2/) protocol to allow
other services to access GitLab resources on user's behalf.

If you want GitLab to be an OAuth authentication service provider to sign into
other services, see the [OAuth2 provider](../integration/oauth_provider.md)
documentation. This functionality is based on the
[doorkeeper Ruby gem](https://github.com/doorkeeper-gem/doorkeeper).

## Supported OAuth2 flows

GitLab currently supports the following authorization flows:

- **Web application flow:** Most secure and common type of flow, designed for
  applications with secure server-side.
- **Implicit grant flow:** This flow is designed for user-agent only apps (e.g., single
  page web application running on GitLab Pages).
- **Resource owner password credentials flow:** To be used **only** for securely
  hosted, first-party services.

Refer to the [OAuth RFC](https://tools.ietf.org/html/rfc6749) to find out
how all those flows work and pick the right one for your use case.

Both **web application** and **implicit grant** flows require `application` to be
registered first via the `/profile/applications` page in your user's account.
During registration, by enabling proper scopes, you can limit the range of
resources which the `application` can access. Upon creation, you'll obtain the
`application` credentials: _Application ID_ and _Client Secret_ - **keep them secure**.

CAUTION: **Important:**
OAuth specification advises sending the `state` parameter with each request to
`/oauth/authorize`. We highly recommended sending a unique value with each request
and validate it against the one in the redirect request. This is important in
order to prevent [CSRF attacks](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)).
The `state` parameter really should have been a requirement in the standard!

In the following sections you will find detailed instructions on how to obtain
authorization with each flow.

### Web application flow

NOTE: **Note:**
Check the [RFC spec](https://tools.ietf.org/html/rfc6749#section-4.1) for a
detailed flow description.

The web application flow is:

1. Request authorization code. To do that, you should redirect the user to the
   `/oauth/authorize` endpoint with the following GET parameters:

   ```
   https://gitlab.example.com/oauth/authorize?client_id=APP_ID&redirect_uri=REDIRECT_URI&response_type=code&state=YOUR_UNIQUE_STATE_HASH&scope=REQUESTED_SCOPES
   ```

   This will ask the user to approve the applications access to their account
   based on the scopes specified in `REQUESTED_SCOPES` and then redirect back to
   the `REDIRECT_URI` you provided. The [scope parameter](https://github.com/doorkeeper-gem/doorkeeper/wiki/Using-Scopes#requesting-particular-scopes)
   is a space separated list of scopes you want to have access to (e.g. `scope=read_user+profile`
   would request `read_user` and `profile` scopes). The redirect will
   include the GET `code` parameter, for example:

   ```
   http://myapp.com/oauth/redirect?code=1234567890&state=YOUR_UNIQUE_STATE_HASH
   ```

   You should then use `code` to request an access token.

1. Once you have the authorization code you can request an `access_token` using the
   code. You can do that by using any HTTP client. In the following example,
   we are using Ruby's `rest-client`:

   ```ruby
   parameters = 'client_id=APP_ID&client_secret=APP_SECRET&code=RETURNED_CODE&grant_type=authorization_code&redirect_uri=REDIRECT_URI'
   RestClient.post 'http://gitlab.example.com/oauth/token', parameters
   ```

   Example response:

   ```json
   {
    "access_token": "de6780bc506a0446309bd9362820ba8aed28aa506c71eedbe1c5c4f9dd350e54",
    "token_type": "bearer",
    "expires_in": 7200,
    "refresh_token": "8257e65c97202ed1726cf9571600918f3bffb2544b26e00a61df9897668c33a1"
   }
   ```

NOTE: **Note:**
The `redirect_uri` must match the `redirect_uri` used in the original
authorization request.

You can now make requests to the API with the access token returned.

### Implicit grant flow

NOTE: **Note:**
Check the [RFC spec](https://tools.ietf.org/html/rfc6749#section-4.2) for a
detailed flow description.

CAUTION: **Important:**
Avoid using this flow for applications that store data outside of the GitLab
instance. If you do, make sure to verify `application id` associated with the
access token before granting access to the data
(see [`/oauth/token/info`](https://github.com/doorkeeper-gem/doorkeeper/wiki/API-endpoint-descriptions-and-examples#get----oauthtokeninfo)).

Unlike the web flow, the client receives an `access token` immediately as a
result of the authorization request. The flow does not use the client secret
or the authorization code because all of the application code and storage is
easily accessible, therefore secrets can leak easily.

To request the access token, you should redirect the user to the
`/oauth/authorize` endpoint using `token` response type:

```
https://gitlab.example.com/oauth/authorize?client_id=APP_ID&redirect_uri=REDIRECT_URI&response_type=token&state=YOUR_UNIQUE_STATE_HASH&scope=REQUESTED_SCOPES
```

This will ask the user to approve the applications access to their account
based on the scopes specified in `REQUESTED_SCOPES` and then redirect back to
the `REDIRECT_URI` you provided. The [scope parameter](https://github.com/doorkeeper-gem/doorkeeper/wiki/Using-Scopes#requesting-particular-scopes)
   is a space separated list of scopes you want to have access to (e.g. `scope=read_user+profile`
would request `read_user` and `profile` scopes). The redirect
will include a fragment with `access_token` as well as token details in GET
parameters, for example:

```
http://myapp.com/oauth/redirect#access_token=ABCDExyz123&state=YOUR_UNIQUE_STATE_HASH&token_type=bearer&expires_in=3600
```

### Resource owner password credentials flow

NOTE: **Note:**
Check the [RFC spec](https://tools.ietf.org/html/rfc6749#section-4.3) for a
detailed flow description.

NOTE: **Note:**
The Resource Owner Password Credentials is disabled for users with [two-factor
authentication](../user/profile/account/two_factor_authentication.md) turned on.
These users can access the API using [personal access tokens](../user/profile/personal_access_tokens.md)
instead.

In this flow, a token is requested in exchange for the resource owner credentials
(username and password).

The credentials should only be used when:

- There is a high degree of trust between the resource owner and the client. For
  example, the client is part of the device operating system or a highly
  privileged application.
- Other authorization grant types are not available (such as an authorization code).

CAUTION: **Important:**
Never store the user's credentials and only use this grant type when your client
is deployed to a trusted environment, in 99% of cases
[personal access tokens](../user/profile/personal_access_tokens.md) are a better
choice.

Even though this grant type requires direct client access to the resource owner
credentials, the resource owner credentials are used for a single request and
are exchanged for an access token. This grant type can eliminate the need for
the client to store the resource owner credentials for future use, by exchanging
the credentials with a long-lived access token or refresh token.

To request an access token, you must make a POST request to `/oauth/token` with
the following parameters:

```json
{
  "grant_type"    : "password",
  "username"      : "user@example.com",
  "password"      : "secret"
}
```

Example cURL request:

```sh
echo 'grant_type=password&username=<your_username>&password=<your_password>' > auth.txt
curl --data "@auth.txt" --request POST https://gitlab.example.com/oauth/token
```

Then, you'll receive the access token back in the response:

```
{
  "access_token": "1f0af717251950dbd4d73154fdf0a474a5c5119adad999683f5b450c460726aa",
  "token_type": "bearer",
  "expires_in": 7200
}
```

For testing, you can use the `oauth2` Ruby gem:

```
client = OAuth2::Client.new('the_client_id', 'the_client_secret', :site => "http://example.com")
access_token = client.password.get_token('user@example.com', 'secret')
puts access_token.token
```

## Access GitLab API with `access token`

The `access token` allows you to make requests to the API on behalf of a user.
You can pass the token either as GET parameter:

```
GET https://gitlab.example.com/api/v4/user?access_token=OAUTH-TOKEN
```

or you can put the token to the Authorization header:

```
curl --header "Authorization: Bearer OAUTH-TOKEN" https://gitlab.example.com/api/v4/user
```


text:
package org.apache.poi.hssf.record.aggregates;

import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.model.RecordStream;
import org.apache.poi.hssf.record.CFHeaderRecord;
import org.apache.poi.hssf.record.CFRuleRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.formula.AreaErrPtg;
import org.apache.poi.hssf.record.formula.AreaPtg;
import org.apache.poi.hssf.record.formula.FormulaShifter;
import org.apache.poi.hssf.record.formula.Ptg;
import org.apache.poi.ss.util.CellRangeAddress;

/**
 * CFRecordsAggregate - aggregates Conditional Formatting records CFHeaderRecord
 * and number of up to three CFRuleRecord records together to simplify
 * access to them.
 *
 * @author Dmitriy Kumshayev
 *
 */
public final class CFRecordsAggregate extends RecordAggregate {
	/** Excel allows up to 3 conditional formating rules */
	private static final int MAX_CONDTIONAL_FORMAT_RULES = 3;

	private final CFHeaderRecord header;

	/** List of CFRuleRecord objects */
	private final List rules;

	private CFRecordsAggregate(CFHeaderRecord pHeader, CFRuleRecord[] pRules) {
		if(pHeader == null) {
			throw new IllegalArgumentException("header must not be null");
		}
		if(pRules == null) {
			throw new IllegalArgumentException("rules must not be null");
		}
		if(pRules.length > MAX_CONDTIONAL_FORMAT_RULES) {
			throw new IllegalArgumentException("No more than "
					+ MAX_CONDTIONAL_FORMAT_RULES + " rules may be specified");
		}
		if (pRules.length != pHeader.getNumberOfConditionalFormats()) {
			throw new RuntimeException("Mismatch number of rules");
		}
		header = pHeader;
		rules = new ArrayList(3);
		for (int i = 0; i < pRules.length; i++) {
			rules.add(pRules[i]);
		}
	}

	public CFRecordsAggregate(CellRangeAddress[] regions, CFRuleRecord[] rules) {
		this(new CFHeaderRecord(regions, rules.length), rules);
	}

	/**
	 * Create CFRecordsAggregate from a list of CF Records
	 * @param rs - the stream to read from
	 * @return CFRecordsAggregate object
	 */
	public static CFRecordsAggregate createCFAggregate(RecordStream rs) {
		Record rec = rs.getNext();
		if (rec.getSid() != CFHeaderRecord.sid) {
			throw new IllegalStateException("next record sid was " + rec.getSid()
					+ " instead of " + CFHeaderRecord.sid + " as expected");
		}

		CFHeaderRecord header = (CFHeaderRecord)rec;
		int nRules = header.getNumberOfConditionalFormats();

		CFRuleRecord[] rules = new CFRuleRecord[nRules];
		for (int i = 0; i < rules.length; i++) {
			rules[i] = (CFRuleRecord) rs.getNext();
		}

		return new CFRecordsAggregate(header, rules);
	}

	/**
	 * Create a deep clone of the record
	 */
	public CFRecordsAggregate cloneCFAggregate()
	{

		CFRuleRecord[] newRecs = new CFRuleRecord[rules.size()];
		for (int i = 0; i < newRecs.length; i++) {
			newRecs[i] = (CFRuleRecord) getRule(i).clone();
		}
		return new CFRecordsAggregate((CFHeaderRecord) header.clone(), newRecs);
	}

	/**
	 * @return the header. Never null.
	 */
	public CFHeaderRecord getHeader()
	{
		return header;
	}

	private void checkRuleIndex(int idx) {
		if(idx < 0 || idx >= rules.size()) {
			throw new IllegalArgumentException("Bad rule record index (" + idx
					+ ") nRules=" + rules.size());
		}
	}
	public CFRuleRecord getRule(int idx) {
		checkRuleIndex(idx);
		return (CFRuleRecord) rules.get(idx);
	}
	public void setRule(int idx, CFRuleRecord r) {
		if (r == null) {
			throw new IllegalArgumentException("r must not be null");
		}
		checkRuleIndex(idx);
		rules.set(idx, r);
	}
	public void addRule(CFRuleRecord r) {
		if (r == null) {
			throw new IllegalArgumentException("r must not be null");
		}
		if(rules.size() >= MAX_CONDTIONAL_FORMAT_RULES) {
			throw new IllegalStateException("Cannot have more than "
					+ MAX_CONDTIONAL_FORMAT_RULES + " conditional format rules");
		}
		rules.add(r);
		header.setNumberOfConditionalFormats(rules.size());
	}
	public int getNumberOfRules() {
		return rules.size();
	}

	/**
	 * String representation of CFRecordsAggregate
	 */
	public String toString()
	{
		StringBuffer buffer = new StringBuffer();

		buffer.append("[CF]\n");
		if( header != null )
		{
			buffer.append(header.toString());
		}
		for(int i=0; i<rules.size(); i++)
		{
			CFRuleRecord cfRule = (CFRuleRecord)rules.get(i);
			buffer.append(cfRule.toString());
		}
		buffer.append("[/CF]\n");
		return buffer.toString();
	}

	public void visitContainedRecords(RecordVisitor rv) {
		rv.visitRecord(header);
		for(int i=0; i<rules.size(); i++) {
			CFRuleRecord rule = (CFRuleRecord)rules.get(i);
			rv.visitRecord(rule);
		}
	}

	/**
	 * @return false if this whole {@link CFHeaderRecord} / {@link CFRuleRecord}s should be deleted
	 */
	public boolean updateFormulasAfterCellShift(FormulaShifter shifter, int currentExternSheetIx) {
		CellRangeAddress[] cellRanges = header.getCellRanges();
		boolean changed = false;
		List temp = new ArrayList();
		for (int i = 0; i < cellRanges.length; i++) {
			CellRangeAddress craOld = cellRanges[i];
			CellRangeAddress craNew = shiftRange(shifter, craOld, currentExternSheetIx);
			if (craNew == null) {
				changed = true;
				continue;
			}
			temp.add(craNew);
			if (craNew != craOld) {
				changed = true;
			}
		}

		if (changed) {
			int nRanges = temp.size();
			if (nRanges == 0) {
				return false;
			}
			CellRangeAddress[] newRanges = new CellRangeAddress[nRanges];
			temp.toArray(newRanges);
			header.setCellRanges(newRanges);
		}

		for(int i=0; i<rules.size(); i++) {
			CFRuleRecord rule = (CFRuleRecord)rules.get(i);
			Ptg[] ptgs;
			ptgs = rule.getParsedExpression1();
			if (ptgs != null && shifter.adjustFormula(ptgs, currentExternSheetIx)) {
				rule.setParsedExpression1(ptgs);
			}
			ptgs = rule.getParsedExpression2();
			if (ptgs != null && shifter.adjustFormula(ptgs, currentExternSheetIx)) {
				rule.setParsedExpression2(ptgs);
			}
		}
		return true;
	}

	private static CellRangeAddress shiftRange(FormulaShifter shifter, CellRangeAddress cra, int currentExternSheetIx) {
		// FormulaShifter works well in terms of Ptgs - so convert CellRangeAddress to AreaPtg (and back) here
		AreaPtg aptg = new AreaPtg(cra.getFirstRow(), cra.getLastRow(), cra.getFirstColumn(), cra.getLastColumn(), false, false, false, false);
		Ptg[] ptgs = { aptg, };

		if (!shifter.adjustFormula(ptgs, currentExternSheetIx)) {
			return cra;
		}
		Ptg ptg0 = ptgs[0];
		if (ptg0 instanceof AreaPtg) {
			AreaPtg bptg = (AreaPtg) ptg0;
			return new CellRangeAddress(bptg.getFirstRow(), bptg.getLastRow(), bptg.getFirstColumn(), bptg.getLastColumn());
		}
		if (ptg0 instanceof AreaErrPtg) {
			return null;
		}
		throw new IllegalStateException("Unexpected shifted ptg class (" + ptg0.getClass().getName() + ")");
	}
}


text:
/**
 *  @file Planner.cpp
 *  @brief Contains Implementation of planner API
 *
 *  This file contains path planner's funtionalities.
 *  It can be accessed by the objects of this class.
 *  This class assumes no initial knowledge of the environment.
 *
 *
 *
 *
 *
 *  @author Banuprathap Anandan
 *  @date   03/14/2017
*/
#include "Planner.hpp"

/**
 * @brief      Destroys the object.
 */
RobotPlanner::~RobotPlanner(void) {
}
/**
 * @brief      Constructs the object.
 */
RobotPlanner::RobotPlanner(RobotSimulator* simulator) {
  p_simulator = simulator;
}
/**
 * @brief      Returns the next move to the simulator
 *
 * @return     Returns a structure variable
 */
double Distance(Point One, Point Two) {
  return sqrt((One._x - Two._x) * (One._x - Two._x) + (One._y - Two._y) *
              (One._y - Two._y));
}
/**
 * @brief      This function computes the next move for the robot
 *
 * @return     Returns the next move dx, dy and dtheta as a structure
 */
RobotMove RobotPlanner::NextMove(void) {
  RobotMove move;
  if (!p_simulator->HasRobotReachedGoal()) {
    double distanceGoal, currDirection, angleGoal;
    double steer, robotSpeed, speed;
    double maxTurn, maxAcceleration, maxRobotSpeed;
    double sizeX, sizeY, sizeHalfDiag;
    double i;
    double repPotX, repPotY, attPotX, attPotY, totPotX, totPotY;
    Point R, G;
    R._x = p_simulator->GetRobotX();
    R._y = p_simulator->GetRobotY();
    currDirection = p_simulator->GetRobotTheta();
    maxTurn = p_simulator->GetRobotTurn();
    maxAcceleration = p_simulator->GetRobotAccel();
    maxRobotSpeed = p_simulator->GetRobotSpeed();
    G._x = p_simulator->GetGoalCenterX();
    G._y = p_simulator->GetGoalCenterY();
    sizeX  = p_simulator->GetRobotSizeX();
    sizeY = p_simulator->GetRobotSizeY();
    sizeHalfDiag = sqrt(pow(sizeX / 2, 2) + pow(sizeY / 2, 2));
    //  speed
    robotSpeed = 5;
    //  Calculate distance from obstacle at front
    i = sizeX / 2 + 1;
    while (1) {
      double _x = (R._x + i * cos(currDirection));
      double _y = (R._y + i * sin(currDirection));
      if (p_simulator->isColliding(_x, _y)) {
        break;
      }
      i++;
    }
    double distanceFront = i - sizeX / 2;
    //  Calculate distance from obstacle at left
    i = sizeY / 2 + 1;
    while (1) {
      double _x = (R._x + i * cos(currDirection - PI / 2));
      double _y = (R._y + i * sin(currDirection - PI / 2));
      if (p_simulator->isColliding(_x, _y)) {
        break;
      }
      i++;
    }
    double distanceLeft = i - sizeY / 2;
    //  Calculate distance from obstacle at Right
    i = sizeY / 2 + 1;
    while (1) {
      double _x = (R._x + i * cos(currDirection + PI / 2));
      double _y = (R._y + i * sin(currDirection + PI / 2));
      if (p_simulator->isColliding(_x, _y)) {
        break;
      }
      i++;
    }
    double distanceRight = i - sizeY / 2;
    //  Calculate distance from obstacle at Front-left-diagonal
    i = sizeHalfDiag  + 1;
    while (1) {
      double _x = (R._x + i * cos(currDirection - PI / 4));
      double _y = (R._y + i * sin(currDirection - PI / 4));
      if (p_simulator->isColliding(_x, _y)) {
        break;
      }
      i++;
    }
    double distanceFrontLeftDiagonal = i - sizeHalfDiag;
    //  Calculate distance from obstacle at Front-left-diagonal
    i = sizeHalfDiag + 1;
    while (1) {
      double _x = (R._x + i * cos(currDirection + PI / 4));
      double _y = (R._y + i * sin(currDirection + PI / 4));
      if (p_simulator->isColliding(_x, _y)) {
        break;
      }
      i++;
    }
    double distanceFrontRightDiagonal = i -  sizeHalfDiag;
    //  Goal
    distanceGoal = sqrt((R._x - G._x) * (R._x - G._x) + (R._y - G. _y) *
                        (R._y - G._y));
    angleGoal = atan2(G._y - R._y, G._x - R._x);
    //  Potential
    repPotY = 1.0 / pow(distanceFront, k) * sin(currDirection) +
              1.0 / pow((distanceLeft), k) * sin(currDirection - PI / 2) +
              1.0 / pow((distanceRight), k) * sin(currDirection + PI / 2) +
              1.0 / pow((distanceFrontLeftDiagonal), k) *
              sin(currDirection - PI / 4) +
              1.0 / pow((distanceFrontRightDiagonal), k) *
              sin(currDirection + PI / 4);
    repPotX = 1.0 / pow((distanceFront), k) * cos(currDirection) +
              1.0 / pow((distanceLeft), k) * cos(currDirection - PI / 2) +
              1.0 / pow((distanceRight), k) * cos(currDirection + PI / 2) +
              1.0 / pow((distanceFrontLeftDiagonal), k) *
              cos(currDirection - PI / 4) +
              1.0 / pow((distanceFrontRightDiagonal), k) *
              cos(currDirection + PI / 4);
    attPotY = std::max(pow((1.0 / distanceGoal), k),
                       minAttPot) * sin(angleGoal)  * attPotScaling;
    attPotX = std::max(pow((1.0 / distanceGoal), k) ,
                       minAttPot) * cos(angleGoal) * attPotScaling;
    totPotX = attPotX - (repPotScaling * repPotX);
    totPotY = attPotY - (repPotScaling * repPotY);
    //  dTheta
    steer = atan2(robotSpeed * cos(currDirection) + totPotX,
                  robotSpeed * sin(currDirection) + totPotY) - currDirection;
    while (steer > PI) {
      steer -= 2 * PI;
    }  //  check to get the angle between -pi and pi
    while (steer < -PI) {
      steer += 2 * PI;
    }  //  check to get the angle between - pi and pi
    steer = std::min(maxTurn, steer);
    steer = std::max(-maxTurn, steer);
    //  set new speed
    speed = sqrt((robotSpeed * sin(currDirection) + totPotY) *
                 (robotSpeed * sin(currDirection) + totPotY) +
                 (robotSpeed * cos(currDirection) + totPotX) *
                 (robotSpeed * cos(currDirection) + totPotX));
    speed = std::min(robotSpeed + maxAcceleration, speed);
    robotSpeed = std::max(robotSpeed - maxAcceleration, speed);
    robotSpeed = std::min(robotSpeed, maxRobotSpeed);
    robotSpeed = std::max(robotSpeed, 0.0);
    if (robotSpeed == 0)
      std::cout << "robot had to stop to avoid collission" << std::endl;
    if (!p_simulator->isColliding(R._x + robotSpeed * sin(currDirection),
                                  R._y + robotSpeed * cos(currDirection))) {
      move.m_dx = robotSpeed * sin(currDirection);
      move.m_dy = robotSpeed * cos(currDirection);
      move.m_dtheta = steer;
    } else if (!p_simulator->isColliding(R._x + 1, R._y + 1)) {
      move.m_dx = 1;
      move.m_dy = 1;
      move.m_dtheta = PI * 0.75;
    }
    move.m_speed = robotSpeed;
  }
  return move;
}


text:
package io.undertow.servlet.compat.rewrite;

import io.undertow.servlet.UndertowServletLogger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @author Stuart Douglas
 */
public class RewriteConfigFactory {

    public static RewriteConfig build(InputStream inputStream) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

        try {
            return parse(reader);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
    }

    private static RewriteConfig parse(BufferedReader reader) {
        ArrayList<RewriteRule> rules = new ArrayList<RewriteRule>();
        ArrayList<RewriteCond> conditions = new ArrayList<RewriteCond>();
        Map<String, RewriteMap> maps = new HashMap<>();
        while (true) {
            try {
                String line = reader.readLine();
                if (line == null) {
                    break;
                }
                Object result = parse(line);
                if (result instanceof RewriteRule) {
                    RewriteRule rule = (RewriteRule) result;
                    if (UndertowServletLogger.ROOT_LOGGER.isDebugEnabled()) {
                        UndertowServletLogger.ROOT_LOGGER.debug("Add rule with pattern " + rule.getPatternString()
                                + " and substitution " + rule.getSubstitutionString());
                    }
                    for (int i = (conditions.size() - 1); i > 0; i--) {
                        if (conditions.get(i - 1).isOrnext()) {
                            conditions.get(i).setOrnext(true);
                        }
                    }
                    for (int i = 0; i < conditions.size(); i++) {
                        if (UndertowServletLogger.ROOT_LOGGER.isDebugEnabled()) {
                            RewriteCond cond = conditions.get(i);
                            UndertowServletLogger.ROOT_LOGGER.debug("Add condition " + cond.getCondPattern()
                                    + " test " + cond.getTestString() + " to rule with pattern "
                                    + rule.getPatternString() + " and substitution "
                                    + rule.getSubstitutionString() + (cond.isOrnext() ? " [OR]" : "")
                                    + (cond.isNocase() ? " [NC]" : ""));
                        }
                        rule.addCondition(conditions.get(i));
                    }
                    conditions.clear();
                    rules.add(rule);
                } else if (result instanceof RewriteCond) {
                    conditions.add((RewriteCond) result);
                } else if (result instanceof Object[]) {
                    String mapName = (String) ((Object[]) result)[0];
                    RewriteMap map = (RewriteMap) ((Object[]) result)[1];
                    maps.put(mapName, map);
                    //if (map instanceof Lifecycle) {
                    //    ((Lifecycle) map).start();
                    //}
                }
            } catch (IOException e) {
                UndertowServletLogger.ROOT_LOGGER.errorReadingRewriteConfiguration(e);
            }
        }
        RewriteRule[] rulesArray = rules.toArray(new RewriteRule[0]);

        // Finish parsing the rules
        for (int i = 0; i < rulesArray.length; i++) {
            rulesArray[i].parse(maps);
        }
        return new RewriteConfig(rulesArray, maps);
    }

    /**
     * This factory method will parse a line formed like:
     *
     * Example:
     *  RewriteCond %{REMOTE_HOST}  ^host1.*  [OR]
     *
     * @param line
     * @return
     */
    private static Object parse(String line) {
        StringTokenizer tokenizer = new StringTokenizer(line);
        if (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            if (token.equals("RewriteCond")) {
                // RewriteCond TestString CondPattern [Flags]
                RewriteCond condition = new RewriteCond();
                if (tokenizer.countTokens() < 2) {
                    throw UndertowServletLogger.ROOT_LOGGER.invalidRewriteConfiguration(line);
                }
                condition.setTestString(tokenizer.nextToken());
                condition.setCondPattern(tokenizer.nextToken());
                if (tokenizer.hasMoreTokens()) {
                    String flags = tokenizer.nextToken();
                    if (flags.startsWith("[") && flags.endsWith("]")) {
                        flags = flags.substring(1, flags.length() - 1);
                    }
                    StringTokenizer flagsTokenizer = new StringTokenizer(flags, ",");
                    while (flagsTokenizer.hasMoreElements()) {
                        parseCondFlag(line, condition, flagsTokenizer.nextToken());
                    }
                }
                return condition;
            } else if (token.equals("RewriteRule")) {
                // RewriteRule Pattern Substitution [Flags]
                RewriteRule rule = new RewriteRule();
                if (tokenizer.countTokens() < 2) {
                    throw UndertowServletLogger.ROOT_LOGGER.invalidRewriteConfiguration(line);
                }
                rule.setPatternString(tokenizer.nextToken());
                rule.setSubstitutionString(tokenizer.nextToken());
                if (tokenizer.hasMoreTokens()) {
                    String flags = tokenizer.nextToken();
                    if (flags.startsWith("[") && flags.endsWith("]")) {
                        flags = flags.substring(1, flags.length() - 1);
                    }
                    StringTokenizer flagsTokenizer = new StringTokenizer(flags, ",");
                    while (flagsTokenizer.hasMoreElements()) {
                        parseRuleFlag(line, rule, flagsTokenizer.nextToken());
                    }
                }
                return rule;
            } else if (token.equals("RewriteMap")) {
                // RewriteMap name rewriteMapClassName whateverOptionalParameterInWhateverFormat
                if (tokenizer.countTokens() < 2) {
                    throw UndertowServletLogger.ROOT_LOGGER.invalidRewriteConfiguration(line);
                }
                String name = tokenizer.nextToken();
                String rewriteMapClassName = tokenizer.nextToken();
                RewriteMap map = null;
                try {
                    map = (RewriteMap) (Class.forName(rewriteMapClassName).newInstance());
                } catch (Exception e) {
                    throw UndertowServletLogger.ROOT_LOGGER.invalidRewriteMap(rewriteMapClassName);
                }
                if (tokenizer.hasMoreTokens()) {
                    map.setParameters(tokenizer.nextToken());
                }
                Object[] result = new Object[2];
                result[0] = name;
                result[1] = map;
                return result;
            } else if (token.startsWith("#")) {
                // it's a comment, ignore it
            } else {
                throw UndertowServletLogger.ROOT_LOGGER.invalidRewriteConfiguration(line);
            }
        }
        return null;
    }

    /**
     * Parser for RewriteCond flags.
     *
     * @param condition
     * @param flag
     */
    protected static void parseCondFlag(String line, RewriteCond condition, String flag) {
        if (flag.equals("NC") || flag.equals("nocase")) {
            condition.setNocase(true);
        } else if (flag.equals("OR") || flag.equals("ornext")) {
            condition.setOrnext(true);
        } else {
            throw UndertowServletLogger.ROOT_LOGGER.invalidRewriteFlags(line, flag);
        }
    }

    /**
     * Parser for ReweriteRule flags.
     *
     * @param rule
     * @param flag
     */
    protected static void parseRuleFlag(String line, RewriteRule rule, String flag) {
        if (flag.equals("chain") || flag.equals("C")) {
            rule.setChain(true);
        } else if (flag.startsWith("cookie=") || flag.startsWith("CO=")) {
            rule.setCookie(true);
            if (flag.startsWith("cookie")) {
                flag = flag.substring("cookie=".length());
            } else if (flag.startsWith("CO=")) {
                flag = flag.substring("CO=".length());
            }
            StringTokenizer tokenizer = new StringTokenizer(flag, ":");
            if (tokenizer.countTokens() < 2) {
                throw UndertowServletLogger.ROOT_LOGGER.invalidRewriteFlags(line);
            }
            rule.setCookieName(tokenizer.nextToken());
            rule.setCookieValue(tokenizer.nextToken());
            if (tokenizer.hasMoreTokens()) {
                rule.setCookieDomain(tokenizer.nextToken());
            }
            if (tokenizer.hasMoreTokens()) {
                try {
                    rule.setCookieLifetime(Integer.parseInt(tokenizer.nextToken()));
                } catch (NumberFormatException e) {
                    throw UndertowServletLogger.ROOT_LOGGER.invalidRewriteFlags(line);
                }
            }
            if (tokenizer.hasMoreTokens()) {
                rule.setCookiePath(tokenizer.nextToken());
            }
            if (tokenizer.hasMoreTokens()) {
                rule.setCookieSecure(Boolean.parseBoolean(tokenizer.nextToken()));
            }
            if (tokenizer.hasMoreTokens()) {
                rule.setCookieHttpOnly(Boolean.parseBoolean(tokenizer.nextToken()));
            }
        } else if (flag.startsWith("env=") || flag.startsWith("E=")) {
            rule.setEnv(true);
            if (flag.startsWith("env=")) {
                flag = flag.substring("env=".length());
            } else if (flag.startsWith("E=")) {
                flag = flag.substring("E=".length());
            }
            int pos = flag.indexOf(':');
            if (pos == -1 || (pos + 1) == flag.length()) {
                throw UndertowServletLogger.ROOT_LOGGER.invalidRewriteFlags(line);
            }
            rule.addEnvName(flag.substring(0, pos));
            rule.addEnvValue(flag.substring(pos + 1));
        } else if (flag.startsWith("forbidden") || flag.startsWith("F")) {
            rule.setForbidden(true);
        } else if (flag.startsWith("gone") || flag.startsWith("G")) {
            rule.setGone(true);
        } else if (flag.startsWith("host") || flag.startsWith("H")) {
            rule.setHost(true);
        } else if (flag.startsWith("last") || flag.startsWith("L")) {
            rule.setLast(true);
        } else if (flag.startsWith("next") || flag.startsWith("N")) {
            rule.setNext(true);
        } else if (flag.startsWith("nocase") || flag.startsWith("NC")) {
            rule.setNocase(true);
        } else if (flag.startsWith("noescape") || flag.startsWith("NE")) {
            rule.setNoescape(true);
        /* Proxy not supported, would require strong proxy capabilities
        } else if (flag.startsWith("proxy") || flag.startsWith("P")) {
            rule.setProxy(true);*/
        } else if (flag.startsWith("qsappend") || flag.startsWith("QSA")) {
            rule.setQsappend(true);
        } else if (flag.startsWith("redirect") || flag.startsWith("R")) {
            if (flag.startsWith("redirect=")) {
                flag = flag.substring("redirect=".length());
                rule.setRedirect(true);
                rule.setRedirectCode(Integer.parseInt(flag));
            } else if (flag.startsWith("R=")) {
                flag = flag.substring("R=".length());
                rule.setRedirect(true);
                rule.setRedirectCode(Integer.parseInt(flag));
            } else {
                rule.setRedirect(true);
                rule.setRedirectCode(HttpServletResponse.SC_FOUND);
            }
        } else if (flag.startsWith("skip") || flag.startsWith("S")) {
            if (flag.startsWith("skip=")) {
                flag = flag.substring("skip=".length());
            } else if (flag.startsWith("S=")) {
                flag = flag.substring("S=".length());
            }
            rule.setSkip(Integer.parseInt(flag));
        } else if (flag.startsWith("type") || flag.startsWith("T")) {
            if (flag.startsWith("type=")) {
                flag = flag.substring("type=".length());
            } else if (flag.startsWith("T=")) {
                flag = flag.substring("T=".length());
            }
            rule.setType(true);
            rule.setTypeValue(flag);
        } else {
            throw UndertowServletLogger.ROOT_LOGGER.invalidRewriteFlags(line, flag);
        }
    }

}


text:
package services

import (
	jwkservices "github.com/raiqub/jose/jwk/services"
	"github.com/raiqub/jose/jws"
	"github.com/raiqub/tlog"
	"gopkg.in/raiqub/slice.v1"
)

// A Verifier represents a service which provides token decoding and validation.
type Verifier struct {
	issuers []string
	keys    map[string]*Cache
}

// NewVerifier creates a new instance of Verifier service.
func NewVerifier(
	svcJWKSet jwkservices.SetService,
	tracer tlog.Tracer,
	issuers ...string,
) (*Verifier, error) {
	if tracer == nil {
		tracer = tlog.NewTracerNop()
	}

	jwkset, err := svcJWKSet.GetCerts(tracer)
	if err != nil {
		return nil, err
	}

	result := &Verifier{
		issuers,
		make(map[string]*Cache, 0),
	}

	for _, k := range jwkset.Keys {
		rawKey, err := k.Key()
		if err != nil {
			return nil, err
		}

		result.keys[k.ID] = &Cache{k, rawKey}
		tracer.AddEntry(
			tlog.LevelInfo, "jwkset_key_loaded", "JWK set key loaded: "+k.ID,
			0, nil, "Verifier", "NewVerifier")
	}

	return result, nil
}

// Verify specified token and decode it.
func (v *Verifier) Verify(
	rawtoken string,
	header jws.Header,
	payload ClaimsSecure,
) (*jws.SignedToken, error) {
	token, err := jws.DecodeAndValidate(
		rawtoken, header, payload,
		func(header jws.Header) (interface{}, error) {
			var key *Cache
			var ok bool

			if key, ok = v.keys[header.GetID()]; !ok {
				return nil, ErrInvalidKeyID(header.GetID())
			}
			if header.GetAlgorithm() != key.JWK.Algorithm {
				return nil, ErrUnexpectedAlg(header.GetAlgorithm())
			}

			return key.RawKey, nil
		},
	)

	if err != nil {
		return nil, err
	}

	if !token.Validate() {
		return nil, ErrInvalidToken(0)
	}

	if secPayload, ok := token.Payload.(ClaimsSecure); !ok ||
		!slice.String(v.issuers).Exists(secPayload.GetIssuer(), false) {
		return nil, ErrInvalidToken(0)
	}

	return token, nil
}


text:
class CreateWeeks < ActiveRecord::Migration
  def change
    create_table :weeks do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end


text:
 Improve this Doc

   View Source

$jsonpCallbacks

      - service in module ng

This service handles the lifecycle of callbacks to handle JSONP requests.
Override this service if you wish to customise where the callbacks are stored and
how they vary compared to the requested url.

Dependencies

$window

Methods

createCallback(url);

$httpBackend calls this method to create a callback and get hold of the path to the callback
to pass to the server, which will be used to call the callback with its payload in the JSONP response.

Parameters

      Param
      Type
      Details

        url

        string

the url of the JSONP request

Returns

    string

the callback path to send to the server as part of the JSONP request

wasCalled(callbackPath);

$httpBackend calls this method to find out whether the JSONP response actually called the
callback that was passed in the request.

Parameters

      Param
      Type
      Details

        callbackPath

        string

the path to the callback that was sent in the JSONP request

Returns

    boolean

whether the callback has been called, as a result of the JSONP response

getResponse(callbackPath);

$httpBackend calls this method to get hold of the data that was provided to the callback
in the JSONP response.

Parameters

      Param
      Type
      Details

        callbackPath

        string

the path to the callback that was sent in the JSONP request

Returns

    *

the data received from the response via the registered callback

removeCallback(callbackPath);

$httpBackend calls this method to remove the callback after the JSONP request has
completed or timed-out.

Parameters

      Param
      Type
      Details

        callbackPath

        string

the path to the callback that was sent in the JSONP request


text:
<?php

declare(strict_types=1);

namespace Doctrine\ODM\MongoDB\Types;

use DateTime;
use DateTimeInterface;
use DateTimeZone;
use InvalidArgumentException;
use MongoDB\BSON\UTCDateTime;
use Throwable;
use const STR_PAD_LEFT;
use function abs;
use function date_default_timezone_get;
use function gettype;
use function is_numeric;
use function is_scalar;
use function is_string;
use function round;
use function sprintf;
use function str_pad;

/**
 * The Date type.
 */
class DateType extends Type
{
    /**
     * Converts a value to a DateTime.
     * Supports microseconds
     *
     * @param mixed $value \DateTimeInterface|\MongoDB\BSON\UTCDateTime|int|float
     *
     * @throws InvalidArgumentException If $value is invalid.
     */
    public static function getDateTime($value) : DateTimeInterface
    {
        $datetime  = false;
        $exception = null;

        if ($value instanceof DateTimeInterface) {
            return $value;
        }

        if ($value instanceof UTCDateTime) {
            $datetime = $value->toDateTime();
            $datetime->setTimezone(new DateTimeZone(date_default_timezone_get()));
        } elseif (is_numeric($value)) {
            $value         = (float) $value;
            $seconds       = (int) $value;
            $microseconds  = abs(round($value - $seconds, 6));
            $microseconds *= 1000000;

            $datetime = static::craftDateTime($seconds, (int) $microseconds);
        } elseif (is_string($value)) {
            try {
                $datetime = new DateTime($value);
            } catch (Throwable $e) {
                $exception = $e;
            }
        }

        if ($datetime === false) {
            throw new InvalidArgumentException(sprintf('Could not convert %s to a date value', is_scalar($value) ? '"' . $value . '"' : gettype($value)), 0, $exception);
        }

        return $datetime;
    }

    /**
     * @return DateTime|false
     */
    private static function craftDateTime(int $seconds, int $microseconds = 0)
    {
        $datetime = new DateTime();
        $datetime->setTimestamp($seconds);
        if ($microseconds > 0) {
            $datetime = DateTime::createFromFormat('Y-m-d H:i:s.u', $datetime->format('Y-m-d H:i:s') . '.' . str_pad((string) $microseconds, 6, '0', STR_PAD_LEFT));
        }

        return $datetime;
    }

    public function convertToDatabaseValue($value)
    {
        if ($value === null || $value instanceof UTCDateTime) {
            return $value;
        }

        $datetime = static::getDateTime($value);

        return new UTCDateTime((int) $datetime->format('Uv'));
    }

    public function convertToPHPValue($value)
    {
        if ($value === null) {
            return null;
        }

        return static::getDateTime($value);
    }

    public function closureToMongo() : string
    {
        return 'if ($value === null || $value instanceof \MongoDB\BSON\UTCDateTime) { $return = $value; } else { $datetime = \\' . static::class . '::getDateTime($value); $return = new \MongoDB\BSON\UTCDateTime((int) $datetime->format(\'Uv\')); }';
    }

    public function closureToPHP() : string
    {
        return 'if ($value === null) { $return = null; } else { $return = \\' . static::class . '::getDateTime($value); }';
    }
}


text:
 class ImageFinder:
    ''' Inteface / Abstract Class concept for readability.'''

    def find(self, image):
        # explicitly set it up so this can't be called directly
        raise NotImplementedError('Exception raised, ImageFinder is supposed to be an interface / abstract class!')

class ImageFinderFlickr(ImageFinder):
    ''' Locates images in flickr'''

    def find(self, image):
        # in reality, query Flickr API for image path
        return "Found image in Flickr: " + image

class ImageFinderDatabase(ImageFinder):
    ''' Locates images in database. '''
    def find(self, image):
        #in reality, query database for image path
        return "Found image in database: " + image

if __name__ == "__main__" :

    finderBase = ImageFinder()
    finderFlickr = ImageFinderFlickr()
    finderDatabase = ImageFinderDatabase()

    try:
        #this is going to blow up!
        print finderBase.find('chickens')
    except NotImplementedError as e:
        print "The following exception was expected:"
        print e

    print finderFlickr.find('chickens')
    print finderFlickr.find('rabbits')
    print finderDatabase.find('dogs')
    print finderDatabase.find('cats')


text:
import pyaudio
import wave
import audioop
from collections import deque
import time
import math
import datetime

# Microphone stream config.
CHUNK = 1024  # CHUNKS of bytes to read each time from mic
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 8000

# The threshold intensity that defines silence
# and noise signal (an int. lower than THRESHOLD is silence).
THRESHOLD = 2400

# Silence limit in seconds. The max ammount of seconds where
# only silence is recorded. When this time passes the
# recording finishes and the file is delivered.
SILENCE_LIMIT = 0.6

# Previous audio (in seconds) to prepend. When noise
# is detected, how much of previously recorded audio is
# prepended. This helps to prevent chopping the beggining
# of the phrase.
PREV_AUDIO = 0.3

def record(threshold=THRESHOLD, silence=SILENCE_LIMIT):
    """
    Listens to Microphone, records voice until phrase ends.

    A "phrase" is sound surrounded by silence (according to threshold).

    :param int threshold: Intensity value that defines silence.
      lower than threshold is silence.
    :param silence: Max ammount of seconds where only silence is
      recorded. When this time passes the recording finishes.
    """

    # Open stream
    p = pyaudio.PyAudio()

    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)

    print ("* Listening mic. ")
    frames = []
    cur_data = ''
    rel = RATE/CHUNK
    window = deque(maxlen=silence * rel)
    prev_audio = deque(maxlen=PREV_AUDIO * rel)
    start = False
    exit_loop = 0

    while (exit_loop != 1):
        cur_data = stream.read(CHUNK)
        window.append(math.sqrt(abs(audioop.avg(cur_data, 4))))
        if(sum([x > THRESHOLD for x in window]) > 0):
            if(not start):
                print ("recording..")
                start = True
            frames.append(cur_data)
        elif start is True:
            print ("Finished")
            save_audio(list(prev_audio) + frames, p)
            start = False
            window = deque(maxlen=silence * rel)
            prev_audio = deque(maxlen=0.5 * rel)
            frames = []
            exit_loop = 1
        else:
            prev_audio.append(cur_data)

    print ("Done recording")
    stream.close()
    p.terminate()

def save_audio(data, params):
    """ Saves mic data to wav file."""

    filename = gettime()
    data = ''.join(data)
    wf = wave.open(filename + '.wav', 'wb')
    wf.setnchannels(1)
    wf.setsampwidth(params.get_sample_size(pyaudio.paInt16))
    wf.setframerate(RATE)
    wf.writeframes(data)
    wf.close()

def gettime():
    """
    Return timestamp string.
    """
    current = time.time()
    tformat = datetime.datetime.fromtimestamp(current).strftime('%d:%H:%M:%S')
    return tformat


text:
<animated-vector
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:aapt="http://schemas.android.com/aapt"
  android:drawable="@drawable/vd_checkable_expandcollapse_expanded">

  <target android:name="chevron">
    <aapt:attr name="android:animation">
      <objectAnimator
        android:duration="500"
        android:interpolator="@android:interpolator/fast_out_slow_in"
        android:propertyName="translateY"
        android:valueFrom="9"
        android:valueTo="15"/>
    </aapt:attr>
  </target>

  <target android:name="leftBar">
    <aapt:attr name="android:animation">
      <objectAnimator
        android:duration="400"
        android:interpolator="@anim/pathmorph_expandcollapse"
        android:propertyName="rotation"
        android:valueFrom="135"
        android:valueTo="45"
        android:valueType="floatType"/>
    </aapt:attr>
  </target>

  <target android:name="rightBar">
    <aapt:attr name="android:animation">
      <objectAnimator
        android:duration="400"
        android:interpolator="@anim/pathmorph_expandcollapse"
        android:propertyName="rotation"
        android:valueFrom="45"
        android:valueTo="135"
        android:valueType="floatType"/>
    </aapt:attr>
  </target>

</animated-vector>


text:
'use strict';

/**
 * Yearly retention schedule.
 *
 */
class YearlyRetentionSchedule {
  /**
   * Create a YearlyRetentionSchedule.
   * @member {string} [retentionScheduleFormatType] Retention schedule format
   * for yearly retention policy. Possible values include: 'Invalid', 'Daily',
   * 'Weekly'
   * @member {array} [monthsOfYear] List of months of year of yearly retention
   * policy.
   * @member {object} [retentionScheduleDaily] Daily retention format for
   * yearly retention policy.
   * @member {array} [retentionScheduleDaily.daysOfTheMonth] List of days of
   * the month.
   * @member {object} [retentionScheduleWeekly] Weekly retention format for
   * yearly retention policy.
   * @member {array} [retentionScheduleWeekly.daysOfTheWeek] List of days of
   * the week.
   * @member {array} [retentionScheduleWeekly.weeksOfTheMonth] List of weeks of
   * month.
   * @member {array} [retentionTimes] Retention times of retention policy.
   * @member {object} [retentionDuration] Retention duration of retention
   * Policy.
   * @member {number} [retentionDuration.count] Count of duration types.
   * Retention duration is obtained by the counting the duration type Count
   * times.
   * For example, when Count = 3 and DurationType = Weeks, retention duration
   * will be three weeks.
   * @member {string} [retentionDuration.durationType] Retention duration type
   * of retention policy. Possible values include: 'Invalid', 'Days', 'Weeks',
   * 'Months', 'Years'
   */
  constructor() {
  }

  /**
   * Defines the metadata of YearlyRetentionSchedule
   *
   * @returns {object} metadata of YearlyRetentionSchedule
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'YearlyRetentionSchedule',
      type: {
        name: 'Composite',
        className: 'YearlyRetentionSchedule',
        modelProperties: {
          retentionScheduleFormatType: {
            required: false,
            serializedName: 'retentionScheduleFormatType',
            type: {
              name: 'String'
            }
          },
          monthsOfYear: {
            required: false,
            serializedName: 'monthsOfYear',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'MonthOfYearElementType',
                  type: {
                    name: 'Enum',
                    allowedValues: [ 'Invalid', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]
                  }
              }
            }
          },
          retentionScheduleDaily: {
            required: false,
            serializedName: 'retentionScheduleDaily',
            type: {
              name: 'Composite',
              className: 'DailyRetentionFormat'
            }
          },
          retentionScheduleWeekly: {
            required: false,
            serializedName: 'retentionScheduleWeekly',
            type: {
              name: 'Composite',
              className: 'WeeklyRetentionFormat'
            }
          },
          retentionTimes: {
            required: false,
            serializedName: 'retentionTimes',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'DateElementType',
                  type: {
                    name: 'DateTime'
                  }
              }
            }
          },
          retentionDuration: {
            required: false,
            serializedName: 'retentionDuration',
            type: {
              name: 'Composite',
              className: 'RetentionDuration'
            }
          }
        }
      }
    };
  }
}

module.exports = YearlyRetentionSchedule;


text:
package org.remdev.android.kotlinapp.commanders;

import android.app.Service;
import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;

import org.remdev.android.commander.ResultCodes;
import org.remdev.android.commander.commander.BaseCommander;
import org.remdev.android.commander.models.InteractionResult;
import org.remdev.android.commander.models.MessageBundle;
import org.remdev.android.kotlinapp.models.WeatherData;
import org.remdev.android.kotlinapp.rest.WeatherDriver;

public class WeatherCommander extends BaseCommander<WeatherDriver.WeatherDriverCallback> {

    public static final int COMMAND_LOAD_WEATHER = 1;
    public static final String LOAD_WEATHER_EXTRA_CITY = WeatherCommander.class.getName() + ".LOAD_WEATHER_EXTRA_CITY";

    public WeatherCommander(Context context, @NonNull WeatherDriver.WeatherDriverCallback callback) {
        super(context, callback, null);
    }

    public void loadWeather(String city) {
        Bundle bundle = new Bundle();
        bundle.putString(LOAD_WEATHER_EXTRA_CITY, city);
        sendCommand(COMMAND_LOAD_WEATHER, bundle);
    }

    @Override
    protected boolean dispatchResult(boolean success, int command, Bundle resultData, WeatherDriver.WeatherDriverCallback callback) {
        return processGenericResult(success, resultData, createGeneralInvoker(command, callback));
    }

    private <T> boolean processGenericResult(boolean success, Bundle resultData, CallbackInvoker<T> invoker) {
        MessageBundle<InteractionResult<T>> messageBundle = MessageBundle.fromBundle(resultData);
        InteractionResult<T> result = messageBundle.getPayload();
        int errorCode = result == null ? ResultCodes.ERROR_CODE_UNKNOWN : result.getErrorCode();
        invoker.invoke(success, errorCode, result == null ? null : result.getPayload());
        return true;
    }

    private void sendCommand(int command) {
        sendMessage(WeatherService.messageForCommand(command, getResultReceiver()));
    }

    private void sendCommand(int command, Bundle date) {
        Message message = WeatherService.messageForCommand(command, getResultReceiver());
        message.setData(date);
        sendMessage(message);
    }

    private <T> CallbackInvoker<T> createGeneralInvoker(final int command, final WeatherDriver.WeatherDriverCallback callback) {
        return new CallbackInvoker<T>() {
            @Override
            public boolean invoke(boolean success, int errorCode, T payload) {
                switch (command) {
                    case COMMAND_LOAD_WEATHER:
                        WeatherData weatherData = (WeatherData) payload;
                        callback.onWeatherLoaded(success, errorCode, weatherData == null ? null : weatherData.getItems());
                        break;
                    default:
                        return false;
                }
                return false;
            }
        };
    }

    private interface CallbackInvoker<T> {
        boolean invoke(boolean success, int errorCode, T payload);
    }

    @NonNull
    @Override
    protected Class<? extends Service> getServiceClass() {
        return WeatherService.class;
    }
}


text:
* update Dir

### 1.0.9

* update header file

### 1.0.8

* update NSDate Categorys

### 1.0.7

* Added GetPropertirs method to NSObject

### 1.0.6

* Change JSON Convert method name
* Added JSON Convert Method to NSData

### 1.0.5

* Format Code LLVM Style

### 1.0.4

* Added Button EnlargeEdge
* Added JSON Convert Method to NSArray
* Update JSON Convert Method in NSDictionary
* Added Dynamic Properties to NSObject

### 1.0.3

* Added NSInvocation CGRect UILabel Categorys

### 1.0.2

* Added prefix to all source files to avoid name collision.

### 1.0.1

* Added UIView Utils.

### 1.0.0

Added Foundation UIKit.

*   Foundation
       * NSString
       * NSArray
       * NSBundle
       * NSDate
       * NSDateFormatter
       * NSDictionary
       * NSFileManager
       * NSNumber
       * NSNumberFormatter
       * NSObject
       * NSURL
       * NSNull
       * NSData
       * NSAttributedString
       * NSNotificationCenter
       * NSOperationQueue
       * NSUserDefaults
       * UIApplication

*   UIKit
       * UIView
       * UIAlertView
       * UIButton
       * UIColor
       * UIDevice
       * UIImage
       * UINavigationController
       * UIResponder
       * UISearchBar
       * UIStoryboard
       * UITableView
       * UIViewController
       * UIWebView
       * UIBarButtonItem
       * UICollectionView
       * UIWindow


text:
package jp.gr.procon.proconapp.api;

import android.text.TextUtils;

import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;

import jp.gr.procon.proconapp.model.Notice;
import jp.gr.procon.proconapp.model.NoticeList;
import jp.gr.procon.proconapp.model.User;
import jp.gr.procon.proconapp.util.JsonUtil;
import timber.log.Timber;

public class NoticeListApi {
    public static class GetRequest extends BaseUserApi<NoticeList> {
        private static final String PATH = "notices";
        private static final String SEGMENT = "list";
        private static final String QUERY_PAGE = "page";
        private static final String QUERY_COUNT = "count";

        public GetRequest(String userToken) {
            super(userToken);
        }

        public GetRequest get(String page, String count) {
            HttpUrl url = getDefaultUrlBuilder()
                    .addEncodedPathSegment(PATH)
                    .addEncodedPathSegment(SEGMENT)
                    .addEncodedQueryParameter(QUERY_PAGE, page)
                    .addEncodedQueryParameter(QUERY_COUNT, count)
                    .build();

            Request req = getDefaultRequestBuilder()
                    .url(url)
                    .get()
                    .build();
            execute(req);

            if (!TextUtils.isEmpty(mResponseBodyText)) {
                Timber.d("post: code=" + mResponseStatusCode + " body=" + mResponseBodyText);
                mResponseObj = JsonUtil.fromJson(mResponseBodyText, NoticeList.class);
            }

            return this;
        }
    }
}


text:
using System;
using Agiil.Domain.Tickets;

namespace Agiil.Domain.Activity
{
    public class TicketWorkLogFactory : IGetsTicketWorkLog
    {
        readonly IParsesTimespan timespanParser;
        readonly IGetsTicketByReference ticketProvider;

        public GetWorklogResponse GetWorkLog(AddWorkLogRequest request)
        {
            if(request == null)
                throw new ArgumentNullException(nameof(request));
            if(request.User == null)
                throw new ArgumentException("User must not be null", nameof(request));

            TimeSpan time;

            try
            {
                time = timespanParser.GetTimeSpan(request.TimeSpent);
            }
            catch(FormatException)
            {
                return new GetWorklogResponse { Success = false, TimeSpentIsInvalid = true, };
            }

            var ticket = ticketProvider.GetTicketByReference(request.TicketReference);
            if(ticket == null)
                return new GetWorklogResponse { Success = false, TicketNotFound = true, };

            var worklog = new TicketWorkLog {
                User = request.User,
                TimeStarted = request.TimeStarted,
            };
            worklog.SetTimeSpent(time);

            return new GetWorklogResponse {
                Success = true,
                Ticket = ticket,
                WorkLog = worklog,
            };
        }

        public TicketWorkLogFactory(IParsesTimespan timespanParser, IGetsTicketByReference ticketProvider)
        {
            if(ticketProvider == null)
                throw new ArgumentNullException(nameof(ticketProvider));
            if(timespanParser == null)
                throw new ArgumentNullException(nameof(timespanParser));
            this.timespanParser = timespanParser;
            this.ticketProvider = ticketProvider;
        }
    }
}


text: Used for browsing the list of users on a particular channel.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.yahoo.ycsb</groupId>
    <artifactId>root</artifactId>
    <version>0.1.4</version>
  </parent>

  <artifactId>hypertable-binding</artifactId>
  <name>Hypertable DB Binding</name>
  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>com.yahoo.ycsb</groupId>
      <artifactId>core</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.thrift</groupId>
      <artifactId>libthrift</artifactId>
      <version>${thrift.version}</version>
    </dependency>
    <dependency>
      <groupId>org.hypertable</groupId>
      <artifactId>hypertable</artifactId>
      <version>${hypertable.version}</version>
    </dependency>
  </dependencies>

  <repositories>
    <repository>
      <id>clojars.org</id>
      <url>http://clojars.org/repo</url>
    </repository>
  </repositories>

  <build>
    <plugins>
     <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>${maven.assembly.version}</version>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
          <appendAssemblyId>false</appendAssemblyId>
        </configuration>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

</project>


text:
(function () {
    "use strict";

    WinJS.UI.Pages.define("/demos/print/print.html", {
        ready: function (element, options) {
            sourceOfVideo.msPlayToSource.connection.addEventListener("statechanged",
                function (pte) {
                    var states = Windows.Media.PlayTo.PlayToConnectionState;
                    var state = "";
                    if (pte.currentState === states.disconnected) {
                        state = "Disconnected";
                    } else if (pte.currentState === states.connected) {
                        state = "Connected";
                    } else if (pte.currentState === states.rendering) {
                        state = "Rendering";
                    }
                    output.innerText = state;
                });// state changed
            souceOfVideo.msPlayToSource.connection.addEventListener("error",
                function (pte) {
                    output.innerText = pte.message;
                });// error
        }// ready
    });// page

})();


text:
package org.yeastrc.xlink.www.dto;

import org.joda.time.DateTime;

/**
 * Table search - Just raw data
 *
 */
public class Search_Core_DTO  {

	private int projectSearchId;
	private int searchId;
	private String path;
	private DateTime load_time;
	private String fastaFilename;
	private String name;
	private int projectId;
	private String directoryName;
	private int displayOrder;
	private boolean hasScanData;

	public int getProjectSearchId() {
		return projectSearchId;
	}
	public void setProjectSearchId(int projectSearchId) {
		this.projectSearchId = projectSearchId;
	}
	public int getSearchId() {
		return searchId;
	}
	public void setSearchId(int searchId) {
		this.searchId = searchId;
	}
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public DateTime getLoad_time() {
		return load_time;
	}
	public void setLoad_time(DateTime load_time) {
		this.load_time = load_time;
	}
	public String getFastaFilename() {
		return fastaFilename;
	}
	public void setFastaFilename(String fastaFilename) {
		this.fastaFilename = fastaFilename;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getProjectId() {
		return projectId;
	}
	public void setProjectId(int projectId) {
		this.projectId = projectId;
	}
	public String getDirectoryName() {
		return directoryName;
	}
	public void setDirectoryName(String directoryName) {
		this.directoryName = directoryName;
	}
	public int getDisplayOrder() {
		return displayOrder;
	}
	public void setDisplayOrder(int displayOrder) {
		this.displayOrder = displayOrder;
	}
	public boolean isHasScanData() {
		return hasScanData;
	}
	public void setHasScanData(boolean hasScanData) {
		this.hasScanData = hasScanData;
	}

}