text:
using System;
using Newtonsoft.Json;

namespace KanbaneryAPI.Core.Models
{
    public class TaskResource
    {
        [JsonProperty(PropertyName = "id")]
        public int TaskId { get; set; }

        [JsonProperty(PropertyName = "title")]
        public string Title { get; set; }

        [JsonProperty(PropertyName = "task_type_id")]
        public int? TaskTypeId { get; set; }

        [JsonProperty(PropertyName = "column_id")]
        public int? ColumnId { get; set; }

        [JsonProperty(PropertyName = "creator_id")]
        public int? CreatorId { get; set; }

        [JsonProperty(PropertyName = "description")]
        public string Description { get; set; }

        [JsonProperty(PropertyName = "estimate_id")]
        public int? EstimateId { get; set; }

        [JsonProperty(PropertyName = "owner_id")]
        public int? OwnerId { get; set; }

        [JsonProperty(PropertyName = "position")]
        public int? Position { get; set; }

        [JsonProperty(PropertyName = "priority")]
        public int? Priority { get; set; }

        [JsonProperty(PropertyName = "ready_to_pull")]
        public bool? ReadyToPull { get; set; }

        [JsonProperty(PropertyName = "blocked")]
        public bool? Blocked { get; set; }

        [JsonProperty(PropertyName = "moved_at")]
        public DateTime? MovedAt { get; set; }

        [JsonProperty(PropertyName = "created_at")]
        public DateTime? CreatedAt { get; set; }

        [JsonProperty(PropertyName = "updated_at")]
        public DateTime? UpdatedAt { get; set; }

        [JsonProperty(PropertyName = "type")]
        public string Type { get; set; }
    }
}


text:
import json
import argparse
import hashlib
import requests

def prepare_training_data(src_fname):
  content = None
  with open(src_fname) as f:
    content = f.readlines()

  events0 = {}
  offset = 0
  last_timestamp = 0
  for i in content:
    jc = json.loads(i)
    if jc:
      period_no = int(jc.get("timestamp"))/(int(args.period)*1000)
      userid = jc.get("userid")
      cart_no = str(period_no)+"_"+userid
      #print cart_no, jc.get("fullname")
      cart = events0.get(cart_no)
      if not cart:
        items = {jc.get("courseid"):1}
        #print jc
        events0[cart_no] = {"user_id":userid,"user_name":jc.get("fullname"),"items":items}
      else:
        items = cart.get("items")
        count = items.get(jc.get("courseid"),0)
        items[jc.get("courseid")] = count + 1
        cart["items"] = items
        events0[cart_no] = cart
  #
  #print "---------------------------"
  #print events0
  #print "---------------------------"
  #
  event = {}
  events = []
  for i in events0.items():
    #print i[1]
    e = i[1]
    #print type(e)
    #print e["user_id"]
    event["user_id"] = e.get("user_id")
    items = []
    for i in e["items"].items():
      items.append(i[0])
    event["items"] = items
    #print items
    #print event
    events.append(event)
  #
  return events

def train(p_data):
  print "Training"
  for i in p_data:
    #print i
    event = i
    event["rtype"] = "train"
    print event
    resp = requests.post(args.recourl,data=json.dumps(event),headers={'Content-Type':'application/json'})
    if resp:
      if resp.status_code != 200:
        raise Exception('POST failed {}'.format(resp.status_code))
      else:
        result = resp.json()
        print result

if __name__ == '__main__':
  parser = argparse.ArgumentParser(description="Training file preprocessor")
  parser.add_argument('--src', default="data/courseInfo_with_cookie.json")
  parser.add_argument('--period', default="604800")
  parser.add_argument('--recourl', default="http://localhost:5000/api/v1.0/router")

  args = parser.parse_args()
  print "src",args.src
  print "period",args.period,"seconds"
  print "url",args.recourl

  data = prepare_training_data(args.src)
  train(data)

redpajama_set_name: RedPajamaGithub


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.cassandra.cql3.selection.Selection.ResultSetBuilder (apache-cassandra API)</title>
<meta name="date" content="2016-04-13">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.cassandra.cql3.selection.Selection.ResultSetBuilder

Packages that use Selection.ResultSetBuilder

Package
Description

org.apache.cassandra.cql3.selection

Uses of Selection.ResultSetBuilder in org.apache.cassandra.cql3.selection

Methods in org.apache.cassandra.cql3.selection that return Selection.ResultSetBuilder

Modifier and Type
Method and Description

Selection.ResultSetBuilder
Selection.resultSetBuilder(boolean isJons)

Methods in org.apache.cassandra.cql3.selection with parameters of type Selection.ResultSetBuilder

Modifier and Type
Method and Description

abstract void
Selector.addInput(int protocolVersion,
        Selection.ResultSetBuilder rs)

Add the current value from the specified ResultSetBuilder.

void
SimpleSelector.addInput(int protocolVersion,
        Selection.ResultSetBuilder rs)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2016 The Apache Software Foundation


text:
<!-- Executes 2nd -->
<script type="module" src="module.js"></script>

<!-- Executes 3rd -->
<script type="module" src="module.js"></script>

<!-- Executes 1st -->
<script><script>


text:
    </div>
<?php
    include_once("./utils/dojo.inc.php");
?>
    <!-- script type="text/javascript" src="./js/selector.js"></script>
    <script type="text/javascript" src="./js/menu.js"></script -->


text:
//
//  FRDStravaClient+Upload.h
//  FRDStravaClient
//
//  Created by Sebastien Windal on 4/27/14.
//

#import "FRDStravaClient.h"
#import "StravaCommon.h"
#import "StravaActivityUploadStatus.h"

typedef NS_ENUM(NSInteger, kUploadDataType) {
    kUploadDataTypeFIT,
    kUploadDataTypeGPX,
    kUploadDataTypeTCX,
    kUploadDataTypeFITGZ,
    kUploadDataTypeGPXGZ,
    kUploadDataTypeTCXGZ
};

@interface FRDStravaClient (Upload)

/**
 Upload an activity file.

 Strava API related documentation: http://strava.github.io/api/v3/uploads/#post-file

 Once upload successfuly completed, you can check the upload activity status of that ride by calling checkStatusOfUpload:success:failure:
 using the uploadStatus.id passed in the callback.

 @param fileURL URL of the new activity file, TCP/FIT or GPX.
 @param name activity name
 @param activityType activity type
 @param dataType upload data type (TCX, GPX, FIT)
 @param private wether the new activity should be private or not
 @param success Success callback
 @param failure Failure callback
 */
-(void) uploadActivity:(NSURL *)fileURL
                  name:(NSString *)name
          activityType:(kActivityType)activityType
              dataType:(kUploadDataType)dataType
               private:(BOOL)private
               success:(void (^)(StravaActivityUploadStatus *uploadStatus))success
               failure:(void (^)(NSError *error))failure;

/**
 Check the status of a previous upload.

 Strava API related documentation: http://strava.github.io/api/v3/uploads/#get-status

 A non zero activityId in the StravaActivityUploadStatus response object indicates the upload processing is complete.
 Success callback being call does not mean the upload was successful, just the call to get the status was.

 @param fileURL URL of the new activity file, TCP/FIT or GPX.
 @param name activity name
 @param activityType activity type
 @param dataType upload data type (TCX, GPX, FIT)
 @param private wether the new activity should be private or not
 @param success Success callback
 @param failure Failure callback
 */
-(void) checkStatusOfUpload:(NSInteger)uploadId
                    success:(void (^)(StravaActivityUploadStatus *uploadStatus))success
                    failure:(void (^)(NSError *error))failure;

@end


text:
namespace app {
namespace Fuse {
namespace Resources {

struct ResourceObject;

struct ResourceObject__uType : ::app::Fuse::Resources::ResourceSetter__object__uType
{
};

ResourceObject__uType* ResourceObject__typeof();

void ResourceObject___ObjInit_2(ResourceObject* __this);
ResourceObject* ResourceObject__New_1(::uStatic* __this);

struct ResourceObject : ::app::Fuse::Resources::ResourceSetter__object
{
    void _ObjInit_2() { ResourceObject___ObjInit_2(this); }
};

}}}

#endif


text: from .value_guided_sampling import ValueGuidedRLPipeline


text:
require "chef/knife"
require "chef/http"

class Chef
  class Knife
    class Raw < Chef::Knife
      banner "knife raw REQUEST_PATH (options)"

      deps do
        require "chef/json_compat"
        require "chef/config"
        require "chef/http"
        require "chef/http/authenticator"
        require "chef/http/cookie_manager"
        require "chef/http/decompressor"
        require "chef/http/json_output"
      end

      option :method,
        long: "--method METHOD",
        short: "-m METHOD",
        default: "GET",
        description: "Request method (GET, POST, PUT or DELETE). Default: GET."

      option :pretty,
        long: "--[no-]pretty",
        boolean: true,
        default: true,
        description: "Pretty-print JSON output. Default: true."

      option :input,
        long: "--input FILE",
        short: "-i FILE",
        description: "Name of file to use for PUT or POST."

      option :proxy_auth,
        long: "--proxy-auth",
        boolean: true,
        default: false,
        description: "Use webui proxy authentication. Client key must be the webui key."

      # We need a custom HTTP client class here because we don't want to even
      # try to decode the body, in case we get back corrupted JSON or whatnot.
      class RawInputServerAPI < Chef::HTTP
        def initialize(options = {})
          # If making a change here, also update Chef::ServerAPI.
          options[:client_name] ||= Chef::Config[:node_name]
          options[:raw_key] ||= Chef::Config[:client_key_contents]
          options[:signing_key_filename] ||= Chef::Config[:client_key] unless options[:raw_key]
          options[:ssh_agent_signing] ||= Chef::Config[:ssh_agent_signing]
          super(Chef::Config[:chef_server_url], options)
        end
        use Chef::HTTP::JSONOutput
        use Chef::HTTP::CookieManager
        use Chef::HTTP::Decompressor
        use Chef::HTTP::Authenticator
        use Chef::HTTP::RemoteRequestID
      end

      def run
        if name_args.length == 0
          show_usage
          ui.fatal("You must provide the path you want to hit on the server")
          exit(1)
        elsif name_args.length > 1
          show_usage
          ui.fatal("You must specify only a single path")
          exit(1)
        end

        path = name_args[0]
        data = false
        if config[:input]
          data = IO.read(config[:input])
        end
        begin
          method = config[:method].to_sym

          headers = { "Content-Type" => "application/json" }

          if config[:proxy_auth]
            headers["x-ops-request-source"] = "web"
          end

          if config[:pretty]
            chef_rest = RawInputServerAPI.new
            result = chef_rest.request(method, name_args[0], headers, data)
            unless result.is_a?(String)
              result = Chef::JSONCompat.to_json_pretty(result)
            end
          else
            chef_rest = RawInputServerAPI.new(raw_output: true)
            result = chef_rest.request(method, name_args[0], headers, data)
          end
          output result
        rescue Timeout::Error => e
          ui.error "Server timeout"
          exit 1
        rescue Net::HTTPServerException => e
          ui.error "Server responded with error #{e.response.code} \"#{e.response.message}\""
          ui.error "Error Body: #{e.response.body}" if e.response.body && e.response.body != ""
          exit 1
        end
      end

    end # class Raw
  end
end


text:
package de.zib.gndms.taskflows.filetransfer.server;

import de.zib.gndms.common.model.gorfx.types.Quote;
import de.zib.gndms.kit.config.MandatoryOptionMissingException;
import de.zib.gndms.logic.model.TaskAction;
import de.zib.gndms.logic.model.gorfx.taskflow.DefaultTaskFlowFactory;
import de.zib.gndms.neomodel.gorfx.TaskFlow;
import de.zib.gndms.taskflows.filetransfer.client.FileTransferMeta;
import de.zib.gndms.taskflows.filetransfer.client.model.FileTransferOrder;
import de.zib.gndms.taskflows.filetransfer.server.logic.FileTransferQuoteCalculator;
import de.zib.gndms.taskflows.filetransfer.server.logic.FileTransferTaskAction;

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

/**
 * ThingAMagic.
 *
 * @author  try ste fan pla nti kow zib
 * @version $Id$
 *
 *          User: stepn Date: 09.10.2008 Time: 12:49:54
 */
public class FileTransferTaskFlowFactory
    extends DefaultTaskFlowFactory<FileTransferOrder, FileTransferQuoteCalculator> {

    public FileTransferTaskFlowFactory( ) {

        super( FileTransferMeta.FILE_TRANSFER_TYPE_KEY, FileTransferQuoteCalculator.class,
                FileTransferOrder.class );
    }

    @Override
    public FileTransferQuoteCalculator getQuoteCalculator() throws MandatoryOptionMissingException {
        final FileTransferQuoteCalculator quoteCalculator = super.getQuoteCalculator();
        injectMembers( quoteCalculator );
        return quoteCalculator;
    }

    @Override
    protected TaskFlow<FileTransferOrder> prepare( TaskFlow<FileTransferOrder>
                                                               fileTransferOrderTaskFlow ) {
        return fileTransferOrderTaskFlow;
    }

    @Override
    protected Map<String, String> getDefaultConfig() {

        final HashMap<String, String> config = new HashMap<String, String>( 1 );
        // todo add default values for gridftp-client factory
        return config;
    }

    @Override
    public TaskAction createAction( final Quote quote ) {
        FileTransferTaskAction action = new FileTransferTaskAction();
        getInjector().injectMembers( action );
        return action;
    }
}


text:
<?php

namespace Symfony\Component\CssSelector\Parser\Shortcut;

use Symfony\Component\CssSelector\Node\ElementNode;
use Symfony\Component\CssSelector\Node\SelectorNode;
use Symfony\Component\CssSelector\Parser\ParserInterface;

/**
 * CSS selector element parser shortcut.
 *
 * This component is a port of the Python cssselector library,
 * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect.
 *
 * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
 */
class ElementParser implements ParserInterface
{
    /**
     * {@inheritdoc}
     */
    public function parse($source)
    {
        // Matches an optional namespace, required element or `*`
        // $source = 'testns|testel';
        // $matches = array (size=4)
        //     0 => string 'testns:testel' (length=13)
        //     1 => string 'testns:' (length=7)
        //     2 => string 'testns' (length=6)
        //     3 => string 'testel' (length=6)
        if (preg_match('/^(([a-z]+)\|)?([\w-]+|\*)$/i', trim($source), $matches)) {
            return array(new SelectorNode(new ElementNode($matches[2] ?: null, $matches[3])));
        }

        return array();
    }
}


text:
package com.microsoft.azure.management.datafactory.v2018_06_01;

import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Execution policy for an activity.
 */
public class ActivityPolicy {
    /**
     * Unmatched properties from the message are deserialized this collection.
     */
    @JsonProperty(value = "")
    private Map<String, Object> additionalProperties;

    /**
     * Specifies the timeout for the activity to run. The default timeout is 7
     * days. Type: string (or Expression with resultType string), pattern:
     * ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
     */
    @JsonProperty(value = "timeout")
    private Object timeout;

    /**
     * Maximum ordinary retry attempts. Default is 0. Type: integer (or
     * Expression with resultType integer), minimum: 0.
     */
    @JsonProperty(value = "retry")
    private Object retry;

    /**
     * Interval between each retry attempt (in seconds). The default is 30 sec.
     */
    @JsonProperty(value = "retryIntervalInSeconds")
    private Integer retryIntervalInSeconds;

    /**
     * When set to true, Input from activity is considered as secure and will
     * not be logged to monitoring.
     */
    @JsonProperty(value = "secureInput")
    private Boolean secureInput;

    /**
     * When set to true, Output from activity is considered as secure and will
     * not be logged to monitoring.
     */
    @JsonProperty(value = "secureOutput")
    private Boolean secureOutput;

    /**
     * Get unmatched properties from the message are deserialized this collection.
     *
     * @return the additionalProperties value
     */
    public Map<String, Object> additionalProperties() {
        return this.additionalProperties;
    }

    /**
     * Set unmatched properties from the message are deserialized this collection.
     *
     * @param additionalProperties the additionalProperties value to set
     * @return the ActivityPolicy object itself.
     */
    public ActivityPolicy withAdditionalProperties(Map<String, Object> additionalProperties) {
        this.additionalProperties = additionalProperties;
        return this;
    }

    /**
     * Get specifies the timeout for the activity to run. The default timeout is 7 days. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
     *
     * @return the timeout value
     */
    public Object timeout() {
        return this.timeout;
    }

    /**
     * Set specifies the timeout for the activity to run. The default timeout is 7 days. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
     *
     * @param timeout the timeout value to set
     * @return the ActivityPolicy object itself.
     */
    public ActivityPolicy withTimeout(Object timeout) {
        this.timeout = timeout;
        return this;
    }

    /**
     * Get maximum ordinary retry attempts. Default is 0. Type: integer (or Expression with resultType integer), minimum: 0.
     *
     * @return the retry value
     */
    public Object retry() {
        return this.retry;
    }

    /**
     * Set maximum ordinary retry attempts. Default is 0. Type: integer (or Expression with resultType integer), minimum: 0.
     *
     * @param retry the retry value to set
     * @return the ActivityPolicy object itself.
     */
    public ActivityPolicy withRetry(Object retry) {
        this.retry = retry;
        return this;
    }

    /**
     * Get interval between each retry attempt (in seconds). The default is 30 sec.
     *
     * @return the retryIntervalInSeconds value
     */
    public Integer retryIntervalInSeconds() {
        return this.retryIntervalInSeconds;
    }

    /**
     * Set interval between each retry attempt (in seconds). The default is 30 sec.
     *
     * @param retryIntervalInSeconds the retryIntervalInSeconds value to set
     * @return the ActivityPolicy object itself.
     */
    public ActivityPolicy withRetryIntervalInSeconds(Integer retryIntervalInSeconds) {
        this.retryIntervalInSeconds = retryIntervalInSeconds;
        return this;
    }

    /**
     * Get when set to true, Input from activity is considered as secure and will not be logged to monitoring.
     *
     * @return the secureInput value
     */
    public Boolean secureInput() {
        return this.secureInput;
    }

    /**
     * Set when set to true, Input from activity is considered as secure and will not be logged to monitoring.
     *
     * @param secureInput the secureInput value to set
     * @return the ActivityPolicy object itself.
     */
    public ActivityPolicy withSecureInput(Boolean secureInput) {
        this.secureInput = secureInput;
        return this;
    }

    /**
     * Get when set to true, Output from activity is considered as secure and will not be logged to monitoring.
     *
     * @return the secureOutput value
     */
    public Boolean secureOutput() {
        return this.secureOutput;
    }

    /**
     * Set when set to true, Output from activity is considered as secure and will not be logged to monitoring.
     *
     * @param secureOutput the secureOutput value to set
     * @return the ActivityPolicy object itself.
     */
    public ActivityPolicy withSecureOutput(Boolean secureOutput) {
        this.secureOutput = secureOutput;
        return this;
    }

}


text:
package eu.cqse.msdnscraper.rules.spcop;

import java.util.ArrayList;
import java.util.Collection;

import com.mpdeimos.webscraper.Scrape;
import com.mpdeimos.webscraper.ScraperSource;
import com.mpdeimos.webscraper.ScraperSource.ScraperSourceProvider;
import com.mpdeimos.webscraper.conversion.ConstructConverter;

import eu.cqse.msdnscraper.rules.IRuleProvider;
import eu.cqse.msdnscraper.rules.Rule;
import eu.cqse.msdnscraper.rules.RuleResolver;

/**
 * Resolver for SpCop rules.
 *
 * @author $Author: hummelb $
 * @version $Rev: 18709 $
 * @ConQAT.Rating YELLOW Hash: A42B8F3E5A2AFCB69A9E73887530CD67
 */
public class SpCopRuleResolver extends RuleResolver {
	/** The base url to start scraping from. */
	static final String BASE_URL = "http://docs.spcaf.com/v4/SPCAF_ANALYZER_RULES.html";

	/** {@inheritDoc} */
	@Override
	protected RuleCategorySite getRuleProvider() {
		return new RuleCategorySite();
	}

	/**
	 * The site available via SpCopRuleResolver#BASE_BASE_URL contains links to
	 * overview sites. These are scraped with this object.
	 */
	public static class RuleCategorySite implements ScraperSourceProvider,
			IRuleProvider {
		/** The rule overview sites found on this site. */
		@Scrape(value = ".OH_selfTocLinks > div a", attribute = "abs:href", converter = ConstructConverter.class)
		public SpCopRuleOverview[] overviews;

		/** {@inheritDoc} */
		@Override
		public ScraperSource getSource() {
			return ScraperSource.fromUrl(BASE_URL);
		}

		/** {@inheritDoc} */
		@Override
		public Collection<? extends Rule> getRules() {
			ArrayList<Rule> rules = new ArrayList<>();
			for (SpCopRuleOverview overview : overviews) {
				rules.addAll(overview.getRules());
			}
			return rules;
		}

	}
}


text:
require 'spec_helper'

describe "Nebula Search" do

  # see spec/support/data.rb
  before { create_nebula }

  describe 'by query' do

    describe 'find by label' do
      subject { Nebula::Node.query(label: 'foo') }
      it { expects(subject.length).to eq(1) }
      it { expects(subject.first.data).to eq("verified" =>  true) }
    end

    describe 'find by data attribute' do
      context 'string value' do
        subject { Nebula::Node.query(data: { foo: 'bar' }) }
        it { expects(subject.length).to eq(2) }
        it { expects(subject.map { |node| node.data['bar'] }).to match_array(%w{ baz bot }) }
      end

      context 'integer value' do
        subject { Nebula::Node.query(data: { foo: 5 }) }
        it { expects(subject.length).to eq(1) }
        it { expects(subject.first.label).to eq('foo5') }
      end

      context 'float value' do
        subject { Nebula::Node.query(data: { foo: 5.2 }) }
        it { expects(subject.length).to eq(1) }
        it { expects(subject.first.label).to eq('foo5.2') }
      end

      context 'conjunctive attributes' do
        subject { Nebula::Node.query(data: { foo: 'bar', bar: 'baz' }) }
        it { expects(subject.length).to eq(1) }
        it { expects(subject.first.label).to eq('foobarbarbaz') }
      end

      context 'disjunctive attributes' do
        subject { Nebula::Node.query(data: [ { bar: 'baz' }, { bar: 'bot' } ]) }
        it { expects(subject.length).to eq(2) }
        it { expects(subject.map(&:label)).to match_array(%w{ foobarbarbaz foobarbarbot }) }
      end

      context 'deep attributes' do
        subject { Nebula::Node.query(data: { foo: { bar: 'baz' } }) }
        it { expects(subject.length).to eq(1) }
        it { expects(subject.first.label).to eq('deepfoobarbaz') }
      end
    end

    describe 'find by incoming edge label' do
      subject { Nebula::Node.query(in: { label: 'foo' }) }
      it { expects(subject.length).to eq(2) }
      it { expects(subject.map(&:label)).to match_array(%w{ in_one in_two }) }
    end

    describe 'find by incoming edge from node' do
      subject { Nebula::Node.query(in: { label: 'internal', from: { label: 'root_b' } }) }
      it { expects(subject.length).to eq(1) }
      it { expects(subject.first.label).to eq('internal_a') }
    end

    describe 'find by incoming edge through node' do
      subject { Nebula::Node.query(in: { label: 'leaf', from: { in: { label: 'internal', from: { label: 'root_b' } } } }) }
      it { expects(subject.length).to eq(2) }
      it { expects(subject.map(&:label)).to match_array(%w{ leaf_a leaf_b }) }
    end

    describe 'find by outgoing edge label' do
      subject { Nebula::Node.query(out: { label: 'bar' }) }
      it { expects(subject.length).to eq(1) }
      it { expects(subject.first.label).to eq('root') }
    end

    describe 'find by outgoing edge to node' do
      subject { Nebula::Node.query(out: { label: 'leaf', to: { label: 'leaf_c' } }) }
      it { expects(subject.length).to eq(1) }
      it { expects(subject.first.label).to eq('internal_b') }
    end

    describe 'find by outgoing edge through node' do
      subject { Nebula::Node.query(out: { label: 'internal', to: { out: { label: 'leaf', to: { label: 'leaf_a' } } } }) }
      it { expects(subject.length).to eq(2) }
      it { expects(subject.map(&:label)).to match_array(%w{ root_a root_b }) }
    end
  end
end


text:
module SSHKit

  class Coordinator

    attr_accessor :hosts

    def initialize(raw_hosts)
      @raw_hosts = Array(raw_hosts)
      @hosts = @raw_hosts.any? ? resolve_hosts : []
    end

    def each(options={}, &block)
      if hosts
        options = default_options.merge(options)
        case options[:in]
        when :parallel then Runner::Parallel
        when :sequence then Runner::Sequential
        when :groups   then Runner::Group
        else
          options[:in]
        end.new(hosts, options, &block).execute
      else
        Runner::Null.new(hosts, options, &block).execute
      end
    end

    private

    def default_options
      { in: SSHKit.config.default_runner }
    end

    def resolve_hosts
      @raw_hosts.collect { |rh| rh.is_a?(Host) ? rh : Host.new(rh) }.uniq
    end

  end

end


text:
//*******************************************************************************************//
//                                                                                //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer       //
//                                                                                //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup               //
//                                                                                //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                //
// https://www.bytescout.com                                                                 //
// https://pdf.co                                                                            //
//                                                                                //
//*******************************************************************************************//

/*jshint esversion: 6 */

// Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost".
// If it's not then please replace this with with your hosting url.

var https = require("https");
var path = require("path");
var fs = require("fs");

// `request` module is required for file upload.
// Use "npm install request" command to install.
var request = require("request");

// Source DOC or DOCX file
const SourceFile = "./sample.docx";
// Destination PDF file name
const DestinationFile = "./result.pdf";

// 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE.
getPresignedUrl(SourceFile)
.then(([uploadUrl, uploadedFileUrl]) => {
    // 2. UPLOAD THE FILE TO CLOUD.
    uploadFile(SourceFile, uploadUrl)
    .then(() => {
        // 3. CONVERT UPLOADED DOC (DOCX) FILE TO PDF
        convertDocToPdf(uploadedFileUrl, DestinationFile);
    })
    .catch(e => {
        console.log(e);
    });
})
.catch(e => {
    console.log(e);
});

function getPresignedUrl(localFile) {
    return new Promise(resolve => {
        // Prepare request to `Get Presigned URL` API endpoint
        let queryPath = `/file/upload/get-presigned-url?contenttype=application/octet-stream&name=${path.basename(SourceFile)}`;
        let reqOptions = {
            host: "localhost",
            path: encodeURI(queryPath)
        };
        // Send request
        https.get(reqOptions, (response) => {
            response.on("data", (d) => {
                let data = JSON.parse(d);
                if (data.error == false) {
                    // Return presigned url we received
                    resolve([data.presignedUrl, data.url]);
                }
                else {
                    // Service reported error
                    console.log("getPresignedUrl(): " + data.message);
                }
            });
        })
        .on("error", (e) => {
            // Request error
            console.log("getPresignedUrl(): " + e);
        });
    });
}

function uploadFile(localFile, uploadUrl) {
    return new Promise(resolve => {
        fs.readFile(SourceFile, (err, data) => {
            request({
                method: "PUT",
                url: uploadUrl,
                body: data,
                headers: {
                    "Content-Type": "application/octet-stream"
                }
            }, (err, res, body) => {
                if (!err) {
                    resolve();
                }
                else {
                    console.log("uploadFile() request error: " + e);
                }
            });
        });
    });
}

function convertDocToPdf(uploadedFileUrl, destinationFile) {
    // Prepare URL for `DOC To PDF` API call
    let queryPath = `/pdf/convert/from/doc?name=${path.basename(destinationFile)}&url=${uploadedFileUrl}`;
    let reqOptions = {
        host: "localhost",
        path: encodeURI(queryPath),
        method: "GET"
    };
    // Send request
    https.get(reqOptions, (response) => {
        response.on("data", (d) => {
            response.setEncoding("utf8");
            // Parse JSON response
            let data = JSON.parse(d);
            if (data.error == false) {
                // Download PDF file
                var file = fs.createWriteStream(destinationFile);
                https.get(data.url, (response2) => {
                    response2.pipe(file)
                    .on("close", () => {
                        console.log(`Generated PDF file saved as "${destinationFile}" file.`);
                    });
                });
            }
            else {
                // Service reported error
                console.log("readBarcodes(): " + data.message);
            }
        });
    })
    .on("error", (e) => {
        // Request error
        console.log("readBarcodes(): " + e);
    });
}


text:
namespace ui {

IdleQueryX11::IdleQueryX11() : connection_(x11::Connection::Get()) {
  // Let the server know the client version before making any requests.
  connection_->screensaver().QueryVersion(
      {x11::ScreenSaver::major_version, x11::ScreenSaver::minor_version});
}

IdleQueryX11::~IdleQueryX11() = default;

int IdleQueryX11::IdleTime() {
  if (auto reply = connection_->screensaver()
                       .QueryInfo(connection_->default_root())
                       .Sync()) {
    return reply->ms_since_user_input / 1000;
  }
  return 0;
}

}  // namespace ui


text:
<?php

namespace Documents\Functional\Ticket\MODM160;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/** @ODM\Document(collection="embedded_test") */
class EmbedManyInArrayLevel0
{
    /** @ODM\Id */
    public $id;
    /** @ODM\Field(type="string") */
    public $name;
    /** @ODM\EmbedMany(targetDocument="EmbedManyInArrayLevel1") */
    public $level1 = array();
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>教程 • iecs' Site</title>
    <meta name="description" content="
  你懂的。。

">
    <meta name="keywords" content="">

	<meta name="twitter:title" content="教程">
	<meta name="twitter:description" content="
  你懂的。。

">
	<meta name="twitter:site" content="@iecs">
	<meta name="twitter:creator" content="@iecs">

	<meta name="twitter:card" content="summary">
	<meta name="twitter:image" content="/images/logo.jpg">

	<meta property="og:locale" content="en">
	<meta property="og:type" content="article">
	<meta property="og:title" content="教程">
	<meta property="og:description" content="
  你懂的。。

">
	<meta property="og:url" content="/test/set-up-site/">
	<meta property="og:site_name" content="iecs' Site">

    <link rel="canonical" href="/test/set-up-site/">

    <link href="/atom.xml" type="application/atom+xml" rel="alternate" title="iecs' Site Atom Feed">
    <link href="/sitemap.xml" type="application/xml" rel="sitemap" title="Sitemap">

    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="cleartype" content="on">

    <link rel="stylesheet" href="/css/main.css">

    iecs' Site

iecs' Site

HOME

Jekyll

test

python

iecs' Site Table of Contents

HOME

Jekyll

test

python

<button type="button" id="js-menu-trigger" class="sliding-menu-button lines-button x2" role="button" aria-label="Toggle Navigation">

</button>

        Home
       ›

        Test

教程

你懂的。。

Written by iecs

	 Share on Twitter
	 Share on Facebook
	 Share on Google+

Updated <time datetime="2017-10-08T00:00:00Z" itemprop="datePublished">October 08, 2017</time>

Please enable JavaScript to view the comments powered by Disqus.

© 2017 iecs' Site powered by Jekyll + Skinny Bones.


text:
template <typename T, size_t Size>
class MovingAverage
{
public:
	typedef CircularBuffer<T, Size> container_type;
	typedef typename container_type::reference reference;
	typedef typename container_type::const_reference const_reference;
	typedef typename container_type::value_type value_type;
	typedef typename container_type::size_type size_type;

private:
	container_type m_buffer;
	value_type m_sum;

public:
	MovingAverage() : m_sum(0)
	{
	}

	void push(const_reference value)
	{
		if (m_buffer.full())
			m_sum -= m_buffer.front();
		m_buffer.push_back(value);
		m_sum += value;
	}

	reference back()
	{
		return m_buffer.back();
	}

	const_reference back() const
	{
		return m_buffer.back();
	}

	size_type capacity() const
	{
		return m_buffer.capacity();
	}

	size_type size() const
	{
		return m_buffer.size();
	}

	bool empty() const
	{
		return m_buffer.empty();
	}

	bool full() const
	{
		return m_buffer.full();
	}

	value_type sum() const
	{
		return m_sum;
	}

	value_type average() const
	{
		return empty() ? 0 : sum() / size();
	}
};

#endif


text:
#ifndef BCHART_H
#define BCHART_H

#include "ChartBase.h"
#include "EdgeHeap.h"
#include "Wrd.h"
#include "FullHist.h"
#include "UnitRules.h"
#include "ExtPos.h"

#define Termstar const Term*

struct Wwegt
{
  int t;
  ECString e;
  float p;
};

class Bchart;

/* WordAndPresence stores the integer associated with a word and whether
   the word is a "hole" or not (false = hole).  ("hole"s are in the
   vocabulary for the purposes of unified vocabulary indexing. */
typedef pair<int, bool> WordAndPresence;

class           Bchart : public ChartBase
{
public:
  Bchart(SentRep& sentence,int id);
  Bchart(SentRep& sentence,ExtPos& extPos,int id);
    virtual ~Bchart();
    virtual double  parse();
    static int&      printDebug() { return printDebug_; }
    static bool      printDebug(int val) { return val < printDebug_; }
    static void     readTermProbs(ECString& path);
    static void     makepUgT(ECString path);
    static void     readpUgT(ECString path);
    int      wtoInt(ECString& str);
    int     extraTime; //if no parse is found on regular time;
    static  Item*    dummyItem;
    static float timeFactor;
    float    denomProbs[MAXSENTLEN];
    void            check();
    static void     setPosStarts();
    ECString intToW(int n);
    bool prned();
    bool issprn(Edge* e);
    static map< ECString, WordAndPresence, less<ECString> > wordMap;
    static ECString invWordMap[MAXNUMWORDS];
  static int lastKnownWord;
  static int lastWord[MAXNUMTHREADS];
  static map<ECString, int> newWordMap[MAXNUMTHREADS];
  static vector<ECString> newWords[MAXNUMTHREADS];
  static UnitRules*  unitRules;
  static bool caseInsensitive;
  static bool tokenize;
  static size_t Nth;
  static bool prettyPrint;
  static bool silent;
  static bool smallCorpus;
  static float smoothPosAmount;
  static const char *HEADWORD_S1;
  Item*   edgesFromTree(InputTree* tree);
  void  set_Betas();

  // 06/01/06 ML: made these methods public for access by parseIt.C
  // in getting at least POS tags when parsing fails.
  list<float>& wordPlist(Wrd* word, int word_num);
  static float& pT(int val)
    {
      if (val < 0 || val >= MAXNUMNTTS)
	{
	  cerr << "Bad val = " << val << endl;
	  assert(val >= 0 && val < MAXNUMTS);
	}
      return pT_[val];
    }
  int depth;
  Val* curVal;
  int curDir;
  Val* gcurVal;
  ExtPos extraPos;
 protected:
  /* this block of functions are only used/defined in rParse */
    Wrd*  add_word(const Term* trm, int st, ECString wrdStr);
    Item* add_item(int b, const Term* trmNm, int wrd);
    Item* add_item2(int b, const Term* trm, int wInt, ECString wrdstr);
    Item* addToChart(const Term* trm);;
    Item* in_chart(int b, const Term* trm, bool& wasThere);
    Item* in_chartT(int b, const Term* trm);
    Edge* add_edge(Item* lhs, Items& rhs);
    void   computeEdgeBeta(Item* itm, Edge* edge);
    void   propagateItemBeta(Item* itm, double quant);
    int   headPosFromItems(Item* lhs, Items& rhs);
    void  readItem(istream& str, int& b, const Term*& trm);
    void  store_word(Wrd* wrd);
    Wrd*  find_word(int wint, int st);
    void  assignRProb(Edge* edge);
    double compute_Betas();
    bool  compute_Beta(Item* itm);
    double compute_EdgeBeta(Edge* edge);
    InputTree* lookUpPhrase(Item* lhs, ECString phrase);
    void  newWord(ECString wrdstr, int wInt, Item* ans);
    Edge*  procPhrasal(Item* lhs, ECString phrase);
    bool   procPhrase(Item* lhs, InputTree* tree);
    void   rPendFactor();
    /* end of block */

    void            add_reg_item(Item * itm);
    void            addFinishedEdge(Edge* newEdge);
    void            add_starter_edges(Item* itm);
    float           meEdgeProb(const Term* trm, Edge* edge, int whichInt);
    float           meFHProb(const Term* trm, FullHist& fh, int whichInt);
    static int printDebug_;

    void            extend_rule(Edge* rule, Item * itm, int right);
    void            already_there_extention(int i, int start, int right,
					    Edge* edge);
    void            add_edge(Edge* rli, int left);
    void            put_in_reg(Item * item);
    void            addWordsToKeylist( );
    Item           *in_chart(const Wrd* hd, const Term * trm,
			     int start, int finish);
    bool            repeatRule(Edge* edge);

    void            redoP(Edge* edge, double probRatio);
    void            redoP(Item *item, double probDiff);

    float           computeMerit(Edge* edge, int whichCalc);

    void  initDenom();
    double  psktt(Wrd* shU, int t);
    double  pCapgt(const Wrd* shU, int t);
    float   pHst(int w, int t);
    double  psutt(const Wrd* shU, int t);
    float   pegt(ECString& sh, int t);
    void    getpHst(const ECString& hd, int t);
    double pHypgt(const ECString& shU, int t);
    static float&  pHcapgt(int i) { return pHcapgt_[i]; }
    static float&  pHhypgt(int i) { return pHhypgt_[i]; }
    static float&  pHugt(int i) { return pHugt_[i]; }

    int     bucket(float val, int whichInt, int whichFt);
    int     bucket(float val);
    int    greaterThan(Wwegt& wwegt, ECString e, int t);
    float  pHegt(ECString& es, int t);
    float  computepTgT(int t1,int t2);
    void   addToDemerits(Edge* edge);
    static Item*    stops[MAXSENTLEN];
    EdgeHeap*       heap;
    int             alreadyPoppedNum;
    Edge*           alreadyPopped[450000]; //was 350000;
    static int&     posStarts(int i, int j);
    static int      posStarts_[MAXNUMNTTS][MAXNUMNTS];
  int     curDemerits_[MAXSENTLEN][MAXSENTLEN];

  static int egtSize_;
  static float bucketLims[14];
  static float pT_[MAXNUMNTTS];
  static float pHcapgt_[MAXNUMTS];
  static float pHhypgt_[MAXNUMTS];
  static float pHugt_[MAXNUMTS];

  static Wwegt* pHegt_;
  list<float> wordPlists[MAXSENTLEN];
};

#endif	/* ! BCHART_H */


text:
from __future__ import absolute_import

from thriftpy import load
from thriftpy.thrift import TPayload, TException, TType

import thriftpy
thriftpy.install_import_hook()

import addressbook as ab
import addressbook_thrift as ab_tt
import storm
import storm_thrift as storm_tt

def test_load_const():
    assert ab.DEFAULT_LIST_SIZE == ab_tt.DEFAULT_LIST_SIZE

def test_load_enum():
    assert ab.PhoneType.MOBILE == ab_tt.PhoneType.MOBILE
    assert ab.PhoneType.HOME == ab_tt.PhoneType.HOME
    assert ab.PhoneType.WORK == ab_tt.PhoneType.WORK

def test_load_struct():
    assert ab_tt.PhoneNumber.__base__ == TPayload

    ab_thrift_spec = {}
    for k, vs in ab.PhoneNumber.thrift_spec.items():
        ab_thrift_spec[k] = [str(v).replace('_thrift', '') for v in vs]

    ab_tt_thrift_spec = {}
    for k, vs in ab_tt.PhoneNumber.thrift_spec.items():
        ab_tt_thrift_spec[k] = [str(v).replace('_thrift', '') for v in vs]
    assert ab_thrift_spec == ab_tt_thrift_spec

    assert storm_tt.NullStruct.__base__ == TPayload
    assert storm.NullStruct.thrift_spec == storm_tt.NullStruct.thrift_spec

    # TODO make this work
    # assert ab_tt.Person.__base__ == TPayload
    # assert ab.Person.thrift_spec == ab_tt.Person.thrift_spec

    # assert ab_tt.AddressBook.__base__ == TPayload
    # assert ab.AddressBook.thrift_spec == ab_tt.AddressBook.thrift_spec

def test_load_union():
    assert storm_tt.JavaObjectArg.__base__ == TPayload
    assert storm.JavaObjectArg.thrift_spec == \
        storm_tt.JavaObjectArg.thrift_spec

def test_load_exc():
    assert ab_tt.PersonNotExistsError.__base__ == TException
    assert ab.PersonNotExistsError.thrift_spec == \
        ab_tt.PersonNotExistsError.thrift_spec

def test_load_service():
    assert not set(ab.AddressBookService.thrift_services).difference(
        ab_tt.AddressBookService.thrift_services)

def test_load_include():
    b = load("base.thrift")
    g = load("parent.thrift")

    ts = g.Greet.thrift_spec
    assert ts[1][2] == b.Hello and ts[2][0] == TType.I64 and ts[3][2] == b.Code


text:
'use strict';

//Setting up route
angular.module('etc-products').config(['$stateProvider',
	function($stateProvider) {
		// Etc products state routing
		$stateProvider.
		state('listEtcProducts', {
			url: '/etc-products',
			templateUrl: 'modules/etc-products/views/list-etc-products.client.view.html'
		}).
		state('createEtcProduct', {
			url: '/etc-products/create',
			templateUrl: 'modules/etc-products/views/create-etc-product.client.view.html'
		}).
		state('viewEtcProduct', {
			url: '/etc-products/:etcProductId',
			templateUrl: 'modules/etc-products/views/view-etc-product.client.view.html'
		}).
		state('editEtcProduct', {
			url: '/etc-products/:etcProductId/edit',
			templateUrl: 'modules/etc-products/views/edit-etc-product.client.view.html'
		});
	}
]);


text:
<?php
/**
 * Text used for 'Entities' (Document Structure Elements) such as
 * Books, Shelves, Chapters & Pages
 */
return [

    // Shared
    'recently_created' => 'Được tạo gần đây',
    'recently_created_pages' => 'Trang được tạo gần đây',
    'recently_updated_pages' => 'Trang được cập nhật gần đây',
    'recently_created_chapters' => 'Chương được tạo gần đây',
    'recently_created_books' => 'Sách được tạo gần đây',
    'recently_created_shelves' => 'Giá sách được tạo gần đây',
    'recently_update' => 'Được cập nhật gần đây',
    'recently_viewed' => 'Được xem gần đây',
    'recent_activity' => 'Hoạt động gần đây',
    'create_now' => 'Tạo ngay',
    'revisions' => 'Phiên bản',
    'meta_revision' => 'Phiên bản #:revisionCount',
    'meta_created' => 'Được tạo :timeLength',
    'meta_created_name' => 'Được tạo :timeLength bởi :user',
    'meta_updated' => 'Được cập nhật :timeLength',
    'meta_updated_name' => 'Được cập nhật :timeLength bởi :user',
    'meta_owned_name' => 'Được sở hữu bởi :user',
    'meta_reference_page_count' => 'Referenced on 1 page|Referenced on :count pages',
    'entity_select' => 'Chọn thực thể',
    'entity_select_lack_permission' => 'You don\'t have the required permissions to select this item',
    'images' => 'Ảnh',
    'my_recent_drafts' => 'Bản nháp gần đây của tôi',
    'my_recently_viewed' => 'Xem gần đây',
    'my_most_viewed_favourites' => 'My Most Viewed Favourites',
    'my_favourites' => 'Danh sách yêu thích của tôi',
    'no_pages_viewed' => 'Bạn chưa xem bất cứ trang nào',
    'no_pages_recently_created' => 'Không có trang nào được tạo gần đây',
    'no_pages_recently_updated' => 'Không có trang nào được cập nhật gần đây',
    'export' => 'Kết xuất',
    'export_html' => 'Đang chứa tệp tin Web',
    'export_pdf' => 'Tệp PDF',
    'export_text' => 'Tệp văn bản thuần túy',
    'export_md' => 'Tệp Markdown',

    // Permissions and restrictions
    'permissions' => 'Quyền',
    'permissions_desc' => 'Set permissions here to override the default permissions provided by user roles.',
    'permissions_book_cascade' => 'Permissions set on books will automatically cascade to child chapters and pages, unless they have their own permissions defined.',
    'permissions_chapter_cascade' => 'Permissions set on chapters will automatically cascade to child pages, unless they have their own permissions defined.',
    'permissions_save' => 'Lưu quyền hạn',
    'permissions_owner' => 'Chủ sở hữu',
    'permissions_role_everyone_else' => 'Everyone Else',
    'permissions_role_everyone_else_desc' => 'Set permissions for all roles not specifically overridden.',
    'permissions_role_override' => 'Override permissions for role',

    // Search
    'search_results' => 'Kết quả Tìm kiếm',
    'search_total_results_found' => 'Tìm thấy :count kết quả|:count tổng kết quả',
    'search_clear' => 'Xoá tìm kiếm',
    'search_no_pages' => 'Không trang nào khớp với tìm kiếm này',
    'search_for_term' => 'Tìm kiếm cho :term',
    'search_more' => 'Thêm kết quả',
    'search_advanced' => 'Tìm kiếm Nâng cao',
    'search_terms' => 'Cụm từ Tìm kiếm',
    'search_content_type' => 'Kiểu Nội dung',
    'search_exact_matches' => 'Hoàn toàn trùng khớp',
    'search_tags' => 'Tìm kiếm Tag',
    'search_options' => 'Tuỳ chọn',
    'search_viewed_by_me' => 'Được xem bởi tôi',
    'search_not_viewed_by_me' => 'Không được xem bởi tôi',
    'search_permissions_set' => 'Phân quyền',
    'search_created_by_me' => 'Được tạo bởi tôi',
    'search_updated_by_me' => 'Được cập nhật bởi tôi',
    'search_owned_by_me' => 'Của tôi',
    'search_date_options' => 'Tùy chọn ngày',
    'search_updated_before' => 'Đã được cập nhật trước đó',
    'search_updated_after' => 'Đã được cập nhật sau',
    'search_created_before' => 'Đã được tạo trước',
    'search_created_after' => 'Đã được tạo sau',
    'search_set_date' => 'Đặt ngày',
    'search_update' => 'Cập nhật tìm kiếm',

    // Shelves
    'shelf' => 'Giá',
    'shelves' => 'Giá',
    'x_shelves' => ':count Giá |:count Giá',
    'shelves_empty' => 'Không có giá nào được tạo',
    'shelves_create' => 'Tạo Giá mới',
    'shelves_popular' => 'Các Giá phổ biến',
    'shelves_new' => 'Các Giá mới',
    'shelves_new_action' => 'Giá mới',
    'shelves_popular_empty' => 'Các giá phổ biến sẽ xuất hiện ở đây.',
    'shelves_new_empty' => 'Các Giá được tạo gần đây sẽ xuất hiện ở đây.',
    'shelves_save' => 'Lưu Giá',
    'shelves_books' => 'Sách trên Giá này',
    'shelves_add_books' => 'Thêm sách vào Giá này',
    'shelves_drag_books' => 'Drag books below to add them to this shelf',
    'shelves_empty_contents' => 'Giá này không có sách nào',
    'shelves_edit_and_assign' => 'Chỉnh sửa kệ để gán sách',
    'shelves_edit_named' => 'Edit Shelf :name',
    'shelves_edit' => 'Edit Shelf',
    'shelves_delete' => 'Delete Shelf',
    'shelves_delete_named' => 'Delete Shelf :name',
    'shelves_delete_explain' => "This will delete the shelf with the name ':name'. Contained books will not be deleted.",
    'shelves_delete_confirmation' => 'Are you sure you want to delete this shelf?',
    'shelves_permissions' => 'Shelf Permissions',
    'shelves_permissions_updated' => 'Shelf Permissions Updated',
    'shelves_permissions_active' => 'Shelf Permissions Active',
    'shelves_permissions_cascade_warning' => 'Permissions on shelves do not automatically cascade to contained books. This is because a book can exist on multiple shelves. Permissions can however be copied down to child books using the option found below.',
    'shelves_copy_permissions_to_books' => 'Sao chép các quyền cho sách',
    'shelves_copy_permissions' => 'Sao chép các quyền',
    'shelves_copy_permissions_explain' => 'This will apply the current permission settings of this shelf to all books contained within. Before activating, ensure any changes to the permissions of this shelf have been saved.',
    'shelves_copy_permission_success' => 'Shelf permissions copied to :count books',

    // Books
    'book' => 'Sách',
    'books' => 'Tất cả sách',
    'x_books' => ':count Sách|:count Tất cả sách',
    'books_empty' => 'Không có cuốn sách nào được tạo',
    'books_popular' => 'Những cuốn sách phổ biến',
    'books_recent' => 'Những cuốn sách gần đây',
    'books_new' => 'Những cuốn sách mới',
    'books_new_action' => 'Sách mới',
    'books_popular_empty' => 'Những cuốn sách phổ biến nhất sẽ xuất hiện ở đây.',
    'books_new_empty' => 'Những cuốn sách tạo gần đây sẽ được xuất hiện ở đây.',
    'books_create' => 'Tạo cuốn sách mới',
    'books_delete' => 'Xóa sách',
    'books_delete_named' => 'Xóa sách :bookName',
    'books_delete_explain' => 'Điều này sẽ xóa cuốn sách với tên \':bookName\'. Tất cả các trang và các chương sẽ bị xóa.',
    'books_delete_confirmation' => 'Bạn có chắc chắn muốn xóa cuốn sách này?',
    'books_edit' => 'Sửa sách',
    'books_edit_named' => 'Sửa sách :bookName',
    'books_form_book_name' => 'Tên sách',
    'books_save' => 'Lưu sách',
    'books_permissions' => 'Các quyền của cuốn sách',
    'books_permissions_updated' => 'Các quyền của cuốn sách đã được cập nhật',
    'books_empty_contents' => 'Không có trang hay chương nào được tạo cho cuốn sách này.',
    'books_empty_create_page' => 'Tao một trang mới',
    'books_empty_sort_current_book' => 'Sắp xếp cuốn sách này',
    'books_empty_add_chapter' => 'Thêm một chương mới',
    'books_permissions_active' => 'Đang bật các quyền hạn từ Sách',
    'books_search_this' => 'Tìm cuốn sách này',
    'books_navigation' => 'Điều hướng cuốn sách',
    'books_sort' => 'Sắp xếp nội dung cuốn sách',
    'books_sort_named' => 'Sắp xếp sách :bookName',
    'books_sort_name' => 'Sắp xếp theo tên',
    'books_sort_created' => 'Sắp xếp theo ngày tạo',
    'books_sort_updated' => 'Sắp xếp theo ngày cập nhật',
    'books_sort_chapters_first' => 'Các Chương đầu',
    'books_sort_chapters_last' => 'Các Chương cuối',
    'books_sort_show_other' => 'Hiển thị các Sách khác',
    'books_sort_save' => 'Lưu thứ tự mới',
    'books_copy' => 'Copy Book',
    'books_copy_success' => 'Book successfully copied',

    // Chapters
    'chapter' => 'Chương',
    'chapters' => 'Các chương',
    'x_chapters' => ':count Chương|:count Chương',
    'chapters_popular' => 'Các Chương phổ biến',
    'chapters_new' => 'Chương mới',
    'chapters_create' => 'Tạo Chương mới',
    'chapters_delete' => 'Xóa Chương',
    'chapters_delete_named' => 'Xóa Chương :chapterName',
    'chapters_delete_explain' => 'Hành động này sẽ xoá chương \':chapterName\'. Tất cả các trang trong chương này cũng sẽ bị xoá.',
    'chapters_delete_confirm' => 'Bạn có chắc chắn muốn xóa chương này?',
    'chapters_edit' => 'Sửa Chương',
    'chapters_edit_named' => 'Sửa chương :chapterName',
    'chapters_save' => 'Lưu Chương',
    'chapters_move' => 'Di chuyển Chương',
    'chapters_move_named' => 'Di chuyển Chương :chapterName',
    'chapter_move_success' => 'Chương được di chuyển đến :bookName',
    'chapters_copy' => 'Copy Chapter',
    'chapters_copy_success' => 'Chapter successfully copied',
    'chapters_permissions' => 'Quyền hạn Chương',
    'chapters_empty' => 'Không có trang nào hiện có trong chương này.',
    'chapters_permissions_active' => 'Đang bật các quyền hạn từ Chương',
    'chapters_permissions_success' => 'Quyền hạn Chương được cập nhật',
    'chapters_search_this' => 'Tìm kiếm trong Chương này',
    'chapter_sort_book' => 'Sort Book',

    // Pages
    'page' => 'Trang',
    'pages' => 'Các trang',
    'x_pages' => ':count Trang|:count Trang',
    'pages_popular' => 'Các Trang phổ biến',
    'pages_new' => 'Trang Mới',
    'pages_attachments' => 'Các đính kèm',
    'pages_navigation' => 'Điều hướng Trang',
    'pages_delete' => 'Xóa Trang',
    'pages_delete_named' => 'Xóa Trang :pageName',
    'pages_delete_draft_named' => 'Xóa Trang Nháp :pageName',
    'pages_delete_draft' => 'Xóa Trang Nháp',
    'pages_delete_success' => 'Đã xóa Trang',
    'pages_delete_draft_success' => 'Đã xóa trang Nháp',
    'pages_delete_confirm' => 'Bạn có chắc chắn muốn xóa trang này?',
    'pages_delete_draft_confirm' => 'Bạn có chắc chắn muốn xóa trang nháp này?',
    'pages_editing_named' => 'Đang chỉnh sửa Trang :pageName',
    'pages_edit_draft_options' => 'Tùy chọn bản nháp',
    'pages_edit_save_draft' => 'Lưu Nháp',
    'pages_edit_draft' => 'Sửa trang nháp',
    'pages_editing_draft' => 'Đang chỉnh sửa Nháp',
    'pages_editing_page' => 'Đang chỉnh sửa Trang',
    'pages_edit_draft_save_at' => 'Bản nháp đã lưu lúc ',
    'pages_edit_delete_draft' => 'Xóa Bản nháp',
    'pages_edit_discard_draft' => 'Hủy bỏ Bản nháp',
    'pages_edit_switch_to_markdown' => 'Switch to Markdown Editor',
    'pages_edit_switch_to_markdown_clean' => '(Clean Content)',
    'pages_edit_switch_to_markdown_stable' => '(Stable Content)',
    'pages_edit_switch_to_wysiwyg' => 'Switch to WYSIWYG Editor',
    'pages_edit_set_changelog' => 'Đặt Changelog',
    'pages_edit_enter_changelog_desc' => 'Viết mô tả ngắn gọn cho các thay đổi mà bạn tạo',
    'pages_edit_enter_changelog' => 'Viết Changelog',
    'pages_editor_switch_title' => 'Switch Editor',
    'pages_editor_switch_are_you_sure' => 'Are you sure you want to change the editor for this page?',
    'pages_editor_switch_consider_following' => 'Consider the following when changing editors:',
    'pages_editor_switch_consideration_a' => 'Once saved, the new editor option will be used by any future editors, including those that may not be able to change editor type themselves.',
    'pages_editor_switch_consideration_b' => 'This can potentially lead to a loss of detail and syntax in certain circumstances.',
    'pages_editor_switch_consideration_c' => 'Tag or changelog changes, made since last save, won\'t persist across this change.',
    'pages_save' => 'Lưu Trang',
    'pages_title' => 'Tiêu đề Trang',
    'pages_name' => 'Tên Trang',
    'pages_md_editor' => 'Trình chỉnh sửa',
    'pages_md_preview' => 'Xem trước',
    'pages_md_insert_image' => 'Chèn hình ảnh',
    'pages_md_insert_link' => 'Chèn liên kết thực thể',
    'pages_md_insert_drawing' => 'Chèn bản vẽ',
    'pages_not_in_chapter' => 'Trang không nằm trong một chương',
    'pages_move' => 'Di chuyển Trang',
    'pages_move_success' => 'Trang đã chuyển tới ":parentName"',
    'pages_copy' => 'Sao chép Trang',
    'pages_copy_desination' => 'Sao lưu đến',
    'pages_copy_success' => 'Trang được sao chép thành công',
    'pages_permissions' => 'Quyền hạn Trang',
    'pages_permissions_success' => 'Quyền hạn Trang được cập nhật',
    'pages_revision' => 'Phiên bản',
    'pages_revisions' => 'Phiên bản Trang',
    'pages_revisions_named' => 'Phiên bản Trang cho :pageName',
    'pages_revision_named' => 'Phiên bản Trang cho :pageName',
    'pages_revision_restored_from' => 'Khôi phục từ #:id; :summary',
    'pages_revisions_created_by' => 'Tạo bởi',
    'pages_revisions_date' => 'Ngày của Phiên bản',
    'pages_revisions_number' => '#',
    'pages_revisions_numbered' => 'Phiên bản #:id',
    'pages_revisions_numbered_changes' => 'Các thay đổi của phiên bản #:id',
    'pages_revisions_editor' => 'Editor Type',
    'pages_revisions_changelog' => 'Nhật ký thay đổi',
    'pages_revisions_changes' => 'Các thay đổi',
    'pages_revisions_current' => 'Phiên bản hiện tại',
    'pages_revisions_preview' => 'Xem trước',
    'pages_revisions_restore' => 'Khôi phục',
    'pages_revisions_none' => 'Trang này không có phiên bản nào',
    'pages_copy_link' => 'Sao chép Liên kết',
    'pages_edit_content_link' => 'Soạn thảo Nội dung',
    'pages_permissions_active' => 'Đang bật các quyền hạn từ Trang',
    'pages_initial_revision' => 'Đăng bài mở đầu',
    'pages_references_update_revision' => 'System auto-update of internal links',
    'pages_initial_name' => 'Trang mới',
    'pages_editing_draft_notification' => 'Bạn hiện đang chỉnh sửa một bản nháp được lưu cách đây :timeDiff.',
    'pages_draft_edited_notification' => 'Trang này đã được cập nhật từ lúc đó. Bạn nên loại bỏ bản nháp này.',
    'pages_draft_page_changed_since_creation' => 'This page has been updated since this draft was created. It is recommended that you discard this draft or take care not to overwrite any page changes.',
    'pages_draft_edit_active' => [
        'start_a' => ':count người dùng đang bắt đầu chỉnh sửa trang này',
        'start_b' => ':userName đang bắt đầu chỉnh sửa trang này',
        'time_a' => 'kể từ khi thang được cập nhật lần cuối',
        'time_b' => 'trong :minCount phút cuối',
        'message' => ':start :time. Hãy cẩn thận đừng ghi đè vào các bản cập nhật của nhau!',
    ],
    'pages_draft_discarded' => 'Bản nháp đã được loại bỏ, Người sửa đã cập nhật trang với nội dung hiện tại',
    'pages_specific' => 'Trang cụ thể',
    'pages_is_template' => 'Biểu mẫu trang',

    // Editor Sidebar
    'page_tags' => 'Các Thẻ Trang',
    'chapter_tags' => 'Các Thẻ Chương',
    'book_tags' => 'Các Thẻ Sách',
    'shelf_tags' => 'Các Thẻ Kệ',
    'tag' => 'Nhãn',
    'tags' =>  'Các Thẻ',
    'tag_name' =>  'Tên Nhãn',
    'tag_value' => 'Giá trị Thẻ (Tùy chọn)',
    'tags_explain' => "Thêm vài thẻ để phân loại nội dung của bạn tốt hơn. \n Bạn có thể đặt giá trị cho thẻ để quản lí kĩ càng hơn.",
    'tags_add' => 'Thêm thẻ khác',
    'tags_remove' => 'Xóa thẻ này',
    'tags_usages' => 'Total tag usages',
    'tags_assigned_pages' => 'Assigned to Pages',
    'tags_assigned_chapters' => 'Assigned to Chapters',
    'tags_assigned_books' => 'Assigned to Books',
    'tags_assigned_shelves' => 'Assigned to Shelves',
    'tags_x_unique_values' => ':count unique values',
    'tags_all_values' => 'All values',
    'tags_view_tags' => 'View Tags',
    'tags_view_existing_tags' => 'View existing tags',
    'tags_list_empty_hint' => 'Tags can be assigned via the page editor sidebar or while editing the details of a book, chapter or shelf.',
    'attachments' => 'Các Đính kèm',
    'attachments_explain' => 'Cập nhật một số tập tin và đính một số liên kết để hiển thị trên trang của bạn. Chúng được hiện trong sidebar của trang.',
    'attachments_explain_instant_save' => 'Các thay đổi ở đây sẽ được lưu ngay lập tức.',
    'attachments_items' => 'Đính kèm các Mục',
    'attachments_upload' => 'Tải lên Tập tin',
    'attachments_link' => 'Đính kèm Liên kết',
    'attachments_set_link' => 'Đặt Liên kết',
    'attachments_delete' => 'Bạn có chắc chắn muốn xóa tập tin đính kèm này?',
    'attachments_dropzone' => 'Thả các tập tin hoặc bấm vào đây để đính kèm một tập tin',
    'attachments_no_files' => 'Không có tập tin nào được tải lên',
    'attachments_explain_link' => 'Bạn có thể đính kèm một liên kết nếu bạn lựa chọn không tải lên tập tin. Liên kết này có thể trỏ đến một trang khác hoặc một tập tin ở trên mạng (đám mây).',
    'attachments_link_name' => 'Tên Liên kết',
    'attachment_link' => 'Liên kết đính kèm',
    'attachments_link_url' => 'Liên kết đến tập tin',
    'attachments_link_url_hint' => 'URL của trang hoặc tập tin',
    'attach' => 'Đính kèm',
    'attachments_insert_link' => 'Thêm Đường dẫn Tập tin đính kèm vào Trang',
    'attachments_edit_file' => 'Sửa tập tin',
    'attachments_edit_file_name' => 'Tên tệp tin',
    'attachments_edit_drop_upload' => 'Thả tập tin hoặc bấm vào đây để tải lên và ghi đè',
    'attachments_order_updated' => 'Đã cập nhật thứ tự đính kèm',
    'attachments_updated_success' => 'Đã cập nhật chi tiết đính kèm',
    'attachments_deleted' => 'Đính kèm đã được xóa',
    'attachments_file_uploaded' => 'Tập tin tải lên thành công',
    'attachments_file_updated' => 'Tập tin cập nhật thành công',
    'attachments_link_attached' => 'Liên kết được đính kèm đến trang thành công',
    'templates' => 'Các Mẫu',
    'templates_set_as_template' => 'Trang là một mẫu',
    'templates_explain_set_as_template' => 'Bạn có thể đặt trang này làm mẫu, nội dung của nó sẽ được sử dụng lại khi tạo các trang mới. Người dùng khác có thể sử dụng mẫu này nếu học có quyền hạn xem trang này.',
    'templates_replace_content' => 'Thay thế nội dung trang',
    'templates_append_content' => 'Viết vào nội dung trang',
    'templates_prepend_content' => 'Thêm vào đầu nội dung trang',

    // Profile View
    'profile_user_for_x' => 'Đã là người dùng trong :time',
    'profile_created_content' => 'Đã tạo nội dung',
    'profile_not_created_pages' => ':userName chưa tạo bất kỳ trang nào',
    'profile_not_created_chapters' => ':userName chưa tạo bất kì chương nào',
    'profile_not_created_books' => ':userName chưa tạo bất cứ sách nào',
    'profile_not_created_shelves' => ':userName chưa tạo bất kỳ giá sách nào',

    // Comments
    'comment' => 'Bình luận',
    'comments' => 'Các bình luận',
    'comment_add' => 'Thêm bình luận',
    'comment_placeholder' => 'Đăng bình luận tại đây',
    'comment_count' => '{0} Không có bình luận|{1} 1 Bình luận|[2,*] :count Bình luận',
    'comment_save' => 'Lưu bình luận',
    'comment_saving' => 'Đang lưu bình luận...',
    'comment_deleting' => 'Đang xóa bình luận...',
    'comment_new' => 'Bình luận mới',
    'comment_created' => 'đã bình luận :createDiff',
    'comment_updated' => 'Đã cập nhật :updateDiff bởi :username',
    'comment_deleted_success' => 'Bình luận đã bị xóa',
    'comment_created_success' => 'Đã thêm bình luận',
    'comment_updated_success' => 'Bình luận đã được cập nhật',
    'comment_delete_confirm' => 'Bạn có chắc bạn muốn xóa bình luận này?',
    'comment_in_reply_to' => 'Trả lời cho :commentId',

    // Revision
    'revision_delete_confirm' => 'Bạn có chắc bạn muốn xóa phiên bản này?',
    'revision_restore_confirm' => 'Bạn có chắc bạn muốn khôi phục phiên bản này? Nội dung trang hiện tại sẽ được thay thế.',
    'revision_delete_success' => 'Phiên bản đã được xóa',
    'revision_cannot_delete_latest' => 'Không thể xóa phiên bản mới nhất.',

    // Copy view
    'copy_consider' => 'Please consider the below when copying content.',
    'copy_consider_permissions' => 'Custom permission settings will not be copied.',
    'copy_consider_owner' => 'You will become the owner of all copied content.',
    'copy_consider_images' => 'Page image files will not be duplicated & the original images will retain their relation to the page they were originally uploaded to.',
    'copy_consider_attachments' => 'Page attachments will not be copied.',
    'copy_consider_access' => 'A change of location, owner or permissions may result in this content being accessible to those previously without access.',

    // Conversions
    'convert_to_shelf' => 'Convert to Shelf',
    'convert_to_shelf_contents_desc' => 'You can convert this book to a new shelf with the same contents. Chapters contained within this book will be converted to new books. If this book contains any pages, that are not in a chapter, this book will be renamed and contain such pages, and this book will become part of the new shelf.',
    'convert_to_shelf_permissions_desc' => 'Any permissions set on this book will be copied to the new shelf and to all new child books that don\'t have their own permissions enforced. Note that permissions on shelves do not auto-cascade to content within, as they do for books.',
    'convert_book' => 'Convert Book',
    'convert_book_confirm' => 'Are you sure you want to convert this book?',
    'convert_undo_warning' => 'This cannot be as easily undone.',
    'convert_to_book' => 'Convert to Book',
    'convert_to_book_desc' => 'You can convert this chapter to a new book with the same contents. Any permissions set on this chapter will be copied to the new book but any inherited permissions, from the parent book, will not be copied which could lead to a change of access control.',
    'convert_chapter' => 'Convert Chapter',
    'convert_chapter_confirm' => 'Are you sure you want to convert this chapter?',

    // References
    'references' => 'References',
    'references_none' => 'There are no tracked references to this item.',
    'references_to_desc' => 'Shown below are all the known pages in the system that link to this item.',
];


text:
<?php

namespace Symfony\Bridge\Twig\Form;

use Symfony\Component\Form\FormRendererEngineInterface;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 *
 * @deprecated since version 3.2, to be removed in 4.0.
 */
interface TwigRendererEngineInterface extends FormRendererEngineInterface
{
    /**
     * Sets Twig's environment.
     *
     * @param \Twig_Environment $environment
     */
    public function setEnvironment(\Twig_Environment $environment);
}


text:
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file was generated by Djinni from my_flags.djinni

package djinni.it;

/** flag comment */
public enum MyFlags {
    /** flag option comment */
    FLAG1,
    FLAG2,
    FLAG3,
    ;
}


text:
<?php

namespace app\modules\setting\models;

/**
 * This is the ActiveQuery class for [[DbCrTrans]].
 *
 * @see DbCrTrans
 */
class DbCrTransQuery extends \yii\db\ActiveQuery
{
    /*public function active()
    {
        $this->andWhere('[[status]]=1');
        return $this;
    }*/

    /**
     * @inheritdoc
     * @return DbCrTrans[]|array
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

    /**
     * @inheritdoc
     * @return DbCrTrans|array|null
     */
    public function one($db = null)
    {
        return parent::one($db);
    }
}


text:
#include BOSS_WEBRTC_U_common_audio__signal_processing__include__signal_processing_library_h //original-code:"common_audio/signal_processing/include/signal_processing_library.h"

/* C version of WebRtcSpl_CrossCorrelation() for generic platforms. */
void WebRtcSpl_CrossCorrelationC(int32_t* cross_correlation,
                                 const int16_t* seq1,
                                 const int16_t* seq2,
                                 size_t dim_seq,
                                 size_t dim_cross_correlation,
                                 int right_shifts,
                                 int step_seq2) {
  size_t i = 0, j = 0;

  for (i = 0; i < dim_cross_correlation; i++) {
    int32_t corr = 0;
    for (j = 0; j < dim_seq; j++)
      corr += (seq1[j] * seq2[j]) >> right_shifts;
    seq2 += step_seq2;
    *cross_correlation++ = corr;
  }
}


text:
package rodrigorar.utils;

public class SystemUtils {

    public static String getDefaultLinuxDirectory() {
        String homeDirectory = System.getProperty("user.home");
        StringBuilder builder = new StringBuilder(homeDirectory);
        builder.append("/");
        builder.append(".tasks");
        return builder.toString();
    }

    public static String getDefaultLinuxData() {
        StringBuilder builder = new StringBuilder(getDefaultLinuxDirectory());
        builder.append("/");
        builder.append("tasks.xml");
        return builder.toString();
    }

    public static String getDefaultLinuxSettings() {
        StringBuilder builder = new StringBuilder(getDefaultLinuxDirectory());
        builder.append("/");
        builder.append("settings.xml");
        return builder.toString();
    }

    public static String getDefaultPriorityDirectory() {
        StringBuilder builder = new StringBuilder(getDefaultLinuxDirectory());
        builder.append("/");
        builder.append("priorities.xml");
        return builder.toString();
    }

    public static String getDefaultLanguage() {
    	return "EN";
    }
}


text:
package googleapi

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"reflect"
	"strings"
	"testing"
)

type SetOpaqueTest struct {
	in             *url.URL
	wantRequestURI string
}

var setOpaqueTests = []SetOpaqueTest{
	// no path
	{
		&url.URL{
			Scheme: "http",
			Host:   "www.golang.org",
		},
		"http://www.golang.org",
	},
	// path
	{
		&url.URL{
			Scheme: "http",
			Host:   "www.golang.org",
			Path:   "/",
		},
		"http://www.golang.org/",
	},
	// file with hex escaping
	{
		&url.URL{
			Scheme: "https",
			Host:   "www.golang.org",
			Path:   "/file%20one&two",
		},
		"https://www.golang.org/file%20one&two",
	},
	// query
	{
		&url.URL{
			Scheme:   "http",
			Host:     "www.golang.org",
			Path:     "/",
			RawQuery: "q=go+language",
		},
		"http://www.golang.org/?q=go+language",
	},
	// file with hex escaping in path plus query
	{
		&url.URL{
			Scheme:   "https",
			Host:     "www.golang.org",
			Path:     "/file%20one&two",
			RawQuery: "q=go+language",
		},
		"https://www.golang.org/file%20one&two?q=go+language",
	},
	// query with hex escaping
	{
		&url.URL{
			Scheme:   "http",
			Host:     "www.golang.org",
			Path:     "/",
			RawQuery: "q=go%20language",
		},
		"http://www.golang.org/?q=go%20language",
	},
}

// prefixTmpl is a template for the expected prefix of the output of writing
// an HTTP request.
const prefixTmpl = "GET %v HTTP/1.1\r\nHost: %v\r\n"

func TestSetOpaque(t *testing.T) {
	for _, test := range setOpaqueTests {
		u := *test.in
		SetOpaque(&u)

		w := &bytes.Buffer{}
		r := &http.Request{URL: &u}
		if err := r.Write(w); err != nil {
			t.Errorf("write request: %v", err)
			continue
		}

		prefix := fmt.Sprintf(prefixTmpl, test.wantRequestURI, test.in.Host)
		if got := string(w.Bytes()); !strings.HasPrefix(got, prefix) {
			t.Errorf("got %q expected prefix %q", got, prefix)
		}
	}
}

type ExpandTest struct {
	in         string
	expansions map[string]string
	want       string
}

var expandTests = []ExpandTest{
	// no expansions
	{
		"http://www.golang.org/",
		map[string]string{},
		"http://www.golang.org/",
	},
	// one expansion, no escaping
	{
		"http://www.golang.org/{bucket}/delete",
		map[string]string{
			"bucket": "red",
		},
		"http://www.golang.org/red/delete",
	},
	// one expansion, with hex escapes
	{
		"http://www.golang.org/{bucket}/delete",
		map[string]string{
			"bucket": "red/blue",
		},
		"http://www.golang.org/red%2Fblue/delete",
	},
	// one expansion, with space
	{
		"http://www.golang.org/{bucket}/delete",
		map[string]string{
			"bucket": "red or blue",
		},
		"http://www.golang.org/red%20or%20blue/delete",
	},
	// expansion not found
	{
		"http://www.golang.org/{object}/delete",
		map[string]string{
			"bucket": "red or blue",
		},
		"http://www.golang.org/{object}/delete",
	},
	// multiple expansions
	{
		"http://www.golang.org/{one}/{two}/{three}/get",
		map[string]string{
			"one":   "ONE",
			"two":   "TWO",
			"three": "THREE",
		},
		"http://www.golang.org/ONE/TWO/THREE/get",
	},
	// utf-8 characters
	{
		"http://www.golang.org/{bucket}/get",
		map[string]string{
			"bucket": "£100",
		},
		"http://www.golang.org/%C2%A3100/get",
	},
	// punctuations
	{
		"http://www.golang.org/{bucket}/get",
		map[string]string{
			"bucket": `/\@:,.`,
		},
		"http://www.golang.org/%2F%5C%40%3A%2C./get",
	},
	// mis-matched brackets
	{
		"http://www.golang.org/{bucket/get",
		map[string]string{
			"bucket": "red",
		},
		"http://www.golang.org/{bucket/get",
	},
}

func TestExpand(t *testing.T) {
	for i, test := range expandTests {
		u := url.URL{
			Path: test.in,
		}
		Expand(&u, test.expansions)
		got := u.Path
		if got != test.want {
			t.Errorf("got %q expected %q in test %d", got, test.want, i+1)
		}
	}
}

type CheckResponseTest struct {
	in       *http.Response
	bodyText string
	want     error
	errText  string
}

var checkResponseTests = []CheckResponseTest{
	{
		&http.Response{
			StatusCode: http.StatusOK,
		},
		"",
		nil,
		"",
	},
	{
		&http.Response{
			StatusCode: http.StatusInternalServerError,
		},
		`{"error":{}}`,
		&Error{
			Code: http.StatusInternalServerError,
			Body: `{"error":{}}`,
		},
		`googleapi: got HTTP response code 500 with body: {"error":{}}`,
	},
	{
		&http.Response{
			StatusCode: http.StatusNotFound,
		},
		`{"error":{"message":"Error message for StatusNotFound."}}`,
		&Error{
			Code:    http.StatusNotFound,
			Message: "Error message for StatusNotFound.",
			Body:    `{"error":{"message":"Error message for StatusNotFound."}}`,
		},
		"googleapi: Error 404: Error message for StatusNotFound.",
	},
	{
		&http.Response{
			StatusCode: http.StatusBadRequest,
		},
		`{"error":"invalid_token","error_description":"Invalid Value"}`,
		&Error{
			Code: http.StatusBadRequest,
			Body: `{"error":"invalid_token","error_description":"Invalid Value"}`,
		},
		`googleapi: got HTTP response code 400 with body: {"error":"invalid_token","error_description":"Invalid Value"}`,
	},
	{
		&http.Response{
			StatusCode: http.StatusBadRequest,
		},
		`{"error":{"errors":[{"domain":"usageLimits","reason":"keyInvalid","message":"Bad Request"}],"code":400,"message":"Bad Request"}}`,
		&Error{
			Code: http.StatusBadRequest,
			Errors: []ErrorItem{
				{
					Reason:  "keyInvalid",
					Message: "Bad Request",
				},
			},
			Body:    `{"error":{"errors":[{"domain":"usageLimits","reason":"keyInvalid","message":"Bad Request"}],"code":400,"message":"Bad Request"}}`,
			Message: "Bad Request",
		},
		"googleapi: Error 400: Bad Request, keyInvalid",
	},
}

func TestCheckResponse(t *testing.T) {
	for _, test := range checkResponseTests {
		res := test.in
		if test.bodyText != "" {
			res.Body = ioutil.NopCloser(strings.NewReader(test.bodyText))
		}
		g := CheckResponse(res)
		if !reflect.DeepEqual(g, test.want) {
			t.Errorf("CheckResponse: got %v, want %v", g, test.want)
			gotJson, err := json.Marshal(g)
			if err != nil {
				t.Error(err)
			}
			wantJson, err := json.Marshal(test.want)
			if err != nil {
				t.Error(err)
			}
			t.Errorf("json(got):  %q\njson(want): %q", string(gotJson), string(wantJson))
		}
		if g != nil && g.Error() != test.errText {
			t.Errorf("CheckResponse: unexpected error message.\nGot:  %q\nwant: %q", g, test.errText)
		}
	}
}

type VariantPoint struct {
	Type        string
	Coordinates []float64
}

type VariantTest struct {
	in     map[string]interface{}
	result bool
	want   VariantPoint
}

var coords = []interface{}{1.0, 2.0}

var variantTests = []VariantTest{
	{
		in: map[string]interface{}{
			"type":        "Point",
			"coordinates": coords,
		},
		result: true,
		want: VariantPoint{
			Type:        "Point",
			Coordinates: []float64{1.0, 2.0},
		},
	},
	{
		in: map[string]interface{}{
			"type":  "Point",
			"bogus": coords,
		},
		result: true,
		want: VariantPoint{
			Type: "Point",
		},
	},
}

func TestVariantType(t *testing.T) {
	for _, test := range variantTests {
		if g := VariantType(test.in); g != test.want.Type {
			t.Errorf("VariantType(%v): got %v, want %v", test.in, g, test.want.Type)
		}
	}
}

func TestConvertVariant(t *testing.T) {
	for _, test := range variantTests {
		g := VariantPoint{}
		r := ConvertVariant(test.in, &g)
		if r != test.result {
			t.Errorf("ConvertVariant(%v): got %v, want %v", test.in, r, test.result)
		}
		if !reflect.DeepEqual(g, test.want) {
			t.Errorf("ConvertVariant(%v): got %v, want %v", test.in, g, test.want)
		}
	}
}


text:
import 'rxjs/add/operator/map';
import {Injectable} from '@angular/core';
import {Http, URLSearchParams} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Cube} from '../models/cube';
import {AggregateRequest} from '../models/aggregate/aggregateRequest';
import {Dimension} from '../models/dimension';
import 'rxjs/add/operator/mergeMap';
import { environment } from '../../environments/environment';
import {FactRequest} from '../models/fact/factRequest';

@Injectable()
export class ApiCubesService {
  private API_PATH: string = environment.apiUrl + '/api/' + environment.versionSuffix + '/cubes';
  private API_PACKAGES_PATH: string = environment.apiUrl + '/search/package';
  private API_PACKAGE_PATH: string = environment.apiUrl + '/api/' + environment.versionSuffix + '/info';
  private _membersCache: Map<string, Map<string, Object>> = new Map<string, Map<string, Object>>();

  constructor(private http: Http) {
  }

  searchCubes(queryTitle: string, size: number, from: number): Observable<any[]> {

    const params = new URLSearchParams();
    params.set('q', `"${queryTitle}"`);
    params.set('size', size.toString());
    params.set('from', from.toString());
    return this.http.get(`${this.API_PACKAGES_PATH}`, {search: params})
      .map(res => res.json())
      ;
  }

  retrieveCube(name: string): Observable<Cube> {
    return this.http.get(`${this.API_PATH}/${name}/model`)
      .map(res => res.json()).flatMap((cube) => {
        const fullCube = new Cube().deserialize(cube);
        const observables = [];

        fullCube.model.dimensions.forEach((dimension) => {
          observables.push(this.loadDimensionMembers(cube, dimension));
        });

        observables.push(this.retrievePackage(cube));

        return Observable.forkJoin(observables, function () {
          return cube;
        });
      });
  }

  retrieveCubeLight(name: string): Observable<Cube> {
    return this.http.get(`${this.API_PATH}/${name}/model`)
      .map(res => res.json()).flatMap((cube) => {
        const observables = [];
         observables.push(this.retrievePackage(cube));

        return Observable.forkJoin(observables, function () {
          return cube;
        });
      });
  }

  retrievePackage(cube: Cube): Observable<Cube> {
    return this.http.get(`${this.API_PACKAGE_PATH}/${cube.name}/package`)
      .map(res => {

        const pckg = res.json();

        cube.pckg = pckg;

        return pckg;

      });
  }

  factToUri(element: FactRequest) {
    const orderString = element.sorts.map(s => s.column.ref + ':' + s.direction.key).join(',');
    const cutString = element.cuts.map(c => c.column.ref + c.transitivity.key + ':' + c.value).join('|');
    const fieldsString = element.fields.map(c => c.ref ).join(',');

    const params = new URLSearchParams();
    if (element.cuts.length > 0) {
      params.set('cut', cutString);
    }
    if (element.sorts.length > 0) {
      params.set('order', orderString);
    }

    if (element.fields.length > 0) {
      params.set('fields', fieldsString);
    }

    if (element.page) {
      params.set('page', element.page.toString());
    }
    if (element.pageSize) {
      params.set('pagesize', element.pageSize.toString());
    }
    return `${this.API_PATH}/${element.cube.name}/facts?${params.toString()}`;

  }

  fact(element: any): Observable<any> {
    let url = '';
    if (element instanceof FactRequest) {
      url = this.factToUri(element);
    } else {
      url = element;
    }

    return this.http.get(url)
      .map(res => {
        return res.json();
      })
      ;
  }

  aggregateToURI(aggregateRequest: AggregateRequest) {
    const drilldownString = aggregateRequest.drilldowns.map(d => d.column.ref).join('|');
    const orderString = aggregateRequest.sorts.map(s => s.column.ref + ':' + s.direction.key).join(',');
    const cutString = aggregateRequest.cuts.map(c => c.column.ref + c.transitivity.key + ':' + c.value).join('|');
    const aggregatesString =  aggregateRequest.aggregates.map(a => a.column.ref).join('|');

    const params = new URLSearchParams();
    if (aggregateRequest.drilldowns.length > 0) {
      params.set('drilldown', drilldownString);
    }
    if (aggregateRequest.cuts.length > 0) {
      params.set('cut', cutString);
    }
    if (aggregateRequest.sorts.length > 0) {
      params.set('order', orderString);
    }
    if (aggregateRequest.aggregates.length > 0) {
      params.set('aggregates', aggregatesString);
    }
    if (aggregateRequest.page) {
      params.set('page', aggregateRequest.page.toString());
    }
    if (aggregateRequest.pageSize) {
      params.set('pagesize', aggregateRequest.pageSize.toString());
    }
    return `${this.API_PATH}/${aggregateRequest.cube.name}/aggregate?${params.toString()}`;
  }

  aggregate(element: any): Observable<Cube> {
    let url = '';
    if (element instanceof AggregateRequest) {
      url = this.aggregateToURI(element);
    } else {
      url = element;
    }

    return this.http.get(url)
      .map(res => {
        return res.json();
      })
      ;
  }

  members(cube: Cube, dimension: Dimension): Observable <Map<string, Object>> {
    ///
    // http://next.openspending.org/api/3/cubes/1c95cb52b1d32ee8537fafd2fe1a945d%3Adouala2015/members/economic_classification_2
    const that = this;
    if (this._membersCache && this._membersCache.has(`${cube.name}.${dimension.ref}`)) {
      return Observable.create(function (observer) {
        observer.next(that._membersCache.get(`${cube.name}.${dimension.ref}`));
      }) ;

    }

    return this.loadDimensionMembers(cube, dimension);

  }

  loadDimensionMembers(cube: Cube, dimension: Dimension) {
    return this.http.get(`${this.API_PATH}/${cube.name}/members/${dimension.ref}`)
      .map(res => {

          const data = res.json().data;

          const members = new Map<string, Object>();

          for (const key in data) {
            if (data.hasOwnProperty(key)) {
              members.set(key, data[key]);
            }
          }

          this._membersCache.set(`${cube.name}.${dimension.ref}`, members);

          return members;

        }
      )
      ;
  }

}


text:
/**
 *
 * @param {(...*) => any)} fn
 * @param {number} ms
 * @returns {(...args: any[]) => void}
 */
export default function debounce(fn, ms) {
  let timeoutId;

  return function (...args) {
    /**
     * if an event happens before the setTimeout has expired.
     * we cancel the setTimeout and reset it, so effectively
     * what this is gonna do, it's to keep reseting the timer
     * as longs as events are ocurring before the timeout has
     * had chance to expire
     */
    clearTimeout(timeoutId);

    timeoutId = setTimeout(() => {
      fn(args);
    }, ms);
  };
}


text:
pot
===

a universal organization tool.
Pot is simple, fast and powerful.

- [Examples](#examples)
- [Commands](#commands)
- [Installation](#installation)

Examples
--------

### indexing images

display the 5 last modified files in sxiv and tag marked ones with
**cute** and **cats**:

```shell
ls -1t | head -5 | sxiv -iot | pot tag cute,cats
```

create a randomized rotation of wallpapers satisfying a given filter:

[potbg] _filter_

and advance on command:

[potbg]

### managing bookmarks

find all resources tagged **sed** that also have the tags
**programming** or **linux** contained in the database located in
bookmarks, select one and load the uri in surf:

```shell
pot --path ~/bookmarks filter "(programming;linux),sed" | dmenu -l 20 | xargs surf
```

Commands
--------

This is a general overview that should get you started. For deeper
understanding please read the manpage.

Arguments in square brackets are read from standard input if not given
on the command line.

`pot delete-tags [tags...]`

`pot filter <filter>`

`pot list-tags`

`pot reverse-search <resource>`

`pot tag some,tags [resource...]`

`pot untag maybe,other,tags [resource...]`

### Filters

Filters combine tags into sets of resources. The following operators
(sorted by descending precedence) can be used in filters:

```
() - parens ensure prioritized evaulation
, - commas intersect two sets
/ - slashes represent the difference of one set from another
; - semicolons unite two sets
```

Installation
------------

[Arch User Repository](https://aur.archlinux.org/packages/pot)

### Dependencies

- [Gambit-C][gambit]
- [musl-libc][musl] (default)

### Building

`make`

#### Variables

- `GSC:=gsc` Gambit-C compiler
- `CC:=musl-gcc` C compiler

### Installing

`make install`

By default, pot attempts to install to `/usr`. To change the
installation path, set make variables `DESTDIR` and `PREFIX` accordingly.

[potbg]: https://github.com/motersen/dotfiles/blob/master/potbg/bin/potbg
[gambit]: http://gambitscheme.org/wiki/index.php/Main_Page
[musl]: http://www.musl-libc.org/


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="android:textColor">@color/primaryBlack</item>
    </style>

    <style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowBackground">@drawable/layer_splash</item>
    </style>

    <style name="GoogleButton" parent="@style/Widget.AppCompat.Button.Colored">
        <item name="android:background">@drawable/btn_google_rounded</item>
        <item name="android:paddingStart">@dimen/normal_distance</item>
        <item name="android:paddingEnd">@dimen/normal_distance</item>
    </style>
</resources>


text:
import React, { Component } from 'react';
import {
  Redirect
} from 'react-router-dom';
import UserListItemContainer from './UserListItemContainer'
import { Loader } from 'semantic-ui-react';

class Conversations extends Component {
  constructor(props) {
    super(props)
    this.state = {
      conversations: [],
      loaded: false,
    }
    this.truncatedMessage = this.truncatedMessage.bind(this);
  }

  componentDidMount() {
    fetch('/conversations', {
      accept: 'application/json',
      headers: {
        'Authorization': localStorage.getItem('gnomad-auth-token')
      },
    }).then(data => data.json())
      .then(dataJson => {
        this.setState({
          conversations: dataJson,
          loaded: true,
        });
      });
  }

  truncatedMessage(message){
    if(message.length>100) {
      return (message.substr(0, 100) + '...');
    } else {
      return message;
    }
  }

  render() {
    // if (!this.props.loggedIn) {
    //   return (<Redirect to="/" />);
    // }
    if (this.state.loaded === true) {
      return (

Chat History

            {this.state.conversations.map((conversation) =>
              <UserListItemContainer key={conversation.id} user={conversation.other} snippet={this.truncatedMessage(conversation.last_message.body)} linkto={`/chats/${conversation.id}`} blocked={conversation.blocked} />
            )}

      );
    } else {
      return (

          <Loader />

      );
    }
  }
}

export default Conversations;


text:
/* @flow */

import {getPackageVersion, runInstall} from '../_helpers.js';

jasmine.DEFAULT_TIMEOUT_INTERVAL = 120000;

test.concurrent('install hoister should prioritise popular transitive dependencies', (): Promise<void> => {
  // a -> b -> b-2
  //        -> c
  //           -> b-2
  return runInstall({}, 'install-should-prioritise-popular-transitive', async (config) => {
    expect(await getPackageVersion(config, 'b')).toEqual('2.0.0');
    expect(await getPackageVersion(config, 'a/b')).toEqual('0.0.0');
  });
});


text:
import sinon from 'sinon';

import '../testHelper';
import { updateCourse, persistCourse } from '../../app/assets/javascripts/actions/course_actions.js';
describe('CourseActions', () => {
  beforeEach(() => {
    sinon.stub($, 'ajax').yieldsTo('success', { course: { title: 'Bar' } });
  });
  afterEach(() => {
    $.ajax.restore();
  });

  it('.updateCourse sets course data in the store', () => {
    const course = { title: 'Foo' };
    expect(reduxStore.getState().course.title).to.eq('');
    reduxStore.dispatch(updateCourse(course));
    const updatedCourse = reduxStore.getState().course;
    const persistedCourse = reduxStore.getState().persistedCourse;
    expect(updatedCourse.title).to.eq('Foo');
    expect(persistedCourse.title).not.to.eq('Foo');
  });

  it('.persistCourse pushes course data to server via ajax then updates with returned data', (done) => {
    const course = { title: 'Foo' };
    persistCourse(course)(reduxStore.dispatch, reduxStore.getState).then(() => {
      expect(reduxStore.getState().course.title).to.eq('Bar');
      expect(reduxStore.getState().persistedCourse.title).to.eq('Bar');
      done();
    });
  });
});


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

<TITLE>
SearchClient (ATG Java API)
</TITLE>

<META NAME="keywords" CONTENT="com.primus.ae.searchclient.SearchClient class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.primus.ae.searchclient

Class SearchClient

java.lang.Object
  com.primus.ae.searchclient.SearchClient

public class SearchClient
extends java.lang.Object

ATG Search client. Entrypoint for client searches.

Constructor Summary

SearchClient()

SearchClient(java.util.Properties p)

          The following properties must be specified:

Method Summary

 SearchSession
beginSession(SessionConfig sessionConfig)

          Begins the user search session, and retrieves user-specified option sets from the server.

 java.lang.String
doSearch(ClientRequest request,
         SearchSession searchSession)

 void
endSession(SearchSession searchSession)

          Ends the user's search session

 Results
extractResults(ClientRequest request,
               java.lang.String resultXml)

static void
main(java.lang.String[] args)

 Results
search(ClientRequest request,
       SearchSession searchSession)

          Submits a request to ES using the provided search session

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SearchClient

public SearchClient()

SearchClient

public SearchClient(java.util.Properties p)
             throws java.lang.Exception

The following properties must be specified:

 searchclient.appservertype=soap|jboss|weblogic|websphere

 searchclient.hostname=hostname of server

 searchclient.hostport=listening port of server, e.g., 1099 or 6060

Parameters:
p - appserver properties

Throws:

java.lang.Exception - if there is a propblem in connecting to the application server

Method Detail

beginSession

public SearchSession beginSession(SessionConfig sessionConfig)

Begins the user search session, and retrieves user-specified option sets from the server.

Parameters:
sessionConfig - configuration parameters for the session

Returns:
SearchSession object

Throws:

PrimusRuntimeException - that wraps any application server related exceptions

endSession

public void endSession(SearchSession searchSession)

Ends the user's search session

Parameters:
searchSession - The return value of beginSession

Throws:

PrimusRuntimeException - that wraps any application server related exceptions

search

public Results search(ClientRequest request,
                      SearchSession searchSession)

Submits a request to ES using the provided search session

Parameters:
request - The request to be submitted
searchSession - The session to use for the request

Returns:
a collection of search results

Throws:

PrimusRuntimeException - that wraps any application server related exceptions

extractResults

public Results extractResults(ClientRequest request,
                              java.lang.String resultXml)

doSearch

public java.lang.String doSearch(ClientRequest request,
                                 SearchSession searchSession)
                          throws java.lang.Exception

Throws:

java.lang.Exception

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception

Throws:

java.lang.Exception

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD